Actual source code: matrix.c

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

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

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

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

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

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

 47:    Logically Collective on Mat

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

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

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

 64:    Level: intermediate


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


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

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

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

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

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

102:    Logically Collective on Mat

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

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

112:    Level: advanced

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

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

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

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

134:    Logically Collective on Mat

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

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

142:    Level: advanced

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

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

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

160:    Logically Collective on Mat

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

165:    Level: developer

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

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

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

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

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

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

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

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

240:   Level: intermediate

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

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

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

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

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

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

273:   Level: intermediate

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


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

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

302:    Not Collective

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

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

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

315:    Level: advanced

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

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

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

342:    Collective on Mat

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

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

350:    Level: advanced

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

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

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

369:    Logically Collective on Mat

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

374:    Level: advanced


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

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

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

397:    Collective on Mat

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

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

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

409:    Level: advanced

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

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


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

434:    Logically Collective on Mat

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

439:    Level: advanced


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

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

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

462:    Not Collective

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

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

471:    Level: advanced


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

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

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

496:    Not Collective

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

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

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

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

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

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

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

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


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

546:    Level: advanced

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

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

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

572:    Logically Collective on Mat

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

577:    Level: advanced

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

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

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

600:    Not Collective

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

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

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

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

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

630:    Level: advanced

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

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

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

654:    Not Collective

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

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

662:    Level: advanced

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

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

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

684:    Not Collective

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

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


693:    Level: advanced

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

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

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

716:    Logically Collective on Mat

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

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

726:    Level: advanced

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

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

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

744:    Logically Collective on Mat

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

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

754:    Level: advanced

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

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

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

772:    Not Collective

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

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

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

784:    Level: advanced

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

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

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

801:    Collective on Mat

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

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

810:    Level: beginner

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

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


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

829:    Collective on Mat

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

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

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

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

841:    Level: beginner

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

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

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

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

877:    Collective on Mat

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

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

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

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

900:    Collective on Mat

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1087:    Collective on PetscViewer

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

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

1099:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1184:    Corresponding MatView() is not yet implemented.

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

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

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

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


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

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

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

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

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

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

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

1264:    Collective on Mat

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

1269:    Level: beginner

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

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

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

1287:   PetscFree((*A)->defaultvectype);
1288:   PetscFree((*A)->bsizes);
1289:   PetscFree((*A)->solvertype);
1290:   MatDestroy_Redundant(&(*A)->redundant);
1291:   MatProductClear(*A);

1293:   MatNullSpaceDestroy(&(*A)->nullsp);
1294:   MatNullSpaceDestroy(&(*A)->transnullsp);
1295:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1296:   MatDestroy(&(*A)->schur);
1297:   PetscLayoutDestroy(&(*A)->rmap);
1298:   PetscLayoutDestroy(&(*A)->cmap);
1299:   PetscHeaderDestroy(A);
1300:   return(0);
1301: }

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

1308:    Not Collective

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

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

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

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

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

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

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

1341:    Level: beginner

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

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

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

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

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

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

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


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

1398:    Not Collective

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

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

1408:    All the nonzeros in the row must be provided

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

1412:    The row must belong to this process

1414:    Level: intermediate

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

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

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

1437:    Not Collective

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

1444:    Notes:
1445:    The values, v, are column-oriented for the block version.

1447:    All the nonzeros in the row must be provided

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

1451:    The row must belong to this process

1453:    Level: advanced

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

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

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

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

1486:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

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

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

1546:    Level: beginner

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

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

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

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

1600:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

1653:    Level: beginner

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

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

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

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

1709:    Not Collective

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


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

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

1725:    Level: beginner

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


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

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

1753:    Not Collective

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

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

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

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

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

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

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

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

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

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

1813:    Level: intermediate

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

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

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

1871: /*@C
1872:    MatGetValues - Gets a block of values from a matrix.

1874:    Not Collective; currently only returns a local block

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

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

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

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

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

1898:    Level: advanced

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

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

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

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

1928:    Not Collective

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

1935:    Output Parameter:
1936: .  y -  a logically two-dimensional array of values

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

1941:    Level: advanced

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

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

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

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

1992:   Not Collective

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

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

2004:   Level: advanced

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

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

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

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

2038:    Not Collective

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

2045:    Level: intermediate


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


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


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

2073:    Not Collective

2075:    Input Parameters:
2076: .  A - the matrix

2078:    Output Parameters:
2079: + rmapping - row mapping
2080: - cmapping - column mapping

2082:    Level: advanced


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

2099: /*@
2100:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2102:    Not Collective

2104:    Input Parameters:
2105: .  A - the matrix

2107:    Output Parameters:
2108: + rmap - row layout
2109: - cmap - column layout

2111:    Level: advanced

2113: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2114: @*/
2115: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2116: {
2122:   if (rmap) *rmap = A->rmap;
2123:   if (cmap) *cmap = A->cmap;
2124:   return(0);
2125: }

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

2131:    Not Collective

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

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

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

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

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

2155:    Level: intermediate

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

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

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

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

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

2214:    Not Collective

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

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

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

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

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

2239:    Level: intermediate

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

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

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

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

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

2307:    Collective on Mat

2309:    Input Parameters:
2310: +  mat - the matrix
2311: -  x   - the vector to be multiplied

2313:    Output Parameters:
2314: .  y - the result

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

2320:    Level: developer

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


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

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

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

2349:    Neighbor-wise Collective on Mat

2351:    Input Parameters:
2352: +  mat - the matrix
2353: -  x   - the vector to be multiplied

2355:    Output Parameters:
2356: .  y - the result

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

2362:    Level: beginner

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

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

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

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

2400:    Neighbor-wise Collective on Mat

2402:    Input Parameters:
2403: +  mat - the matrix
2404: -  x   - the vector to be multiplied

2406:    Output Parameters:
2407: .  y - the result

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

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

2416:    Level: beginner

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


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

2440:   if (!mat->ops->multtranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined",((PetscObject)mat)->type_name);
2441:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2442:   VecLockReadPush(x);
2443:   (*mat->ops->multtranspose)(mat,x,y);
2444:   VecLockReadPop(x);
2445:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2446:   PetscObjectStateIncrease((PetscObject)y);
2447:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2448:   return(0);
2449: }

2451: /*@
2452:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2454:    Neighbor-wise Collective on Mat

2456:    Input Parameters:
2457: +  mat - the matrix
2458: -  x   - the vector to be multilplied

2460:    Output Parameters:
2461: .  y - the result

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

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

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

2471:    Level: beginner

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


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

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

2513: /*@
2514:     MatMultAdd -  Computes v3 = v2 + A * v1.

2516:     Neighbor-wise Collective on Mat

2518:     Input Parameters:
2519: +   mat - the matrix
2520: -   v1, v2 - the vectors

2522:     Output Parameters:
2523: .   v3 - the result

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

2529:     Level: beginner

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


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

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

2564: /*@
2565:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2567:    Neighbor-wise Collective on Mat

2569:    Input Parameters:
2570: +  mat - the matrix
2571: -  v1, v2 - the vectors

2573:    Output Parameters:
2574: .  v3 - the result

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

2580:    Level: beginner

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


2595:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2596:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2597:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2598:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2599:   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);
2600:   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);
2601:   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);
2602:   MatCheckPreallocated(mat,1);

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

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

2616:    Neighbor-wise Collective on Mat

2618:    Input Parameters:
2619: +  mat - the matrix
2620: -  v1, v2 - the vectors

2622:    Output Parameters:
2623: .  v3 - the result

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

2629:    Level: beginner

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


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

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

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

2682:    Neighbor-wise Collective on Mat

2684:    Input Parameters:
2685: +  mat - the matrix
2686: -  x   - the vector to be multilplied

2688:    Output Parameters:
2689: .  y - the result

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

2695:    Level: beginner

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

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

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

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

2727:    Neighbor-wise Collective on Mat

2729:    Input Parameters:
2730: +  mat - the matrix
2731: -  x   - the vector to be multilplied

2733:    Output Parameters:
2734: .  y - the result

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

2740:    Level: beginner

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

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

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

2765: /*@C
2766:    MatGetFactorType - gets the type of factorization it is

2768:    Not Collective

2770:    Input Parameters:
2771: .  mat - the matrix

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

2776:    Level: intermediate

2778: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2779: @*/
2780: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2781: {
2786:   *t = mat->factortype;
2787:   return(0);
2788: }

2790: /*@C
2791:    MatSetFactorType - sets the type of factorization it is

2793:    Logically Collective on Mat

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

2799:    Level: intermediate

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

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

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

2819:    Input Parameters:
2820: .  mat - the matrix

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

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

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

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

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

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

2866:     Level: intermediate

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

2871: .seealso: MatStashGetInfo()

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

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

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

2897:   PetscMemzero(info,sizeof(MatInfo));
2898:   return(0);
2899: }

2901: /* ----------------------------------------------------------*/

2903: /*@C
2904:    MatLUFactor - Performs in-place LU factorization of matrix.

2906:    Collective on Mat

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

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

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

2925:    Level: developer

2927: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2928:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

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

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

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

2961: /*@C
2962:    MatILUFactor - Performs in-place ILU factorization of matrix.

2964:    Collective on Mat

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

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

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

2984:    Level: developer

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

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

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

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

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

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

3019:    Collective on Mat

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


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

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

3038:    Level: developer

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

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

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

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

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

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

3082:    Collective on Mat

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

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

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

3097:    Level: developer

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

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

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

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

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

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

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

3137:    Collective on Mat

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

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

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

3152:    Level: developer

3154: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3155:           MatGetOrdering()

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

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

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

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

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

3192:    Collective on Mat

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

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

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

3211:    Level: developer

3213: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3214:           MatGetOrdering()

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

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

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

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

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

3257:    Collective on Mat

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


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

3271:    Level: developer

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

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

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

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

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

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

3310:    Neighbor-wise Collective on Mat

3312:    Input Parameters:
3313: +  mat - the factored matrix
3314: -  b - the right-hand-side vector

3316:    Output Parameter:
3317: .  x - the result vector

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

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

3328:    Level: developer

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

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

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

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

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

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

3397:    Neighbor-wise Collective on Mat

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

3403:    Output Parameter:
3404: .  X - the result matrix (dense matrix)

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

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

3416:    Level: developer

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

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

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

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

3453:    Neighbor-wise Collective on Mat

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

3459:    Output Parameter:
3460: .  X - the result matrix (dense matrix)

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

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

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

3474:    Level: developer

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

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

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

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

3513:    Neighbor-wise Collective on Mat

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

3519:    Output Parameter:
3520: .  X - the result matrix (dense matrix)

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

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

3530:    Level: developer

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


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

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

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

3566:    Neighbor-wise Collective on Mat

3568:    Input Parameters:
3569: +  mat - the factored matrix
3570: -  b - the right-hand-side vector

3572:    Output Parameter:
3573: .  x - the result vector

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

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

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

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

3592:    Level: developer

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

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

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

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

3626:    Neighbor-wise Collective on Mat

3628:    Input Parameters:
3629: +  mat - the factored matrix
3630: -  b - the right-hand-side vector

3632:    Output Parameter:
3633: .  x - the result vector

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

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

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

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

3652:    Level: developer

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

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

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

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

3685:    Neighbor-wise Collective on Mat

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

3692:    Output Parameter:
3693: .  x - the result vector

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

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

3703:    Level: developer

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

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

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

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

3759:    Neighbor-wise Collective on Mat

3761:    Input Parameters:
3762: +  mat - the factored matrix
3763: -  b - the right-hand-side vector

3765:    Output Parameter:
3766: .  x - the result vector

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

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

3776:    Level: developer

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

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

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

3813:    Neighbor-wise Collective on Mat

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

3820:    Output Parameter:
3821: .  x - the result vector

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

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

3831:    Level: developer

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

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

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

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

3887:    Neighbor-wise Collective on Mat

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

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

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

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

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

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

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

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

3933:    Vectors x and b CANNOT be the same

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

3937:    Level: developer

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

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

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

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

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

3998: /*@
3999:    MatCopy - Copies a matrix to another matrix.

4001:    Collective on Mat

4003:    Input Parameters:
4004: +  A - the matrix
4005: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4007:    Output Parameter:
4008: .  B - where the copy is put

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

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

4018:    Level: intermediate

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

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

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

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

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

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

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

4064:    Collective on Mat

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

4074:    Output Parameter:
4075: .  M - pointer to place new matrix

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

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

4086:    Level: intermediate

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

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

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

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

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

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

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

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

4172:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4173:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4174:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4175:     MatSetType(B,newtype);
4176:     for (i=0; i<3; i++) {
4177:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4178:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4179:       PetscStrlcat(convname,"_",sizeof(convname));
4180:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4181:       PetscStrlcat(convname,newtype,sizeof(convname));
4182:       PetscStrlcat(convname,"_C",sizeof(convname));
4183:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4184:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4185:       if (conv) {
4186:         MatDestroy(&B);
4187:         goto foundconv;
4188:       }
4189:     }

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

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

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

4203:     /* 5) Use a really basic converter. */
4204:     PetscInfo(mat,"Using MatConvert_Basic\n");
4205:     conv = MatConvert_Basic;

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

4229:   /* Copy Mat options */
4230:   if (issymmetric) {
4231:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4232:   }
4233:   if (ishermitian) {
4234:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4235:   }
4236:   return(0);
4237: }

4239: /*@C
4240:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4242:    Not Collective

4244:    Input Parameter:
4245: .  mat - the matrix, must be a factored matrix

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

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

4254:    Level: intermediate

4256: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4257: @*/
4258: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4259: {
4260:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4265:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4266:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4267:   if (!conv) {
4268:     *type = MATSOLVERPETSC;
4269:   } else {
4270:     (*conv)(mat,type);
4271:   }
4272:   return(0);
4273: }

4275: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4276: struct _MatSolverTypeForSpecifcType {
4277:   MatType                        mtype;
4278:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4279:   MatSolverTypeForSpecifcType next;
4280: };

4282: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4283: struct _MatSolverTypeHolder {
4284:   char                           *name;
4285:   MatSolverTypeForSpecifcType handlers;
4286:   MatSolverTypeHolder         next;
4287: };

4289: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4294:    Input Parameters:
4295: +    package - name of the package, for example petsc or superlu
4296: .    mtype - the matrix type that works with this package
4297: .    ftype - the type of factorization supported by the package
4298: -    getfactor - routine that will create the factored matrix ready to be used

4300:     Level: intermediate

4302: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4303: @*/
4304: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4305: {
4306:   PetscErrorCode              ierr;
4307:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4308:   PetscBool                   flg;
4309:   MatSolverTypeForSpecifcType inext,iprev = NULL;

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

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

4354:    Input Parameters:
4355: +    package - name of the package, for example petsc or superlu
4356: .    ftype - the type of factorization supported by the package
4357: -    mtype - the matrix type that works with this package

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

4364:     Level: intermediate

4366: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4367: @*/
4368: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4369: {
4370:   PetscErrorCode              ierr;
4371:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4372:   PetscBool                   flg;
4373:   MatSolverTypeForSpecifcType inext;

4376:   if (foundpackage) *foundpackage = PETSC_FALSE;
4377:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4378:   if (getfactor)    *getfactor    = NULL;

4380:   if (package) {
4381:     while (next) {
4382:       PetscStrcasecmp(package,next->name,&flg);
4383:       if (flg) {
4384:         if (foundpackage) *foundpackage = PETSC_TRUE;
4385:         inext = next->handlers;
4386:         while (inext) {
4387:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4388:           if (flg) {
4389:             if (foundmtype) *foundmtype = PETSC_TRUE;
4390:             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4391:             return(0);
4392:           }
4393:           inext = inext->next;
4394:         }
4395:       }
4396:       next = next->next;
4397:     }
4398:   } else {
4399:     while (next) {
4400:       inext = next->handlers;
4401:       while (inext) {
4402:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4403:         if (flg && inext->getfactor[(int)ftype-1]) {
4404:           if (foundpackage) *foundpackage = PETSC_TRUE;
4405:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4406:           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
4407:           return(0);
4408:         }
4409:         inext = inext->next;
4410:       }
4411:       next = next->next;
4412:     }
4413:   }
4414:   return(0);
4415: }

4417: PetscErrorCode MatSolverTypeDestroy(void)
4418: {
4419:   PetscErrorCode              ierr;
4420:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4421:   MatSolverTypeForSpecifcType inext,iprev;

4424:   while (next) {
4425:     PetscFree(next->name);
4426:     inext = next->handlers;
4427:     while (inext) {
4428:       PetscFree(inext->mtype);
4429:       iprev = inext;
4430:       inext = inext->next;
4431:       PetscFree(iprev);
4432:     }
4433:     prev = next;
4434:     next = next->next;
4435:     PetscFree(prev);
4436:   }
4437:   MatSolverTypeHolders = NULL;
4438:   return(0);
4439: }

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

4444:    Collective on Mat

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

4451:    Output Parameters:
4452: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4454:    Notes:
4455:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4456:      such as pastix, superlu, mumps etc.

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

4460:    Level: intermediate

4462: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4463: @*/
4464: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4465: {
4466:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4467:   PetscBool      foundpackage,foundmtype;


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

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

4487:   (*conv)(mat,ftype,f);
4488:   return(0);
4489: }

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

4494:    Not Collective

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

4501:    Output Parameter:
4502: .    flg - PETSC_TRUE if the factorization is available

4504:    Notes:
4505:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4506:      such as pastix, superlu, mumps etc.

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

4510:    Level: intermediate

4512: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4513: @*/
4514: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4515: {
4516:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4525:   *flg = PETSC_FALSE;
4526:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4527:   if (gconv) {
4528:     *flg = PETSC_TRUE;
4529:   }
4530:   return(0);
4531: }

4533:  #include <petscdmtypes.h>

4535: /*@
4536:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4538:    Collective on Mat

4540:    Input Parameters:
4541: +  mat - the matrix
4542: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4543:         See the manual page for MatDuplicateOption for an explanation of these options.

4545:    Output Parameter:
4546: .  M - pointer to place new matrix

4548:    Level: intermediate

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

4554: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4555: @*/
4556: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4557: {
4559:   Mat            B;
4560:   PetscInt       i;
4561:   DM             dm;
4562:   void           (*viewf)(void);

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

4572:   *M = 0;
4573:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4574:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4575:   (*mat->ops->duplicate)(mat,op,M);
4576:   B    = *M;

4578:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4579:   if (viewf) {
4580:     MatSetOperation(B,MATOP_VIEW,viewf);
4581:   }

4583:   B->stencil.dim = mat->stencil.dim;
4584:   B->stencil.noc = mat->stencil.noc;
4585:   for (i=0; i<=mat->stencil.dim; i++) {
4586:     B->stencil.dims[i]   = mat->stencil.dims[i];
4587:     B->stencil.starts[i] = mat->stencil.starts[i];
4588:   }

4590:   B->nooffproczerorows = mat->nooffproczerorows;
4591:   B->nooffprocentries  = mat->nooffprocentries;

4593:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4594:   if (dm) {
4595:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4596:   }
4597:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4598:   PetscObjectStateIncrease((PetscObject)B);
4599:   return(0);
4600: }

4602: /*@
4603:    MatGetDiagonal - Gets the diagonal of a matrix.

4605:    Logically Collective on Mat

4607:    Input Parameters:
4608: +  mat - the matrix
4609: -  v - the vector for storing the diagonal

4611:    Output Parameter:
4612: .  v - the diagonal of the matrix

4614:    Level: intermediate

4616:    Note:
4617:    Currently only correct in parallel for square matrices.

4619: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4620: @*/
4621: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4622: {

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

4633:   (*mat->ops->getdiagonal)(mat,v);
4634:   PetscObjectStateIncrease((PetscObject)v);
4635:   return(0);
4636: }

4638: /*@C
4639:    MatGetRowMin - Gets the minimum value (of the real part) of each
4640:         row of the matrix

4642:    Logically Collective on Mat

4644:    Input Parameters:
4645: .  mat - the matrix

4647:    Output Parameter:
4648: +  v - the vector for storing the maximums
4649: -  idx - the indices of the column found for each row (optional)

4651:    Level: intermediate

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

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

4659: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4660:           MatGetRowMax()
4661: @*/
4662: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4663: {

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

4674:   (*mat->ops->getrowmin)(mat,v,idx);
4675:   PetscObjectStateIncrease((PetscObject)v);
4676:   return(0);
4677: }

4679: /*@C
4680:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4681:         row of the matrix

4683:    Logically Collective on Mat

4685:    Input Parameters:
4686: .  mat - the matrix

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

4692:    Level: intermediate

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

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

4700: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4701: @*/
4702: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4703: {

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

4715:   (*mat->ops->getrowminabs)(mat,v,idx);
4716:   PetscObjectStateIncrease((PetscObject)v);
4717:   return(0);
4718: }

4720: /*@C
4721:    MatGetRowMax - Gets the maximum value (of the real part) of each
4722:         row of the matrix

4724:    Logically Collective on Mat

4726:    Input Parameters:
4727: .  mat - the matrix

4729:    Output Parameter:
4730: +  v - the vector for storing the maximums
4731: -  idx - the indices of the column found for each row (optional)

4733:    Level: intermediate

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

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

4741: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4742: @*/
4743: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4744: {

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

4755:   (*mat->ops->getrowmax)(mat,v,idx);
4756:   PetscObjectStateIncrease((PetscObject)v);
4757:   return(0);
4758: }

4760: /*@C
4761:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4762:         row of the matrix

4764:    Logically Collective on Mat

4766:    Input Parameters:
4767: .  mat - the matrix

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

4773:    Level: intermediate

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

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

4781: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4782: @*/
4783: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4784: {

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

4796:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4797:   PetscObjectStateIncrease((PetscObject)v);
4798:   return(0);
4799: }

4801: /*@
4802:    MatGetRowSum - Gets the sum of each row of the matrix

4804:    Logically or Neighborhood Collective on Mat

4806:    Input Parameters:
4807: .  mat - the matrix

4809:    Output Parameter:
4810: .  v - the vector for storing the sum of rows

4812:    Level: intermediate

4814:    Notes:
4815:     This code is slow since it is not currently specialized for different formats

4817: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4818: @*/
4819: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4820: {
4821:   Vec            ones;

4828:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4829:   MatCheckPreallocated(mat,1);
4830:   MatCreateVecs(mat,&ones,NULL);
4831:   VecSet(ones,1.);
4832:   MatMult(mat,ones,v);
4833:   VecDestroy(&ones);
4834:   return(0);
4835: }

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

4840:    Collective on Mat

4842:    Input Parameter:
4843: +  mat - the matrix to transpose
4844: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4846:    Output Parameters:
4847: .  B - the transpose

4849:    Notes:
4850:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4856:    Level: intermediate

4858: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4859: @*/
4860: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4861: {

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

4874:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4875:   (*mat->ops->transpose)(mat,reuse,B);
4876:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4877:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4878:   return(0);
4879: }

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

4885:    Collective on Mat

4887:    Input Parameter:
4888: +  A - the matrix to test
4889: -  B - the matrix to test against, this can equal the first parameter

4891:    Output Parameters:
4892: .  flg - the result

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

4899:    Level: intermediate

4901: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4902: @*/
4903: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4904: {
4905:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

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

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

4933:    Collective on Mat

4935:    Input Parameter:
4936: +  mat - the matrix to transpose and complex conjugate
4937: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

4939:    Output Parameters:
4940: .  B - the Hermitian

4942:    Level: intermediate

4944: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4945: @*/
4946: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4947: {

4951:   MatTranspose(mat,reuse,B);
4952: #if defined(PETSC_USE_COMPLEX)
4953:   MatConjugate(*B);
4954: #endif
4955:   return(0);
4956: }

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

4961:    Collective on Mat

4963:    Input Parameter:
4964: +  A - the matrix to test
4965: -  B - the matrix to test against, this can equal the first parameter

4967:    Output Parameters:
4968: .  flg - the result

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

4975:    Level: intermediate

4977: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4978: @*/
4979: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4980: {
4981:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

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

4997: /*@
4998:    MatPermute - Creates a new matrix with rows and columns permuted from the
4999:    original.

5001:    Collective on Mat

5003:    Input Parameters:
5004: +  mat - the matrix to permute
5005: .  row - row permutation, each processor supplies only the permutation for its rows
5006: -  col - column permutation, each processor supplies only the permutation for its columns

5008:    Output Parameters:
5009: .  B - the permuted matrix

5011:    Level: advanced

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

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

5019: @*/
5020: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5021: {

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

5035:   (*mat->ops->permute)(mat,row,col,B);
5036:   PetscObjectStateIncrease((PetscObject)*B);
5037:   return(0);
5038: }

5040: /*@
5041:    MatEqual - Compares two matrices.

5043:    Collective on Mat

5045:    Input Parameters:
5046: +  A - the first matrix
5047: -  B - the second matrix

5049:    Output Parameter:
5050: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5052:    Level: intermediate

5054: @*/
5055: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5056: {

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

5075:   (*A->ops->equal)(A,B,flg);
5076:   return(0);
5077: }

5079: /*@
5080:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5081:    matrices that are stored as vectors.  Either of the two scaling
5082:    matrices can be NULL.

5084:    Collective on Mat

5086:    Input Parameters:
5087: +  mat - the matrix to be scaled
5088: .  l - the left scaling vector (or NULL)
5089: -  r - the right scaling vector (or NULL)

5091:    Notes:
5092:    MatDiagonalScale() computes A = LAR, where
5093:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5094:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5096:    Level: intermediate


5099: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5100: @*/
5101: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5102: {

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

5115:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5116:   (*mat->ops->diagonalscale)(mat,l,r);
5117:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5118:   PetscObjectStateIncrease((PetscObject)mat);
5119:   return(0);
5120: }

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

5125:     Logically Collective on Mat

5127:     Input Parameters:
5128: +   mat - the matrix to be scaled
5129: -   a  - the scaling value

5131:     Output Parameter:
5132: .   mat - the scaled matrix

5134:     Level: intermediate

5136: .seealso: MatDiagonalScale()
5137: @*/
5138: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5139: {

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

5151:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5152:   if (a != (PetscScalar)1.0) {
5153:     (*mat->ops->scale)(mat,a);
5154:     PetscObjectStateIncrease((PetscObject)mat);
5155:   }
5156:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5157:   return(0);
5158: }

5160: /*@
5161:    MatNorm - Calculates various norms of a matrix.

5163:    Collective on Mat

5165:    Input Parameters:
5166: +  mat - the matrix
5167: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5169:    Output Parameters:
5170: .  nrm - the resulting norm

5172:    Level: intermediate

5174: @*/
5175: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5176: {


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

5189:   (*mat->ops->norm)(mat,type,nrm);
5190:   return(0);
5191: }

5193: /*
5194:      This variable is used to prevent counting of MatAssemblyBegin() that
5195:    are called from within a MatAssemblyEnd().
5196: */
5197: static PetscInt MatAssemblyEnd_InUse = 0;
5198: /*@
5199:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5200:    be called after completing all calls to MatSetValues().

5202:    Collective on Mat

5204:    Input Parameters:
5205: +  mat - the matrix
5206: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5208:    Notes:
5209:    MatSetValues() generally caches the values.  The matrix is ready to
5210:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5211:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5212:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5213:    using the matrix.

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

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

5223:    Level: beginner

5225: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5226: @*/
5227: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5228: {

5234:   MatCheckPreallocated(mat,1);
5235:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5236:   if (mat->assembled) {
5237:     mat->was_assembled = PETSC_TRUE;
5238:     mat->assembled     = PETSC_FALSE;
5239:   }

5241:   if (!MatAssemblyEnd_InUse) {
5242:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5243:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5244:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5245:   } else if (mat->ops->assemblybegin) {
5246:     (*mat->ops->assemblybegin)(mat,type);
5247:   }
5248:   return(0);
5249: }

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

5255:    Not Collective

5257:    Input Parameter:
5258: .  mat - the matrix

5260:    Output Parameter:
5261: .  assembled - PETSC_TRUE or PETSC_FALSE

5263:    Level: advanced

5265: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5266: @*/
5267: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5268: {
5272:   *assembled = mat->assembled;
5273:   return(0);
5274: }

5276: /*@
5277:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5278:    be called after MatAssemblyBegin().

5280:    Collective on Mat

5282:    Input Parameters:
5283: +  mat - the matrix
5284: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

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

5299:    Notes:
5300:    MatSetValues() generally caches the values.  The matrix is ready to
5301:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5302:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5303:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5304:    using the matrix.

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

5310:    Level: beginner

5312: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5313: @*/
5314: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5315: {
5316:   PetscErrorCode  ierr;
5317:   static PetscInt inassm = 0;
5318:   PetscBool       flg    = PETSC_FALSE;


5324:   inassm++;
5325:   MatAssemblyEnd_InUse++;
5326:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5327:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5328:     if (mat->ops->assemblyend) {
5329:       (*mat->ops->assemblyend)(mat,type);
5330:     }
5331:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5332:   } else if (mat->ops->assemblyend) {
5333:     (*mat->ops->assemblyend)(mat,type);
5334:   }

5336:   /* Flush assembly is not a true assembly */
5337:   if (type != MAT_FLUSH_ASSEMBLY) {
5338:     mat->num_ass++;
5339:     mat->assembled        = PETSC_TRUE;
5340:     mat->ass_nonzerostate = mat->nonzerostate;
5341:   }

5343:   mat->insertmode = NOT_SET_VALUES;
5344:   MatAssemblyEnd_InUse--;
5345:   PetscObjectStateIncrease((PetscObject)mat);
5346:   if (!mat->symmetric_eternal) {
5347:     mat->symmetric_set              = PETSC_FALSE;
5348:     mat->hermitian_set              = PETSC_FALSE;
5349:     mat->structurally_symmetric_set = PETSC_FALSE;
5350:   }
5351:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5352:     MatViewFromOptions(mat,NULL,"-mat_view");

5354:     if (mat->checksymmetryonassembly) {
5355:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5356:       if (flg) {
5357:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5358:       } else {
5359:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5360:       }
5361:     }
5362:     if (mat->nullsp && mat->checknullspaceonassembly) {
5363:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5364:     }
5365:   }
5366:   inassm--;
5367:   return(0);
5368: }

5370: /*@
5371:    MatSetOption - Sets a parameter option for a matrix. Some options
5372:    may be specific to certain storage formats.  Some options
5373:    determine how values will be inserted (or added). Sorted,
5374:    row-oriented input will generally assemble the fastest. The default
5375:    is row-oriented.

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

5379:    Input Parameters:
5380: +  mat - the matrix
5381: .  option - the option, one of those listed below (and possibly others),
5382: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

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


5398:    Options For Use with MatSetValues():
5399:    Insert a logically dense subblock, which can be
5400: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5482:    Level: intermediate

5484: .seealso:  MatOption, Mat

5486: @*/
5487: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5488: {

5494:   if (op > 0) {
5497:   }

5499:   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);
5500:   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()");

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

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

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

5577:    Input Parameters:
5578: +  mat - the matrix
5579: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5587:    Level: intermediate

5589: .seealso:  MatOption, MatSetOption()

5591: @*/
5592: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5593: {

5598:   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);
5599:   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()");

5601:   switch (op) {
5602:   case MAT_NO_OFF_PROC_ENTRIES:
5603:     *flg = mat->nooffprocentries;
5604:     break;
5605:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5606:     *flg = mat->nooffproczerorows;
5607:     break;
5608:   case MAT_SYMMETRIC:
5609:     *flg = mat->symmetric;
5610:     break;
5611:   case MAT_HERMITIAN:
5612:     *flg = mat->hermitian;
5613:     break;
5614:   case MAT_STRUCTURALLY_SYMMETRIC:
5615:     *flg = mat->structurally_symmetric;
5616:     break;
5617:   case MAT_SYMMETRY_ETERNAL:
5618:     *flg = mat->symmetric_eternal;
5619:     break;
5620:   case MAT_SPD:
5621:     *flg = mat->spd;
5622:     break;
5623:   default:
5624:     break;
5625:   }
5626:   return(0);
5627: }

5629: /*@
5630:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5631:    this routine retains the old nonzero structure.

5633:    Logically Collective on Mat

5635:    Input Parameters:
5636: .  mat - the matrix

5638:    Level: intermediate

5640:    Notes:
5641:     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.
5642:    See the Performance chapter of the users manual for information on preallocating matrices.

5644: .seealso: MatZeroRows()
5645: @*/
5646: PetscErrorCode MatZeroEntries(Mat mat)
5647: {

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

5658:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5659:   (*mat->ops->zeroentries)(mat);
5660:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5661:   PetscObjectStateIncrease((PetscObject)mat);
5662:   return(0);
5663: }

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

5669:    Collective on Mat

5671:    Input Parameters:
5672: +  mat - the matrix
5673: .  numRows - the number of rows to remove
5674: .  rows - the global row indices
5675: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5676: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5677: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5696:    Level: intermediate

5698: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5699:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5700: @*/
5701: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5702: {

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

5714:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5715:   MatViewFromOptions(mat,NULL,"-mat_view");
5716:   PetscObjectStateIncrease((PetscObject)mat);
5717:   return(0);
5718: }

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

5724:    Collective on Mat

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

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

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

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

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

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

5750:    Level: intermediate

5752: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5753:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5754: @*/
5755: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5756: {
5758:   PetscInt       numRows;
5759:   const PetscInt *rows;

5766:   ISGetLocalSize(is,&numRows);
5767:   ISGetIndices(is,&rows);
5768:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5769:   ISRestoreIndices(is,&rows);
5770:   return(0);
5771: }

5773: /*@
5774:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5775:    of a set of rows of a matrix.

5777:    Collective on Mat

5779:    Input Parameters:
5780: +  mat - the matrix
5781: .  numRows - the number of rows to remove
5782: .  rows - the global row indices
5783: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5784: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5785: -  b - optional vector of right hand side, that will be adjusted by provided solution

5787:    Notes:
5788:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5789:    but does not release memory.  For the dense and block diagonal
5790:    formats this does not alter the nonzero structure.

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

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

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

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

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

5811:    Level: intermediate

5813: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5814:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5815: @*/
5816: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5817: {

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

5829:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5830:   MatViewFromOptions(mat,NULL,"-mat_view");
5831:   PetscObjectStateIncrease((PetscObject)mat);
5832:   return(0);
5833: }

5835: /*@
5836:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5837:    of a set of rows of a matrix.

5839:    Collective on Mat

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

5848:    Notes:
5849:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5850:    but does not release memory.  For the dense and block diagonal
5851:    formats this does not alter the nonzero structure.

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

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

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

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

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

5872:    Level: intermediate

5874: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5875:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5876: @*/
5877: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5878: {
5879:   PetscInt       numRows;
5880:   const PetscInt *rows;

5887:   ISGetLocalSize(is,&numRows);
5888:   ISGetIndices(is,&rows);
5889:   MatZeroRows(mat,numRows,rows,diag,x,b);
5890:   ISRestoreIndices(is,&rows);
5891:   return(0);
5892: }

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

5898:    Collective on Mat

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

5908:    Notes:
5909:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5910:    but does not release memory.  For the dense and block diagonal
5911:    formats this does not alter the nonzero structure.

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

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

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

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

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

5931:    In Fortran idxm and idxn should be declared as
5932: $     MatStencil idxm(4,m)
5933:    and the values inserted using
5934: $    idxm(MatStencil_i,1) = i
5935: $    idxm(MatStencil_j,1) = j
5936: $    idxm(MatStencil_k,1) = k
5937: $    idxm(MatStencil_c,1) = c
5938:    etc

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

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

5948:    Level: intermediate

5950: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5951:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5952: @*/
5953: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5954: {
5955:   PetscInt       dim     = mat->stencil.dim;
5956:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5957:   PetscInt       *dims   = mat->stencil.dims+1;
5958:   PetscInt       *starts = mat->stencil.starts;
5959:   PetscInt       *dxm    = (PetscInt*) rows;
5960:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5968:   PetscMalloc1(numRows, &jdxm);
5969:   for (i = 0; i < numRows; ++i) {
5970:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5971:     for (j = 0; j < 3-sdim; ++j) dxm++;
5972:     /* Local index in X dir */
5973:     tmp = *dxm++ - starts[0];
5974:     /* Loop over remaining dimensions */
5975:     for (j = 0; j < dim-1; ++j) {
5976:       /* If nonlocal, set index to be negative */
5977:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5978:       /* Update local index */
5979:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5980:     }
5981:     /* Skip component slot if necessary */
5982:     if (mat->stencil.noc) dxm++;
5983:     /* Local row number */
5984:     if (tmp >= 0) {
5985:       jdxm[numNewRows++] = tmp;
5986:     }
5987:   }
5988:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5989:   PetscFree(jdxm);
5990:   return(0);
5991: }

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

5997:    Collective on Mat

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

6007:    Notes:
6008:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6009:    but does not release memory.  For the dense and block diagonal
6010:    formats this does not alter the nonzero structure.

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

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

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

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

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

6030:    In Fortran idxm and idxn should be declared as
6031: $     MatStencil idxm(4,m)
6032:    and the values inserted using
6033: $    idxm(MatStencil_i,1) = i
6034: $    idxm(MatStencil_j,1) = j
6035: $    idxm(MatStencil_k,1) = k
6036: $    idxm(MatStencil_c,1) = c
6037:    etc

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

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

6047:    Level: intermediate

6049: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6050:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6051: @*/
6052: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6053: {
6054:   PetscInt       dim     = mat->stencil.dim;
6055:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6056:   PetscInt       *dims   = mat->stencil.dims+1;
6057:   PetscInt       *starts = mat->stencil.starts;
6058:   PetscInt       *dxm    = (PetscInt*) rows;
6059:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6067:   PetscMalloc1(numRows, &jdxm);
6068:   for (i = 0; i < numRows; ++i) {
6069:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6070:     for (j = 0; j < 3-sdim; ++j) dxm++;
6071:     /* Local index in X dir */
6072:     tmp = *dxm++ - starts[0];
6073:     /* Loop over remaining dimensions */
6074:     for (j = 0; j < dim-1; ++j) {
6075:       /* If nonlocal, set index to be negative */
6076:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6077:       /* Update local index */
6078:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6079:     }
6080:     /* Skip component slot if necessary */
6081:     if (mat->stencil.noc) dxm++;
6082:     /* Local row number */
6083:     if (tmp >= 0) {
6084:       jdxm[numNewRows++] = tmp;
6085:     }
6086:   }
6087:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6088:   PetscFree(jdxm);
6089:   return(0);
6090: }

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

6096:    Collective on Mat

6098:    Input Parameters:
6099: +  mat - the matrix
6100: .  numRows - the number of rows to remove
6101: .  rows - the global row indices
6102: .  diag - value put in all diagonals of eliminated rows
6103: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6104: -  b - optional vector of right hand side, that will be adjusted by provided solution

6106:    Notes:
6107:    Before calling MatZeroRowsLocal(), the user must first set the
6108:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6110:    For the AIJ matrix formats this removes the old nonzero structure,
6111:    but does not release memory.  For the dense and block diagonal
6112:    formats this does not alter the nonzero structure.

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

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

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

6125:    Level: intermediate

6127: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6128:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6129: @*/
6130: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6131: {

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

6142:   if (mat->ops->zerorowslocal) {
6143:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6144:   } else {
6145:     IS             is, newis;
6146:     const PetscInt *newRows;

6148:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6149:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6150:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6151:     ISGetIndices(newis,&newRows);
6152:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6153:     ISRestoreIndices(newis,&newRows);
6154:     ISDestroy(&newis);
6155:     ISDestroy(&is);
6156:   }
6157:   PetscObjectStateIncrease((PetscObject)mat);
6158:   return(0);
6159: }

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

6165:    Collective on Mat

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

6174:    Notes:
6175:    Before calling MatZeroRowsLocalIS(), the user must first set the
6176:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6178:    For the AIJ matrix formats this removes the old nonzero structure,
6179:    but does not release memory.  For the dense and block diagonal
6180:    formats this does not alter the nonzero structure.

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

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

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

6193:    Level: intermediate

6195: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6196:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6197: @*/
6198: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6199: {
6201:   PetscInt       numRows;
6202:   const PetscInt *rows;

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

6212:   ISGetLocalSize(is,&numRows);
6213:   ISGetIndices(is,&rows);
6214:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6215:   ISRestoreIndices(is,&rows);
6216:   return(0);
6217: }

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

6223:    Collective on Mat

6225:    Input Parameters:
6226: +  mat - the matrix
6227: .  numRows - the number of rows to remove
6228: .  rows - the global row indices
6229: .  diag - value put in all diagonals of eliminated rows
6230: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6231: -  b - optional vector of right hand side, that will be adjusted by provided solution

6233:    Notes:
6234:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6235:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6241:    Level: intermediate

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

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

6260:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6261:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6262:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6263:   ISGetIndices(newis,&newRows);
6264:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6265:   ISRestoreIndices(newis,&newRows);
6266:   ISDestroy(&newis);
6267:   ISDestroy(&is);
6268:   PetscObjectStateIncrease((PetscObject)mat);
6269:   return(0);
6270: }

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

6276:    Collective on Mat

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

6285:    Notes:
6286:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6287:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6293:    Level: intermediate

6295: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6296:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6297: @*/
6298: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6299: {
6301:   PetscInt       numRows;
6302:   const PetscInt *rows;

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

6312:   ISGetLocalSize(is,&numRows);
6313:   ISGetIndices(is,&rows);
6314:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6315:   ISRestoreIndices(is,&rows);
6316:   return(0);
6317: }

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

6322:    Not Collective

6324:    Input Parameter:
6325: .  mat - the matrix

6327:    Output Parameters:
6328: +  m - the number of global rows
6329: -  n - the number of global columns

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

6333:    Level: beginner

6335: .seealso: MatGetLocalSize()
6336: @*/
6337: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6338: {
6341:   if (m) *m = mat->rmap->N;
6342:   if (n) *n = mat->cmap->N;
6343:   return(0);
6344: }

6346: /*@C
6347:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6348:    stored locally.  This information may be implementation dependent, so
6349:    use with care.

6351:    Not Collective

6353:    Input Parameters:
6354: .  mat - the matrix

6356:    Output Parameters:
6357: +  m - the number of local rows
6358: -  n - the number of local columns

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

6362:    Level: beginner

6364: .seealso: MatGetSize()
6365: @*/
6366: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6367: {
6372:   if (m) *m = mat->rmap->n;
6373:   if (n) *n = mat->cmap->n;
6374:   return(0);
6375: }

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

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

6383:    Input Parameters:
6384: .  mat - the matrix

6386:    Output Parameters:
6387: +  m - the global index of the first local column
6388: -  n - one more than the global index of the last local column

6390:    Notes:
6391:     both output parameters can be NULL on input.

6393:    Level: developer

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

6397: @*/
6398: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6399: {
6405:   MatCheckPreallocated(mat,1);
6406:   if (m) *m = mat->cmap->rstart;
6407:   if (n) *n = mat->cmap->rend;
6408:   return(0);
6409: }

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

6417:    Not Collective

6419:    Input Parameters:
6420: .  mat - the matrix

6422:    Output Parameters:
6423: +  m - the global index of the first local row
6424: -  n - one more than the global index of the last local row

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

6431:    Level: beginner

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

6435: @*/
6436: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6437: {
6443:   MatCheckPreallocated(mat,1);
6444:   if (m) *m = mat->rmap->rstart;
6445:   if (n) *n = mat->rmap->rend;
6446:   return(0);
6447: }

6449: /*@C
6450:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6451:    each process

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

6455:    Input Parameters:
6456: .  mat - the matrix

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

6461:    Level: beginner

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

6465: @*/
6466: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6467: {

6473:   MatCheckPreallocated(mat,1);
6474:   PetscLayoutGetRanges(mat->rmap,ranges);
6475:   return(0);
6476: }

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

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

6484:    Input Parameters:
6485: .  mat - the matrix

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

6490:    Level: beginner

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

6494: @*/
6495: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6496: {

6502:   MatCheckPreallocated(mat,1);
6503:   PetscLayoutGetRanges(mat->cmap,ranges);
6504:   return(0);
6505: }

6507: /*@C
6508:    MatGetOwnershipIS - Get row and column ownership as index sets

6510:    Not Collective

6512:    Input Arguments:
6513: .  A - matrix of type Elemental

6515:    Output Arguments:
6516: +  rows - rows in which this process owns elements
6517: -  cols - columns in which this process owns elements

6519:    Level: intermediate

6521: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6522: @*/
6523: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6524: {
6525:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6528:   MatCheckPreallocated(A,1);
6529:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6530:   if (f) {
6531:     (*f)(A,rows,cols);
6532:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6533:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6534:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6535:   }
6536:   return(0);
6537: }

6539: /*@C
6540:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6541:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6542:    to complete the factorization.

6544:    Collective on Mat

6546:    Input Parameters:
6547: +  mat - the matrix
6548: .  row - row permutation
6549: .  column - column permutation
6550: -  info - structure containing
6551: $      levels - number of levels of fill.
6552: $      expected fill - as ratio of original fill.
6553: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6554:                 missing diagonal entries)

6556:    Output Parameters:
6557: .  fact - new matrix that has been symbolically factored

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

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

6566:    Level: developer

6568: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6569:           MatGetOrdering(), MatFactorInfo

6571:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6576:    References:
6577:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6578: @*/
6579: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6580: {

6590:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6591:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6592:   if (!(fact)->ops->ilufactorsymbolic) {
6593:     MatSolverType spackage;
6594:     MatFactorGetSolverType(fact,&spackage);
6595:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6596:   }
6597:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6598:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6599:   MatCheckPreallocated(mat,2);

6601:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6602:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6603:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6604:   return(0);
6605: }

6607: /*@C
6608:    MatICCFactorSymbolic - Performs symbolic incomplete
6609:    Cholesky factorization for a symmetric matrix.  Use
6610:    MatCholeskyFactorNumeric() to complete the factorization.

6612:    Collective on Mat

6614:    Input Parameters:
6615: +  mat - the matrix
6616: .  perm - row and column permutation
6617: -  info - structure containing
6618: $      levels - number of levels of fill.
6619: $      expected fill - as ratio of original fill.

6621:    Output Parameter:
6622: .  fact - the factored matrix

6624:    Notes:
6625:    Most users should employ the KSP interface for linear solvers
6626:    instead of working directly with matrix algebra routines such as this.
6627:    See, e.g., KSPCreate().

6629:    Level: developer

6631: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6633:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6638:    References:
6639:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6640: @*/
6641: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6642: {

6651:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6652:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6653:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6654:   if (!(fact)->ops->iccfactorsymbolic) {
6655:     MatSolverType spackage;
6656:     MatFactorGetSolverType(fact,&spackage);
6657:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6658:   }
6659:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6660:   MatCheckPreallocated(mat,2);

6662:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6663:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6664:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6665:   return(0);
6666: }

6668: /*@C
6669:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6670:    points to an array of valid matrices, they may be reused to store the new
6671:    submatrices.

6673:    Collective on Mat

6675:    Input Parameters:
6676: +  mat - the matrix
6677: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6678: .  irow, icol - index sets of rows and columns to extract
6679: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6681:    Output Parameter:
6682: .  submat - the array of submatrices

6684:    Notes:
6685:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6686:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6687:    to extract a parallel submatrix.

6689:    Some matrix types place restrictions on the row and column
6690:    indices, such as that they be sorted or that they be equal to each other.

6692:    The index sets may not have duplicate entries.

6694:    When extracting submatrices from a parallel matrix, each processor can
6695:    form a different submatrix by setting the rows and columns of its
6696:    individual index sets according to the local submatrix desired.

6698:    When finished using the submatrices, the user should destroy
6699:    them with MatDestroySubMatrices().

6701:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6702:    original matrix has not changed from that last call to MatCreateSubMatrices().

6704:    This routine creates the matrices in submat; you should NOT create them before
6705:    calling it. It also allocates the array of matrix pointers submat.

6707:    For BAIJ matrices the index sets must respect the block structure, that is if they
6708:    request one row/column in a block, they must request all rows/columns that are in
6709:    that block. For example, if the block size is 2 you cannot request just row 0 and
6710:    column 0.

6712:    Fortran Note:
6713:    The Fortran interface is slightly different from that given below; it
6714:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6716:    Level: advanced


6719: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6720: @*/
6721: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6722: {
6724:   PetscInt       i;
6725:   PetscBool      eq;

6730:   if (n) {
6735:   }
6737:   if (n && scall == MAT_REUSE_MATRIX) {
6740:   }
6741:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6742:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6743:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6744:   MatCheckPreallocated(mat,1);

6746:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6747:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6748:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6749:   for (i=0; i<n; i++) {
6750:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6751:     ISEqualUnsorted(irow[i],icol[i],&eq);
6752:     if (eq) {
6753:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6754:     }
6755:   }
6756:   return(0);
6757: }

6759: /*@C
6760:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6762:    Collective on Mat

6764:    Input Parameters:
6765: +  mat - the matrix
6766: .  n   - the number of submatrixes to be extracted
6767: .  irow, icol - index sets of rows and columns to extract
6768: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6770:    Output Parameter:
6771: .  submat - the array of submatrices

6773:    Level: advanced


6776: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6777: @*/
6778: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6779: {
6781:   PetscInt       i;
6782:   PetscBool      eq;

6787:   if (n) {
6792:   }
6794:   if (n && scall == MAT_REUSE_MATRIX) {
6797:   }
6798:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6799:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6800:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6801:   MatCheckPreallocated(mat,1);

6803:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6804:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6805:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6806:   for (i=0; i<n; i++) {
6807:     ISEqualUnsorted(irow[i],icol[i],&eq);
6808:     if (eq) {
6809:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6810:     }
6811:   }
6812:   return(0);
6813: }

6815: /*@C
6816:    MatDestroyMatrices - Destroys an array of matrices.

6818:    Collective on Mat

6820:    Input Parameters:
6821: +  n - the number of local matrices
6822: -  mat - the matrices (note that this is a pointer to the array of matrices)

6824:    Level: advanced

6826:     Notes:
6827:     Frees not only the matrices, but also the array that contains the matrices
6828:            In Fortran will not free the array.

6830: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6831: @*/
6832: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6833: {
6835:   PetscInt       i;

6838:   if (!*mat) return(0);
6839:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6842:   for (i=0; i<n; i++) {
6843:     MatDestroy(&(*mat)[i]);
6844:   }

6846:   /* memory is allocated even if n = 0 */
6847:   PetscFree(*mat);
6848:   return(0);
6849: }

6851: /*@C
6852:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6854:    Collective on Mat

6856:    Input Parameters:
6857: +  n - the number of local matrices
6858: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6859:                        sequence of MatCreateSubMatrices())

6861:    Level: advanced

6863:     Notes:
6864:     Frees not only the matrices, but also the array that contains the matrices
6865:            In Fortran will not free the array.

6867: .seealso: MatCreateSubMatrices()
6868: @*/
6869: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6870: {
6872:   Mat            mat0;

6875:   if (!*mat) return(0);
6876:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6877:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6880:   mat0 = (*mat)[0];
6881:   if (mat0 && mat0->ops->destroysubmatrices) {
6882:     (mat0->ops->destroysubmatrices)(n,mat);
6883:   } else {
6884:     MatDestroyMatrices(n,mat);
6885:   }
6886:   return(0);
6887: }

6889: /*@C
6890:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6892:    Collective on Mat

6894:    Input Parameters:
6895: .  mat - the matrix

6897:    Output Parameter:
6898: .  matstruct - the sequential matrix with the nonzero structure of mat

6900:   Level: intermediate

6902: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6903: @*/
6904: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6905: {


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

6916:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6917:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6918:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6919:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6920:   return(0);
6921: }

6923: /*@C
6924:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6926:    Collective on Mat

6928:    Input Parameters:
6929: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6930:                        sequence of MatGetSequentialNonzeroStructure())

6932:    Level: advanced

6934:     Notes:
6935:     Frees not only the matrices, but also the array that contains the matrices

6937: .seealso: MatGetSeqNonzeroStructure()
6938: @*/
6939: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6940: {

6945:   MatDestroy(mat);
6946:   return(0);
6947: }

6949: /*@
6950:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6951:    replaces the index sets by larger ones that represent submatrices with
6952:    additional overlap.

6954:    Collective on Mat

6956:    Input Parameters:
6957: +  mat - the matrix
6958: .  n   - the number of index sets
6959: .  is  - the array of index sets (these index sets will changed during the call)
6960: -  ov  - the additional overlap requested

6962:    Options Database:
6963: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

6965:    Level: developer


6968: .seealso: MatCreateSubMatrices()
6969: @*/
6970: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6971: {

6977:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6978:   if (n) {
6981:   }
6982:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6983:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6984:   MatCheckPreallocated(mat,1);

6986:   if (!ov) return(0);
6987:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6988:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6989:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
6990:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6991:   return(0);
6992: }


6995: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

6997: /*@
6998:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
6999:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7000:    additional overlap.

7002:    Collective on Mat

7004:    Input Parameters:
7005: +  mat - the matrix
7006: .  n   - the number of index sets
7007: .  is  - the array of index sets (these index sets will changed during the call)
7008: -  ov  - the additional overlap requested

7010:    Options Database:
7011: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7013:    Level: developer


7016: .seealso: MatCreateSubMatrices()
7017: @*/
7018: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7019: {
7020:   PetscInt       i;

7026:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7027:   if (n) {
7030:   }
7031:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7032:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7033:   MatCheckPreallocated(mat,1);
7034:   if (!ov) return(0);
7035:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7036:   for(i=0; i<n; i++){
7037:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7038:   }
7039:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7040:   return(0);
7041: }




7046: /*@
7047:    MatGetBlockSize - Returns the matrix block size.

7049:    Not Collective

7051:    Input Parameter:
7052: .  mat - the matrix

7054:    Output Parameter:
7055: .  bs - block size

7057:    Notes:
7058:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7060:    If the block size has not been set yet this routine returns 1.

7062:    Level: intermediate

7064: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7065: @*/
7066: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7067: {
7071:   *bs = PetscAbs(mat->rmap->bs);
7072:   return(0);
7073: }

7075: /*@
7076:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7078:    Not Collective

7080:    Input Parameter:
7081: .  mat - the matrix

7083:    Output Parameter:
7084: +  rbs - row block size
7085: -  cbs - column block size

7087:    Notes:
7088:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7089:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7091:    If a block size has not been set yet this routine returns 1.

7093:    Level: intermediate

7095: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7096: @*/
7097: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7098: {
7103:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7104:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7105:   return(0);
7106: }

7108: /*@
7109:    MatSetBlockSize - Sets the matrix block size.

7111:    Logically Collective on Mat

7113:    Input Parameters:
7114: +  mat - the matrix
7115: -  bs - block size

7117:    Notes:
7118:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7119:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7121:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7122:     is compatible with the matrix local sizes.

7124:    Level: intermediate

7126: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7127: @*/
7128: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7129: {

7135:   MatSetBlockSizes(mat,bs,bs);
7136:   return(0);
7137: }

7139: /*@
7140:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7142:    Logically Collective on Mat

7144:    Input Parameters:
7145: +  mat - the matrix
7146: .  nblocks - the number of blocks on this process
7147: -  bsizes - the block sizes

7149:    Notes:
7150:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7152:    Level: intermediate

7154: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7155: @*/
7156: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7157: {
7159:   PetscInt       i,ncnt = 0, nlocal;

7163:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7164:   MatGetLocalSize(mat,&nlocal,NULL);
7165:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7166:   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);
7167:   PetscFree(mat->bsizes);
7168:   mat->nblocks = nblocks;
7169:   PetscMalloc1(nblocks,&mat->bsizes);
7170:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7171:   return(0);
7172: }

7174: /*@C
7175:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7177:    Logically Collective on Mat

7179:    Input Parameters:
7180: .  mat - the matrix

7182:    Output Parameters:
7183: +  nblocks - the number of blocks on this process
7184: -  bsizes - the block sizes

7186:    Notes: Currently not supported from Fortran

7188:    Level: intermediate

7190: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7191: @*/
7192: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7193: {
7196:   *nblocks = mat->nblocks;
7197:   *bsizes  = mat->bsizes;
7198:   return(0);
7199: }

7201: /*@
7202:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7204:    Logically Collective on Mat

7206:    Input Parameters:
7207: +  mat - the matrix
7208: .  rbs - row block size
7209: -  cbs - column block size

7211:    Notes:
7212:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7213:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7214:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7216:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7217:     are compatible with the matrix local sizes.

7219:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7221:    Level: intermediate

7223: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7224: @*/
7225: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7226: {

7233:   if (mat->ops->setblocksizes) {
7234:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7235:   }
7236:   if (mat->rmap->refcnt) {
7237:     ISLocalToGlobalMapping l2g = NULL;
7238:     PetscLayout            nmap = NULL;

7240:     PetscLayoutDuplicate(mat->rmap,&nmap);
7241:     if (mat->rmap->mapping) {
7242:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7243:     }
7244:     PetscLayoutDestroy(&mat->rmap);
7245:     mat->rmap = nmap;
7246:     mat->rmap->mapping = l2g;
7247:   }
7248:   if (mat->cmap->refcnt) {
7249:     ISLocalToGlobalMapping l2g = NULL;
7250:     PetscLayout            nmap = NULL;

7252:     PetscLayoutDuplicate(mat->cmap,&nmap);
7253:     if (mat->cmap->mapping) {
7254:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7255:     }
7256:     PetscLayoutDestroy(&mat->cmap);
7257:     mat->cmap = nmap;
7258:     mat->cmap->mapping = l2g;
7259:   }
7260:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7261:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7262:   return(0);
7263: }

7265: /*@
7266:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7268:    Logically Collective on Mat

7270:    Input Parameters:
7271: +  mat - the matrix
7272: .  fromRow - matrix from which to copy row block size
7273: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7275:    Level: developer

7277: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7278: @*/
7279: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7280: {

7287:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7288:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7289:   return(0);
7290: }

7292: /*@
7293:    MatResidual - Default routine to calculate the residual.

7295:    Collective on Mat

7297:    Input Parameters:
7298: +  mat - the matrix
7299: .  b   - the right-hand-side
7300: -  x   - the approximate solution

7302:    Output Parameter:
7303: .  r - location to store the residual

7305:    Level: developer

7307: .seealso: PCMGSetResidual()
7308: @*/
7309: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7310: {

7319:   MatCheckPreallocated(mat,1);
7320:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7321:   if (!mat->ops->residual) {
7322:     MatMult(mat,x,r);
7323:     VecAYPX(r,-1.0,b);
7324:   } else {
7325:     (*mat->ops->residual)(mat,b,x,r);
7326:   }
7327:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7328:   return(0);
7329: }

7331: /*@C
7332:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7334:    Collective on Mat

7336:     Input Parameters:
7337: +   mat - the matrix
7338: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7339: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7340: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7341:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7342:                  always used.

7344:     Output Parameters:
7345: +   n - number of rows in the (possibly compressed) matrix
7346: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7347: .   ja - the column indices
7348: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7349:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7351:     Level: developer

7353:     Notes:
7354:     You CANNOT change any of the ia[] or ja[] values.

7356:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7358:     Fortran Notes:
7359:     In Fortran use
7360: $
7361: $      PetscInt ia(1), ja(1)
7362: $      PetscOffset iia, jja
7363: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7364: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7366:      or
7367: $
7368: $    PetscInt, pointer :: ia(:),ja(:)
7369: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7370: $    ! Access the ith and jth entries via ia(i) and ja(j)

7372: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7373: @*/
7374: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7375: {

7385:   MatCheckPreallocated(mat,1);
7386:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7387:   else {
7388:     *done = PETSC_TRUE;
7389:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7390:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7391:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7392:   }
7393:   return(0);
7394: }

7396: /*@C
7397:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7399:     Collective on Mat

7401:     Input Parameters:
7402: +   mat - the matrix
7403: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7404: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7405:                 symmetrized
7406: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7407:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7408:                  always used.
7409: .   n - number of columns in the (possibly compressed) matrix
7410: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7411: -   ja - the row indices

7413:     Output Parameters:
7414: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7416:     Level: developer

7418: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7419: @*/
7420: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7421: {

7431:   MatCheckPreallocated(mat,1);
7432:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7433:   else {
7434:     *done = PETSC_TRUE;
7435:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7436:   }
7437:   return(0);
7438: }

7440: /*@C
7441:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7442:     MatGetRowIJ().

7444:     Collective on Mat

7446:     Input Parameters:
7447: +   mat - the matrix
7448: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7449: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7450:                 symmetrized
7451: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7452:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7453:                  always used.
7454: .   n - size of (possibly compressed) matrix
7455: .   ia - the row pointers
7456: -   ja - the column indices

7458:     Output Parameters:
7459: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7461:     Note:
7462:     This routine zeros out n, ia, and ja. This is to prevent accidental
7463:     us of the array after it has been restored. If you pass NULL, it will
7464:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7466:     Level: developer

7468: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7469: @*/
7470: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7471: {

7480:   MatCheckPreallocated(mat,1);

7482:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7483:   else {
7484:     *done = PETSC_TRUE;
7485:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7486:     if (n)  *n = 0;
7487:     if (ia) *ia = NULL;
7488:     if (ja) *ja = NULL;
7489:   }
7490:   return(0);
7491: }

7493: /*@C
7494:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7495:     MatGetColumnIJ().

7497:     Collective on Mat

7499:     Input Parameters:
7500: +   mat - the matrix
7501: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7502: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7503:                 symmetrized
7504: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7505:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7506:                  always used.

7508:     Output Parameters:
7509: +   n - size of (possibly compressed) matrix
7510: .   ia - the column pointers
7511: .   ja - the row indices
7512: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7514:     Level: developer

7516: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7517: @*/
7518: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7519: {

7528:   MatCheckPreallocated(mat,1);

7530:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7531:   else {
7532:     *done = PETSC_TRUE;
7533:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7534:     if (n)  *n = 0;
7535:     if (ia) *ia = NULL;
7536:     if (ja) *ja = NULL;
7537:   }
7538:   return(0);
7539: }

7541: /*@C
7542:     MatColoringPatch -Used inside matrix coloring routines that
7543:     use MatGetRowIJ() and/or MatGetColumnIJ().

7545:     Collective on Mat

7547:     Input Parameters:
7548: +   mat - the matrix
7549: .   ncolors - max color value
7550: .   n   - number of entries in colorarray
7551: -   colorarray - array indicating color for each column

7553:     Output Parameters:
7554: .   iscoloring - coloring generated using colorarray information

7556:     Level: developer

7558: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7560: @*/
7561: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7562: {

7570:   MatCheckPreallocated(mat,1);

7572:   if (!mat->ops->coloringpatch) {
7573:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7574:   } else {
7575:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7576:   }
7577:   return(0);
7578: }


7581: /*@
7582:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7584:    Logically Collective on Mat

7586:    Input Parameter:
7587: .  mat - the factored matrix to be reset

7589:    Notes:
7590:    This routine should be used only with factored matrices formed by in-place
7591:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7592:    format).  This option can save memory, for example, when solving nonlinear
7593:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7594:    ILU(0) preconditioner.

7596:    Note that one can specify in-place ILU(0) factorization by calling
7597: .vb
7598:      PCType(pc,PCILU);
7599:      PCFactorSeUseInPlace(pc);
7600: .ve
7601:    or by using the options -pc_type ilu -pc_factor_in_place

7603:    In-place factorization ILU(0) can also be used as a local
7604:    solver for the blocks within the block Jacobi or additive Schwarz
7605:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7606:    for details on setting local solver options.

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

7612:    Level: developer

7614: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7616: @*/
7617: PetscErrorCode MatSetUnfactored(Mat mat)
7618: {

7624:   MatCheckPreallocated(mat,1);
7625:   mat->factortype = MAT_FACTOR_NONE;
7626:   if (!mat->ops->setunfactored) return(0);
7627:   (*mat->ops->setunfactored)(mat);
7628:   return(0);
7629: }

7631: /*MC
7632:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7634:     Synopsis:
7635:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7637:     Not collective

7639:     Input Parameter:
7640: .   x - matrix

7642:     Output Parameters:
7643: +   xx_v - the Fortran90 pointer to the array
7644: -   ierr - error code

7646:     Example of Usage:
7647: .vb
7648:       PetscScalar, pointer xx_v(:,:)
7649:       ....
7650:       call MatDenseGetArrayF90(x,xx_v,ierr)
7651:       a = xx_v(3)
7652:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7653: .ve

7655:     Level: advanced

7657: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7659: M*/

7661: /*MC
7662:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7663:     accessed with MatDenseGetArrayF90().

7665:     Synopsis:
7666:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7668:     Not collective

7670:     Input Parameters:
7671: +   x - matrix
7672: -   xx_v - the Fortran90 pointer to the array

7674:     Output Parameter:
7675: .   ierr - error code

7677:     Example of Usage:
7678: .vb
7679:        PetscScalar, pointer xx_v(:,:)
7680:        ....
7681:        call MatDenseGetArrayF90(x,xx_v,ierr)
7682:        a = xx_v(3)
7683:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7684: .ve

7686:     Level: advanced

7688: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7690: M*/


7693: /*MC
7694:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7696:     Synopsis:
7697:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7699:     Not collective

7701:     Input Parameter:
7702: .   x - matrix

7704:     Output Parameters:
7705: +   xx_v - the Fortran90 pointer to the array
7706: -   ierr - error code

7708:     Example of Usage:
7709: .vb
7710:       PetscScalar, pointer xx_v(:)
7711:       ....
7712:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7713:       a = xx_v(3)
7714:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7715: .ve

7717:     Level: advanced

7719: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7721: M*/

7723: /*MC
7724:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7725:     accessed with MatSeqAIJGetArrayF90().

7727:     Synopsis:
7728:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7730:     Not collective

7732:     Input Parameters:
7733: +   x - matrix
7734: -   xx_v - the Fortran90 pointer to the array

7736:     Output Parameter:
7737: .   ierr - error code

7739:     Example of Usage:
7740: .vb
7741:        PetscScalar, pointer xx_v(:)
7742:        ....
7743:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7744:        a = xx_v(3)
7745:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7746: .ve

7748:     Level: advanced

7750: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7752: M*/


7755: /*@
7756:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7757:                       as the original matrix.

7759:     Collective on Mat

7761:     Input Parameters:
7762: +   mat - the original matrix
7763: .   isrow - parallel IS containing the rows this processor should obtain
7764: .   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.
7765: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7767:     Output Parameter:
7768: .   newmat - the new submatrix, of the same type as the old

7770:     Level: advanced

7772:     Notes:
7773:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7775:     Some matrix types place restrictions on the row and column indices, such
7776:     as that they be sorted or that they be equal to each other.

7778:     The index sets may not have duplicate entries.

7780:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7781:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7782:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7783:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7784:    you are finished using it.

7786:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7787:     the input matrix.

7789:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7791:    Example usage:
7792:    Consider the following 8x8 matrix with 34 non-zero values, that is
7793:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7794:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7795:    as follows:

7797: .vb
7798:             1  2  0  |  0  3  0  |  0  4
7799:     Proc0   0  5  6  |  7  0  0  |  8  0
7800:             9  0 10  | 11  0  0  | 12  0
7801:     -------------------------------------
7802:            13  0 14  | 15 16 17  |  0  0
7803:     Proc1   0 18  0  | 19 20 21  |  0  0
7804:             0  0  0  | 22 23  0  | 24  0
7805:     -------------------------------------
7806:     Proc2  25 26 27  |  0  0 28  | 29  0
7807:            30  0  0  | 31 32 33  |  0 34
7808: .ve

7810:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7812: .vb
7813:             2  0  |  0  3  0  |  0
7814:     Proc0   5  6  |  7  0  0  |  8
7815:     -------------------------------
7816:     Proc1  18  0  | 19 20 21  |  0
7817:     -------------------------------
7818:     Proc2  26 27  |  0  0 28  | 29
7819:             0  0  | 31 32 33  |  0
7820: .ve


7823: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7824: @*/
7825: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7826: {
7828:   PetscMPIInt    size;
7829:   Mat            *local;
7830:   IS             iscoltmp;
7831:   PetscBool      flg;

7840:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7841:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7843:   MatCheckPreallocated(mat,1);
7844:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7846:   if (!iscol || isrow == iscol) {
7847:     PetscBool   stride;
7848:     PetscMPIInt grabentirematrix = 0,grab;
7849:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7850:     if (stride) {
7851:       PetscInt first,step,n,rstart,rend;
7852:       ISStrideGetInfo(isrow,&first,&step);
7853:       if (step == 1) {
7854:         MatGetOwnershipRange(mat,&rstart,&rend);
7855:         if (rstart == first) {
7856:           ISGetLocalSize(isrow,&n);
7857:           if (n == rend-rstart) {
7858:             grabentirematrix = 1;
7859:           }
7860:         }
7861:       }
7862:     }
7863:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7864:     if (grab) {
7865:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7866:       if (cll == MAT_INITIAL_MATRIX) {
7867:         *newmat = mat;
7868:         PetscObjectReference((PetscObject)mat);
7869:       }
7870:       return(0);
7871:     }
7872:   }

7874:   if (!iscol) {
7875:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7876:   } else {
7877:     iscoltmp = iscol;
7878:   }

7880:   /* if original matrix is on just one processor then use submatrix generated */
7881:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7882:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7883:     goto setproperties;
7884:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7885:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7886:     *newmat = *local;
7887:     PetscFree(local);
7888:     goto setproperties;
7889:   } else if (!mat->ops->createsubmatrix) {
7890:     /* Create a new matrix type that implements the operation using the full matrix */
7891:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7892:     switch (cll) {
7893:     case MAT_INITIAL_MATRIX:
7894:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7895:       break;
7896:     case MAT_REUSE_MATRIX:
7897:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7898:       break;
7899:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7900:     }
7901:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7902:     goto setproperties;
7903:   }

7905:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7906:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7907:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7908:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

7910: setproperties:
7911:   ISEqualUnsorted(isrow,iscoltmp,&flg);
7912:   if (flg) {
7913:     MatPropagateSymmetryOptions(mat,*newmat);
7914:   }
7915:   if (!iscol) {ISDestroy(&iscoltmp);}
7916:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7917:   return(0);
7918: }

7920: /*@
7921:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

7923:    Not Collective

7925:    Input Parameters:
7926: +  A - the matrix we wish to propagate options from
7927: -  B - the matrix we wish to propagate options to

7929:    Level: beginner

7931:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

7933: .seealso: MatSetOption()
7934: @*/
7935: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7936: {

7942:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7943:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
7944:   }
7945:   if (A->structurally_symmetric_set) {
7946:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
7947:   }
7948:   if (A->hermitian_set) {
7949:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
7950:   }
7951:   if (A->spd_set) {
7952:     MatSetOption(B,MAT_SPD,A->spd);
7953:   }
7954:   if (A->symmetric_set) {
7955:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
7956:   }
7957:   return(0);
7958: }

7960: /*@
7961:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7962:    used during the assembly process to store values that belong to
7963:    other processors.

7965:    Not Collective

7967:    Input Parameters:
7968: +  mat   - the matrix
7969: .  size  - the initial size of the stash.
7970: -  bsize - the initial size of the block-stash(if used).

7972:    Options Database Keys:
7973: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7974: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7976:    Level: intermediate

7978:    Notes:
7979:      The block-stash is used for values set with MatSetValuesBlocked() while
7980:      the stash is used for values set with MatSetValues()

7982:      Run with the option -info and look for output of the form
7983:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7984:      to determine the appropriate value, MM, to use for size and
7985:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7986:      to determine the value, BMM to use for bsize


7989: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

7991: @*/
7992: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7993: {

7999:   MatStashSetInitialSize_Private(&mat->stash,size);
8000:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8001:   return(0);
8002: }

8004: /*@
8005:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8006:      the matrix

8008:    Neighbor-wise Collective on Mat

8010:    Input Parameters:
8011: +  mat   - the matrix
8012: .  x,y - the vectors
8013: -  w - where the result is stored

8015:    Level: intermediate

8017:    Notes:
8018:     w may be the same vector as y.

8020:     This allows one to use either the restriction or interpolation (its transpose)
8021:     matrix to do the interpolation

8023: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8025: @*/
8026: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8027: {
8029:   PetscInt       M,N,Ny;

8037:   MatCheckPreallocated(A,1);
8038:   MatGetSize(A,&M,&N);
8039:   VecGetSize(y,&Ny);
8040:   if (M == Ny) {
8041:     MatMultAdd(A,x,y,w);
8042:   } else {
8043:     MatMultTransposeAdd(A,x,y,w);
8044:   }
8045:   return(0);
8046: }

8048: /*@
8049:    MatInterpolate - 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

8058:    Level: intermediate

8060:    Notes:
8061:     This allows one to use either the restriction or interpolation (its transpose)
8062:     matrix to do the interpolation

8064: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8066: @*/
8067: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8068: {
8070:   PetscInt       M,N,Ny;

8077:   MatCheckPreallocated(A,1);
8078:   MatGetSize(A,&M,&N);
8079:   VecGetSize(y,&Ny);
8080:   if (M == Ny) {
8081:     MatMult(A,x,y);
8082:   } else {
8083:     MatMultTranspose(A,x,y);
8084:   }
8085:   return(0);
8086: }

8088: /*@
8089:    MatRestrict - y = A*x or A'*x

8091:    Neighbor-wise Collective on Mat

8093:    Input Parameters:
8094: +  mat   - the matrix
8095: -  x,y - the vectors

8097:    Level: intermediate

8099:    Notes:
8100:     This allows one to use either the restriction or interpolation (its transpose)
8101:     matrix to do the restriction

8103: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8105: @*/
8106: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8107: {
8109:   PetscInt       M,N,Ny;

8116:   MatCheckPreallocated(A,1);

8118:   MatGetSize(A,&M,&N);
8119:   VecGetSize(y,&Ny);
8120:   if (M == Ny) {
8121:     MatMult(A,x,y);
8122:   } else {
8123:     MatMultTranspose(A,x,y);
8124:   }
8125:   return(0);
8126: }

8128: /*@
8129:    MatGetNullSpace - retrieves the null space of a matrix.

8131:    Logically Collective on Mat

8133:    Input Parameters:
8134: +  mat - the matrix
8135: -  nullsp - the null space object

8137:    Level: developer

8139: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8140: @*/
8141: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8142: {
8146:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8147:   return(0);
8148: }

8150: /*@
8151:    MatSetNullSpace - attaches a null space to a matrix.

8153:    Logically Collective on Mat

8155:    Input Parameters:
8156: +  mat - the matrix
8157: -  nullsp - the null space object

8159:    Level: advanced

8161:    Notes:
8162:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8164:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8165:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8167:       You can remove the null space by calling this routine with an nullsp of NULL


8170:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8171:    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).
8172:    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
8173:    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
8174:    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).

8176:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8178:     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
8179:     routine also automatically calls MatSetTransposeNullSpace().

8181: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8182: @*/
8183: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8184: {

8190:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8191:   MatNullSpaceDestroy(&mat->nullsp);
8192:   mat->nullsp = nullsp;
8193:   if (mat->symmetric_set && mat->symmetric) {
8194:     MatSetTransposeNullSpace(mat,nullsp);
8195:   }
8196:   return(0);
8197: }

8199: /*@
8200:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8202:    Logically Collective on Mat

8204:    Input Parameters:
8205: +  mat - the matrix
8206: -  nullsp - the null space object

8208:    Level: developer

8210: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8211: @*/
8212: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8213: {
8218:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8219:   return(0);
8220: }

8222: /*@
8223:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8225:    Logically Collective on Mat

8227:    Input Parameters:
8228: +  mat - the matrix
8229: -  nullsp - the null space object

8231:    Level: advanced

8233:    Notes:
8234:       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.
8235:       You must also call MatSetNullSpace()


8238:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8239:    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).
8240:    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
8241:    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
8242:    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).

8244:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8246: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8247: @*/
8248: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8249: {

8255:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8256:   MatNullSpaceDestroy(&mat->transnullsp);
8257:   mat->transnullsp = nullsp;
8258:   return(0);
8259: }

8261: /*@
8262:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8263:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8265:    Logically Collective on Mat

8267:    Input Parameters:
8268: +  mat - the matrix
8269: -  nullsp - the null space object

8271:    Level: advanced

8273:    Notes:
8274:       Overwrites any previous near null space that may have been attached

8276:       You can remove the null space by calling this routine with an nullsp of NULL

8278: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8279: @*/
8280: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8281: {

8288:   MatCheckPreallocated(mat,1);
8289:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8290:   MatNullSpaceDestroy(&mat->nearnullsp);
8291:   mat->nearnullsp = nullsp;
8292:   return(0);
8293: }

8295: /*@
8296:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8298:    Not Collective

8300:    Input Parameter:
8301: .  mat - the matrix

8303:    Output Parameter:
8304: .  nullsp - the null space object, NULL if not set

8306:    Level: developer

8308: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8309: @*/
8310: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8311: {
8316:   MatCheckPreallocated(mat,1);
8317:   *nullsp = mat->nearnullsp;
8318:   return(0);
8319: }

8321: /*@C
8322:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8324:    Collective on Mat

8326:    Input Parameters:
8327: +  mat - the matrix
8328: .  row - row/column permutation
8329: .  fill - expected fill factor >= 1.0
8330: -  level - level of fill, for ICC(k)

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

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

8340:    Level: developer


8343: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8348: @*/
8349: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8350: {

8358:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8359:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8360:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8361:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8362:   MatCheckPreallocated(mat,1);
8363:   (*mat->ops->iccfactor)(mat,row,info);
8364:   PetscObjectStateIncrease((PetscObject)mat);
8365:   return(0);
8366: }

8368: /*@
8369:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8370:          ghosted ones.

8372:    Not Collective

8374:    Input Parameters:
8375: +  mat - the matrix
8376: -  diag = the diagonal values, including ghost ones

8378:    Level: developer

8380:    Notes:
8381:     Works only for MPIAIJ and MPIBAIJ matrices

8383: .seealso: MatDiagonalScale()
8384: @*/
8385: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8386: {
8388:   PetscMPIInt    size;


8395:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8396:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8397:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8398:   if (size == 1) {
8399:     PetscInt n,m;
8400:     VecGetSize(diag,&n);
8401:     MatGetSize(mat,0,&m);
8402:     if (m == n) {
8403:       MatDiagonalScale(mat,0,diag);
8404:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8405:   } else {
8406:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8407:   }
8408:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8409:   PetscObjectStateIncrease((PetscObject)mat);
8410:   return(0);
8411: }

8413: /*@
8414:    MatGetInertia - Gets the inertia from a factored matrix

8416:    Collective on Mat

8418:    Input Parameter:
8419: .  mat - the matrix

8421:    Output Parameters:
8422: +   nneg - number of negative eigenvalues
8423: .   nzero - number of zero eigenvalues
8424: -   npos - number of positive eigenvalues

8426:    Level: advanced

8428:    Notes:
8429:     Matrix must have been factored by MatCholeskyFactor()


8432: @*/
8433: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8434: {

8440:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8441:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8442:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8443:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8444:   return(0);
8445: }

8447: /* ----------------------------------------------------------------*/
8448: /*@C
8449:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8451:    Neighbor-wise Collective on Mats

8453:    Input Parameters:
8454: +  mat - the factored matrix
8455: -  b - the right-hand-side vectors

8457:    Output Parameter:
8458: .  x - the result vectors

8460:    Notes:
8461:    The vectors b and x cannot be the same.  I.e., one cannot
8462:    call MatSolves(A,x,x).

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

8469:    Level: developer

8471: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8472: @*/
8473: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8474: {

8480:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8481:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8482:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8484:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8485:   MatCheckPreallocated(mat,1);
8486:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8487:   (*mat->ops->solves)(mat,b,x);
8488:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8489:   return(0);
8490: }

8492: /*@
8493:    MatIsSymmetric - Test whether a matrix is symmetric

8495:    Collective on Mat

8497:    Input Parameter:
8498: +  A - the matrix to test
8499: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8501:    Output Parameters:
8502: .  flg - the result

8504:    Notes:
8505:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8507:    Level: intermediate

8509: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8510: @*/
8511: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8512: {


8519:   if (!A->symmetric_set) {
8520:     if (!A->ops->issymmetric) {
8521:       MatType mattype;
8522:       MatGetType(A,&mattype);
8523:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8524:     }
8525:     (*A->ops->issymmetric)(A,tol,flg);
8526:     if (!tol) {
8527:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8528:     }
8529:   } else if (A->symmetric) {
8530:     *flg = PETSC_TRUE;
8531:   } else if (!tol) {
8532:     *flg = PETSC_FALSE;
8533:   } else {
8534:     if (!A->ops->issymmetric) {
8535:       MatType mattype;
8536:       MatGetType(A,&mattype);
8537:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8538:     }
8539:     (*A->ops->issymmetric)(A,tol,flg);
8540:   }
8541:   return(0);
8542: }

8544: /*@
8545:    MatIsHermitian - Test whether a matrix is Hermitian

8547:    Collective on Mat

8549:    Input Parameter:
8550: +  A - the matrix to test
8551: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8553:    Output Parameters:
8554: .  flg - the result

8556:    Level: intermediate

8558: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8559:           MatIsSymmetricKnown(), MatIsSymmetric()
8560: @*/
8561: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8562: {


8569:   if (!A->hermitian_set) {
8570:     if (!A->ops->ishermitian) {
8571:       MatType mattype;
8572:       MatGetType(A,&mattype);
8573:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8574:     }
8575:     (*A->ops->ishermitian)(A,tol,flg);
8576:     if (!tol) {
8577:       MatSetOption(A,MAT_HERMITIAN,*flg);
8578:     }
8579:   } else if (A->hermitian) {
8580:     *flg = PETSC_TRUE;
8581:   } else if (!tol) {
8582:     *flg = PETSC_FALSE;
8583:   } else {
8584:     if (!A->ops->ishermitian) {
8585:       MatType mattype;
8586:       MatGetType(A,&mattype);
8587:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8588:     }
8589:     (*A->ops->ishermitian)(A,tol,flg);
8590:   }
8591:   return(0);
8592: }

8594: /*@
8595:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8597:    Not Collective

8599:    Input Parameter:
8600: .  A - the matrix to check

8602:    Output Parameters:
8603: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8604: -  flg - the result

8606:    Level: advanced

8608:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8609:          if you want it explicitly checked

8611: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8612: @*/
8613: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8614: {
8619:   if (A->symmetric_set) {
8620:     *set = PETSC_TRUE;
8621:     *flg = A->symmetric;
8622:   } else {
8623:     *set = PETSC_FALSE;
8624:   }
8625:   return(0);
8626: }

8628: /*@
8629:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8631:    Not Collective

8633:    Input Parameter:
8634: .  A - the matrix to check

8636:    Output Parameters:
8637: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8638: -  flg - the result

8640:    Level: advanced

8642:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8643:          if you want it explicitly checked

8645: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8646: @*/
8647: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8648: {
8653:   if (A->hermitian_set) {
8654:     *set = PETSC_TRUE;
8655:     *flg = A->hermitian;
8656:   } else {
8657:     *set = PETSC_FALSE;
8658:   }
8659:   return(0);
8660: }

8662: /*@
8663:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8665:    Collective on Mat

8667:    Input Parameter:
8668: .  A - the matrix to test

8670:    Output Parameters:
8671: .  flg - the result

8673:    Level: intermediate

8675: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8676: @*/
8677: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8678: {

8684:   if (!A->structurally_symmetric_set) {
8685:     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);
8686:     (*A->ops->isstructurallysymmetric)(A,flg);
8687:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8688:   } else *flg = A->structurally_symmetric;
8689:   return(0);
8690: }

8692: /*@
8693:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8694:        to be communicated to other processors during the MatAssemblyBegin/End() process

8696:     Not collective

8698:    Input Parameter:
8699: .   vec - the vector

8701:    Output Parameters:
8702: +   nstash   - the size of the stash
8703: .   reallocs - the number of additional mallocs incurred.
8704: .   bnstash   - the size of the block stash
8705: -   breallocs - the number of additional mallocs incurred.in the block stash

8707:    Level: advanced

8709: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8711: @*/
8712: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8713: {

8717:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8718:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8719:   return(0);
8720: }

8722: /*@C
8723:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8724:      parallel layout

8726:    Collective on Mat

8728:    Input Parameter:
8729: .  mat - the matrix

8731:    Output Parameter:
8732: +   right - (optional) vector that the matrix can be multiplied against
8733: -   left - (optional) vector that the matrix vector product can be stored in

8735:    Notes:
8736:     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().

8738:   Notes:
8739:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8741:   Level: advanced

8743: .seealso: MatCreate(), VecDestroy()
8744: @*/
8745: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8746: {

8752:   if (mat->ops->getvecs) {
8753:     (*mat->ops->getvecs)(mat,right,left);
8754:   } else {
8755:     PetscInt rbs,cbs;
8756:     MatGetBlockSizes(mat,&rbs,&cbs);
8757:     if (right) {
8758:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8759:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8760:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8761:       VecSetBlockSize(*right,cbs);
8762:       VecSetType(*right,mat->defaultvectype);
8763:       PetscLayoutReference(mat->cmap,&(*right)->map);
8764:     }
8765:     if (left) {
8766:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8767:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8768:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8769:       VecSetBlockSize(*left,rbs);
8770:       VecSetType(*left,mat->defaultvectype);
8771:       PetscLayoutReference(mat->rmap,&(*left)->map);
8772:     }
8773:   }
8774:   return(0);
8775: }

8777: /*@C
8778:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8779:      with default values.

8781:    Not Collective

8783:    Input Parameters:
8784: .    info - the MatFactorInfo data structure


8787:    Notes:
8788:     The solvers are generally used through the KSP and PC objects, for example
8789:           PCLU, PCILU, PCCHOLESKY, PCICC

8791:    Level: developer

8793: .seealso: MatFactorInfo

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

8798: @*/

8800: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8801: {

8805:   PetscMemzero(info,sizeof(MatFactorInfo));
8806:   return(0);
8807: }

8809: /*@
8810:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8812:    Collective on Mat

8814:    Input Parameters:
8815: +  mat - the factored matrix
8816: -  is - the index set defining the Schur indices (0-based)

8818:    Notes:
8819:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8821:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8823:    Level: developer

8825: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8826:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8828: @*/
8829: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8830: {
8831:   PetscErrorCode ierr,(*f)(Mat,IS);

8839:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8840:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8841:   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");
8842:   MatDestroy(&mat->schur);
8843:   (*f)(mat,is);
8844:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8845:   return(0);
8846: }

8848: /*@
8849:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8851:    Logically Collective on Mat

8853:    Input Parameters:
8854: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8855: .  S - location where to return the Schur complement, can be NULL
8856: -  status - the status of the Schur complement matrix, can be NULL

8858:    Notes:
8859:    You must call MatFactorSetSchurIS() before calling this routine.

8861:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8862:    The caller must destroy the object when it is no longer needed.
8863:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8865:    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)

8867:    Developer Notes:
8868:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8869:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8871:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8873:    Level: advanced

8875:    References:

8877: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8878: @*/
8879: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8880: {

8887:   if (S) {
8888:     PetscErrorCode (*f)(Mat,Mat*);

8890:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8891:     if (f) {
8892:       (*f)(F,S);
8893:     } else {
8894:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8895:     }
8896:   }
8897:   if (status) *status = F->schur_status;
8898:   return(0);
8899: }

8901: /*@
8902:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

8904:    Logically Collective on Mat

8906:    Input Parameters:
8907: +  F - the factored matrix obtained by calling MatGetFactor()
8908: .  *S - location where to return the Schur complement, can be NULL
8909: -  status - the status of the Schur complement matrix, can be NULL

8911:    Notes:
8912:    You must call MatFactorSetSchurIS() before calling this routine.

8914:    Schur complement mode is currently implemented for sequential matrices.
8915:    The routine returns a the Schur Complement stored within the data strutures of the solver.
8916:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8917:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

8919:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

8921:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8923:    Level: advanced

8925:    References:

8927: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8928: @*/
8929: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8930: {
8935:   if (S) *S = F->schur;
8936:   if (status) *status = F->schur_status;
8937:   return(0);
8938: }

8940: /*@
8941:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

8943:    Logically Collective on Mat

8945:    Input Parameters:
8946: +  F - the factored matrix obtained by calling MatGetFactor()
8947: .  *S - location where the Schur complement is stored
8948: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

8950:    Notes:

8952:    Level: advanced

8954:    References:

8956: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8957: @*/
8958: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8959: {

8964:   if (S) {
8966:     *S = NULL;
8967:   }
8968:   F->schur_status = status;
8969:   MatFactorUpdateSchurStatus_Private(F);
8970:   return(0);
8971: }

8973: /*@
8974:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

8976:    Logically Collective on Mat

8978:    Input Parameters:
8979: +  F - the factored matrix obtained by calling MatGetFactor()
8980: .  rhs - location where the right hand side of the Schur complement system is stored
8981: -  sol - location where the solution of the Schur complement system has to be returned

8983:    Notes:
8984:    The sizes of the vectors should match the size of the Schur complement

8986:    Must be called after MatFactorSetSchurIS()

8988:    Level: advanced

8990:    References:

8992: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
8993: @*/
8994: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
8995: {

9007:   MatFactorFactorizeSchurComplement(F);
9008:   switch (F->schur_status) {
9009:   case MAT_FACTOR_SCHUR_FACTORED:
9010:     MatSolveTranspose(F->schur,rhs,sol);
9011:     break;
9012:   case MAT_FACTOR_SCHUR_INVERTED:
9013:     MatMultTranspose(F->schur,rhs,sol);
9014:     break;
9015:   default:
9016:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9017:     break;
9018:   }
9019:   return(0);
9020: }

9022: /*@
9023:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9025:    Logically Collective on Mat

9027:    Input Parameters:
9028: +  F - the factored matrix obtained by calling MatGetFactor()
9029: .  rhs - location where the right hand side of the Schur complement system is stored
9030: -  sol - location where the solution of the Schur complement system has to be returned

9032:    Notes:
9033:    The sizes of the vectors should match the size of the Schur complement

9035:    Must be called after MatFactorSetSchurIS()

9037:    Level: advanced

9039:    References:

9041: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9042: @*/
9043: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9044: {

9056:   MatFactorFactorizeSchurComplement(F);
9057:   switch (F->schur_status) {
9058:   case MAT_FACTOR_SCHUR_FACTORED:
9059:     MatSolve(F->schur,rhs,sol);
9060:     break;
9061:   case MAT_FACTOR_SCHUR_INVERTED:
9062:     MatMult(F->schur,rhs,sol);
9063:     break;
9064:   default:
9065:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9066:     break;
9067:   }
9068:   return(0);
9069: }

9071: /*@
9072:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9074:    Logically Collective on Mat

9076:    Input Parameters:
9077: .  F - the factored matrix obtained by calling MatGetFactor()

9079:    Notes:
9080:     Must be called after MatFactorSetSchurIS().

9082:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9084:    Level: advanced

9086:    References:

9088: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9089: @*/
9090: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9091: {

9097:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9098:   MatFactorFactorizeSchurComplement(F);
9099:   MatFactorInvertSchurComplement_Private(F);
9100:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9101:   return(0);
9102: }

9104: /*@
9105:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9107:    Logically Collective on Mat

9109:    Input Parameters:
9110: .  F - the factored matrix obtained by calling MatGetFactor()

9112:    Notes:
9113:     Must be called after MatFactorSetSchurIS().

9115:    Level: advanced

9117:    References:

9119: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9120: @*/
9121: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9122: {

9128:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9129:   MatFactorFactorizeSchurComplement_Private(F);
9130:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9131:   return(0);
9132: }

9134: /*@
9135:    MatPtAP - Creates the matrix product C = P^T * A * P

9137:    Neighbor-wise Collective on Mat

9139:    Input Parameters:
9140: +  A - the matrix
9141: .  P - the projection matrix
9142: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9143: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9144:           if the result is a dense matrix this is irrelevent

9146:    Output Parameters:
9147: .  C - the product matrix

9149:    Notes:
9150:    C will be created and must be destroyed by the user with MatDestroy().

9152:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9154:    Level: intermediate

9156: .seealso: MatMatMult(), MatRARt()
9157: @*/
9158: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9159: {

9163:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9165:   if (scall == MAT_INITIAL_MATRIX) {
9166:     MatProductCreate(A,P,NULL,C);
9167:     MatProductSetType(*C,MATPRODUCT_PtAP);
9168:     MatProductSetAlgorithm(*C,"default");
9169:     MatProductSetFill(*C,fill);

9171:     (*C)->product->api_user = PETSC_TRUE;
9172:     MatProductSetFromOptions(*C);
9173:     MatProductSymbolic(*C);
9174:   } else {
9175:     Mat_Product *product = (*C)->product;
9176:     if (product) { /* user may chage input matrices A or B when REUSE */
9177:       MatProductReplaceMats(A,P,NULL,*C);
9178:     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9179:   }

9181:   MatProductNumeric(*C);
9182:   if (A->symmetric_set && A->symmetric) {
9183:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9184:   }
9185:   return(0);
9186: }

9188: /*@
9189:    MatRARt - Creates the matrix product C = R * A * R^T

9191:    Neighbor-wise Collective on Mat

9193:    Input Parameters:
9194: +  A - the matrix
9195: .  R - the projection matrix
9196: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9197: -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9198:           if the result is a dense matrix this is irrelevent

9200:    Output Parameters:
9201: .  C - the product matrix

9203:    Notes:
9204:    C will be created and must be destroyed by the user with MatDestroy().

9206:    This routine is currently only implemented for pairs of AIJ matrices and classes
9207:    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9208:    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9209:    We recommend using MatPtAP().

9211:    Level: intermediate

9213: .seealso: MatMatMult(), MatPtAP()
9214: @*/
9215: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9216: {

9220:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9222:   if (scall == MAT_INITIAL_MATRIX) {
9223:     MatProductCreate(A,R,NULL,C);
9224:     MatProductSetType(*C,MATPRODUCT_RARt);
9225:     MatProductSetAlgorithm(*C,"default");
9226:     MatProductSetFill(*C,fill);

9228:     (*C)->product->api_user = PETSC_TRUE;
9229:     MatProductSetFromOptions(*C);
9230:     MatProductSymbolic(*C);
9231:   } else { /* scall == MAT_REUSE_MATRIX */
9232:     Mat_Product *product = (*C)->product;
9233:     if (product) {
9234:       /* user may chage input matrices A or R when REUSE */
9235:       MatProductReplaceMats(A,R,NULL,*C);
9236:     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9237:   }

9239:   MatProductNumeric(*C);
9240:   return(0);
9241: }


9244: static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
9245: {
9246:   PetscBool      clearproduct = PETSC_FALSE;

9250:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9252:   if (scall == MAT_INITIAL_MATRIX) {
9253:     MatProductCreate(A,B,NULL,C);
9254:     MatProductSetType(*C,ptype);
9255:     MatProductSetAlgorithm(*C,"default");
9256:     MatProductSetFill(*C,fill);

9258:     (*C)->product->api_user = PETSC_TRUE;
9259:     MatProductSetFromOptions(*C);
9260:     MatProductSymbolic(*C);
9261:   } else { /* scall == MAT_REUSE_MATRIX */
9262:     Mat_Product *product = (*C)->product;
9263:     if (!product) {
9264:       /* user provide the dense matrix *C without calling MatProductCreate() */
9265:       PetscBool seqdense,mpidense,dense;
9266: #if defined(PETSC_HAVE_CUDA)
9267:       PetscBool seqdensecuda;
9268: #endif
9269:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
9270:       PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
9271:       PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
9272: #if defined(PETSC_HAVE_CUDA)
9273:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSECUDA,&seqdensecuda);
9274:       if (seqdense || mpidense || dense || seqdensecuda) {
9275: #else
9276:       if (seqdense || mpidense || dense) {
9277: #endif
9278:         /* user wants to reuse an assembled dense matrix */
9279:         /* Create product -- see MatCreateProduct() */
9280:         MatProductCreate_Private(A,B,NULL,*C);
9281:         product = (*C)->product;
9282:         product->fill     = fill;
9283:         product->api_user = PETSC_TRUE;

9285:         MatProductSetType(*C,ptype);
9286:         MatProductSetFromOptions(*C);
9287:         MatProductSymbolic(*C);
9288:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9289:       clearproduct = PETSC_TRUE;
9290:     } else { /* user may chage input matrices A or B when REUSE */
9291:       MatProductReplaceMats(A,B,NULL,*C);
9292:     }
9293:   }
9294:   MatProductNumeric(*C);
9295:   if (clearproduct) {
9296:     MatProductClear(*C);
9297:   }
9298:   return(0);
9299: }

9301: /*@
9302:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

9304:    Neighbor-wise Collective on Mat

9306:    Input Parameters:
9307: +  A - the left matrix
9308: .  B - the right matrix
9309: .  scall - either MAT_INITIAL_MATRIX or