Actual source code: matrix.c

petsc-master 2019-10-23
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 SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Not coded for this matrix type");
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: {

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

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

495:    Not Collective

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

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

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

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

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

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

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

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


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

545:    Level: advanced

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

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

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

571:    Logically Collective on Mat

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

576:    Level: advanced

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

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

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

599:    Not Collective

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

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

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

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

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

629:    Level: advanced

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

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

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

653:    Not Collective

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

658:    Notes:
659:    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.

661:    Level: advanced

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

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

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

683:    Not Collective

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

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


692:    Level: advanced

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

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

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

715:    Logically Collective on Mat

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

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

725:    Level: advanced

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

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

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

743:    Logically Collective on Mat

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

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

753:    Level: advanced

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

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

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

771:    Not Collective

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

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

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

783:    Level: advanced

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

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

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

800:    Collective on Mat

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

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

809:    Level: beginner

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

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


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

828:    Collective on Mat

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

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

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

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

840:    Level: beginner

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

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

869: #if defined(PETSC_HAVE_SAWS)
870:  #include <petscviewersaws.h>
871: #endif
872: /*@C
873:    MatView - Visualizes a matrix object.

875:    Collective on Mat

877:    Input Parameters:
878: +  mat - the matrix
879: -  viewer - visualization context

881:   Notes:
882:   The available visualization contexts include
883: +    PETSC_VIEWER_STDOUT_SELF - for sequential matrices
884: .    PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
885: .    PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
886: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

888:    The user can open alternative visualization contexts with
889: +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
890: .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
891:          specified file; corresponding input uses MatLoad()
892: .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
893:          an X window display
894: -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
895:          Currently only the sequential dense and AIJ
896:          matrix types support the Socket viewer.

898:    The user can call PetscViewerPushFormat() to specify the output
899:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
900:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
901: +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
902: .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
903: .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
904: .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
905:          format common among all matrix types
906: .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
907:          format (which is in many cases the same as the default)
908: .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
909:          size and structure (not the matrix entries)
910: -    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
911:          the matrix structure

913:    Options Database Keys:
914: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
915: .  -mat_view ::ascii_info_detail - Prints more detailed info
916: .  -mat_view - Prints matrix in ASCII format
917: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
918: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
919: .  -display <name> - Sets display name (default is host)
920: .  -draw_pause <sec> - Sets number of seconds to pause after display
921: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 12 Using MATLAB with PETSc for details)
922: .  -viewer_socket_machine <machine> -
923: .  -viewer_socket_port <port> -
924: .  -mat_view binary - save matrix to file in binary format
925: -  -viewer_binary_filename <name> -
926:    Level: beginner

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

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

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

938:       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
939:       and then use the following mouse functions.
940: + left mouse: zoom in
941: . middle mouse: zoom out
942: - right mouse: continue with the simulation

944: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
945:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
946: @*/
947: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
948: {
949:   PetscErrorCode    ierr;
950:   PetscInt          rows,cols,rbs,cbs;
951:   PetscBool         iascii,ibinary,isstring;
952:   PetscViewerFormat format;
953:   PetscMPIInt       size;
954: #if defined(PETSC_HAVE_SAWS)
955:   PetscBool         issaws;
956: #endif

961:   if (!viewer) {
962:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
963:   }
966:   MatCheckPreallocated(mat,1);
967:   PetscViewerGetFormat(viewer,&format);
968:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
969:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
970:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
971:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
972:   if (ibinary) {
973:     PetscBool mpiio;
974:     PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);
975:     if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
976:   }

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

984: #if defined(PETSC_HAVE_SAWS)
985:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
986: #endif
987:   if (iascii) {
988:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
989:     PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
990:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
991:       MatNullSpace nullsp,transnullsp;

993:       PetscViewerASCIIPushTab(viewer);
994:       MatGetSize(mat,&rows,&cols);
995:       MatGetBlockSizes(mat,&rbs,&cbs);
996:       if (rbs != 1 || cbs != 1) {
997:         if (rbs != cbs) {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs=%D\n",rows,cols,rbs,cbs);}
998:         else            {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);}
999:       } else {
1000:         PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);
1001:       }
1002:       if (mat->factortype) {
1003:         MatSolverType solver;
1004:         MatFactorGetSolverType(mat,&solver);
1005:         PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);
1006:       }
1007:       if (mat->ops->getinfo) {
1008:         MatInfo info;
1009:         MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
1010:         PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);
1011:         PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls=%D\n",(PetscInt)info.mallocs);
1012:       }
1013:       MatGetNullSpace(mat,&nullsp);
1014:       MatGetTransposeNullSpace(mat,&transnullsp);
1015:       if (nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached null space\n");}
1016:       if (transnullsp && transnullsp != nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached transposed null space\n");}
1017:       MatGetNearNullSpace(mat,&nullsp);
1018:       if (nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");}
1019:     }
1020: #if defined(PETSC_HAVE_SAWS)
1021:   } else if (issaws) {
1022:     PetscMPIInt rank;

1024:     PetscObjectName((PetscObject)mat);
1025:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1026:     if (!((PetscObject)mat)->amsmem && !rank) {
1027:       PetscObjectViewSAWs((PetscObject)mat,viewer);
1028:     }
1029: #endif
1030:   } else if (isstring) {
1031:     const char *type;
1032:     MatGetType(mat,&type);
1033:     PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);
1034:     if (mat->ops->view) {(*mat->ops->view)(mat,viewer);}
1035:   }
1036:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1037:     PetscViewerASCIIPushTab(viewer);
1038:     (*mat->ops->viewnative)(mat,viewer);
1039:     PetscViewerASCIIPopTab(viewer);
1040:   } else if (mat->ops->view) {
1041:     PetscViewerASCIIPushTab(viewer);
1042:     (*mat->ops->view)(mat,viewer);
1043:     PetscViewerASCIIPopTab(viewer);
1044:   }
1045:   if (iascii) {
1046:     PetscViewerGetFormat(viewer,&format);
1047:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1048:       PetscViewerASCIIPopTab(viewer);
1049:     }
1050:   }
1051:   PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1052:   return(0);
1053: }

1055: #if defined(PETSC_USE_DEBUG)
1056: #include <../src/sys/totalview/tv_data_display.h>
1057: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1058: {
1059:   TV_add_row("Local rows", "int", &mat->rmap->n);
1060:   TV_add_row("Local columns", "int", &mat->cmap->n);
1061:   TV_add_row("Global rows", "int", &mat->rmap->N);
1062:   TV_add_row("Global columns", "int", &mat->cmap->N);
1063:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1064:   return TV_format_OK;
1065: }
1066: #endif

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

1074:    Collective on PetscViewer

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

1081:    Options Database Keys:
1082:    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1083:    block size
1084: .    -matload_block_size <bs>

1086:    Level: beginner

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

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

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

1101:    In parallel, each processor can load a subset of rows (or the
1102:    entire matrix).  This routine is especially useful when a large
1103:    matrix is stored on disk and only part of it is desired on each
1104:    processor.  For example, a parallel solver may access only some of
1105:    the rows from each processor.  The algorithm used here reads
1106:    relatively small blocks of data rather than reading the entire
1107:    matrix and then subsetting it.

1109:    Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1110:    Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1111:    or the sequence like
1112: $    PetscViewer v;
1113: $    PetscViewerCreate(PETSC_COMM_WORLD,&v);
1114: $    PetscViewerSetType(v,PETSCVIEWERBINARY);
1115: $    PetscViewerSetFromOptions(v);
1116: $    PetscViewerFileSetMode(v,FILE_MODE_READ);
1117: $    PetscViewerFileSetName(v,"datafile");
1118:    The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1119: $ -viewer_type {binary,hdf5}

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

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

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

1135: $    PetscInt    MAT_FILE_CLASSID
1136: $    PetscInt    number of rows
1137: $    PetscInt    number of columns
1138: $    PetscInt    total number of nonzeros
1139: $    PetscInt    *number nonzeros in each row
1140: $    PetscInt    *column indices of all nonzeros (starting index is zero)
1141: $    PetscScalar *values of all nonzeros

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

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

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

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

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

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

1171:    Corresponding MatView() is not yet implemented.

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

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

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

1184:  @*/
1185: PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1186: {
1188:   PetscBool      flg;


1194:   if (!((PetscObject)newmat)->type_name) {
1195:     MatSetType(newmat,MATAIJ);
1196:   }

1198:   flg  = PETSC_FALSE;
1199:   PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);
1200:   if (flg) {
1201:     MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);
1202:     MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1203:   }
1204:   flg  = PETSC_FALSE;
1205:   PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);
1206:   if (flg) {
1207:     MatSetOption(newmat,MAT_SPD,PETSC_TRUE);
1208:   }

1210:   if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
1211:   PetscLogEventBegin(MAT_Load,viewer,0,0,0);
1212:   (*newmat->ops->load)(newmat,viewer);
1213:   PetscLogEventEnd(MAT_Load,viewer,0,0,0);
1214:   return(0);
1215: }

1217: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1218: {
1220:   Mat_Redundant  *redund = *redundant;
1221:   PetscInt       i;

1224:   if (redund){
1225:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1226:       ISDestroy(&redund->isrow);
1227:       ISDestroy(&redund->iscol);
1228:       MatDestroySubMatrices(1,&redund->matseq);
1229:     } else {
1230:       PetscFree2(redund->send_rank,redund->recv_rank);
1231:       PetscFree(redund->sbuf_j);
1232:       PetscFree(redund->sbuf_a);
1233:       for (i=0; i<redund->nrecvs; i++) {
1234:         PetscFree(redund->rbuf_j[i]);
1235:         PetscFree(redund->rbuf_a[i]);
1236:       }
1237:       PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1238:     }

1240:     if (redund->subcomm) {
1241:       PetscCommDestroy(&redund->subcomm);
1242:     }
1243:     PetscFree(redund);
1244:   }
1245:   return(0);
1246: }

1248: /*@
1249:    MatDestroy - Frees space taken by a matrix.

1251:    Collective on Mat

1253:    Input Parameter:
1254: .  A - the matrix

1256:    Level: beginner

1258: @*/
1259: PetscErrorCode MatDestroy(Mat *A)
1260: {

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

1268:   /* if memory was published with SAWs then destroy it */
1269:   PetscObjectSAWsViewOff((PetscObject)*A);
1270:   if ((*A)->ops->destroy) {
1271:     (*(*A)->ops->destroy)(*A);
1272:   }

1274:   PetscFree((*A)->defaultvectype);
1275:   PetscFree((*A)->bsizes);
1276:   PetscFree((*A)->solvertype);
1277:   MatDestroy_Redundant(&(*A)->redundant);
1278:   MatNullSpaceDestroy(&(*A)->nullsp);
1279:   MatNullSpaceDestroy(&(*A)->transnullsp);
1280:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1281:   MatDestroy(&(*A)->schur);
1282:   PetscLayoutDestroy(&(*A)->rmap);
1283:   PetscLayoutDestroy(&(*A)->cmap);
1284:   PetscHeaderDestroy(A);
1285:   return(0);
1286: }

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

1293:    Not Collective

1295:    Input Parameters:
1296: +  mat - the matrix
1297: .  v - a logically two-dimensional array of values
1298: .  m, idxm - the number of rows and their global indices
1299: .  n, idxn - the number of columns and their global indices
1300: -  addv - either ADD_VALUES or INSERT_VALUES, where
1301:    ADD_VALUES adds values to any existing entries, and
1302:    INSERT_VALUES replaces existing entries with new values

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

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

1310:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1311:    options cannot be mixed without intervening calls to the assembly
1312:    routines.

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

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

1322:    Efficiency Alert:
1323:    The routine MatSetValuesBlocked() may offer much better efficiency
1324:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1326:    Level: beginner

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

1332: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1333:           InsertMode, INSERT_VALUES, ADD_VALUES
1334: @*/
1335: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1336: {
1338: #if defined(PETSC_USE_DEBUG)
1339:   PetscInt       i,j;
1340: #endif

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

1350:   if (mat->insertmode == NOT_SET_VALUES) {
1351:     mat->insertmode = addv;
1352:   }
1353: #if defined(PETSC_USE_DEBUG)
1354:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1355:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1356:   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

1358:   for (i=0; i<m; i++) {
1359:     for (j=0; j<n; j++) {
1360:       if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1361: #if defined(PETSC_USE_COMPLEX)
1362:         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]);
1363: #else
1364:         SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1365: #endif
1366:     }
1367:   }
1368: #endif

1370:   if (mat->assembled) {
1371:     mat->was_assembled = PETSC_TRUE;
1372:     mat->assembled     = PETSC_FALSE;
1373:   }
1374:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1375:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1376:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1377:   return(0);
1378: }


1381: /*@
1382:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1383:         values into a matrix

1385:    Not Collective

1387:    Input Parameters:
1388: +  mat - the matrix
1389: .  row - the (block) row to set
1390: -  v - a logically two-dimensional array of values

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

1395:    All the nonzeros in the row must be provided

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

1399:    The row must belong to this process

1401:    Level: intermediate

1403: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1404:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1405: @*/
1406: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1407: {
1409:   PetscInt       globalrow;

1415:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1416:   MatSetValuesRow(mat,globalrow,v);
1417:   return(0);
1418: }

1420: /*@
1421:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1422:         values into a matrix

1424:    Not Collective

1426:    Input Parameters:
1427: +  mat - the matrix
1428: .  row - the (block) row to set
1429: -  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

1431:    Notes:
1432:    The values, v, are column-oriented for the block version.

1434:    All the nonzeros in the row must be provided

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

1438:    The row must belong to this process

1440:    Level: advanced

1442: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1443:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1444: @*/
1445: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1446: {

1452:   MatCheckPreallocated(mat,1);
1454: #if defined(PETSC_USE_DEBUG)
1455:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1456:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1457: #endif
1458:   mat->insertmode = INSERT_VALUES;

1460:   if (mat->assembled) {
1461:     mat->was_assembled = PETSC_TRUE;
1462:     mat->assembled     = PETSC_FALSE;
1463:   }
1464:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1465:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1466:   (*mat->ops->setvaluesrow)(mat,row,v);
1467:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1468:   return(0);
1469: }

1471: /*@
1472:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1473:      Using structured grid indexing

1475:    Not Collective

1477:    Input Parameters:
1478: +  mat - the matrix
1479: .  m - number of rows being entered
1480: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1481: .  n - number of columns being entered
1482: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1483: .  v - a logically two-dimensional array of values
1484: -  addv - either ADD_VALUES or INSERT_VALUES, where
1485:    ADD_VALUES adds values to any existing entries, and
1486:    INSERT_VALUES replaces existing entries with new values

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

1491:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1492:    options cannot be mixed without intervening calls to the assembly
1493:    routines.

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

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

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

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

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

1511:    In Fortran idxm and idxn should be declared as
1512: $     MatStencil idxm(4,m),idxn(4,n)
1513:    and the values inserted using
1514: $    idxm(MatStencil_i,1) = i
1515: $    idxm(MatStencil_j,1) = j
1516: $    idxm(MatStencil_k,1) = k
1517: $    idxm(MatStencil_c,1) = c
1518:    etc

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

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

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

1531:    Efficiency Alert:
1532:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1533:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1535:    Level: beginner

1537: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1538:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1539: @*/
1540: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1541: {
1543:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1544:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1545:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1554:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1555:     jdxm = buf; jdxn = buf+m;
1556:   } else {
1557:     PetscMalloc2(m,&bufm,n,&bufn);
1558:     jdxm = bufm; jdxn = bufn;
1559:   }
1560:   for (i=0; i<m; i++) {
1561:     for (j=0; j<3-sdim; j++) dxm++;
1562:     tmp = *dxm++ - starts[0];
1563:     for (j=0; j<dim-1; j++) {
1564:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1565:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1566:     }
1567:     if (mat->stencil.noc) dxm++;
1568:     jdxm[i] = tmp;
1569:   }
1570:   for (i=0; i<n; i++) {
1571:     for (j=0; j<3-sdim; j++) dxn++;
1572:     tmp = *dxn++ - starts[0];
1573:     for (j=0; j<dim-1; j++) {
1574:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1575:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1576:     }
1577:     if (mat->stencil.noc) dxn++;
1578:     jdxn[i] = tmp;
1579:   }
1580:   MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1581:   PetscFree2(bufm,bufn);
1582:   return(0);
1583: }

1585: /*@
1586:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1587:      Using structured grid indexing

1589:    Not Collective

1591:    Input Parameters:
1592: +  mat - the matrix
1593: .  m - number of rows being entered
1594: .  idxm - grid coordinates for matrix rows being entered
1595: .  n - number of columns being entered
1596: .  idxn - grid coordinates for matrix columns being entered
1597: .  v - a logically two-dimensional array of values
1598: -  addv - either ADD_VALUES or INSERT_VALUES, where
1599:    ADD_VALUES adds values to any existing entries, and
1600:    INSERT_VALUES replaces existing entries with new values

1602:    Notes:
1603:    By default the values, v, are row-oriented and unsorted.
1604:    See MatSetOption() for other options.

1606:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1607:    options cannot be mixed without intervening calls to the assembly
1608:    routines.

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

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

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

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

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

1626:    In Fortran idxm and idxn should be declared as
1627: $     MatStencil idxm(4,m),idxn(4,n)
1628:    and the values inserted using
1629: $    idxm(MatStencil_i,1) = i
1630: $    idxm(MatStencil_j,1) = j
1631: $    idxm(MatStencil_k,1) = k
1632:    etc

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

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

1642:    Level: beginner

1644: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1645:           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1646:           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1647: @*/
1648: PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1649: {
1651:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1652:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1653:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1663:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1664:     jdxm = buf; jdxn = buf+m;
1665:   } else {
1666:     PetscMalloc2(m,&bufm,n,&bufn);
1667:     jdxm = bufm; jdxn = bufn;
1668:   }
1669:   for (i=0; i<m; i++) {
1670:     for (j=0; j<3-sdim; j++) dxm++;
1671:     tmp = *dxm++ - starts[0];
1672:     for (j=0; j<sdim-1; j++) {
1673:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1674:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1675:     }
1676:     dxm++;
1677:     jdxm[i] = tmp;
1678:   }
1679:   for (i=0; i<n; i++) {
1680:     for (j=0; j<3-sdim; j++) dxn++;
1681:     tmp = *dxn++ - starts[0];
1682:     for (j=0; j<sdim-1; j++) {
1683:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1684:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1685:     }
1686:     dxn++;
1687:     jdxn[i] = tmp;
1688:   }
1689:   MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1690:   PetscFree2(bufm,bufn);
1691:   return(0);
1692: }

1694: /*@
1695:    MatSetStencil - Sets the grid information for setting values into a matrix via
1696:         MatSetValuesStencil()

1698:    Not Collective

1700:    Input Parameters:
1701: +  mat - the matrix
1702: .  dim - dimension of the grid 1, 2, or 3
1703: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1704: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1705: -  dof - number of degrees of freedom per node


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

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

1714:    Level: beginner

1716: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1717:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1718: @*/
1719: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1720: {
1721:   PetscInt i;


1728:   mat->stencil.dim = dim + (dof > 1);
1729:   for (i=0; i<dim; i++) {
1730:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1731:     mat->stencil.starts[i] = starts[dim-i-1];
1732:   }
1733:   mat->stencil.dims[dim]   = dof;
1734:   mat->stencil.starts[dim] = 0;
1735:   mat->stencil.noc         = (PetscBool)(dof == 1);
1736:   return(0);
1737: }

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

1742:    Not Collective

1744:    Input Parameters:
1745: +  mat - the matrix
1746: .  v - a logically two-dimensional array of values
1747: .  m, idxm - the number of block rows and their global block indices
1748: .  n, idxn - the number of block columns and their global block indices
1749: -  addv - either ADD_VALUES or INSERT_VALUES, where
1750:    ADD_VALUES adds values to any existing entries, and
1751:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

1769:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1770:    options cannot be mixed without intervening calls to the assembly
1771:    routines.

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

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

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

1787:    Example:
1788: $   Suppose m=n=2 and block size(bs) = 2 The array is
1789: $
1790: $   1  2  | 3  4
1791: $   5  6  | 7  8
1792: $   - - - | - - -
1793: $   9  10 | 11 12
1794: $   13 14 | 15 16
1795: $
1796: $   v[] should be passed in like
1797: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1798: $
1799: $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1800: $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]

1802:    Level: intermediate

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

1813:   if (!m || !n) return(0); /* no values to insert */
1817:   MatCheckPreallocated(mat,1);
1818:   if (mat->insertmode == NOT_SET_VALUES) {
1819:     mat->insertmode = addv;
1820:   }
1821: #if defined(PETSC_USE_DEBUG)
1822:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1823:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1824:   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1825: #endif

1827:   if (mat->assembled) {
1828:     mat->was_assembled = PETSC_TRUE;
1829:     mat->assembled     = PETSC_FALSE;
1830:   }
1831:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1832:   if (mat->ops->setvaluesblocked) {
1833:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1834:   } else {
1835:     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1836:     PetscInt i,j,bs,cbs;
1837:     MatGetBlockSizes(mat,&bs,&cbs);
1838:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1839:       iidxm = buf; iidxn = buf + m*bs;
1840:     } else {
1841:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1842:       iidxm = bufr; iidxn = bufc;
1843:     }
1844:     for (i=0; i<m; i++) {
1845:       for (j=0; j<bs; j++) {
1846:         iidxm[i*bs+j] = bs*idxm[i] + j;
1847:       }
1848:     }
1849:     for (i=0; i<n; i++) {
1850:       for (j=0; j<cbs; j++) {
1851:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1852:       }
1853:     }
1854:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1855:     PetscFree2(bufr,bufc);
1856:   }
1857:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1858:   return(0);
1859: }

1861: /*@
1862:    MatGetValues - Gets a block of values from a matrix.

1864:    Not Collective; currently only returns a local block

1866:    Input Parameters:
1867: +  mat - the matrix
1868: .  v - a logically two-dimensional array for storing the values
1869: .  m, idxm - the number of rows and their global indices
1870: -  n, idxn - the number of columns and their global indices

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

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

1880:    MatGetValues() requires that the matrix has been assembled
1881:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1882:    MatSetValues() and MatGetValues() CANNOT be made in succession
1883:    without intermediate matrix assembly.

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

1888:    Level: advanced

1890: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1891: @*/
1892: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1893: {

1899:   if (!m || !n) return(0);
1903:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1904:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1905:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1906:   MatCheckPreallocated(mat,1);

1908:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1909:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1910:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1911:   return(0);
1912: }

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

1918:   Not Collective

1920:   Input Parameters:
1921: + mat - the matrix
1922: . nb - the number of blocks
1923: . bs - the number of rows (and columns) in each block
1924: . rows - a concatenation of the rows for each block
1925: - v - a concatenation of logically two-dimensional arrays of values

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

1930:   Level: advanced

1932: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1933:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1934: @*/
1935: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1936: {

1944: #if defined(PETSC_USE_DEBUG)
1945:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1946: #endif

1948:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
1949:   if (mat->ops->setvaluesbatch) {
1950:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
1951:   } else {
1952:     PetscInt b;
1953:     for (b = 0; b < nb; ++b) {
1954:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
1955:     }
1956:   }
1957:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
1958:   return(0);
1959: }

1961: /*@
1962:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1963:    the routine MatSetValuesLocal() to allow users to insert matrix entries
1964:    using a local (per-processor) numbering.

1966:    Not Collective

1968:    Input Parameters:
1969: +  x - the matrix
1970: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
1971: - cmapping - column mapping

1973:    Level: intermediate


1976: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
1977: @*/
1978: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
1979: {


1988:   if (x->ops->setlocaltoglobalmapping) {
1989:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
1990:   } else {
1991:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
1992:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
1993:   }
1994:   return(0);
1995: }


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

2001:    Not Collective

2003:    Input Parameters:
2004: .  A - the matrix

2006:    Output Parameters:
2007: + rmapping - row mapping
2008: - cmapping - column mapping

2010:    Level: advanced


2013: .seealso:  MatSetValuesLocal()
2014: @*/
2015: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2016: {
2022:   if (rmapping) *rmapping = A->rmap->mapping;
2023:   if (cmapping) *cmapping = A->cmap->mapping;
2024:   return(0);
2025: }

2027: /*@
2028:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2030:    Not Collective

2032:    Input Parameters:
2033: .  A - the matrix

2035:    Output Parameters:
2036: + rmap - row layout
2037: - cmap - column layout

2039:    Level: advanced

2041: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2042: @*/
2043: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2044: {
2050:   if (rmap) *rmap = A->rmap;
2051:   if (cmap) *cmap = A->cmap;
2052:   return(0);
2053: }

2055: /*@C
2056:    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2057:    using a local ordering of the nodes.

2059:    Not Collective

2061:    Input Parameters:
2062: +  mat - the matrix
2063: .  nrow, irow - number of rows and their local indices
2064: .  ncol, icol - number of columns and their local indices
2065: .  y -  a logically two-dimensional array of values
2066: -  addv - either INSERT_VALUES or ADD_VALUES, where
2067:    ADD_VALUES adds values to any existing entries, and
2068:    INSERT_VALUES replaces existing entries with new values

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

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

2076:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2077:    options cannot be mixed without intervening calls to the assembly
2078:    routines.

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

2083:    Level: intermediate

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

2089: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2090:            MatSetValueLocal()
2091: @*/
2092: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2093: {

2099:   MatCheckPreallocated(mat,1);
2100:   if (!nrow || !ncol) return(0); /* no values to insert */
2103:   if (mat->insertmode == NOT_SET_VALUES) {
2104:     mat->insertmode = addv;
2105:   }
2106: #if defined(PETSC_USE_DEBUG)
2107:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2108:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2109:   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2110: #endif

2112:   if (mat->assembled) {
2113:     mat->was_assembled = PETSC_TRUE;
2114:     mat->assembled     = PETSC_FALSE;
2115:   }
2116:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2117:   if (mat->ops->setvalueslocal) {
2118:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2119:   } else {
2120:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2121:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2122:       irowm = buf; icolm = buf+nrow;
2123:     } else {
2124:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2125:       irowm = bufr; icolm = bufc;
2126:     }
2127:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2128:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2129:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2130:     PetscFree2(bufr,bufc);
2131:   }
2132:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2133:   return(0);
2134: }

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

2140:    Not Collective

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

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

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

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

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

2165:    Level: intermediate

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

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

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

2195:   if (mat->assembled) {
2196:     mat->was_assembled = PETSC_TRUE;
2197:     mat->assembled     = PETSC_FALSE;
2198:   }
2199: #if defined(PETSC_USE_DEBUG)
2200:   /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2201:   if (mat->rmap->mapping) {
2202:     PetscInt irbs, rbs;
2203:     MatGetBlockSizes(mat, &rbs, NULL);
2204:     ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2205:     if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2206:   }
2207:   if (mat->cmap->mapping) {
2208:     PetscInt icbs, cbs;
2209:     MatGetBlockSizes(mat,NULL,&cbs);
2210:     ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2211:     if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2212:   }
2213: #endif
2214:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2215:   if (mat->ops->setvaluesblockedlocal) {
2216:     (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2217:   } else {
2218:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2219:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2220:       irowm = buf; icolm = buf + nrow;
2221:     } else {
2222:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2223:       irowm = bufr; icolm = bufc;
2224:     }
2225:     ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2226:     ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2227:     MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2228:     PetscFree2(bufr,bufc);
2229:   }
2230:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2231:   return(0);
2232: }

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

2237:    Collective on Mat

2239:    Input Parameters:
2240: +  mat - the matrix
2241: -  x   - the vector to be multiplied

2243:    Output Parameters:
2244: .  y - the result

2246:    Notes:
2247:    The vectors x and y cannot be the same.  I.e., one cannot
2248:    call MatMult(A,y,y).

2250:    Level: developer

2252: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2253: @*/
2254: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2255: {


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

2269:   if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2270:   (*mat->ops->multdiagonalblock)(mat,x,y);
2271:   PetscObjectStateIncrease((PetscObject)y);
2272:   return(0);
2273: }

2275: /* --------------------------------------------------------*/
2276: /*@
2277:    MatMult - Computes the matrix-vector product, y = Ax.

2279:    Neighbor-wise Collective on Mat

2281:    Input Parameters:
2282: +  mat - the matrix
2283: -  x   - the vector to be multiplied

2285:    Output Parameters:
2286: .  y - the result

2288:    Notes:
2289:    The vectors x and y cannot be the same.  I.e., one cannot
2290:    call MatMult(A,y,y).

2292:    Level: beginner

2294: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2295: @*/
2296: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2297: {

2305:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2306:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2307:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2308: #if !defined(PETSC_HAVE_CONSTRAINTS)
2309:   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);
2310:   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);
2311:   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);
2312: #endif
2313:   VecSetErrorIfLocked(y,3);
2314:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2315:   MatCheckPreallocated(mat,1);

2317:   VecLockReadPush(x);
2318:   if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2319:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2320:   (*mat->ops->mult)(mat,x,y);
2321:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2322:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2323:   VecLockReadPop(x);
2324:   return(0);
2325: }

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

2330:    Neighbor-wise Collective on Mat

2332:    Input Parameters:
2333: +  mat - the matrix
2334: -  x   - the vector to be multiplied

2336:    Output Parameters:
2337: .  y - the result

2339:    Notes:
2340:    The vectors x and y cannot be the same.  I.e., one cannot
2341:    call MatMultTranspose(A,y,y).

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

2346:    Level: beginner

2348: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2349: @*/
2350: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2351: {


2360:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2361:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2362:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2363: #if !defined(PETSC_HAVE_CONSTRAINTS)
2364:   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);
2365:   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);
2366: #endif
2367:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2368:   MatCheckPreallocated(mat,1);

2370:   if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2371:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2372:   VecLockReadPush(x);
2373:   (*mat->ops->multtranspose)(mat,x,y);
2374:   VecLockReadPop(x);
2375:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2376:   PetscObjectStateIncrease((PetscObject)y);
2377:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2378:   return(0);
2379: }

2381: /*@
2382:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2384:    Neighbor-wise Collective on Mat

2386:    Input Parameters:
2387: +  mat - the matrix
2388: -  x   - the vector to be multilplied

2390:    Output Parameters:
2391: .  y - the result

2393:    Notes:
2394:    The vectors x and y cannot be the same.  I.e., one cannot
2395:    call MatMultHermitianTranspose(A,y,y).

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

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

2401:    Level: beginner

2403: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2404: @*/
2405: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2406: {
2408:   Vec            w;


2416:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2417:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2418:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2419: #if !defined(PETSC_HAVE_CONSTRAINTS)
2420:   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);
2421:   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);
2422: #endif
2423:   MatCheckPreallocated(mat,1);

2425:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2426:   if (mat->ops->multhermitiantranspose) {
2427:     VecLockReadPush(x);
2428:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2429:     VecLockReadPop(x);
2430:   } else {
2431:     VecDuplicate(x,&w);
2432:     VecCopy(x,w);
2433:     VecConjugate(w);
2434:     MatMultTranspose(mat,w,y);
2435:     VecDestroy(&w);
2436:     VecConjugate(y);
2437:   }
2438:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2439:   PetscObjectStateIncrease((PetscObject)y);
2440:   return(0);
2441: }

2443: /*@
2444:     MatMultAdd -  Computes v3 = v2 + A * v1.

2446:     Neighbor-wise Collective on Mat

2448:     Input Parameters:
2449: +   mat - the matrix
2450: -   v1, v2 - the vectors

2452:     Output Parameters:
2453: .   v3 - the result

2455:     Notes:
2456:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2457:     call MatMultAdd(A,v1,v2,v1).

2459:     Level: beginner

2461: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2462: @*/
2463: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2464: {


2474:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2475:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2476:   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);
2477:   /* 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);
2478:      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); */
2479:   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);
2480:   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);
2481:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2482:   MatCheckPreallocated(mat,1);

2484:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2485:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2486:   VecLockReadPush(v1);
2487:   (*mat->ops->multadd)(mat,v1,v2,v3);
2488:   VecLockReadPop(v1);
2489:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2490:   PetscObjectStateIncrease((PetscObject)v3);
2491:   return(0);
2492: }

2494: /*@
2495:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2497:    Neighbor-wise Collective on Mat

2499:    Input Parameters:
2500: +  mat - the matrix
2501: -  v1, v2 - the vectors

2503:    Output Parameters:
2504: .  v3 - the result

2506:    Notes:
2507:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2508:    call MatMultTransposeAdd(A,v1,v2,v1).

2510:    Level: beginner

2512: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2513: @*/
2514: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2515: {


2525:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2526:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2527:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2528:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2529:   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);
2530:   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);
2531:   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);
2532:   MatCheckPreallocated(mat,1);

2534:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2535:   VecLockReadPush(v1);
2536:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2537:   VecLockReadPop(v1);
2538:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2539:   PetscObjectStateIncrease((PetscObject)v3);
2540:   return(0);
2541: }

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

2546:    Neighbor-wise Collective on Mat

2548:    Input Parameters:
2549: +  mat - the matrix
2550: -  v1, v2 - the vectors

2552:    Output Parameters:
2553: .  v3 - the result

2555:    Notes:
2556:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2557:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2559:    Level: beginner

2561: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2562: @*/
2563: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2564: {


2574:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2575:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2576:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2577:   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);
2578:   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);
2579:   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);
2580:   MatCheckPreallocated(mat,1);

2582:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2583:   VecLockReadPush(v1);
2584:   if (mat->ops->multhermitiantransposeadd) {
2585:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2586:   } else {
2587:     Vec w,z;
2588:     VecDuplicate(v1,&w);
2589:     VecCopy(v1,w);
2590:     VecConjugate(w);
2591:     VecDuplicate(v3,&z);
2592:     MatMultTranspose(mat,w,z);
2593:     VecDestroy(&w);
2594:     VecConjugate(z);
2595:     if (v2 != v3) {
2596:       VecWAXPY(v3,1.0,v2,z);
2597:     } else {
2598:       VecAXPY(v3,1.0,z);
2599:     }
2600:     VecDestroy(&z);
2601:   }
2602:   VecLockReadPop(v1);
2603:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2604:   PetscObjectStateIncrease((PetscObject)v3);
2605:   return(0);
2606: }

2608: /*@
2609:    MatMultConstrained - The inner multiplication routine for a
2610:    constrained matrix P^T A P.

2612:    Neighbor-wise Collective on Mat

2614:    Input Parameters:
2615: +  mat - the matrix
2616: -  x   - the vector to be multilplied

2618:    Output Parameters:
2619: .  y - the result

2621:    Notes:
2622:    The vectors x and y cannot be the same.  I.e., one cannot
2623:    call MatMult(A,y,y).

2625:    Level: beginner

2627: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2628: @*/
2629: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2630: {

2637:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2638:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2639:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2640:   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);
2641:   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);
2642:   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);

2644:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2645:   VecLockReadPush(x);
2646:   (*mat->ops->multconstrained)(mat,x,y);
2647:   VecLockReadPop(x);
2648:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2649:   PetscObjectStateIncrease((PetscObject)y);
2650:   return(0);
2651: }

2653: /*@
2654:    MatMultTransposeConstrained - The inner multiplication routine for a
2655:    constrained matrix P^T A^T P.

2657:    Neighbor-wise Collective on Mat

2659:    Input Parameters:
2660: +  mat - the matrix
2661: -  x   - the vector to be multilplied

2663:    Output Parameters:
2664: .  y - the result

2666:    Notes:
2667:    The vectors x and y cannot be the same.  I.e., one cannot
2668:    call MatMult(A,y,y).

2670:    Level: beginner

2672: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2673: @*/
2674: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2675: {

2682:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2683:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2684:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2685:   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);
2686:   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);

2688:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2689:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2690:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2691:   PetscObjectStateIncrease((PetscObject)y);
2692:   return(0);
2693: }

2695: /*@C
2696:    MatGetFactorType - gets the type of factorization it is

2698:    Not Collective

2700:    Input Parameters:
2701: .  mat - the matrix

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

2706:    Level: intermediate

2708: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2709: @*/
2710: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2711: {
2716:   *t = mat->factortype;
2717:   return(0);
2718: }

2720: /*@C
2721:    MatSetFactorType - sets the type of factorization it is

2723:    Logically Collective on Mat

2725:    Input Parameters:
2726: +  mat - the matrix
2727: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2729:    Level: intermediate

2731: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2732: @*/
2733: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2734: {
2738:   mat->factortype = t;
2739:   return(0);
2740: }

2742: /* ------------------------------------------------------------*/
2743: /*@C
2744:    MatGetInfo - Returns information about matrix storage (number of
2745:    nonzeros, memory, etc.).

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

2749:    Input Parameters:
2750: .  mat - the matrix

2752:    Output Parameters:
2753: +  flag - flag indicating the type of parameters to be returned
2754:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2755:    MAT_GLOBAL_SUM - sum over all processors)
2756: -  info - matrix information context

2758:    Notes:
2759:    The MatInfo context contains a variety of matrix data, including
2760:    number of nonzeros allocated and used, number of mallocs during
2761:    matrix assembly, etc.  Additional information for factored matrices
2762:    is provided (such as the fill ratio, number of mallocs during
2763:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2764:    when using the runtime options
2765: $       -info -mat_view ::ascii_info

2767:    Example for C/C++ Users:
2768:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2769:    data within the MatInfo context.  For example,
2770: .vb
2771:       MatInfo info;
2772:       Mat     A;
2773:       double  mal, nz_a, nz_u;

2775:       MatGetInfo(A,MAT_LOCAL,&info);
2776:       mal  = info.mallocs;
2777:       nz_a = info.nz_allocated;
2778: .ve

2780:    Example for Fortran Users:
2781:    Fortran users should declare info as a double precision
2782:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2783:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2784:    a complete list of parameter names.
2785: .vb
2786:       double  precision info(MAT_INFO_SIZE)
2787:       double  precision mal, nz_a
2788:       Mat     A
2789:       integer ierr

2791:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2792:       mal = info(MAT_INFO_MALLOCS)
2793:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2794: .ve

2796:     Level: intermediate

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

2801: .seealso: MatStashGetInfo()

2803: @*/
2804: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2805: {

2812:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2813:   MatCheckPreallocated(mat,1);
2814:   (*mat->ops->getinfo)(mat,flag,info);
2815:   return(0);
2816: }

2818: /*
2819:    This is used by external packages where it is not easy to get the info from the actual
2820:    matrix factorization.
2821: */
2822: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2823: {

2827:   PetscMemzero(info,sizeof(MatInfo));
2828:   return(0);
2829: }

2831: /* ----------------------------------------------------------*/

2833: /*@C
2834:    MatLUFactor - Performs in-place LU factorization of matrix.

2836:    Collective on Mat

2838:    Input Parameters:
2839: +  mat - the matrix
2840: .  row - row permutation
2841: .  col - column permutation
2842: -  info - options for factorization, includes
2843: $          fill - expected fill as ratio of original fill.
2844: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2845: $                   Run with the option -info to determine an optimal value to use

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

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

2855:    Level: developer

2857: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2858:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2863: @*/
2864: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2865: {
2867:   MatFactorInfo  tinfo;

2875:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2876:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2877:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2878:   MatCheckPreallocated(mat,1);
2879:   if (!info) {
2880:     MatFactorInfoInitialize(&tinfo);
2881:     info = &tinfo;
2882:   }

2884:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2885:   (*mat->ops->lufactor)(mat,row,col,info);
2886:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2887:   PetscObjectStateIncrease((PetscObject)mat);
2888:   return(0);
2889: }

2891: /*@C
2892:    MatILUFactor - Performs in-place ILU factorization of matrix.

2894:    Collective on Mat

2896:    Input Parameters:
2897: +  mat - the matrix
2898: .  row - row permutation
2899: .  col - column permutation
2900: -  info - structure containing
2901: $      levels - number of levels of fill.
2902: $      expected fill - as ratio of original fill.
2903: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2904:                 missing diagonal entries)

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

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

2914:    Level: developer

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

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

2921: @*/
2922: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2923: {

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

2938:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
2939:   (*mat->ops->ilufactor)(mat,row,col,info);
2940:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
2941:   PetscObjectStateIncrease((PetscObject)mat);
2942:   return(0);
2943: }

2945: /*@C
2946:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2947:    Call this routine before calling MatLUFactorNumeric().

2949:    Collective on Mat

2951:    Input Parameters:
2952: +  fact - the factor matrix obtained with MatGetFactor()
2953: .  mat - the matrix
2954: .  row, col - row and column permutations
2955: -  info - options for factorization, includes
2956: $          fill - expected fill as ratio of original fill.
2957: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2958: $                   Run with the option -info to determine an optimal value to use


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

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

2968:    Level: developer

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

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

2975: @*/
2976: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
2977: {
2979:   MatFactorInfo  tinfo;

2988:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2989:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2990:   if (!(fact)->ops->lufactorsymbolic) {
2991:     MatSolverType spackage;
2992:     MatFactorGetSolverType(fact,&spackage);
2993:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
2994:   }
2995:   MatCheckPreallocated(mat,2);
2996:   if (!info) {
2997:     MatFactorInfoInitialize(&tinfo);
2998:     info = &tinfo;
2999:   }

3001:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3002:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3003:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3004:   PetscObjectStateIncrease((PetscObject)fact);
3005:   return(0);
3006: }

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

3012:    Collective on Mat

3014:    Input Parameters:
3015: +  fact - the factor matrix obtained with MatGetFactor()
3016: .  mat - the matrix
3017: -  info - options for factorization

3019:    Notes:
3020:    See MatLUFactor() for in-place factorization.  See
3021:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3027:    Level: developer

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

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

3034: @*/
3035: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3036: {
3037:   MatFactorInfo  tinfo;

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

3048:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3049:   MatCheckPreallocated(mat,2);
3050:   if (!info) {
3051:     MatFactorInfoInitialize(&tinfo);
3052:     info = &tinfo;
3053:   }

3055:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3056:   (fact->ops->lufactornumeric)(fact,mat,info);
3057:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3058:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3059:   PetscObjectStateIncrease((PetscObject)fact);
3060:   return(0);
3061: }

3063: /*@C
3064:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3065:    symmetric matrix.

3067:    Collective on Mat

3069:    Input Parameters:
3070: +  mat - the matrix
3071: .  perm - row and column permutations
3072: -  f - expected fill as ratio of original fill

3074:    Notes:
3075:    See MatLUFactor() for the nonsymmetric case.  See also
3076:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3082:    Level: developer

3084: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3085:           MatGetOrdering()

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

3090: @*/
3091: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3092: {
3094:   MatFactorInfo  tinfo;

3101:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3102:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3103:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3104:   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);
3105:   MatCheckPreallocated(mat,1);
3106:   if (!info) {
3107:     MatFactorInfoInitialize(&tinfo);
3108:     info = &tinfo;
3109:   }

3111:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3112:   (*mat->ops->choleskyfactor)(mat,perm,info);
3113:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3114:   PetscObjectStateIncrease((PetscObject)mat);
3115:   return(0);
3116: }

3118: /*@C
3119:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3120:    of a symmetric matrix.

3122:    Collective on Mat

3124:    Input Parameters:
3125: +  fact - the factor matrix obtained with MatGetFactor()
3126: .  mat - the matrix
3127: .  perm - row and column permutations
3128: -  info - options for factorization, includes
3129: $          fill - expected fill as ratio of original fill.
3130: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3131: $                   Run with the option -info to determine an optimal value to use

3133:    Notes:
3134:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3135:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3141:    Level: developer

3143: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3144:           MatGetOrdering()

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

3149: @*/
3150: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3151: {
3153:   MatFactorInfo  tinfo;

3161:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3162:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3163:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3164:   if (!(fact)->ops->choleskyfactorsymbolic) {
3165:     MatSolverType spackage;
3166:     MatFactorGetSolverType(fact,&spackage);
3167:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3168:   }
3169:   MatCheckPreallocated(mat,2);
3170:   if (!info) {
3171:     MatFactorInfoInitialize(&tinfo);
3172:     info = &tinfo;
3173:   }

3175:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3176:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3177:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3178:   PetscObjectStateIncrease((PetscObject)fact);
3179:   return(0);
3180: }

3182: /*@C
3183:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3184:    of a symmetric matrix. Call this routine after first calling
3185:    MatCholeskyFactorSymbolic().

3187:    Collective on Mat

3189:    Input Parameters:
3190: +  fact - the factor matrix obtained with MatGetFactor()
3191: .  mat - the initial matrix
3192: .  info - options for factorization
3193: -  fact - the symbolic factor of mat


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

3201:    Level: developer

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

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

3208: @*/
3209: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3210: {
3211:   MatFactorInfo  tinfo;

3219:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3220:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3221:   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);
3222:   MatCheckPreallocated(mat,2);
3223:   if (!info) {
3224:     MatFactorInfoInitialize(&tinfo);
3225:     info = &tinfo;
3226:   }

3228:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3229:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3230:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3231:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3232:   PetscObjectStateIncrease((PetscObject)fact);
3233:   return(0);
3234: }

3236: /* ----------------------------------------------------------------*/
3237: /*@
3238:    MatSolve - Solves A x = b, given a factored matrix.

3240:    Neighbor-wise Collective on Mat

3242:    Input Parameters:
3243: +  mat - the factored matrix
3244: -  b - the right-hand-side vector

3246:    Output Parameter:
3247: .  x - the result vector

3249:    Notes:
3250:    The vectors b and x cannot be the same.  I.e., one cannot
3251:    call MatSolve(A,x,x).

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

3258:    Level: developer

3260: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3261: @*/
3262: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3263: {

3273:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3274:   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);
3275:   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);
3276:   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);
3277:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3278:   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3279:   MatCheckPreallocated(mat,1);

3281:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3282:   if (mat->factorerrortype) {
3283:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3284:     VecSetInf(x);
3285:   } else {
3286:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3287:     (*mat->ops->solve)(mat,b,x);
3288:   }
3289:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3290:   PetscObjectStateIncrease((PetscObject)x);
3291:   return(0);
3292: }

3294: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3295: {
3297:   Vec            b,x;
3298:   PetscInt       m,N,i;
3299:   PetscScalar    *bb,*xx;

3302:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3303:   MatDenseGetArray(X,&xx);
3304:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3305:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3306:   MatCreateVecs(A,&x,&b);
3307:   for (i=0; i<N; i++) {
3308:     VecPlaceArray(b,bb + i*m);
3309:     VecPlaceArray(x,xx + i*m);
3310:     if (trans) {
3311:       MatSolveTranspose(A,b,x);
3312:     } else {
3313:       MatSolve(A,b,x);
3314:     }
3315:     VecResetArray(x);
3316:     VecResetArray(b);
3317:   }
3318:   VecDestroy(&b);
3319:   VecDestroy(&x);
3320:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3321:   MatDenseRestoreArray(X,&xx);
3322:   return(0);
3323: }

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

3328:    Neighbor-wise Collective on Mat

3330:    Input Parameters:
3331: +  A - the factored matrix
3332: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3334:    Output Parameter:
3335: .  X - the result matrix (dense matrix)

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

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

3347:    Level: developer

3349: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3350: @*/
3351: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3352: {

3362:   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);
3363:   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);
3364:   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");
3365:   if (!A->rmap->N && !A->cmap->N) return(0);
3366:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3367:   MatCheckPreallocated(A,1);

3369:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3370:   if (!A->ops->matsolve) {
3371:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3372:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3373:   } else {
3374:     (*A->ops->matsolve)(A,B,X);
3375:   }
3376:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3377:   PetscObjectStateIncrease((PetscObject)X);
3378:   return(0);
3379: }

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

3384:    Neighbor-wise Collective on Mat

3386:    Input Parameters:
3387: +  A - the factored matrix
3388: -  B - the right-hand-side matrix  (dense matrix)

3390:    Output Parameter:
3391: .  X - the result matrix (dense matrix)

3393:    Notes:
3394:    The matrices B and X cannot be the same.  I.e., one cannot
3395:    call MatMatSolveTranspose(A,X,X).

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

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

3405:    Level: developer

3407: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3408: @*/
3409: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3410: {

3420:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3421:   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);
3422:   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);
3423:   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);
3424:   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");
3425:   if (!A->rmap->N && !A->cmap->N) return(0);
3426:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3427:   MatCheckPreallocated(A,1);

3429:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3430:   if (!A->ops->matsolvetranspose) {
3431:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3432:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3433:   } else {
3434:     (*A->ops->matsolvetranspose)(A,B,X);
3435:   }
3436:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3437:   PetscObjectStateIncrease((PetscObject)X);
3438:   return(0);
3439: }

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

3444:    Neighbor-wise Collective on Mat

3446:    Input Parameters:
3447: +  A - the factored matrix
3448: -  Bt - the transpose of right-hand-side matrix

3450:    Output Parameter:
3451: .  X - the result matrix (dense matrix)

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

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

3461:    Level: developer

3463: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3464: @*/
3465: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3466: {


3477:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3478:   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);
3479:   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);
3480:   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");
3481:   if (!A->rmap->N && !A->cmap->N) return(0);
3482:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3483:   MatCheckPreallocated(A,1);

3485:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3486:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3487:   (*A->ops->mattransposesolve)(A,Bt,X);
3488:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3489:   PetscObjectStateIncrease((PetscObject)X);
3490:   return(0);
3491: }

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

3497:    Neighbor-wise Collective on Mat

3499:    Input Parameters:
3500: +  mat - the factored matrix
3501: -  b - the right-hand-side vector

3503:    Output Parameter:
3504: .  x - the result vector

3506:    Notes:
3507:    MatSolve() should be used for most applications, as it performs
3508:    a forward solve followed by a backward solve.

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

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

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

3523:    Level: developer

3525: .seealso: MatSolve(), MatBackwardSolve()
3526: @*/
3527: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3528: {

3538:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3539:   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);
3540:   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);
3541:   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);
3542:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3543:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3544:   MatCheckPreallocated(mat,1);

3546:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3547:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3548:   (*mat->ops->forwardsolve)(mat,b,x);
3549:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3550:   PetscObjectStateIncrease((PetscObject)x);
3551:   return(0);
3552: }

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

3558:    Neighbor-wise Collective on Mat

3560:    Input Parameters:
3561: +  mat - the factored matrix
3562: -  b - the right-hand-side vector

3564:    Output Parameter:
3565: .  x - the result vector

3567:    Notes:
3568:    MatSolve() should be used for most applications, as it performs
3569:    a forward solve followed by a backward solve.

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

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

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

3584:    Level: developer

3586: .seealso: MatSolve(), MatForwardSolve()
3587: @*/
3588: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3589: {

3599:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3600:   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);
3601:   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);
3602:   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);
3603:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3604:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3605:   MatCheckPreallocated(mat,1);

3607:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3608:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3609:   (*mat->ops->backwardsolve)(mat,b,x);
3610:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3611:   PetscObjectStateIncrease((PetscObject)x);
3612:   return(0);
3613: }

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

3618:    Neighbor-wise Collective on Mat

3620:    Input Parameters:
3621: +  mat - the factored matrix
3622: .  b - the right-hand-side vector
3623: -  y - the vector to be added to

3625:    Output Parameter:
3626: .  x - the result vector

3628:    Notes:
3629:    The vectors b and x cannot be the same.  I.e., one cannot
3630:    call MatSolveAdd(A,x,y,x).

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

3636:    Level: developer

3638: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3639: @*/
3640: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3641: {
3642:   PetscScalar    one = 1.0;
3643:   Vec            tmp;

3655:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3656:   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);
3657:   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);
3658:   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);
3659:   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);
3660:   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);
3661:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3662:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3663:   MatCheckPreallocated(mat,1);

3665:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3666:   if (mat->ops->solveadd) {
3667:     (*mat->ops->solveadd)(mat,b,y,x);
3668:   } else {
3669:     /* do the solve then the add manually */
3670:     if (x != y) {
3671:       MatSolve(mat,b,x);
3672:       VecAXPY(x,one,y);
3673:     } else {
3674:       VecDuplicate(x,&tmp);
3675:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3676:       VecCopy(x,tmp);
3677:       MatSolve(mat,b,x);
3678:       VecAXPY(x,one,tmp);
3679:       VecDestroy(&tmp);
3680:     }
3681:   }
3682:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3683:   PetscObjectStateIncrease((PetscObject)x);
3684:   return(0);
3685: }

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

3690:    Neighbor-wise Collective on Mat

3692:    Input Parameters:
3693: +  mat - the factored matrix
3694: -  b - the right-hand-side vector

3696:    Output Parameter:
3697: .  x - the result vector

3699:    Notes:
3700:    The vectors b and x cannot be the same.  I.e., one cannot
3701:    call MatSolveTranspose(A,x,x).

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

3707:    Level: developer

3709: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3710: @*/
3711: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3712: {

3722:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3723:   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);
3724:   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);
3725:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3726:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3727:   MatCheckPreallocated(mat,1);
3728:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3729:   if (mat->factorerrortype) {
3730:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3731:     VecSetInf(x);
3732:   } else {
3733:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3734:     (*mat->ops->solvetranspose)(mat,b,x);
3735:   }
3736:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3737:   PetscObjectStateIncrease((PetscObject)x);
3738:   return(0);
3739: }

3741: /*@
3742:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3743:                       factored matrix.

3745:    Neighbor-wise Collective on Mat

3747:    Input Parameters:
3748: +  mat - the factored matrix
3749: .  b - the right-hand-side vector
3750: -  y - the vector to be added to

3752:    Output Parameter:
3753: .  x - the result vector

3755:    Notes:
3756:    The vectors b and x cannot be the same.  I.e., one cannot
3757:    call MatSolveTransposeAdd(A,x,y,x).

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

3763:    Level: developer

3765: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3766: @*/
3767: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3768: {
3769:   PetscScalar    one = 1.0;
3771:   Vec            tmp;

3782:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3783:   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);
3784:   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);
3785:   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);
3786:   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);
3787:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3788:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3789:   MatCheckPreallocated(mat,1);

3791:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3792:   if (mat->ops->solvetransposeadd) {
3793:     if (mat->factorerrortype) {
3794:       PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3795:       VecSetInf(x);
3796:     } else {
3797:       (*mat->ops->solvetransposeadd)(mat,b,y,x);
3798:     }
3799:   } else {
3800:     /* do the solve then the add manually */
3801:     if (x != y) {
3802:       MatSolveTranspose(mat,b,x);
3803:       VecAXPY(x,one,y);
3804:     } else {
3805:       VecDuplicate(x,&tmp);
3806:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3807:       VecCopy(x,tmp);
3808:       MatSolveTranspose(mat,b,x);
3809:       VecAXPY(x,one,tmp);
3810:       VecDestroy(&tmp);
3811:     }
3812:   }
3813:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3814:   PetscObjectStateIncrease((PetscObject)x);
3815:   return(0);
3816: }
3817: /* ----------------------------------------------------------------*/

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

3822:    Neighbor-wise Collective on Mat

3824:    Input Parameters:
3825: +  mat - the matrix
3826: .  b - the right hand side
3827: .  omega - the relaxation factor
3828: .  flag - flag indicating the type of SOR (see below)
3829: .  shift -  diagonal shift
3830: .  its - the number of iterations
3831: -  lits - the number of local iterations

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

3836:    SOR Flags:
3837: +     SOR_FORWARD_SWEEP - forward SOR
3838: .     SOR_BACKWARD_SWEEP - backward SOR
3839: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3840: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3841: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3842: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3843: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3844:          upper/lower triangular part of matrix to
3845:          vector (with omega)
3846: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

3848:    Notes:
3849:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3850:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3851:    on each processor.

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

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

3859:    Notes for Advanced Users:
3860:    The flags are implemented as bitwise inclusive or operations.
3861:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3862:    to specify a zero initial guess for SSOR.

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

3868:    Vectors x and b CANNOT be the same

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

3872:    Level: developer

3874: @*/
3875: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3876: {

3886:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3887:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3888:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3889:   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);
3890:   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);
3891:   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);
3892:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3893:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3894:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

3896:   MatCheckPreallocated(mat,1);
3897:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3898:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3899:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3900:   PetscObjectStateIncrease((PetscObject)x);
3901:   return(0);
3902: }

3904: /*
3905:       Default matrix copy routine.
3906: */
3907: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3908: {
3909:   PetscErrorCode    ierr;
3910:   PetscInt          i,rstart = 0,rend = 0,nz;
3911:   const PetscInt    *cwork;
3912:   const PetscScalar *vwork;

3915:   if (B->assembled) {
3916:     MatZeroEntries(B);
3917:   }
3918:   if (str == SAME_NONZERO_PATTERN) {
3919:     MatGetOwnershipRange(A,&rstart,&rend);
3920:     for (i=rstart; i<rend; i++) {
3921:       MatGetRow(A,i,&nz,&cwork,&vwork);
3922:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3923:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
3924:     }
3925:   } else {
3926:     MatAYPX(B,0.0,A,str);
3927:   }
3928:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3929:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3930:   return(0);
3931: }

3933: /*@
3934:    MatCopy - Copies a matrix to another matrix.

3936:    Collective on Mat

3938:    Input Parameters:
3939: +  A - the matrix
3940: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

3942:    Output Parameter:
3943: .  B - where the copy is put

3945:    Notes:
3946:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3947:    same nonzero pattern or the routine will crash.

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

3953:    Level: intermediate

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

3957: @*/
3958: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
3959: {
3961:   PetscInt       i;

3969:   MatCheckPreallocated(B,2);
3970:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3971:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3972:   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);
3973:   MatCheckPreallocated(A,1);
3974:   if (A == B) return(0);

3976:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
3977:   if (A->ops->copy) {
3978:     (*A->ops->copy)(A,B,str);
3979:   } else { /* generic conversion */
3980:     MatCopy_Basic(A,B,str);
3981:   }

3983:   B->stencil.dim = A->stencil.dim;
3984:   B->stencil.noc = A->stencil.noc;
3985:   for (i=0; i<=A->stencil.dim; i++) {
3986:     B->stencil.dims[i]   = A->stencil.dims[i];
3987:     B->stencil.starts[i] = A->stencil.starts[i];
3988:   }

3990:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
3991:   PetscObjectStateIncrease((PetscObject)B);
3992:   return(0);
3993: }

3995: /*@C
3996:    MatConvert - Converts a matrix to another matrix, either of the same
3997:    or different type.

3999:    Collective on Mat

4001:    Input Parameters:
4002: +  mat - the matrix
4003: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4004:    same type as the original matrix.
4005: -  reuse - denotes if the destination matrix is to be created or reused.
4006:    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
4007:    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).

4009:    Output Parameter:
4010: .  M - pointer to place new matrix

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

4017:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4018:    the MPI communicator of the generated matrix is always the same as the communicator
4019:    of the input matrix.

4021:    Level: intermediate

4023: .seealso: MatCopy(), MatDuplicate()
4024: @*/
4025: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4026: {
4028:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4029:   char           convname[256],mtype[256];
4030:   Mat            B;

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

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

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

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

4053:   /* Cache Mat options because some converter use MatHeaderReplace  */
4054:   issymmetric = mat->symmetric;
4055:   ishermitian = mat->hermitian;

4057:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4058:     PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4059:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4060:   } else {
4061:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4062:     const char     *prefix[3] = {"seq","mpi",""};
4063:     PetscInt       i;
4064:     /*
4065:        Order of precedence:
4066:        0) See if newtype is a superclass of the current matrix.
4067:        1) See if a specialized converter is known to the current matrix.
4068:        2) See if a specialized converter is known to the desired matrix class.
4069:        3) See if a good general converter is registered for the desired class
4070:           (as of 6/27/03 only MATMPIADJ falls into this category).
4071:        4) See if a good general converter is known for the current matrix.
4072:        5) Use a really basic converter.
4073:     */

4075:     /* 0) See if newtype is a superclass of the current matrix.
4076:           i.e mat is mpiaij and newtype is aij */
4077:     for (i=0; i<2; i++) {
4078:       PetscStrncpy(convname,prefix[i],sizeof(convname));
4079:       PetscStrlcat(convname,newtype,sizeof(convname));
4080:       PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4081:       PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4082:       if (flg) {
4083:         if (reuse == MAT_INPLACE_MATRIX) {
4084:           return(0);
4085:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4086:           (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4087:           return(0);
4088:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4089:           MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4090:           return(0);
4091:         }
4092:       }
4093:     }
4094:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4095:     for (i=0; i<3; i++) {
4096:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4097:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4098:       PetscStrlcat(convname,"_",sizeof(convname));
4099:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4100:       PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4101:       PetscStrlcat(convname,"_C",sizeof(convname));
4102:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4103:       PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4104:       if (conv) goto foundconv;
4105:     }

4107:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4108:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4109:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4110:     MatSetType(B,newtype);
4111:     for (i=0; i<3; i++) {
4112:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4113:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4114:       PetscStrlcat(convname,"_",sizeof(convname));
4115:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4116:       PetscStrlcat(convname,newtype,sizeof(convname));
4117:       PetscStrlcat(convname,"_C",sizeof(convname));
4118:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4119:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4120:       if (conv) {
4121:         MatDestroy(&B);
4122:         goto foundconv;
4123:       }
4124:     }

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

4132:     /* 4) See if a good general converter is known for the current matrix */
4133:     if (mat->ops->convert) {
4134:       conv = mat->ops->convert;
4135:     }
4136:     PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);
4137:     if (conv) goto foundconv;

4139:     /* 5) Use a really basic converter. */
4140:     PetscInfo(mat,"Using MatConvert_Basic\n");
4141:     conv = MatConvert_Basic;

4143: foundconv:
4144:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4145:     (*conv)(mat,newtype,reuse,M);
4146:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4147:       /* the block sizes must be same if the mappings are copied over */
4148:       (*M)->rmap->bs = mat->rmap->bs;
4149:       (*M)->cmap->bs = mat->cmap->bs;
4150:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4151:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4152:       (*M)->rmap->mapping = mat->rmap->mapping;
4153:       (*M)->cmap->mapping = mat->cmap->mapping;
4154:     }
4155:     (*M)->stencil.dim = mat->stencil.dim;
4156:     (*M)->stencil.noc = mat->stencil.noc;
4157:     for (i=0; i<=mat->stencil.dim; i++) {
4158:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4159:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4160:     }
4161:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4162:   }
4163:   PetscObjectStateIncrease((PetscObject)*M);

4165:   /* Copy Mat options */
4166:   if (issymmetric) {
4167:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4168:   }
4169:   if (ishermitian) {
4170:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4171:   }
4172:   return(0);
4173: }

4175: /*@C
4176:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4178:    Not Collective

4180:    Input Parameter:
4181: .  mat - the matrix, must be a factored matrix

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

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

4190:    Level: intermediate

4192: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4193: @*/
4194: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4195: {
4196:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4201:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4202:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4203:   if (!conv) {
4204:     *type = MATSOLVERPETSC;
4205:   } else {
4206:     (*conv)(mat,type);
4207:   }
4208:   return(0);
4209: }

4211: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4212: struct _MatSolverTypeForSpecifcType {
4213:   MatType                        mtype;
4214:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4215:   MatSolverTypeForSpecifcType next;
4216: };

4218: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4219: struct _MatSolverTypeHolder {
4220:   char                           *name;
4221:   MatSolverTypeForSpecifcType handlers;
4222:   MatSolverTypeHolder         next;
4223: };

4225: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4230:    Input Parameters:
4231: +    package - name of the package, for example petsc or superlu
4232: .    mtype - the matrix type that works with this package
4233: .    ftype - the type of factorization supported by the package
4234: -    getfactor - routine that will create the factored matrix ready to be used

4236:     Level: intermediate

4238: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4239: @*/
4240: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4241: {
4242:   PetscErrorCode              ierr;
4243:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4244:   PetscBool                   flg;
4245:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4248:   MatInitializePackage();
4249:   if (!next) {
4250:     PetscNew(&MatSolverTypeHolders);
4251:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4252:     PetscNew(&MatSolverTypeHolders->handlers);
4253:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4254:     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4255:     return(0);
4256:   }
4257:   while (next) {
4258:     PetscStrcasecmp(package,next->name,&flg);
4259:     if (flg) {
4260:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4261:       inext = next->handlers;
4262:       while (inext) {
4263:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4264:         if (flg) {
4265:           inext->getfactor[(int)ftype-1] = getfactor;
4266:           return(0);
4267:         }
4268:         iprev = inext;
4269:         inext = inext->next;
4270:       }
4271:       PetscNew(&iprev->next);
4272:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4273:       iprev->next->getfactor[(int)ftype-1] = getfactor;
4274:       return(0);
4275:     }
4276:     prev = next;
4277:     next = next->next;
4278:   }
4279:   PetscNew(&prev->next);
4280:   PetscStrallocpy(package,&prev->next->name);
4281:   PetscNew(&prev->next->handlers);
4282:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4283:   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4284:   return(0);
4285: }

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

4290:    Input Parameters:
4291: +    package - name of the package, for example petsc or superlu
4292: .    ftype - the type of factorization supported by the package
4293: -    mtype - the matrix type that works with this package

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

4300:     Level: intermediate

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

4312:   if (foundpackage) *foundpackage = PETSC_FALSE;
4313:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4314:   if (getfactor)    *getfactor    = NULL;

4316:   if (package) {
4317:     while (next) {
4318:       PetscStrcasecmp(package,next->name,&flg);
4319:       if (flg) {
4320:         if (foundpackage) *foundpackage = PETSC_TRUE;
4321:         inext = next->handlers;
4322:         while (inext) {
4323:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4324:           if (flg) {
4325:             if (foundmtype) *foundmtype = PETSC_TRUE;
4326:             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4327:             return(0);
4328:           }
4329:           inext = inext->next;
4330:         }
4331:       }
4332:       next = next->next;
4333:     }
4334:   } else {
4335:     while (next) {
4336:       inext = next->handlers;
4337:       while (inext) {
4338:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4339:         if (flg && inext->getfactor[(int)ftype-1]) {
4340:           if (foundpackage) *foundpackage = PETSC_TRUE;
4341:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4342:           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
4343:           return(0);
4344:         }
4345:         inext = inext->next;
4346:       }
4347:       next = next->next;
4348:     }
4349:   }
4350:   return(0);
4351: }

4353: PetscErrorCode MatSolverTypeDestroy(void)
4354: {
4355:   PetscErrorCode              ierr;
4356:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4357:   MatSolverTypeForSpecifcType inext,iprev;

4360:   while (next) {
4361:     PetscFree(next->name);
4362:     inext = next->handlers;
4363:     while (inext) {
4364:       PetscFree(inext->mtype);
4365:       iprev = inext;
4366:       inext = inext->next;
4367:       PetscFree(iprev);
4368:     }
4369:     prev = next;
4370:     next = next->next;
4371:     PetscFree(prev);
4372:   }
4373:   MatSolverTypeHolders = NULL;
4374:   return(0);
4375: }

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

4380:    Collective on Mat

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

4387:    Output Parameters:
4388: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4390:    Notes:
4391:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4392:      such as pastix, superlu, mumps etc.

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

4396:    Level: intermediate

4398: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4399: @*/
4400: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4401: {
4402:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4403:   PetscBool      foundpackage,foundmtype;


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

4412:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4413:   if (!foundpackage) {
4414:     if (type) {
4415:       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4416:     } else {
4417:       SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4418:     }
4419:   }

4421:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4422:   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);

4424: #if defined(PETSC_USE_COMPLEX)
4425:   if (mat->hermitian && !mat->symmetric && (ftype == MAT_FACTOR_CHOLESKY||ftype == MAT_FACTOR_ICC)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Hermitian CHOLESKY or ICC Factor is not supported");
4426: #endif

4428:   (*conv)(mat,ftype,f);
4429:   return(0);
4430: }

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

4435:    Not Collective

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

4442:    Output Parameter:
4443: .    flg - PETSC_TRUE if the factorization is available

4445:    Notes:
4446:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4447:      such as pastix, superlu, mumps etc.

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

4451:    Level: intermediate

4453: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4454: @*/
4455: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4456: {
4457:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4466:   *flg = PETSC_FALSE;
4467:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4468:   if (gconv) {
4469:     *flg = PETSC_TRUE;
4470:   }
4471:   return(0);
4472: }

4474:  #include <petscdmtypes.h>

4476: /*@
4477:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4479:    Collective on Mat

4481:    Input Parameters:
4482: +  mat - the matrix
4483: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4484:         See the manual page for MatDuplicateOption for an explanation of these options.

4486:    Output Parameter:
4487: .  M - pointer to place new matrix

4489:    Level: intermediate

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

4495: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4496: @*/
4497: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4498: {
4500:   Mat            B;
4501:   PetscInt       i;
4502:   DM             dm;
4503:   void           (*viewf)(void);

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

4513:   *M = 0;
4514:   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4515:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4516:   (*mat->ops->duplicate)(mat,op,M);
4517:   B    = *M;

4519:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4520:   if (viewf) {
4521:     MatSetOperation(B,MATOP_VIEW,viewf);
4522:   }

4524:   B->stencil.dim = mat->stencil.dim;
4525:   B->stencil.noc = mat->stencil.noc;
4526:   for (i=0; i<=mat->stencil.dim; i++) {
4527:     B->stencil.dims[i]   = mat->stencil.dims[i];
4528:     B->stencil.starts[i] = mat->stencil.starts[i];
4529:   }

4531:   B->nooffproczerorows = mat->nooffproczerorows;
4532:   B->nooffprocentries  = mat->nooffprocentries;

4534:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4535:   if (dm) {
4536:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4537:   }
4538:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4539:   PetscObjectStateIncrease((PetscObject)B);
4540:   return(0);
4541: }

4543: /*@
4544:    MatGetDiagonal - Gets the diagonal of a matrix.

4546:    Logically Collective on Mat

4548:    Input Parameters:
4549: +  mat - the matrix
4550: -  v - the vector for storing the diagonal

4552:    Output Parameter:
4553: .  v - the diagonal of the matrix

4555:    Level: intermediate

4557:    Note:
4558:    Currently only correct in parallel for square matrices.

4560: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4561: @*/
4562: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4563: {

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

4574:   (*mat->ops->getdiagonal)(mat,v);
4575:   PetscObjectStateIncrease((PetscObject)v);
4576:   return(0);
4577: }

4579: /*@C
4580:    MatGetRowMin - Gets the minimum value (of the real part) of each
4581:         row of the matrix

4583:    Logically Collective on Mat

4585:    Input Parameters:
4586: .  mat - the matrix

4588:    Output Parameter:
4589: +  v - the vector for storing the maximums
4590: -  idx - the indices of the column found for each row (optional)

4592:    Level: intermediate

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

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

4600: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4601:           MatGetRowMax()
4602: @*/
4603: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4604: {

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

4615:   (*mat->ops->getrowmin)(mat,v,idx);
4616:   PetscObjectStateIncrease((PetscObject)v);
4617:   return(0);
4618: }

4620: /*@C
4621:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4622:         row of the matrix

4624:    Logically Collective on Mat

4626:    Input Parameters:
4627: .  mat - the matrix

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

4633:    Level: intermediate

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

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

4641: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4642: @*/
4643: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4644: {

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

4656:   (*mat->ops->getrowminabs)(mat,v,idx);
4657:   PetscObjectStateIncrease((PetscObject)v);
4658:   return(0);
4659: }

4661: /*@C
4662:    MatGetRowMax - Gets the maximum value (of the real part) of each
4663:         row of the matrix

4665:    Logically Collective on Mat

4667:    Input Parameters:
4668: .  mat - the matrix

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

4674:    Level: intermediate

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

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

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

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

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

4701: /*@C
4702:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4703:         row of the matrix

4705:    Logically Collective on Mat

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

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

4714:    Level: intermediate

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

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

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

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

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

4742: /*@
4743:    MatGetRowSum - Gets the sum of each row of the matrix

4745:    Logically or Neighborhood Collective on Mat

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

4750:    Output Parameter:
4751: .  v - the vector for storing the sum of rows

4753:    Level: intermediate

4755:    Notes:
4756:     This code is slow since it is not currently specialized for different formats

4758: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4759: @*/
4760: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4761: {
4762:   Vec            ones;

4769:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4770:   MatCheckPreallocated(mat,1);
4771:   MatCreateVecs(mat,&ones,NULL);
4772:   VecSet(ones,1.);
4773:   MatMult(mat,ones,v);
4774:   VecDestroy(&ones);
4775:   return(0);
4776: }

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

4781:    Collective on Mat

4783:    Input Parameter:
4784: +  mat - the matrix to transpose
4785: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4787:    Output Parameters:
4788: .  B - the transpose

4790:    Notes:
4791:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4797:    Level: intermediate

4799: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4800: @*/
4801: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4802: {

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

4815:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4816:   (*mat->ops->transpose)(mat,reuse,B);
4817:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4818:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4819:   return(0);
4820: }

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

4826:    Collective on Mat

4828:    Input Parameter:
4829: +  A - the matrix to test
4830: -  B - the matrix to test against, this can equal the first parameter

4832:    Output Parameters:
4833: .  flg - the result

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

4840:    Level: intermediate

4842: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4843: @*/
4844: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4845: {
4846:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4852:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4853:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4854:   *flg = PETSC_FALSE;
4855:   if (f && g) {
4856:     if (f == g) {
4857:       (*f)(A,B,tol,flg);
4858:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4859:   } else {
4860:     MatType mattype;
4861:     if (!f) {
4862:       MatGetType(A,&mattype);
4863:     } else {
4864:       MatGetType(B,&mattype);
4865:     }
4866:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4867:   }
4868:   return(0);
4869: }

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

4874:    Collective on Mat

4876:    Input Parameter:
4877: +  mat - the matrix to transpose and complex conjugate
4878: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

4880:    Output Parameters:
4881: .  B - the Hermitian

4883:    Level: intermediate

4885: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4886: @*/
4887: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4888: {

4892:   MatTranspose(mat,reuse,B);
4893: #if defined(PETSC_USE_COMPLEX)
4894:   MatConjugate(*B);
4895: #endif
4896:   return(0);
4897: }

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

4902:    Collective on Mat

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

4908:    Output Parameters:
4909: .  flg - the result

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

4916:    Level: intermediate

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

4928:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4929:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
4930:   if (f && g) {
4931:     if (f==g) {
4932:       (*f)(A,B,tol,flg);
4933:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4934:   }
4935:   return(0);
4936: }

4938: /*@
4939:    MatPermute - Creates a new matrix with rows and columns permuted from the
4940:    original.

4942:    Collective on Mat

4944:    Input Parameters:
4945: +  mat - the matrix to permute
4946: .  row - row permutation, each processor supplies only the permutation for its rows
4947: -  col - column permutation, each processor supplies only the permutation for its columns

4949:    Output Parameters:
4950: .  B - the permuted matrix

4952:    Level: advanced

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

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

4960: @*/
4961: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
4962: {

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

4976:   (*mat->ops->permute)(mat,row,col,B);
4977:   PetscObjectStateIncrease((PetscObject)*B);
4978:   return(0);
4979: }

4981: /*@
4982:    MatEqual - Compares two matrices.

4984:    Collective on Mat

4986:    Input Parameters:
4987: +  A - the first matrix
4988: -  B - the second matrix

4990:    Output Parameter:
4991: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

4993:    Level: intermediate

4995: @*/
4996: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
4997: {

5007:   MatCheckPreallocated(B,2);
5008:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5009:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5010:   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);
5011:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5012:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5013:   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);
5014:   MatCheckPreallocated(A,1);

5016:   (*A->ops->equal)(A,B,flg);
5017:   return(0);
5018: }

5020: /*@
5021:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5022:    matrices that are stored as vectors.  Either of the two scaling
5023:    matrices can be NULL.

5025:    Collective on Mat

5027:    Input Parameters:
5028: +  mat - the matrix to be scaled
5029: .  l - the left scaling vector (or NULL)
5030: -  r - the right scaling vector (or NULL)

5032:    Notes:
5033:    MatDiagonalScale() computes A = LAR, where
5034:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5035:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5037:    Level: intermediate


5040: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5041: @*/
5042: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5043: {

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

5056:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5057:   (*mat->ops->diagonalscale)(mat,l,r);
5058:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5059:   PetscObjectStateIncrease((PetscObject)mat);
5060:   return(0);
5061: }

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

5066:     Logically Collective on Mat

5068:     Input Parameters:
5069: +   mat - the matrix to be scaled
5070: -   a  - the scaling value

5072:     Output Parameter:
5073: .   mat - the scaled matrix

5075:     Level: intermediate

5077: .seealso: MatDiagonalScale()
5078: @*/
5079: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5080: {

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

5092:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5093:   if (a != (PetscScalar)1.0) {
5094:     (*mat->ops->scale)(mat,a);
5095:     PetscObjectStateIncrease((PetscObject)mat);
5096:   }
5097:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5098:   return(0);
5099: }

5101: /*@
5102:    MatNorm - Calculates various norms of a matrix.

5104:    Collective on Mat

5106:    Input Parameters:
5107: +  mat - the matrix
5108: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5110:    Output Parameters:
5111: .  nrm - the resulting norm

5113:    Level: intermediate

5115: @*/
5116: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5117: {


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

5130:   (*mat->ops->norm)(mat,type,nrm);
5131:   return(0);
5132: }

5134: /*
5135:      This variable is used to prevent counting of MatAssemblyBegin() that
5136:    are called from within a MatAssemblyEnd().
5137: */
5138: static PetscInt MatAssemblyEnd_InUse = 0;
5139: /*@
5140:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5141:    be called after completing all calls to MatSetValues().

5143:    Collective on Mat

5145:    Input Parameters:
5146: +  mat - the matrix
5147: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5149:    Notes:
5150:    MatSetValues() generally caches the values.  The matrix is ready to
5151:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5152:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5153:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5154:    using the matrix.

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

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

5164:    Level: beginner

5166: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5167: @*/
5168: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5169: {

5175:   MatCheckPreallocated(mat,1);
5176:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5177:   if (mat->assembled) {
5178:     mat->was_assembled = PETSC_TRUE;
5179:     mat->assembled     = PETSC_FALSE;
5180:   }

5182:   if (!MatAssemblyEnd_InUse) {
5183:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5184:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5185:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5186:   } else if (mat->ops->assemblybegin) {
5187:     (*mat->ops->assemblybegin)(mat,type);
5188:   }
5189:   return(0);
5190: }

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

5196:    Not Collective

5198:    Input Parameter:
5199: .  mat - the matrix

5201:    Output Parameter:
5202: .  assembled - PETSC_TRUE or PETSC_FALSE

5204:    Level: advanced

5206: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5207: @*/
5208: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5209: {
5213:   *assembled = mat->assembled;
5214:   return(0);
5215: }

5217: /*@
5218:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5219:    be called after MatAssemblyBegin().

5221:    Collective on Mat

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

5227:    Options Database Keys:
5228: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5229: .  -mat_view ::ascii_info_detail - Prints more detailed info
5230: .  -mat_view - Prints matrix in ASCII format
5231: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5232: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5233: .  -display <name> - Sets display name (default is host)
5234: .  -draw_pause <sec> - Sets number of seconds to pause after display
5235: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5236: .  -viewer_socket_machine <machine> - Machine to use for socket
5237: .  -viewer_socket_port <port> - Port number to use for socket
5238: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5240:    Notes:
5241:    MatSetValues() generally caches the values.  The matrix is ready to
5242:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5243:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5244:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5245:    using the matrix.

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

5251:    Level: beginner

5253: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5254: @*/
5255: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5256: {
5257:   PetscErrorCode  ierr;
5258:   static PetscInt inassm = 0;
5259:   PetscBool       flg    = PETSC_FALSE;


5265:   inassm++;
5266:   MatAssemblyEnd_InUse++;
5267:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5268:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5269:     if (mat->ops->assemblyend) {
5270:       (*mat->ops->assemblyend)(mat,type);
5271:     }
5272:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5273:   } else if (mat->ops->assemblyend) {
5274:     (*mat->ops->assemblyend)(mat,type);
5275:   }

5277:   /* Flush assembly is not a true assembly */
5278:   if (type != MAT_FLUSH_ASSEMBLY) {
5279:     mat->num_ass++;
5280:     mat->assembled        = PETSC_TRUE;
5281:     mat->ass_nonzerostate = mat->nonzerostate;
5282:   }

5284:   mat->insertmode = NOT_SET_VALUES;
5285:   MatAssemblyEnd_InUse--;
5286:   PetscObjectStateIncrease((PetscObject)mat);
5287:   if (!mat->symmetric_eternal) {
5288:     mat->symmetric_set              = PETSC_FALSE;
5289:     mat->hermitian_set              = PETSC_FALSE;
5290:     mat->structurally_symmetric_set = PETSC_FALSE;
5291:   }
5292:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5293:     MatViewFromOptions(mat,NULL,"-mat_view");

5295:     if (mat->checksymmetryonassembly) {
5296:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5297:       if (flg) {
5298:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5299:       } else {
5300:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5301:       }
5302:     }
5303:     if (mat->nullsp && mat->checknullspaceonassembly) {
5304:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5305:     }
5306:   }
5307:   inassm--;
5308:   return(0);
5309: }

5311: /*@
5312:    MatSetOption - Sets a parameter option for a matrix. Some options
5313:    may be specific to certain storage formats.  Some options
5314:    determine how values will be inserted (or added). Sorted,
5315:    row-oriented input will generally assemble the fastest. The default
5316:    is row-oriented.

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

5320:    Input Parameters:
5321: +  mat - the matrix
5322: .  option - the option, one of those listed below (and possibly others),
5323: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5325:   Options Describing Matrix Structure:
5326: +    MAT_SPD - symmetric positive definite
5327: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5328: .    MAT_HERMITIAN - transpose is the complex conjugation
5329: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5330: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5331:                             you set to be kept with all future use of the matrix
5332:                             including after MatAssemblyBegin/End() which could
5333:                             potentially change the symmetry structure, i.e. you
5334:                             KNOW the matrix will ALWAYS have the property you set.


5337:    Options For Use with MatSetValues():
5338:    Insert a logically dense subblock, which can be
5339: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5393:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5394:    searches during matrix assembly. When this flag is set, the hash table
5395:    is created during the first Matrix Assembly. This hash table is
5396:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5397:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5398:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5399:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5421:    Level: intermediate

5423: .seealso:  MatOption, Mat

5425: @*/
5426: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5427: {

5433:   if (op > 0) {
5436:   }

5438:   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);
5439:   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()");

5441:   switch (op) {
5442:   case MAT_NO_OFF_PROC_ENTRIES:
5443:     mat->nooffprocentries = flg;
5444:     return(0);
5445:     break;
5446:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5447:     mat->assembly_subset = flg;
5448:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5449: #if !defined(PETSC_HAVE_MPIUNI)
5450:       MatStashScatterDestroy_BTS(&mat->stash);
5451: #endif
5452:       mat->stash.first_assembly_done = PETSC_FALSE;
5453:     }
5454:     return(0);
5455:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5456:     mat->nooffproczerorows = flg;
5457:     return(0);
5458:     break;
5459:   case MAT_SPD:
5460:     mat->spd_set = PETSC_TRUE;
5461:     mat->spd     = flg;
5462:     if (flg) {
5463:       mat->symmetric                  = PETSC_TRUE;
5464:       mat->structurally_symmetric     = PETSC_TRUE;
5465:       mat->symmetric_set              = PETSC_TRUE;
5466:       mat->structurally_symmetric_set = PETSC_TRUE;
5467:     }
5468:     break;
5469:   case MAT_SYMMETRIC:
5470:     mat->symmetric = flg;
5471:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5472:     mat->symmetric_set              = PETSC_TRUE;
5473:     mat->structurally_symmetric_set = flg;
5474: #if !defined(PETSC_USE_COMPLEX)
5475:     mat->hermitian     = flg;
5476:     mat->hermitian_set = PETSC_TRUE;
5477: #endif
5478:     break;
5479:   case MAT_HERMITIAN:
5480:     mat->hermitian = flg;
5481:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5482:     mat->hermitian_set              = PETSC_TRUE;
5483:     mat->structurally_symmetric_set = flg;
5484: #if !defined(PETSC_USE_COMPLEX)
5485:     mat->symmetric     = flg;
5486:     mat->symmetric_set = PETSC_TRUE;
5487: #endif
5488:     break;
5489:   case MAT_STRUCTURALLY_SYMMETRIC:
5490:     mat->structurally_symmetric     = flg;
5491:     mat->structurally_symmetric_set = PETSC_TRUE;
5492:     break;
5493:   case MAT_SYMMETRY_ETERNAL:
5494:     mat->symmetric_eternal = flg;
5495:     break;
5496:   case MAT_STRUCTURE_ONLY:
5497:     mat->structure_only = flg;
5498:     break;
5499:   case MAT_SORTED_FULL:
5500:     mat->sortedfull = flg;
5501:     break;
5502:   default:
5503:     break;
5504:   }
5505:   if (mat->ops->setoption) {
5506:     (*mat->ops->setoption)(mat,op,flg);
5507:   }
5508:   return(0);
5509: }

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

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

5516:    Input Parameters:
5517: +  mat - the matrix
5518: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5526:    Level: intermediate

5528: .seealso:  MatOption, MatSetOption()

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

5537:   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);
5538:   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()");

5540:   switch (op) {
5541:   case MAT_NO_OFF_PROC_ENTRIES:
5542:     *flg = mat->nooffprocentries;
5543:     break;
5544:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5545:     *flg = mat->nooffproczerorows;
5546:     break;
5547:   case MAT_SYMMETRIC:
5548:     *flg = mat->symmetric;
5549:     break;
5550:   case MAT_HERMITIAN:
5551:     *flg = mat->hermitian;
5552:     break;
5553:   case MAT_STRUCTURALLY_SYMMETRIC:
5554:     *flg = mat->structurally_symmetric;
5555:     break;
5556:   case MAT_SYMMETRY_ETERNAL:
5557:     *flg = mat->symmetric_eternal;
5558:     break;
5559:   case MAT_SPD:
5560:     *flg = mat->spd;
5561:     break;
5562:   default:
5563:     break;
5564:   }
5565:   return(0);
5566: }

5568: /*@
5569:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5570:    this routine retains the old nonzero structure.

5572:    Logically Collective on Mat

5574:    Input Parameters:
5575: .  mat - the matrix

5577:    Level: intermediate

5579:    Notes:
5580:     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.
5581:    See the Performance chapter of the users manual for information on preallocating matrices.

5583: .seealso: MatZeroRows()
5584: @*/
5585: PetscErrorCode MatZeroEntries(Mat mat)
5586: {

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

5597:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5598:   (*mat->ops->zeroentries)(mat);
5599:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5600:   PetscObjectStateIncrease((PetscObject)mat);
5601:   return(0);
5602: }

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

5608:    Collective on Mat

5610:    Input Parameters:
5611: +  mat - the matrix
5612: .  numRows - the number of rows to remove
5613: .  rows - the global row indices
5614: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5615: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5616: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5635:    Level: intermediate

5637: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5638:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5639: @*/
5640: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5641: {

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

5653:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5654:   MatViewFromOptions(mat,NULL,"-mat_view");
5655:   PetscObjectStateIncrease((PetscObject)mat);
5656:   return(0);
5657: }

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

5663:    Collective on Mat

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

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

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

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

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

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

5689:    Level: intermediate

5691: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5692:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5693: @*/
5694: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5695: {
5697:   PetscInt       numRows;
5698:   const PetscInt *rows;

5705:   ISGetLocalSize(is,&numRows);
5706:   ISGetIndices(is,&rows);
5707:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5708:   ISRestoreIndices(is,&rows);
5709:   return(0);
5710: }

5712: /*@
5713:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5714:    of a set of rows of a matrix.

5716:    Collective on Mat

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

5726:    Notes:
5727:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5728:    but does not release memory.  For the dense and block diagonal
5729:    formats this does not alter the nonzero structure.

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

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

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

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

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

5750:    Level: intermediate

5752: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5753:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5754: @*/
5755: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5756: {

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

5768:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5769:   MatViewFromOptions(mat,NULL,"-mat_view");
5770:   PetscObjectStateIncrease((PetscObject)mat);
5771:   return(0);
5772: }

5774: /*@
5775:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5776:    of a set of rows of a matrix.

5778:    Collective on Mat

5780:    Input Parameters:
5781: +  mat - the matrix
5782: .  is - index set of rows to remove
5783: .  diag - value put in all diagonals of eliminated rows
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: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5814:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5815: @*/
5816: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5817: {
5818:   PetscInt       numRows;
5819:   const PetscInt *rows;

5826:   ISGetLocalSize(is,&numRows);
5827:   ISGetIndices(is,&rows);
5828:   MatZeroRows(mat,numRows,rows,diag,x,b);
5829:   ISRestoreIndices(is,&rows);
5830:   return(0);
5831: }

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

5837:    Collective on Mat

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

5847:    Notes:
5848:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5849:    but does not release memory.  For the dense and block diagonal
5850:    formats this does not alter the nonzero structure.

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

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

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

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

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

5870:    In Fortran idxm and idxn should be declared as
5871: $     MatStencil idxm(4,m)
5872:    and the values inserted using
5873: $    idxm(MatStencil_i,1) = i
5874: $    idxm(MatStencil_j,1) = j
5875: $    idxm(MatStencil_k,1) = k
5876: $    idxm(MatStencil_c,1) = c
5877:    etc

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

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

5887:    Level: intermediate

5889: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5890:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5891: @*/
5892: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5893: {
5894:   PetscInt       dim     = mat->stencil.dim;
5895:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5896:   PetscInt       *dims   = mat->stencil.dims+1;
5897:   PetscInt       *starts = mat->stencil.starts;
5898:   PetscInt       *dxm    = (PetscInt*) rows;
5899:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5907:   PetscMalloc1(numRows, &jdxm);
5908:   for (i = 0; i < numRows; ++i) {
5909:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5910:     for (j = 0; j < 3-sdim; ++j) dxm++;
5911:     /* Local index in X dir */
5912:     tmp = *dxm++ - starts[0];
5913:     /* Loop over remaining dimensions */
5914:     for (j = 0; j < dim-1; ++j) {
5915:       /* If nonlocal, set index to be negative */
5916:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5917:       /* Update local index */
5918:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5919:     }
5920:     /* Skip component slot if necessary */
5921:     if (mat->stencil.noc) dxm++;
5922:     /* Local row number */
5923:     if (tmp >= 0) {
5924:       jdxm[numNewRows++] = tmp;
5925:     }
5926:   }
5927:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5928:   PetscFree(jdxm);
5929:   return(0);
5930: }

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

5936:    Collective on Mat

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

5946:    Notes:
5947:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5948:    but does not release memory.  For the dense and block diagonal
5949:    formats this does not alter the nonzero structure.

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

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

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

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

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

5969:    In Fortran idxm and idxn should be declared as
5970: $     MatStencil idxm(4,m)
5971:    and the values inserted using
5972: $    idxm(MatStencil_i,1) = i
5973: $    idxm(MatStencil_j,1) = j
5974: $    idxm(MatStencil_k,1) = k
5975: $    idxm(MatStencil_c,1) = c
5976:    etc

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

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

5986:    Level: intermediate

5988: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5989:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
5990: @*/
5991: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5992: {
5993:   PetscInt       dim     = mat->stencil.dim;
5994:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5995:   PetscInt       *dims   = mat->stencil.dims+1;
5996:   PetscInt       *starts = mat->stencil.starts;
5997:   PetscInt       *dxm    = (PetscInt*) rows;
5998:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


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

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

6035:    Collective on Mat

6037:    Input Parameters:
6038: +  mat - the matrix
6039: .  numRows - the number of rows to remove
6040: .  rows - the global row indices
6041: .  diag - value put in all diagonals of eliminated rows
6042: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6043: -  b - optional vector of right hand side, that will be adjusted by provided solution

6045:    Notes:
6046:    Before calling MatZeroRowsLocal(), the user must first set the
6047:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6049:    For the AIJ matrix formats this removes the old nonzero structure,
6050:    but does not release memory.  For the dense and block diagonal
6051:    formats this does not alter the nonzero structure.

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

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

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

6064:    Level: intermediate

6066: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6067:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6068: @*/
6069: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6070: {

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

6081:   if (mat->ops->zerorowslocal) {
6082:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6083:   } else {
6084:     IS             is, newis;
6085:     const PetscInt *newRows;

6087:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6088:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6089:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6090:     ISGetIndices(newis,&newRows);
6091:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6092:     ISRestoreIndices(newis,&newRows);
6093:     ISDestroy(&newis);
6094:     ISDestroy(&is);
6095:   }
6096:   PetscObjectStateIncrease((PetscObject)mat);
6097:   return(0);
6098: }

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

6104:    Collective on Mat

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

6113:    Notes:
6114:    Before calling MatZeroRowsLocalIS(), the user must first set the
6115:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6117:    For the AIJ matrix formats this removes the old nonzero structure,
6118:    but does not release memory.  For the dense and block diagonal
6119:    formats this does not alter the nonzero structure.

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

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

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

6132:    Level: intermediate

6134: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6135:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6136: @*/
6137: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6138: {
6140:   PetscInt       numRows;
6141:   const PetscInt *rows;

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

6151:   ISGetLocalSize(is,&numRows);
6152:   ISGetIndices(is,&rows);
6153:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6154:   ISRestoreIndices(is,&rows);
6155:   return(0);
6156: }

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

6162:    Collective on Mat

6164:    Input Parameters:
6165: +  mat - the matrix
6166: .  numRows - the number of rows to remove
6167: .  rows - the global row indices
6168: .  diag - value put in all diagonals of eliminated rows
6169: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6170: -  b - optional vector of right hand side, that will be adjusted by provided solution

6172:    Notes:
6173:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6174:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6180:    Level: intermediate

6182: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6183:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6184: @*/
6185: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6186: {
6188:   IS             is, newis;
6189:   const PetscInt *newRows;

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

6199:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6200:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6201:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6202:   ISGetIndices(newis,&newRows);
6203:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6204:   ISRestoreIndices(newis,&newRows);
6205:   ISDestroy(&newis);
6206:   ISDestroy(&is);
6207:   PetscObjectStateIncrease((PetscObject)mat);
6208:   return(0);
6209: }

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

6215:    Collective on Mat

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

6224:    Notes:
6225:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6226:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6232:    Level: intermediate

6234: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6235:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6236: @*/
6237: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6238: {
6240:   PetscInt       numRows;
6241:   const PetscInt *rows;

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

6251:   ISGetLocalSize(is,&numRows);
6252:   ISGetIndices(is,&rows);
6253:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6254:   ISRestoreIndices(is,&rows);
6255:   return(0);
6256: }

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

6261:    Not Collective

6263:    Input Parameter:
6264: .  mat - the matrix

6266:    Output Parameters:
6267: +  m - the number of global rows
6268: -  n - the number of global columns

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

6272:    Level: beginner

6274: .seealso: MatGetLocalSize()
6275: @*/
6276: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6277: {
6280:   if (m) *m = mat->rmap->N;
6281:   if (n) *n = mat->cmap->N;
6282:   return(0);
6283: }

6285: /*@C
6286:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6287:    stored locally.  This information may be implementation dependent, so
6288:    use with care.

6290:    Not Collective

6292:    Input Parameters:
6293: .  mat - the matrix

6295:    Output Parameters:
6296: +  m - the number of local rows
6297: -  n - the number of local columns

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

6301:    Level: beginner

6303: .seealso: MatGetSize()
6304: @*/
6305: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6306: {
6311:   if (m) *m = mat->rmap->n;
6312:   if (n) *n = mat->cmap->n;
6313:   return(0);
6314: }

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

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

6322:    Input Parameters:
6323: .  mat - the matrix

6325:    Output Parameters:
6326: +  m - the global index of the first local column
6327: -  n - one more than the global index of the last local column

6329:    Notes:
6330:     both output parameters can be NULL on input.

6332:    Level: developer

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

6336: @*/
6337: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6338: {
6344:   MatCheckPreallocated(mat,1);
6345:   if (m) *m = mat->cmap->rstart;
6346:   if (n) *n = mat->cmap->rend;
6347:   return(0);
6348: }

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

6356:    Not Collective

6358:    Input Parameters:
6359: .  mat - the matrix

6361:    Output Parameters:
6362: +  m - the global index of the first local row
6363: -  n - one more than the global index of the last local row

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

6370:    Level: beginner

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

6374: @*/
6375: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6376: {
6382:   MatCheckPreallocated(mat,1);
6383:   if (m) *m = mat->rmap->rstart;
6384:   if (n) *n = mat->rmap->rend;
6385:   return(0);
6386: }

6388: /*@C
6389:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6390:    each process

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

6394:    Input Parameters:
6395: .  mat - the matrix

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

6400:    Level: beginner

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

6404: @*/
6405: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6406: {

6412:   MatCheckPreallocated(mat,1);
6413:   PetscLayoutGetRanges(mat->rmap,ranges);
6414:   return(0);
6415: }

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

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

6423:    Input Parameters:
6424: .  mat - the matrix

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

6429:    Level: beginner

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

6433: @*/
6434: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6435: {

6441:   MatCheckPreallocated(mat,1);
6442:   PetscLayoutGetRanges(mat->cmap,ranges);
6443:   return(0);
6444: }

6446: /*@C
6447:    MatGetOwnershipIS - Get row and column ownership as index sets

6449:    Not Collective

6451:    Input Arguments:
6452: .  A - matrix of type Elemental

6454:    Output Arguments:
6455: +  rows - rows in which this process owns elements
6456: -  cols - columns in which this process owns elements

6458:    Level: intermediate

6460: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6461: @*/
6462: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6463: {
6464:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6467:   MatCheckPreallocated(A,1);
6468:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6469:   if (f) {
6470:     (*f)(A,rows,cols);
6471:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6472:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6473:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6474:   }
6475:   return(0);
6476: }

6478: /*@C
6479:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6480:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6481:    to complete the factorization.

6483:    Collective on Mat

6485:    Input Parameters:
6486: +  mat - the matrix
6487: .  row - row permutation
6488: .  column - column permutation
6489: -  info - structure containing
6490: $      levels - number of levels of fill.
6491: $      expected fill - as ratio of original fill.
6492: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6493:                 missing diagonal entries)

6495:    Output Parameters:
6496: .  fact - new matrix that has been symbolically factored

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

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

6505:    Level: developer

6507: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6508:           MatGetOrdering(), MatFactorInfo

6510:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6515:    References:
6516:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6517: @*/
6518: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6519: {

6529:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6530:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6531:   if (!(fact)->ops->ilufactorsymbolic) {
6532:     MatSolverType spackage;
6533:     MatFactorGetSolverType(fact,&spackage);
6534:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6535:   }
6536:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6537:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6538:   MatCheckPreallocated(mat,2);

6540:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6541:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6542:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6543:   return(0);
6544: }

6546: /*@C
6547:    MatICCFactorSymbolic - Performs symbolic incomplete
6548:    Cholesky factorization for a symmetric matrix.  Use
6549:    MatCholeskyFactorNumeric() to complete the factorization.

6551:    Collective on Mat

6553:    Input Parameters:
6554: +  mat - the matrix
6555: .  perm - row and column permutation
6556: -  info - structure containing
6557: $      levels - number of levels of fill.
6558: $      expected fill - as ratio of original fill.

6560:    Output Parameter:
6561: .  fact - the factored matrix

6563:    Notes:
6564:    Most users should employ the KSP interface for linear solvers
6565:    instead of working directly with matrix algebra routines such as this.
6566:    See, e.g., KSPCreate().

6568:    Level: developer

6570: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6572:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6577:    References:
6578:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6579: @*/
6580: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6581: {

6590:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6591:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6592:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6593:   if (!(fact)->ops->iccfactorsymbolic) {
6594:     MatSolverType spackage;
6595:     MatFactorGetSolverType(fact,&spackage);
6596:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6597:   }
6598:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6599:   MatCheckPreallocated(mat,2);

6601:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6602:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6603:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6604:   return(0);
6605: }

6607: /*@C
6608:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6609:    points to an array of valid matrices, they may be reused to store the new
6610:    submatrices.

6612:    Collective on Mat

6614:    Input Parameters:
6615: +  mat - the matrix
6616: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6617: .  irow, icol - index sets of rows and columns to extract
6618: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6620:    Output Parameter:
6621: .  submat - the array of submatrices

6623:    Notes:
6624:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6625:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6626:    to extract a parallel submatrix.

6628:    Some matrix types place restrictions on the row and column
6629:    indices, such as that they be sorted or that they be equal to each other.

6631:    The index sets may not have duplicate entries.

6633:    When extracting submatrices from a parallel matrix, each processor can
6634:    form a different submatrix by setting the rows and columns of its
6635:    individual index sets according to the local submatrix desired.

6637:    When finished using the submatrices, the user should destroy
6638:    them with MatDestroySubMatrices().

6640:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6641:    original matrix has not changed from that last call to MatCreateSubMatrices().

6643:    This routine creates the matrices in submat; you should NOT create them before
6644:    calling it. It also allocates the array of matrix pointers submat.

6646:    For BAIJ matrices the index sets must respect the block structure, that is if they
6647:    request one row/column in a block, they must request all rows/columns that are in
6648:    that block. For example, if the block size is 2 you cannot request just row 0 and
6649:    column 0.

6651:    Fortran Note:
6652:    The Fortran interface is slightly different from that given below; it
6653:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6655:    Level: advanced


6658: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6659: @*/
6660: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6661: {
6663:   PetscInt       i;
6664:   PetscBool      eq;

6669:   if (n) {
6674:   }
6676:   if (n && scall == MAT_REUSE_MATRIX) {
6679:   }
6680:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6681:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6682:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6683:   MatCheckPreallocated(mat,1);

6685:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6686:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6687:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6688:   for (i=0; i<n; i++) {
6689:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6690:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6691:       ISEqual(irow[i],icol[i],&eq);
6692:       if (eq) {
6693:         if (mat->symmetric) {
6694:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6695:         } else if (mat->hermitian) {
6696:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6697:         } else if (mat->structurally_symmetric) {
6698:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6699:         }
6700:       }
6701:     }
6702:   }
6703:   return(0);
6704: }

6706: /*@C
6707:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6709:    Collective on Mat

6711:    Input Parameters:
6712: +  mat - the matrix
6713: .  n   - the number of submatrixes to be extracted
6714: .  irow, icol - index sets of rows and columns to extract
6715: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6717:    Output Parameter:
6718: .  submat - the array of submatrices

6720:    Level: advanced


6723: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6724: @*/
6725: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6726: {
6728:   PetscInt       i;
6729:   PetscBool      eq;

6734:   if (n) {
6739:   }
6741:   if (n && scall == MAT_REUSE_MATRIX) {
6744:   }
6745:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6746:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6747:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6748:   MatCheckPreallocated(mat,1);

6750:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6751:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6752:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6753:   for (i=0; i<n; i++) {
6754:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6755:       ISEqual(irow[i],icol[i],&eq);
6756:       if (eq) {
6757:         if (mat->symmetric) {
6758:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6759:         } else if (mat->hermitian) {
6760:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6761:         } else if (mat->structurally_symmetric) {
6762:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6763:         }
6764:       }
6765:     }
6766:   }
6767:   return(0);
6768: }

6770: /*@C
6771:    MatDestroyMatrices - Destroys an array of matrices.

6773:    Collective on Mat

6775:    Input Parameters:
6776: +  n - the number of local matrices
6777: -  mat - the matrices (note that this is a pointer to the array of matrices)

6779:    Level: advanced

6781:     Notes:
6782:     Frees not only the matrices, but also the array that contains the matrices
6783:            In Fortran will not free the array.

6785: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6786: @*/
6787: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6788: {
6790:   PetscInt       i;

6793:   if (!*mat) return(0);
6794:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6797:   for (i=0; i<n; i++) {
6798:     MatDestroy(&(*mat)[i]);
6799:   }

6801:   /* memory is allocated even if n = 0 */
6802:   PetscFree(*mat);
6803:   return(0);
6804: }

6806: /*@C
6807:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6809:    Collective on Mat

6811:    Input Parameters:
6812: +  n - the number of local matrices
6813: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6814:                        sequence of MatCreateSubMatrices())

6816:    Level: advanced

6818:     Notes:
6819:     Frees not only the matrices, but also the array that contains the matrices
6820:            In Fortran will not free the array.

6822: .seealso: MatCreateSubMatrices()
6823: @*/
6824: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6825: {
6827:   Mat            mat0;

6830:   if (!*mat) return(0);
6831:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6832:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6835:   mat0 = (*mat)[0];
6836:   if (mat0 && mat0->ops->destroysubmatrices) {
6837:     (mat0->ops->destroysubmatrices)(n,mat);
6838:   } else {
6839:     MatDestroyMatrices(n,mat);
6840:   }
6841:   return(0);
6842: }

6844: /*@C
6845:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6847:    Collective on Mat

6849:    Input Parameters:
6850: .  mat - the matrix

6852:    Output Parameter:
6853: .  matstruct - the sequential matrix with the nonzero structure of mat

6855:   Level: intermediate

6857: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6858: @*/
6859: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6860: {


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

6871:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6872:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6873:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6874:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6875:   return(0);
6876: }

6878: /*@C
6879:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6881:    Collective on Mat

6883:    Input Parameters:
6884: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6885:                        sequence of MatGetSequentialNonzeroStructure())

6887:    Level: advanced

6889:     Notes:
6890:     Frees not only the matrices, but also the array that contains the matrices

6892: .seealso: MatGetSeqNonzeroStructure()
6893: @*/
6894: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6895: {

6900:   MatDestroy(mat);
6901:   return(0);
6902: }

6904: /*@
6905:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6906:    replaces the index sets by larger ones that represent submatrices with
6907:    additional overlap.

6909:    Collective on Mat

6911:    Input Parameters:
6912: +  mat - the matrix
6913: .  n   - the number of index sets
6914: .  is  - the array of index sets (these index sets will changed during the call)
6915: -  ov  - the additional overlap requested

6917:    Options Database:
6918: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

6920:    Level: developer


6923: .seealso: MatCreateSubMatrices()
6924: @*/
6925: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6926: {

6932:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6933:   if (n) {
6936:   }
6937:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6938:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6939:   MatCheckPreallocated(mat,1);

6941:   if (!ov) return(0);
6942:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6943:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6944:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
6945:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6946:   return(0);
6947: }


6950: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

6952: /*@
6953:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
6954:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
6955:    additional overlap.

6957:    Collective on Mat

6959:    Input Parameters:
6960: +  mat - the matrix
6961: .  n   - the number of index sets
6962: .  is  - the array of index sets (these index sets will changed during the call)
6963: -  ov  - the additional overlap requested

6965:    Options Database:
6966: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

6968:    Level: developer


6971: .seealso: MatCreateSubMatrices()
6972: @*/
6973: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
6974: {
6975:   PetscInt       i;

6981:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6982:   if (n) {
6985:   }
6986:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6987:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6988:   MatCheckPreallocated(mat,1);
6989:   if (!ov) return(0);
6990:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6991:   for(i=0; i<n; i++){
6992:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
6993:   }
6994:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6995:   return(0);
6996: }




7001: /*@
7002:    MatGetBlockSize - Returns the matrix block size.

7004:    Not Collective

7006:    Input Parameter:
7007: .  mat - the matrix

7009:    Output Parameter:
7010: .  bs - block size

7012:    Notes:
7013:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7015:    If the block size has not been set yet this routine returns 1.

7017:    Level: intermediate

7019: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7020: @*/
7021: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7022: {
7026:   *bs = PetscAbs(mat->rmap->bs);
7027:   return(0);
7028: }

7030: /*@
7031:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7033:    Not Collective

7035:    Input Parameter:
7036: .  mat - the matrix

7038:    Output Parameter:
7039: +  rbs - row block size
7040: -  cbs - column block size

7042:    Notes:
7043:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7044:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7046:    If a block size has not been set yet this routine returns 1.

7048:    Level: intermediate

7050: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7051: @*/
7052: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7053: {
7058:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7059:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7060:   return(0);
7061: }

7063: /*@
7064:    MatSetBlockSize - Sets the matrix block size.

7066:    Logically Collective on Mat

7068:    Input Parameters:
7069: +  mat - the matrix
7070: -  bs - block size

7072:    Notes:
7073:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7074:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7076:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7077:     is compatible with the matrix local sizes.

7079:    Level: intermediate

7081: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7082: @*/
7083: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7084: {

7090:   MatSetBlockSizes(mat,bs,bs);
7091:   return(0);
7092: }

7094: /*@
7095:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7097:    Logically Collective on Mat

7099:    Input Parameters:
7100: +  mat - the matrix
7101: .  nblocks - the number of blocks on this process
7102: -  bsizes - the block sizes

7104:    Notes:
7105:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7107:    Level: intermediate

7109: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7110: @*/
7111: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7112: {
7114:   PetscInt       i,ncnt = 0, nlocal;

7118:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7119:   MatGetLocalSize(mat,&nlocal,NULL);
7120:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7121:   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);
7122:   PetscFree(mat->bsizes);
7123:   mat->nblocks = nblocks;
7124:   PetscMalloc1(nblocks,&mat->bsizes);
7125:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7126:   return(0);
7127: }

7129: /*@C
7130:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7132:    Logically Collective on Mat

7134:    Input Parameters:
7135: .  mat - the matrix

7137:    Output Parameters:
7138: +  nblocks - the number of blocks on this process
7139: -  bsizes - the block sizes

7141:    Notes: Currently not supported from Fortran

7143:    Level: intermediate

7145: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7146: @*/
7147: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7148: {
7151:   *nblocks = mat->nblocks;
7152:   *bsizes  = mat->bsizes;
7153:   return(0);
7154: }

7156: /*@
7157:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7159:    Logically Collective on Mat

7161:    Input Parameters:
7162: +  mat - the matrix
7163: .  rbs - row block size
7164: -  cbs - column block size

7166:    Notes:
7167:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7168:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7169:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7171:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7172:     are compatible with the matrix local sizes.

7174:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7176:    Level: intermediate

7178: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7179: @*/
7180: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7181: {

7188:   if (mat->ops->setblocksizes) {
7189:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7190:   }
7191:   if (mat->rmap->refcnt) {
7192:     ISLocalToGlobalMapping l2g = NULL;
7193:     PetscLayout            nmap = NULL;

7195:     PetscLayoutDuplicate(mat->rmap,&nmap);
7196:     if (mat->rmap->mapping) {
7197:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7198:     }
7199:     PetscLayoutDestroy(&mat->rmap);
7200:     mat->rmap = nmap;
7201:     mat->rmap->mapping = l2g;
7202:   }
7203:   if (mat->cmap->refcnt) {
7204:     ISLocalToGlobalMapping l2g = NULL;
7205:     PetscLayout            nmap = NULL;

7207:     PetscLayoutDuplicate(mat->cmap,&nmap);
7208:     if (mat->cmap->mapping) {
7209:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7210:     }
7211:     PetscLayoutDestroy(&mat->cmap);
7212:     mat->cmap = nmap;
7213:     mat->cmap->mapping = l2g;
7214:   }
7215:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7216:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7217:   return(0);
7218: }

7220: /*@
7221:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7223:    Logically Collective on Mat

7225:    Input Parameters:
7226: +  mat - the matrix
7227: .  fromRow - matrix from which to copy row block size
7228: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7230:    Level: developer

7232: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7233: @*/
7234: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7235: {

7242:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7243:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7244:   return(0);
7245: }

7247: /*@
7248:    MatResidual - Default routine to calculate the residual.

7250:    Collective on Mat

7252:    Input Parameters:
7253: +  mat - the matrix
7254: .  b   - the right-hand-side
7255: -  x   - the approximate solution

7257:    Output Parameter:
7258: .  r - location to store the residual

7260:    Level: developer

7262: .seealso: PCMGSetResidual()
7263: @*/
7264: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7265: {

7274:   MatCheckPreallocated(mat,1);
7275:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7276:   if (!mat->ops->residual) {
7277:     MatMult(mat,x,r);
7278:     VecAYPX(r,-1.0,b);
7279:   } else {
7280:     (*mat->ops->residual)(mat,b,x,r);
7281:   }
7282:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7283:   return(0);
7284: }

7286: /*@C
7287:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7289:    Collective on Mat

7291:     Input Parameters:
7292: +   mat - the matrix
7293: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7294: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7295: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7296:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7297:                  always used.

7299:     Output Parameters:
7300: +   n - number of rows in the (possibly compressed) matrix
7301: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7302: .   ja - the column indices
7303: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7304:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7306:     Level: developer

7308:     Notes:
7309:     You CANNOT change any of the ia[] or ja[] values.

7311:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7313:     Fortran Notes:
7314:     In Fortran use
7315: $
7316: $      PetscInt ia(1), ja(1)
7317: $      PetscOffset iia, jja
7318: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7319: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7321:      or
7322: $
7323: $    PetscInt, pointer :: ia(:),ja(:)
7324: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7325: $    ! Access the ith and jth entries via ia(i) and ja(j)

7327: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7328: @*/
7329: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7330: {

7340:   MatCheckPreallocated(mat,1);
7341:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7342:   else {
7343:     *done = PETSC_TRUE;
7344:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7345:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7346:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7347:   }
7348:   return(0);
7349: }

7351: /*@C
7352:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7354:     Collective on Mat

7356:     Input Parameters:
7357: +   mat - the matrix
7358: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7359: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7360:                 symmetrized
7361: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7362:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7363:                  always used.
7364: .   n - number of columns in the (possibly compressed) matrix
7365: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7366: -   ja - the row indices

7368:     Output Parameters:
7369: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7371:     Level: developer

7373: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7374: @*/
7375: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7376: {

7386:   MatCheckPreallocated(mat,1);
7387:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7388:   else {
7389:     *done = PETSC_TRUE;
7390:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7391:   }
7392:   return(0);
7393: }

7395: /*@C
7396:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7397:     MatGetRowIJ().

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 - size of (possibly compressed) matrix
7410: .   ia - the row pointers
7411: -   ja - the column indices

7413:     Output Parameters:
7414: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7416:     Note:
7417:     This routine zeros out n, ia, and ja. This is to prevent accidental
7418:     us of the array after it has been restored. If you pass NULL, it will
7419:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7421:     Level: developer

7423: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7424: @*/
7425: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7426: {

7435:   MatCheckPreallocated(mat,1);

7437:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7438:   else {
7439:     *done = PETSC_TRUE;
7440:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7441:     if (n)  *n = 0;
7442:     if (ia) *ia = NULL;
7443:     if (ja) *ja = NULL;
7444:   }
7445:   return(0);
7446: }

7448: /*@C
7449:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7450:     MatGetColumnIJ().

7452:     Collective on Mat

7454:     Input Parameters:
7455: +   mat - the matrix
7456: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7457: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7458:                 symmetrized
7459: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7460:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7461:                  always used.

7463:     Output Parameters:
7464: +   n - size of (possibly compressed) matrix
7465: .   ia - the column pointers
7466: .   ja - the row indices
7467: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7469:     Level: developer

7471: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7472: @*/
7473: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7474: {

7483:   MatCheckPreallocated(mat,1);

7485:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7486:   else {
7487:     *done = PETSC_TRUE;
7488:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7489:     if (n)  *n = 0;
7490:     if (ia) *ia = NULL;
7491:     if (ja) *ja = NULL;
7492:   }
7493:   return(0);
7494: }

7496: /*@C
7497:     MatColoringPatch -Used inside matrix coloring routines that
7498:     use MatGetRowIJ() and/or MatGetColumnIJ().

7500:     Collective on Mat

7502:     Input Parameters:
7503: +   mat - the matrix
7504: .   ncolors - max color value
7505: .   n   - number of entries in colorarray
7506: -   colorarray - array indicating color for each column

7508:     Output Parameters:
7509: .   iscoloring - coloring generated using colorarray information

7511:     Level: developer

7513: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7515: @*/
7516: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7517: {

7525:   MatCheckPreallocated(mat,1);

7527:   if (!mat->ops->coloringpatch) {
7528:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7529:   } else {
7530:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7531:   }
7532:   return(0);
7533: }


7536: /*@
7537:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7539:    Logically Collective on Mat

7541:    Input Parameter:
7542: .  mat - the factored matrix to be reset

7544:    Notes:
7545:    This routine should be used only with factored matrices formed by in-place
7546:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7547:    format).  This option can save memory, for example, when solving nonlinear
7548:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7549:    ILU(0) preconditioner.

7551:    Note that one can specify in-place ILU(0) factorization by calling
7552: .vb
7553:      PCType(pc,PCILU);
7554:      PCFactorSeUseInPlace(pc);
7555: .ve
7556:    or by using the options -pc_type ilu -pc_factor_in_place

7558:    In-place factorization ILU(0) can also be used as a local
7559:    solver for the blocks within the block Jacobi or additive Schwarz
7560:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7561:    for details on setting local solver options.

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

7567:    Level: developer

7569: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7571: @*/
7572: PetscErrorCode MatSetUnfactored(Mat mat)
7573: {

7579:   MatCheckPreallocated(mat,1);
7580:   mat->factortype = MAT_FACTOR_NONE;
7581:   if (!mat->ops->setunfactored) return(0);
7582:   (*mat->ops->setunfactored)(mat);
7583:   return(0);
7584: }

7586: /*MC
7587:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7589:     Synopsis:
7590:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7592:     Not collective

7594:     Input Parameter:
7595: .   x - matrix

7597:     Output Parameters:
7598: +   xx_v - the Fortran90 pointer to the array
7599: -   ierr - error code

7601:     Example of Usage:
7602: .vb
7603:       PetscScalar, pointer xx_v(:,:)
7604:       ....
7605:       call MatDenseGetArrayF90(x,xx_v,ierr)
7606:       a = xx_v(3)
7607:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7608: .ve

7610:     Level: advanced

7612: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7614: M*/

7616: /*MC
7617:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7618:     accessed with MatDenseGetArrayF90().

7620:     Synopsis:
7621:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7623:     Not collective

7625:     Input Parameters:
7626: +   x - matrix
7627: -   xx_v - the Fortran90 pointer to the array

7629:     Output Parameter:
7630: .   ierr - error code

7632:     Example of Usage:
7633: .vb
7634:        PetscScalar, pointer xx_v(:,:)
7635:        ....
7636:        call MatDenseGetArrayF90(x,xx_v,ierr)
7637:        a = xx_v(3)
7638:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7639: .ve

7641:     Level: advanced

7643: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7645: M*/


7648: /*MC
7649:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7651:     Synopsis:
7652:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7654:     Not collective

7656:     Input Parameter:
7657: .   x - matrix

7659:     Output Parameters:
7660: +   xx_v - the Fortran90 pointer to the array
7661: -   ierr - error code

7663:     Example of Usage:
7664: .vb
7665:       PetscScalar, pointer xx_v(:)
7666:       ....
7667:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7668:       a = xx_v(3)
7669:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7670: .ve

7672:     Level: advanced

7674: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7676: M*/

7678: /*MC
7679:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7680:     accessed with MatSeqAIJGetArrayF90().

7682:     Synopsis:
7683:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7685:     Not collective

7687:     Input Parameters:
7688: +   x - matrix
7689: -   xx_v - the Fortran90 pointer to the array

7691:     Output Parameter:
7692: .   ierr - error code

7694:     Example of Usage:
7695: .vb
7696:        PetscScalar, pointer xx_v(:)
7697:        ....
7698:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7699:        a = xx_v(3)
7700:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7701: .ve

7703:     Level: advanced

7705: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7707: M*/


7710: /*@
7711:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7712:                       as the original matrix.

7714:     Collective on Mat

7716:     Input Parameters:
7717: +   mat - the original matrix
7718: .   isrow - parallel IS containing the rows this processor should obtain
7719: .   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.
7720: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7722:     Output Parameter:
7723: .   newmat - the new submatrix, of the same type as the old

7725:     Level: advanced

7727:     Notes:
7728:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7730:     Some matrix types place restrictions on the row and column indices, such
7731:     as that they be sorted or that they be equal to each other.

7733:     The index sets may not have duplicate entries.

7735:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7736:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7737:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7738:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7739:    you are finished using it.

7741:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7742:     the input matrix.

7744:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7746:    Example usage:
7747:    Consider the following 8x8 matrix with 34 non-zero values, that is
7748:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7749:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7750:    as follows:

7752: .vb
7753:             1  2  0  |  0  3  0  |  0  4
7754:     Proc0   0  5  6  |  7  0  0  |  8  0
7755:             9  0 10  | 11  0  0  | 12  0
7756:     -------------------------------------
7757:            13  0 14  | 15 16 17  |  0  0
7758:     Proc1   0 18  0  | 19 20 21  |  0  0
7759:             0  0  0  | 22 23  0  | 24  0
7760:     -------------------------------------
7761:     Proc2  25 26 27  |  0  0 28  | 29  0
7762:            30  0  0  | 31 32 33  |  0 34
7763: .ve

7765:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7767: .vb
7768:             2  0  |  0  3  0  |  0
7769:     Proc0   5  6  |  7  0  0  |  8
7770:     -------------------------------
7771:     Proc1  18  0  | 19 20 21  |  0
7772:     -------------------------------
7773:     Proc2  26 27  |  0  0 28  | 29
7774:             0  0  | 31 32 33  |  0
7775: .ve


7778: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7779: @*/
7780: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7781: {
7783:   PetscMPIInt    size;
7784:   Mat            *local;
7785:   IS             iscoltmp;

7794:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7795:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7797:   MatCheckPreallocated(mat,1);
7798:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7800:   if (!iscol || isrow == iscol) {
7801:     PetscBool   stride;
7802:     PetscMPIInt grabentirematrix = 0,grab;
7803:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7804:     if (stride) {
7805:       PetscInt first,step,n,rstart,rend;
7806:       ISStrideGetInfo(isrow,&first,&step);
7807:       if (step == 1) {
7808:         MatGetOwnershipRange(mat,&rstart,&rend);
7809:         if (rstart == first) {
7810:           ISGetLocalSize(isrow,&n);
7811:           if (n == rend-rstart) {
7812:             grabentirematrix = 1;
7813:           }
7814:         }
7815:       }
7816:     }
7817:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7818:     if (grab) {
7819:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7820:       if (cll == MAT_INITIAL_MATRIX) {
7821:         *newmat = mat;
7822:         PetscObjectReference((PetscObject)mat);
7823:       }
7824:       return(0);
7825:     }
7826:   }

7828:   if (!iscol) {
7829:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7830:   } else {
7831:     iscoltmp = iscol;
7832:   }

7834:   /* if original matrix is on just one processor then use submatrix generated */
7835:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7836:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7837:     goto setproperties;
7838:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7839:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7840:     *newmat = *local;
7841:     PetscFree(local);
7842:     goto setproperties;
7843:   } else if (!mat->ops->createsubmatrix) {
7844:     /* Create a new matrix type that implements the operation using the full matrix */
7845:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7846:     switch (cll) {
7847:     case MAT_INITIAL_MATRIX:
7848:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7849:       break;
7850:     case MAT_REUSE_MATRIX:
7851:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7852:       break;
7853:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7854:     }
7855:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7856:     goto setproperties;
7857:   }

7859:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7860:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7861:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7862:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

7864:   /* Propagate symmetry information for diagonal blocks */
7865: setproperties:
7866:   if (isrow == iscoltmp) {
7867:     if (mat->symmetric_set && mat->symmetric) {
7868:       MatSetOption(*newmat,MAT_SYMMETRIC,PETSC_TRUE);
7869:     }
7870:     if (mat->structurally_symmetric_set && mat->structurally_symmetric) {
7871:       MatSetOption(*newmat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
7872:     }
7873:     if (mat->hermitian_set && mat->hermitian) {
7874:       MatSetOption(*newmat,MAT_HERMITIAN,PETSC_TRUE);
7875:     }
7876:     if (mat->spd_set && mat->spd) {
7877:       MatSetOption(*newmat,MAT_SPD,PETSC_TRUE);
7878:     }
7879:   }

7881:   if (!iscol) {ISDestroy(&iscoltmp);}
7882:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7883:   return(0);
7884: }

7886: /*@
7887:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7888:    used during the assembly process to store values that belong to
7889:    other processors.

7891:    Not Collective

7893:    Input Parameters:
7894: +  mat   - the matrix
7895: .  size  - the initial size of the stash.
7896: -  bsize - the initial size of the block-stash(if used).

7898:    Options Database Keys:
7899: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7900: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7902:    Level: intermediate

7904:    Notes:
7905:      The block-stash is used for values set with MatSetValuesBlocked() while
7906:      the stash is used for values set with MatSetValues()

7908:      Run with the option -info and look for output of the form
7909:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7910:      to determine the appropriate value, MM, to use for size and
7911:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7912:      to determine the value, BMM to use for bsize


7915: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

7917: @*/
7918: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7919: {

7925:   MatStashSetInitialSize_Private(&mat->stash,size);
7926:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
7927:   return(0);
7928: }

7930: /*@
7931:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7932:      the matrix

7934:    Neighbor-wise Collective on Mat

7936:    Input Parameters:
7937: +  mat   - the matrix
7938: .  x,y - the vectors
7939: -  w - where the result is stored

7941:    Level: intermediate

7943:    Notes:
7944:     w may be the same vector as y.

7946:     This allows one to use either the restriction or interpolation (its transpose)
7947:     matrix to do the interpolation

7949: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

7951: @*/
7952: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
7953: {
7955:   PetscInt       M,N,Ny;

7963:   MatCheckPreallocated(A,1);
7964:   MatGetSize(A,&M,&N);
7965:   VecGetSize(y,&Ny);
7966:   if (M == Ny) {
7967:     MatMultAdd(A,x,y,w);
7968:   } else {
7969:     MatMultTransposeAdd(A,x,y,w);
7970:   }
7971:   return(0);
7972: }

7974: /*@
7975:    MatInterpolate - y = A*x or A'*x depending on the shape of
7976:      the matrix

7978:    Neighbor-wise Collective on Mat

7980:    Input Parameters:
7981: +  mat   - the matrix
7982: -  x,y - the vectors

7984:    Level: intermediate

7986:    Notes:
7987:     This allows one to use either the restriction or interpolation (its transpose)
7988:     matrix to do the interpolation

7990: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

7992: @*/
7993: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
7994: {
7996:   PetscInt       M,N,Ny;

8003:   MatCheckPreallocated(A,1);
8004:   MatGetSize(A,&M,&N);
8005:   VecGetSize(y,&Ny);
8006:   if (M == Ny) {
8007:     MatMult(A,x,y);
8008:   } else {
8009:     MatMultTranspose(A,x,y);
8010:   }
8011:   return(0);
8012: }

8014: /*@
8015:    MatRestrict - y = A*x or A'*x

8017:    Neighbor-wise Collective on Mat

8019:    Input Parameters:
8020: +  mat   - the matrix
8021: -  x,y - the vectors

8023:    Level: intermediate

8025:    Notes:
8026:     This allows one to use either the restriction or interpolation (its transpose)
8027:     matrix to do the restriction

8029: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8031: @*/
8032: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8033: {
8035:   PetscInt       M,N,Ny;

8042:   MatCheckPreallocated(A,1);

8044:   MatGetSize(A,&M,&N);
8045:   VecGetSize(y,&Ny);
8046:   if (M == Ny) {
8047:     MatMult(A,x,y);
8048:   } else {
8049:     MatMultTranspose(A,x,y);
8050:   }
8051:   return(0);
8052: }

8054: /*@
8055:    MatGetNullSpace - retrieves the null space of a matrix.

8057:    Logically Collective on Mat

8059:    Input Parameters:
8060: +  mat - the matrix
8061: -  nullsp - the null space object

8063:    Level: developer

8065: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8066: @*/
8067: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8068: {
8072:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8073:   return(0);
8074: }

8076: /*@
8077:    MatSetNullSpace - attaches a null space to a matrix.

8079:    Logically Collective on Mat

8081:    Input Parameters:
8082: +  mat - the matrix
8083: -  nullsp - the null space object

8085:    Level: advanced

8087:    Notes:
8088:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8090:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8091:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8093:       You can remove the null space by calling this routine with an nullsp of NULL


8096:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8097:    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).
8098:    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
8099:    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
8100:    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).

8102:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8104:     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
8105:     routine also automatically calls MatSetTransposeNullSpace().

8107: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8108: @*/
8109: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8110: {

8116:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8117:   MatNullSpaceDestroy(&mat->nullsp);
8118:   mat->nullsp = nullsp;
8119:   if (mat->symmetric_set && mat->symmetric) {
8120:     MatSetTransposeNullSpace(mat,nullsp);
8121:   }
8122:   return(0);
8123: }

8125: /*@
8126:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8128:    Logically Collective on Mat

8130:    Input Parameters:
8131: +  mat - the matrix
8132: -  nullsp - the null space object

8134:    Level: developer

8136: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8137: @*/
8138: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8139: {
8144:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8145:   return(0);
8146: }

8148: /*@
8149:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8151:    Logically Collective on Mat

8153:    Input Parameters:
8154: +  mat - the matrix
8155: -  nullsp - the null space object

8157:    Level: advanced

8159:    Notes:
8160:       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.
8161:       You must also call MatSetNullSpace()


8164:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8165:    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).
8166:    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
8167:    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
8168:    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).

8170:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8172: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8173: @*/
8174: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8175: {

8181:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8182:   MatNullSpaceDestroy(&mat->transnullsp);
8183:   mat->transnullsp = nullsp;
8184:   return(0);
8185: }

8187: /*@
8188:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8189:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8191:    Logically Collective on Mat

8193:    Input Parameters:
8194: +  mat - the matrix
8195: -  nullsp - the null space object

8197:    Level: advanced

8199:    Notes:
8200:       Overwrites any previous near null space that may have been attached

8202:       You can remove the null space by calling this routine with an nullsp of NULL

8204: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8205: @*/
8206: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8207: {

8214:   MatCheckPreallocated(mat,1);
8215:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8216:   MatNullSpaceDestroy(&mat->nearnullsp);
8217:   mat->nearnullsp = nullsp;
8218:   return(0);
8219: }

8221: /*@
8222:    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()

8224:    Not Collective

8226:    Input Parameters:
8227: .  mat - the matrix

8229:    Output Parameters:
8230: .  nullsp - the null space object, NULL if not set

8232:    Level: developer

8234: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8235: @*/
8236: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8237: {
8242:   MatCheckPreallocated(mat,1);
8243:   *nullsp = mat->nearnullsp;
8244:   return(0);
8245: }

8247: /*@C
8248:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8250:    Collective on Mat

8252:    Input Parameters:
8253: +  mat - the matrix
8254: .  row - row/column permutation
8255: .  fill - expected fill factor >= 1.0
8256: -  level - level of fill, for ICC(k)

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

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

8266:    Level: developer


8269: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8274: @*/
8275: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8276: {

8284:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8285:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8286:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8287:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8288:   MatCheckPreallocated(mat,1);
8289:   (*mat->ops->iccfactor)(mat,row,info);
8290:   PetscObjectStateIncrease((PetscObject)mat);
8291:   return(0);
8292: }

8294: /*@
8295:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8296:          ghosted ones.

8298:    Not Collective

8300:    Input Parameters:
8301: +  mat - the matrix
8302: -  diag = the diagonal values, including ghost ones

8304:    Level: developer

8306:    Notes:
8307:     Works only for MPIAIJ and MPIBAIJ matrices

8309: .seealso: MatDiagonalScale()
8310: @*/
8311: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8312: {
8314:   PetscMPIInt    size;


8321:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8322:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8323:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8324:   if (size == 1) {
8325:     PetscInt n,m;
8326:     VecGetSize(diag,&n);
8327:     MatGetSize(mat,0,&m);
8328:     if (m == n) {
8329:       MatDiagonalScale(mat,0,diag);
8330:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8331:   } else {
8332:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8333:   }
8334:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8335:   PetscObjectStateIncrease((PetscObject)mat);
8336:   return(0);
8337: }

8339: /*@
8340:    MatGetInertia - Gets the inertia from a factored matrix

8342:    Collective on Mat

8344:    Input Parameter:
8345: .  mat - the matrix

8347:    Output Parameters:
8348: +   nneg - number of negative eigenvalues
8349: .   nzero - number of zero eigenvalues
8350: -   npos - number of positive eigenvalues

8352:    Level: advanced

8354:    Notes:
8355:     Matrix must have been factored by MatCholeskyFactor()


8358: @*/
8359: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8360: {

8366:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8367:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8368:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8369:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8370:   return(0);
8371: }

8373: /* ----------------------------------------------------------------*/
8374: /*@C
8375:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8377:    Neighbor-wise Collective on Mats

8379:    Input Parameters:
8380: +  mat - the factored matrix
8381: -  b - the right-hand-side vectors

8383:    Output Parameter:
8384: .  x - the result vectors

8386:    Notes:
8387:    The vectors b and x cannot be the same.  I.e., one cannot
8388:    call MatSolves(A,x,x).

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

8395:    Level: developer

8397: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8398: @*/
8399: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8400: {

8406:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8407:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8408:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8410:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8411:   MatCheckPreallocated(mat,1);
8412:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8413:   (*mat->ops->solves)(mat,b,x);
8414:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8415:   return(0);
8416: }

8418: /*@
8419:    MatIsSymmetric - Test whether a matrix is symmetric

8421:    Collective on Mat

8423:    Input Parameter:
8424: +  A - the matrix to test
8425: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8427:    Output Parameters:
8428: .  flg - the result

8430:    Notes:
8431:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8433:    Level: intermediate

8435: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8436: @*/
8437: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8438: {


8445:   if (!A->symmetric_set) {
8446:     if (!A->ops->issymmetric) {
8447:       MatType mattype;
8448:       MatGetType(A,&mattype);
8449:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8450:     }
8451:     (*A->ops->issymmetric)(A,tol,flg);
8452:     if (!tol) {
8453:       A->symmetric_set = PETSC_TRUE;
8454:       A->symmetric     = *flg;
8455:       if (A->symmetric) {
8456:         A->structurally_symmetric_set = PETSC_TRUE;
8457:         A->structurally_symmetric     = PETSC_TRUE;
8458:       }
8459:     }
8460:   } else if (A->symmetric) {
8461:     *flg = PETSC_TRUE;
8462:   } else if (!tol) {
8463:     *flg = PETSC_FALSE;
8464:   } else {
8465:     if (!A->ops->issymmetric) {
8466:       MatType mattype;
8467:       MatGetType(A,&mattype);
8468:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8469:     }
8470:     (*A->ops->issymmetric)(A,tol,flg);
8471:   }
8472:   return(0);
8473: }

8475: /*@
8476:    MatIsHermitian - Test whether a matrix is Hermitian

8478:    Collective on Mat

8480:    Input Parameter:
8481: +  A - the matrix to test
8482: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8484:    Output Parameters:
8485: .  flg - the result

8487:    Level: intermediate

8489: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8490:           MatIsSymmetricKnown(), MatIsSymmetric()
8491: @*/
8492: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8493: {


8500:   if (!A->hermitian_set) {
8501:     if (!A->ops->ishermitian) {
8502:       MatType mattype;
8503:       MatGetType(A,&mattype);
8504:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8505:     }
8506:     (*A->ops->ishermitian)(A,tol,flg);
8507:     if (!tol) {
8508:       A->hermitian_set = PETSC_TRUE;
8509:       A->hermitian     = *flg;
8510:       if (A->hermitian) {
8511:         A->structurally_symmetric_set = PETSC_TRUE;
8512:         A->structurally_symmetric     = PETSC_TRUE;
8513:       }
8514:     }
8515:   } else if (A->hermitian) {
8516:     *flg = PETSC_TRUE;
8517:   } else if (!tol) {
8518:     *flg = PETSC_FALSE;
8519:   } else {
8520:     if (!A->ops->ishermitian) {
8521:       MatType mattype;
8522:       MatGetType(A,&mattype);
8523:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8524:     }
8525:     (*A->ops->ishermitian)(A,tol,flg);
8526:   }
8527:   return(0);
8528: }

8530: /*@
8531:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8533:    Not Collective

8535:    Input Parameter:
8536: .  A - the matrix to check

8538:    Output Parameters:
8539: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8540: -  flg - the result

8542:    Level: advanced

8544:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8545:          if you want it explicitly checked

8547: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8548: @*/
8549: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8550: {
8555:   if (A->symmetric_set) {
8556:     *set = PETSC_TRUE;
8557:     *flg = A->symmetric;
8558:   } else {
8559:     *set = PETSC_FALSE;
8560:   }
8561:   return(0);
8562: }

8564: /*@
8565:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8567:    Not Collective

8569:    Input Parameter:
8570: .  A - the matrix to check

8572:    Output Parameters:
8573: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8574: -  flg - the result

8576:    Level: advanced

8578:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8579:          if you want it explicitly checked

8581: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8582: @*/
8583: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8584: {
8589:   if (A->hermitian_set) {
8590:     *set = PETSC_TRUE;
8591:     *flg = A->hermitian;
8592:   } else {
8593:     *set = PETSC_FALSE;
8594:   }
8595:   return(0);
8596: }

8598: /*@
8599:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8601:    Collective on Mat

8603:    Input Parameter:
8604: .  A - the matrix to test

8606:    Output Parameters:
8607: .  flg - the result

8609:    Level: intermediate

8611: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8612: @*/
8613: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8614: {

8620:   if (!A->structurally_symmetric_set) {
8621:     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8622:     (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);

8624:     A->structurally_symmetric_set = PETSC_TRUE;
8625:   }
8626:   *flg = A->structurally_symmetric;
8627:   return(0);
8628: }

8630: /*@
8631:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8632:        to be communicated to other processors during the MatAssemblyBegin/End() process

8634:     Not collective

8636:    Input Parameter:
8637: .   vec - the vector

8639:    Output Parameters:
8640: +   nstash   - the size of the stash
8641: .   reallocs - the number of additional mallocs incurred.
8642: .   bnstash   - the size of the block stash
8643: -   breallocs - the number of additional mallocs incurred.in the block stash

8645:    Level: advanced

8647: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8649: @*/
8650: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8651: {

8655:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8656:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8657:   return(0);
8658: }

8660: /*@C
8661:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8662:      parallel layout

8664:    Collective on Mat

8666:    Input Parameter:
8667: .  mat - the matrix

8669:    Output Parameter:
8670: +   right - (optional) vector that the matrix can be multiplied against
8671: -   left - (optional) vector that the matrix vector product can be stored in

8673:    Notes:
8674:     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().

8676:   Notes:
8677:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8679:   Level: advanced

8681: .seealso: MatCreate(), VecDestroy()
8682: @*/
8683: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8684: {

8690:   if (mat->ops->getvecs) {
8691:     (*mat->ops->getvecs)(mat,right,left);
8692:   } else {
8693:     PetscInt rbs,cbs;
8694:     MatGetBlockSizes(mat,&rbs,&cbs);
8695:     if (right) {
8696:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8697:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8698:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8699:       VecSetBlockSize(*right,cbs);
8700:       VecSetType(*right,mat->defaultvectype);
8701:       PetscLayoutReference(mat->cmap,&(*right)->map);
8702:     }
8703:     if (left) {
8704:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8705:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8706:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8707:       VecSetBlockSize(*left,rbs);
8708:       VecSetType(*left,mat->defaultvectype);
8709:       PetscLayoutReference(mat->rmap,&(*left)->map);
8710:     }
8711:   }
8712:   return(0);
8713: }

8715: /*@C
8716:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8717:      with default values.

8719:    Not Collective

8721:    Input Parameters:
8722: .    info - the MatFactorInfo data structure


8725:    Notes:
8726:     The solvers are generally used through the KSP and PC objects, for example
8727:           PCLU, PCILU, PCCHOLESKY, PCICC

8729:    Level: developer

8731: .seealso: MatFactorInfo

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

8736: @*/

8738: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8739: {

8743:   PetscMemzero(info,sizeof(MatFactorInfo));
8744:   return(0);
8745: }

8747: /*@
8748:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8750:    Collective on Mat

8752:    Input Parameters:
8753: +  mat - the factored matrix
8754: -  is - the index set defining the Schur indices (0-based)

8756:    Notes:
8757:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8759:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8761:    Level: developer

8763: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8764:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8766: @*/
8767: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8768: {
8769:   PetscErrorCode ierr,(*f)(Mat,IS);

8777:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8778:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8779:   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");
8780:   MatDestroy(&mat->schur);
8781:   (*f)(mat,is);
8782:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8783:   return(0);
8784: }

8786: /*@
8787:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8789:    Logically Collective on Mat

8791:    Input Parameters:
8792: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8793: .  S - location where to return the Schur complement, can be NULL
8794: -  status - the status of the Schur complement matrix, can be NULL

8796:    Notes:
8797:    You must call MatFactorSetSchurIS() before calling this routine.

8799:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8800:    The caller must destroy the object when it is no longer needed.
8801:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8803:    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)

8805:    Developer Notes:
8806:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8807:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8809:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8811:    Level: advanced

8813:    References:

8815: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8816: @*/
8817: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8818: {

8825:   if (S) {
8826:     PetscErrorCode (*f)(Mat,Mat*);

8828:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8829:     if (f) {
8830:       (*f)(F,S);
8831:     } else {
8832:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8833:     }
8834:   }
8835:   if (status) *status = F->schur_status;
8836:   return(0);
8837: }

8839: /*@
8840:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

8842:    Logically Collective on Mat

8844:    Input Parameters:
8845: +  F - the factored matrix obtained by calling MatGetFactor()
8846: .  *S - location where to return the Schur complement, can be NULL
8847: -  status - the status of the Schur complement matrix, can be NULL

8849:    Notes:
8850:    You must call MatFactorSetSchurIS() before calling this routine.

8852:    Schur complement mode is currently implemented for sequential matrices.
8853:    The routine returns a the Schur Complement stored within the data strutures of the solver.
8854:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8855:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

8857:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

8859:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8861:    Level: advanced

8863:    References:

8865: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8866: @*/
8867: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8868: {
8873:   if (S) *S = F->schur;
8874:   if (status) *status = F->schur_status;
8875:   return(0);
8876: }

8878: /*@
8879:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

8881:    Logically Collective on Mat

8883:    Input Parameters:
8884: +  F - the factored matrix obtained by calling MatGetFactor()
8885: .  *S - location where the Schur complement is stored
8886: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

8888:    Notes:

8890:    Level: advanced

8892:    References:

8894: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8895: @*/
8896: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8897: {

8902:   if (S) {
8904:     *S = NULL;
8905:   }
8906:   F->schur_status = status;
8907:   MatFactorUpdateSchurStatus_Private(F);
8908:   return(0);
8909: }

8911: /*@
8912:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

8914:    Logically Collective on Mat

8916:    Input Parameters:
8917: +  F - the factored matrix obtained by calling MatGetFactor()
8918: .  rhs - location where the right hand side of the Schur complement system is stored
8919: -  sol - location where the solution of the Schur complement system has to be returned

8921:    Notes:
8922:    The sizes of the vectors should match the size of the Schur complement

8924:    Must be called after MatFactorSetSchurIS()

8926:    Level: advanced

8928:    References:

8930: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
8931: @*/
8932: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
8933: {

8945:   MatFactorFactorizeSchurComplement(F);
8946:   switch (F->schur_status) {
8947:   case MAT_FACTOR_SCHUR_FACTORED:
8948:     MatSolveTranspose(F->schur,rhs,sol);
8949:     break;
8950:   case MAT_FACTOR_SCHUR_INVERTED:
8951:     MatMultTranspose(F->schur,rhs,sol);
8952:     break;
8953:   default:
8954:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
8955:     break;
8956:   }
8957:   return(0);
8958: }

8960: /*@
8961:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

8963:    Logically Collective on Mat

8965:    Input Parameters:
8966: +  F - the factored matrix obtained by calling MatGetFactor()
8967: .  rhs - location where the right hand side of the Schur complement system is stored
8968: -  sol - location where the solution of the Schur complement system has to be returned

8970:    Notes:
8971:    The sizes of the vectors should match the size of the Schur complement

8973:    Must be called after MatFactorSetSchurIS()

8975:    Level: advanced

8977:    References:

8979: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
8980: @*/
8981: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
8982: {

8994:   MatFactorFactorizeSchurComplement(F);
8995:   switch (F->schur_status) {
8996:   case MAT_FACTOR_SCHUR_FACTORED:
8997:     MatSolve(F->schur,rhs,sol);
8998:     break;
8999:   case MAT_FACTOR_SCHUR_INVERTED:
9000:     MatMult(F->schur,rhs,sol);
9001:     break;
9002:   default:
9003:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9004:     break;
9005:   }
9006:   return(0);
9007: }

9009: /*@
9010:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9012:    Logically Collective on Mat

9014:    Input Parameters:
9015: .  F - the factored matrix obtained by calling MatGetFactor()

9017:    Notes:
9018:     Must be called after MatFactorSetSchurIS().

9020:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9022:    Level: advanced

9024:    References:

9026: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9027: @*/
9028: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9029: {

9035:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9036:   MatFactorFactorizeSchurComplement(F);
9037:   MatFactorInvertSchurComplement_Private(F);
9038:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9039:   return(0);
9040: }

9042: /*@
9043:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9045:    Logically Collective on Mat

9047:    Input Parameters:
9048: .  F - the factored matrix obtained by calling MatGetFactor()

9050:    Notes:
9051:     Must be called after MatFactorSetSchurIS().

9053:    Level: advanced

9055:    References:

9057: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9058: @*/
9059: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9060: {

9066:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9067:   MatFactorFactorizeSchurComplement_Private(F);
9068:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9069:   return(0);
9070: }

9072: PetscErrorCode MatPtAP_Basic(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9073: {
9074:   Mat            AP;

9078:   PetscInfo2(A,"Mat types %s and %s using basic PtAP\n",((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9079:   MatMatMult(A,P,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&AP);
9080:   MatTransposeMatMult(P,AP,scall,fill,C);
9081:   MatDestroy(&AP);
9082:   return(0);
9083: }

9085: /*@
9086:    MatPtAP - Creates the matrix product C = P^T * A * P

9088:    Neighbor-wise Collective on Mat

9090:    Input Parameters:
9091: +  A - the matrix
9092: .  P - the projection matrix
9093: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9094: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9095:           if the result is a dense matrix this is irrelevent

9097:    Output Parameters:
9098: .  C - the product matrix

9100:    Notes:
9101:    C will be created and must be destroyed by the user with MatDestroy().

9103:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9105:    Level: intermediate

9107: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9108: @*/
9109: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9110: {
9112:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9113:   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9114:   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9115:   PetscBool      sametype;

9120:   MatCheckPreallocated(A,1);
9121:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9122:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9123:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9126:   MatCheckPreallocated(P,2);
9127:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9128:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9130:   if (A->rmap->N != A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix A must be square, %D != %D",A->rmap->N,A->cmap->N);
9131:   if (P->rmap->N != A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
9132:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9133:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9135:   if (scall == MAT_REUSE_MATRIX) {

9139:     PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9140:     PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9141:     if ((*C)->ops->ptapnumeric) {
9142:       (*(*C)->ops->ptapnumeric)(A,P,*C);
9143:     } else {
9144:       MatPtAP_Basic(A,P,scall,fill,C);
9145:     }
9146:     PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9147:     PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9148:     return(0);
9149:   }

9151:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9152:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9154:   fA = A->ops->ptap;
9155:   fP = P->ops->ptap;
9156:   PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);
9157:   if (fP == fA && sametype) {
9158:     ptap = fA;
9159:   } else {
9160:     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9161:     char ptapname[256];
9162:     PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));
9163:     PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));
9164:     PetscStrlcat(ptapname,"_",sizeof(ptapname));
9165:     PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));
9166:     PetscStrlcat(ptapname,"_C",sizeof(ptapname)); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9167:     PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
9168:   }

9170:   if (!ptap) ptap = MatPtAP_Basic;
9171:   PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9172:   (*ptap)(A,P,scall,fill,C);
9173:   PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9174:   if (A->symmetric_set && A->symmetric) {
9175:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9176:   }
9177:   return(0);
9178: }

9180: /*@
9181:    MatPtAPNumeric - Computes the matrix product C = P^T * A * P

9183:    Neighbor-wise Collective on Mat

9185:    Input Parameters:
9186: +  A - the matrix
9187: -  P - the projection matrix

9189:    Output Parameters:
9190: .  C - the product matrix

9192:    Notes:
9193:    C must have been created by calling MatPtAPSymbolic and must be destroyed by
9194:    the user using MatDeatroy().

9196:    This routine is currently only implemented for pairs of AIJ matrices and classes
9197:    which inherit from AIJ.  C will be of type MATAIJ.

9199:    Level: intermediate

9201: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9202: @*/
9203: PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9204: {

9210:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9211:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9214:   MatCheckPreallocated(P,2);
9215:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9216:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9219:   MatCheckPreallocated(C,3);
9220:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9221:   if (P->cmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->rmap->N);
9222:   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
9223:   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
9224:   if (P->cmap->N!=C->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->cmap->N);
9225:   MatCheckPreallocated(A,1);

9227:   if (!C->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You should call MatPtAPSymbolic first");
9228:   PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9229:   (*C->ops->ptapnumeric)(A,P,C);
9230:   PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9231:   return(0);
9232: }

9234: /*@
9235:    MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P

9237:    Neighbor-wise Collective on Mat

9239:    Input Parameters:
9240: +  A - the matrix
9241: -  P - the projection matrix

9243:    Output Parameters:
9244: .  C - the (i,j) structure of the product matrix

9246:    Notes:
9247:    C will be created and must be destroyed by the user with MatDestroy().

9249:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9250:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
9251:    this (i,j) structure by calling MatPtAPNumeric().

9253:    Level: intermediate

9255: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
9256: @*/
9257: PetscErrorCode MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
9258: {

9264:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9265:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9266:   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9269:   MatCheckPreallocated(P,2);
9270:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9271:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9274:   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
9275:   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
9276:   MatCheckPreallocated(A,1);

9278:   if (!A->ops->ptapsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatType %s",((PetscObject)A)->type_name);
9279:   PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);
9280:   (*A->ops->ptapsymbolic)(A,P,fill,C);
9281:   PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);

9283:   /* MatSetBlockSize(*C,A->rmap->bs); NO! this is not always true -ma */
9284:   return(0);
9285: }

9287: /*@