Actual source code: matrix.c

petsc-master 2019-06-15
Report Typos and Errors

  2: /*
  3:    This is where the abstract matrix operations are defined
  4: */

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

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

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

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

 42: /*@
 43:    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:    Logically Collective on Mat

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

 52:    Output Parameter:
 53: .  x  - the matrix

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

 62:    Level: intermediate


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


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

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

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

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

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

100:    Logically Collective on Mat

102:    Input Parameters:
103: .  mat - the factored matrix

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

110:    Level: advanced

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

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

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

129: /*@
130:    MatFactorGetError - gets the error code from a factorization

132:    Logically Collective on Mat

134:    Input Parameters:
135: .  mat - the factored matrix

137:    Output Parameter:
138: .  err  - the error code

140:    Level: advanced

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

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

155: /*@
156:    MatFactorClearError - clears the error code in a factorization

158:    Logically Collective on Mat

160:    Input Parameter:
161: .  mat - the factored matrix

163:    Level: developer

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

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

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

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

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

229:   Input Parameter:
230: .    A  - the matrix

232:   Output Parameter:
233: .    keptrows - the rows that are not completely zero

235:   Notes:
236:     keptrows is set to NULL if all rows are nonzero.

238:   Level: intermediate

240:  @*/
241: PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
242: {

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

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

262:   Input Parameter:
263: .    A  - the matrix

265:   Output Parameter:
266: .    zerorows - the rows that are completely zero

268:   Notes:
269:     zerorows is set to NULL if no rows are zero.

271:   Level: intermediate

273:  @*/
274: PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
275: {
277:   IS keptrows;
278:   PetscInt m, n;


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

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

300:    Not Collective

302:    Input Parameters:
303: .   A - the matrix

305:    Output Parameters:
306: .   a - the diagonal part (which is a SEQUENTIAL matrix)

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

313:    Level: advanced

315: @*/
316: PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
317: {

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

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

340:    Collective on Mat

342:    Input Parameters:
343: .  mat - the matrix

345:    Output Parameter:
346: .   trace - the sum of the diagonal entries

348:    Level: advanced

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

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

364: /*@
365:    MatRealPart - Zeros out the imaginary part of the matrix

367:    Logically Collective on Mat

369:    Input Parameters:
370: .  mat - the matrix

372:    Level: advanced


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

384:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
385:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
386:   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
387:   MatCheckPreallocated(mat,1);
388:   (*mat->ops->realpart)(mat);
389: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
390:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
391:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
392:   }
393: #endif
394:   return(0);
395: }

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

400:    Collective on Mat

402:    Input Parameter:
403: .  mat - the matrix

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

409:    Notes:
410:     the nghosts and ghosts are suitable to pass into VecCreateGhost()

412:    Level: advanced

414: @*/
415: PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
416: {

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


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

437:    Logically Collective on Mat

439:    Input Parameters:
440: .  mat - the matrix

442:    Level: advanced


445: .seealso: MatRealPart()
446: @*/
447: PetscErrorCode MatImaginaryPart(Mat mat)
448: {

454:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
455:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
456:   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
457:   MatCheckPreallocated(mat,1);
458:   (*mat->ops->imaginarypart)(mat);
459: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
460:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
461:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
462:   }
463: #endif
464:   return(0);
465: }

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

470:    Not Collective

472:    Input Parameter:
473: .  mat - the matrix

475:    Output Parameters:
476: +  missing - is any diagonal missing
477: -  dd - first diagonal entry that is missing (optional) on this process

479:    Level: advanced


482: .seealso: MatRealPart()
483: @*/
484: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
485: {

491:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
492:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
493:   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
494:   (*mat->ops->missingdiagonal)(mat,missing,dd);
495:   return(0);
496: }

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

503:    Not Collective

505:    Input Parameters:
506: +  mat - the matrix
507: -  row - the row to get

509:    Output Parameters:
510: +  ncols -  if not NULL, the number of nonzeros in the row
511: .  cols - if not NULL, the column numbers
512: -  vals - if not NULL, the values

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

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

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

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

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

536:    Fortran Notes:
537:    The calling sequence from Fortran is
538: .vb
539:    MatGetRow(matrix,row,ncols,cols,values,ierr)
540:          Mat     matrix (input)
541:          integer row    (input)
542:          integer ncols  (output)
543:          integer cols(maxcols) (output)
544:          double precision (or double complex) values(maxcols) output
545: .ve
546:    where maxcols >= maximum nonzeros in any row of the matrix.


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

553:    Level: advanced

555: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
556: @*/
557: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
558: {
560:   PetscInt       incols;

565:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
566:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
567:   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
568:   MatCheckPreallocated(mat,1);
569:   PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
570:   (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
571:   if (ncols) *ncols = incols;
572:   PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
573:   return(0);
574: }

576: /*@
577:    MatConjugate - replaces the matrix values with their complex conjugates

579:    Logically Collective on Mat

581:    Input Parameters:
582: .  mat - the matrix

584:    Level: advanced

586: .seealso:  VecConjugate()
587: @*/
588: PetscErrorCode MatConjugate(Mat mat)
589: {
590: #if defined(PETSC_USE_COMPLEX)

595:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
596:   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");
597:   (*mat->ops->conjugate)(mat);
598: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
599:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
600:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
601:   }
602: #endif
603:   return(0);
604: #else
605:   return 0;
606: #endif
607: }

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

612:    Not Collective

614:    Input Parameters:
615: +  mat - the matrix
616: .  row - the row to get
617: .  ncols, cols - the number of nonzeros and their columns
618: -  vals - if nonzero the column values

620:    Notes:
621:    This routine should be called after you have finished examining the entries.

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

627:    Fortran Notes:
628:    The calling sequence from Fortran is
629: .vb
630:    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
631:       Mat     matrix (input)
632:       integer row    (input)
633:       integer ncols  (output)
634:       integer cols(maxcols) (output)
635:       double precision (or double complex) values(maxcols) output
636: .ve
637:    Where maxcols >= maximum nonzeros in any row of the matrix.

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

642:    Level: advanced

644: .seealso:  MatGetRow()
645: @*/
646: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
647: {

653:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
654:   if (!mat->ops->restorerow) return(0);
655:   (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
656:   if (ncols) *ncols = 0;
657:   if (cols)  *cols = NULL;
658:   if (vals)  *vals = NULL;
659:   return(0);
660: }

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

666:    Not Collective

668:    Input Parameters:
669: +  mat - the matrix

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

674:    Level: advanced

676: .seealso: MatRestoreRowUpperTriangular()
677: @*/
678: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
679: {

685:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
686:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
687:   MatCheckPreallocated(mat,1);
688:   if (!mat->ops->getrowuppertriangular) return(0);
689:   (*mat->ops->getrowuppertriangular)(mat);
690:   return(0);
691: }

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

696:    Not Collective

698:    Input Parameters:
699: +  mat - the matrix

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


705:    Level: advanced

707: .seealso:  MatGetRowUpperTriangular()
708: @*/
709: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
710: {

716:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
717:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
718:   MatCheckPreallocated(mat,1);
719:   if (!mat->ops->restorerowuppertriangular) return(0);
720:   (*mat->ops->restorerowuppertriangular)(mat);
721:   return(0);
722: }

724: /*@C
725:    MatSetOptionsPrefix - Sets the prefix used for searching for all
726:    Mat options in the database.

728:    Logically Collective on Mat

730:    Input Parameter:
731: +  A - the Mat context
732: -  prefix - the prefix to prepend to all option names

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

738:    Level: advanced

740: .seealso: MatSetFromOptions()
741: @*/
742: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
743: {

748:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
749:   return(0);
750: }

752: /*@C
753:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
754:    Mat options in the database.

756:    Logically Collective on Mat

758:    Input Parameters:
759: +  A - the Mat context
760: -  prefix - the prefix to prepend to all option names

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

766:    Level: advanced

768: .seealso: MatGetOptionsPrefix()
769: @*/
770: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
771: {

776:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
777:   return(0);
778: }

780: /*@C
781:    MatGetOptionsPrefix - Sets the prefix used for searching for all
782:    Mat options in the database.

784:    Not Collective

786:    Input Parameter:
787: .  A - the Mat context

789:    Output Parameter:
790: .  prefix - pointer to the prefix string used

792:    Notes:
793:     On the fortran side, the user should pass in a string 'prefix' of
794:    sufficient length to hold the prefix.

796:    Level: advanced

798: .seealso: MatAppendOptionsPrefix()
799: @*/
800: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
801: {

806:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
807:   return(0);
808: }

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

813:    Collective on Mat

815:    Input Parameters:
816: .  A - the Mat context

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

822:    Level: beginner

824: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
825: @*/
826: PetscErrorCode MatResetPreallocation(Mat A)
827: {

833:   PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
834:   return(0);
835: }


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

841:    Collective on Mat

843:    Input Parameters:
844: .  A - the Mat context

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

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

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

853:    Level: beginner

855: .seealso: MatCreate(), MatDestroy()
856: @*/
857: PetscErrorCode MatSetUp(Mat A)
858: {
859:   PetscMPIInt    size;

864:   if (!((PetscObject)A)->type_name) {
865:     MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
866:     if (size == 1) {
867:       MatSetType(A, MATSEQAIJ);
868:     } else {
869:       MatSetType(A, MATMPIAIJ);
870:     }
871:   }
872:   if (!A->preallocated && A->ops->setup) {
873:     PetscInfo(A,"Warning not preallocating matrix storage\n");
874:     (*A->ops->setup)(A);
875:   }
876:   PetscLayoutSetUp(A->rmap);
877:   PetscLayoutSetUp(A->cmap);
878:   A->preallocated = PETSC_TRUE;
879:   return(0);
880: }

882: #if defined(PETSC_HAVE_SAWS)
883:  #include <petscviewersaws.h>
884: #endif
885: /*@C
886:    MatView - Visualizes a matrix object.

888:    Collective on Mat

890:    Input Parameters:
891: +  mat - the matrix
892: -  viewer - visualization context

894:   Notes:
895:   The available visualization contexts include
896: +    PETSC_VIEWER_STDOUT_SELF - for sequential matrices
897: .    PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
898: .    PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
899: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

901:    The user can open alternative visualization contexts with
902: +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
903: .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
904:          specified file; corresponding input uses MatLoad()
905: .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
906:          an X window display
907: -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
908:          Currently only the sequential dense and AIJ
909:          matrix types support the Socket viewer.

911:    The user can call PetscViewerPushFormat() to specify the output
912:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
913:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
914: +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
915: .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
916: .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
917: .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
918:          format common among all matrix types
919: .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
920:          format (which is in many cases the same as the default)
921: .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
922:          size and structure (not the matrix entries)
923: -    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
924:          the matrix structure

926:    Options Database Keys:
927: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
928: .  -mat_view ::ascii_info_detail - Prints more detailed info
929: .  -mat_view - Prints matrix in ASCII format
930: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
931: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
932: .  -display <name> - Sets display name (default is host)
933: .  -draw_pause <sec> - Sets number of seconds to pause after display
934: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 12 Using MATLAB with PETSc for details)
935: .  -viewer_socket_machine <machine> -
936: .  -viewer_socket_port <port> -
937: .  -mat_view binary - save matrix to file in binary format
938: -  -viewer_binary_filename <name> -
939:    Level: beginner

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

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

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

951:       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
952:       and then use the following mouse functions.
953: + left mouse: zoom in
954: . middle mouse: zoom out
955: - right mouse: continue with the simulation

957: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
958:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
959: @*/
960: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
961: {
962:   PetscErrorCode    ierr;
963:   PetscInt          rows,cols,rbs,cbs;
964:   PetscBool         iascii,ibinary,isstring;
965:   PetscViewerFormat format;
966:   PetscMPIInt       size;
967: #if defined(PETSC_HAVE_SAWS)
968:   PetscBool         issaws;
969: #endif

974:   if (!viewer) {
975:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
976:   }
979:   MatCheckPreallocated(mat,1);
980:   PetscViewerGetFormat(viewer,&format);
981:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
982:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
983:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
984:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
985:   if (ibinary) {
986:     PetscBool mpiio;
987:     PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);
988:     if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
989:   }

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

997: #if defined(PETSC_HAVE_SAWS)
998:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
999: #endif
1000:   if (iascii) {
1001:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1002:     PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
1003:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1004:       MatNullSpace nullsp,transnullsp;

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

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

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

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

1087:    Collective on PetscViewer

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

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

1099:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1184:    Corresponding MatView() is not yet implemented.

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

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

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

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


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

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

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

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

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

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

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

1264:    Collective on Mat

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

1269:    Level: beginner

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

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

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

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

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

1306:    Not Collective

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

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

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

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

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

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

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

1339:    Level: beginner

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

1345: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1346:           InsertMode, INSERT_VALUES, ADD_VALUES
1347: @*/
1348: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1349: {
1351: #if defined(PETSC_USE_DEBUG)
1352:   PetscInt       i,j;
1353: #endif

1358:   if (!m || !n) return(0); /* no values to insert */
1362:   MatCheckPreallocated(mat,1);
1363:   if (mat->insertmode == NOT_SET_VALUES) {
1364:     mat->insertmode = addv;
1365:   }
1366: #if defined(PETSC_USE_DEBUG)
1367:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1368:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1369:   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

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

1383:   if (mat->assembled) {
1384:     mat->was_assembled = PETSC_TRUE;
1385:     mat->assembled     = PETSC_FALSE;
1386:   }
1387:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1388:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1389:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1390: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1391:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1392:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1393:   }
1394: #endif
1395:   return(0);
1396: }


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

1403:    Not Collective

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

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

1413:    All the nonzeros in the row must be provided

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

1417:    The row must belong to this process

1419:    Level: intermediate

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

1433:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1434:   MatSetValuesRow(mat,globalrow,v);
1435: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1436:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1437:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1438:   }
1439: #endif
1440:   return(0);
1441: }

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

1447:    Not Collective

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

1454:    Notes:
1455:    The values, v, are column-oriented for the block version.

1457:    All the nonzeros in the row must be provided

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

1461:    The row must belong to this process

1463:    Level: advanced

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

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

1483:   if (mat->assembled) {
1484:     mat->was_assembled = PETSC_TRUE;
1485:     mat->assembled     = PETSC_FALSE;
1486:   }
1487:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1488:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1489:   (*mat->ops->setvaluesrow)(mat,row,v);
1490:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1491: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1492:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1493:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1494:   }
1495: #endif
1496:   return(0);
1497: }

1499: /*@
1500:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1501:      Using structured grid indexing

1503:    Not Collective

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

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

1519:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1520:    options cannot be mixed without intervening calls to the assembly
1521:    routines.

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

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

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

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

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

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

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

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

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

1559:    Efficiency Alert:
1560:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1561:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1563:    Level: beginner

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

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

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

1614: /*@
1615:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1616:      Using structured grid indexing

1618:    Not Collective

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

1631:    Notes:
1632:    By default the values, v, are row-oriented and unsorted.
1633:    See MatSetOption() for other options.

1635:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1636:    options cannot be mixed without intervening calls to the assembly
1637:    routines.

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

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

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

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

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

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

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

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

1671:    Level: beginner

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

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

1692:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1693:     jdxm = buf; jdxn = buf+m;
1694:   } else {
1695:     PetscMalloc2(m,&bufm,n,&bufn);
1696:     jdxm = bufm; jdxn = bufn;
1697:   }
1698:   for (i=0; i<m; i++) {
1699:     for (j=0; j<3-sdim; j++) dxm++;
1700:     tmp = *dxm++ - starts[0];
1701:     for (j=0; j<sdim-1; j++) {
1702:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1703:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1704:     }
1705:     dxm++;
1706:     jdxm[i] = tmp;
1707:   }
1708:   for (i=0; i<n; i++) {
1709:     for (j=0; j<3-sdim; j++) dxn++;
1710:     tmp = *dxn++ - starts[0];
1711:     for (j=0; j<sdim-1; j++) {
1712:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1713:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1714:     }
1715:     dxn++;
1716:     jdxn[i] = tmp;
1717:   }
1718:   MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1719:   PetscFree2(bufm,bufn);
1720: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1721:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1722:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1723:   }
1724: #endif
1725:   return(0);
1726: }

1728: /*@
1729:    MatSetStencil - Sets the grid information for setting values into a matrix via
1730:         MatSetValuesStencil()

1732:    Not Collective

1734:    Input Parameters:
1735: +  mat - the matrix
1736: .  dim - dimension of the grid 1, 2, or 3
1737: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1738: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1739: -  dof - number of degrees of freedom per node


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

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

1748:    Level: beginner

1750: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1751:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1752: @*/
1753: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1754: {
1755:   PetscInt i;


1762:   mat->stencil.dim = dim + (dof > 1);
1763:   for (i=0; i<dim; i++) {
1764:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1765:     mat->stencil.starts[i] = starts[dim-i-1];
1766:   }
1767:   mat->stencil.dims[dim]   = dof;
1768:   mat->stencil.starts[dim] = 0;
1769:   mat->stencil.noc         = (PetscBool)(dof == 1);
1770:   return(0);
1771: }

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

1776:    Not Collective

1778:    Input Parameters:
1779: +  mat - the matrix
1780: .  v - a logically two-dimensional array of values
1781: .  m, idxm - the number of block rows and their global block indices
1782: .  n, idxn - the number of block columns and their global block indices
1783: -  addv - either ADD_VALUES or INSERT_VALUES, where
1784:    ADD_VALUES adds values to any existing entries, and
1785:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

1803:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1804:    options cannot be mixed without intervening calls to the assembly
1805:    routines.

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

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

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

1821:    Example:
1822: $   Suppose m=n=2 and block size(bs) = 2 The array is
1823: $
1824: $   1  2  | 3  4
1825: $   5  6  | 7  8
1826: $   - - - | - - -
1827: $   9  10 | 11 12
1828: $   13 14 | 15 16
1829: $
1830: $   v[] should be passed in like
1831: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1832: $
1833: $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1834: $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]

1836:    Level: intermediate

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

1847:   if (!m || !n) return(0); /* no values to insert */
1851:   MatCheckPreallocated(mat,1);
1852:   if (mat->insertmode == NOT_SET_VALUES) {
1853:     mat->insertmode = addv;
1854:   }
1855: #if defined(PETSC_USE_DEBUG)
1856:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1857:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1858:   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1859: #endif

1861:   if (mat->assembled) {
1862:     mat->was_assembled = PETSC_TRUE;
1863:     mat->assembled     = PETSC_FALSE;
1864:   }
1865:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1866:   if (mat->ops->setvaluesblocked) {
1867:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1868:   } else {
1869:     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1870:     PetscInt i,j,bs,cbs;
1871:     MatGetBlockSizes(mat,&bs,&cbs);
1872:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1873:       iidxm = buf; iidxn = buf + m*bs;
1874:     } else {
1875:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1876:       iidxm = bufr; iidxn = bufc;
1877:     }
1878:     for (i=0; i<m; i++) {
1879:       for (j=0; j<bs; j++) {
1880:         iidxm[i*bs+j] = bs*idxm[i] + j;
1881:       }
1882:     }
1883:     for (i=0; i<n; i++) {
1884:       for (j=0; j<cbs; j++) {
1885:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1886:       }
1887:     }
1888:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1889:     PetscFree2(bufr,bufc);
1890:   }
1891:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1892: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1893:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1894:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1895:   }
1896: #endif
1897:   return(0);
1898: }

1900: /*@
1901:    MatGetValues - Gets a block of values from a matrix.

1903:    Not Collective; currently only returns a local block

1905:    Input Parameters:
1906: +  mat - the matrix
1907: .  v - a logically two-dimensional array for storing the values
1908: .  m, idxm - the number of rows and their global indices
1909: -  n, idxn - the number of columns and their global indices

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

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

1919:    MatGetValues() requires that the matrix has been assembled
1920:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1921:    MatSetValues() and MatGetValues() CANNOT be made in succession
1922:    without intermediate matrix assembly.

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

1927:    Level: advanced

1929: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1930: @*/
1931: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1932: {

1938:   if (!m || !n) return(0);
1942:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1943:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1944:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1945:   MatCheckPreallocated(mat,1);

1947:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1948:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1949:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1950:   return(0);
1951: }

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

1957:   Not Collective

1959:   Input Parameters:
1960: + mat - the matrix
1961: . nb - the number of blocks
1962: . bs - the number of rows (and columns) in each block
1963: . rows - a concatenation of the rows for each block
1964: - v - a concatenation of logically two-dimensional arrays of values

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

1969:   Level: advanced

1971: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1972:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1973: @*/
1974: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1975: {

1983: #if defined(PETSC_USE_DEBUG)
1984:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1985: #endif

1987:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
1988:   if (mat->ops->setvaluesbatch) {
1989:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
1990:   } else {
1991:     PetscInt b;
1992:     for (b = 0; b < nb; ++b) {
1993:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
1994:     }
1995:   }
1996:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
1997:   return(0);
1998: }

2000: /*@
2001:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2002:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2003:    using a local (per-processor) numbering.

2005:    Not Collective

2007:    Input Parameters:
2008: +  x - the matrix
2009: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2010: - cmapping - column mapping

2012:    Level: intermediate


2015: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2016: @*/
2017: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2018: {


2027:   if (x->ops->setlocaltoglobalmapping) {
2028:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2029:   } else {
2030:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2031:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2032:   }
2033:   return(0);
2034: }


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

2040:    Not Collective

2042:    Input Parameters:
2043: .  A - the matrix

2045:    Output Parameters:
2046: + rmapping - row mapping
2047: - cmapping - column mapping

2049:    Level: advanced


2052: .seealso:  MatSetValuesLocal()
2053: @*/
2054: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2055: {
2061:   if (rmapping) *rmapping = A->rmap->mapping;
2062:   if (cmapping) *cmapping = A->cmap->mapping;
2063:   return(0);
2064: }

2066: /*@
2067:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2069:    Not Collective

2071:    Input Parameters:
2072: .  A - the matrix

2074:    Output Parameters:
2075: + rmap - row layout
2076: - cmap - column layout

2078:    Level: advanced

2080: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2081: @*/
2082: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2083: {
2089:   if (rmap) *rmap = A->rmap;
2090:   if (cmap) *cmap = A->cmap;
2091:   return(0);
2092: }

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

2098:    Not Collective

2100:    Input Parameters:
2101: +  mat - the matrix
2102: .  nrow, irow - number of rows and their local indices
2103: .  ncol, icol - number of columns and their local indices
2104: .  y -  a logically two-dimensional array of values
2105: -  addv - either INSERT_VALUES or ADD_VALUES, where
2106:    ADD_VALUES adds values to any existing entries, and
2107:    INSERT_VALUES replaces existing entries with new values

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

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

2115:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2116:    options cannot be mixed without intervening calls to the assembly
2117:    routines.

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

2122:    Level: intermediate

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

2128: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2129:            MatSetValueLocal()
2130: @*/
2131: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2132: {

2138:   MatCheckPreallocated(mat,1);
2139:   if (!nrow || !ncol) return(0); /* no values to insert */
2143:   if (mat->insertmode == NOT_SET_VALUES) {
2144:     mat->insertmode = addv;
2145:   }
2146: #if defined(PETSC_USE_DEBUG)
2147:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2148:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2149:   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2150: #endif

2152:   if (mat->assembled) {
2153:     mat->was_assembled = PETSC_TRUE;
2154:     mat->assembled     = PETSC_FALSE;
2155:   }
2156:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2157:   if (mat->ops->setvalueslocal) {
2158:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2159:   } else {
2160:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2161:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2162:       irowm = buf; icolm = buf+nrow;
2163:     } else {
2164:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2165:       irowm = bufr; icolm = bufc;
2166:     }
2167:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2168:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2169:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2170:     PetscFree2(bufr,bufc);
2171:   }
2172:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2173: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2174:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2175:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2176:   }
2177: #endif
2178:   return(0);
2179: }

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

2185:    Not Collective

2187:    Input Parameters:
2188: +  x - the matrix
2189: .  nrow, irow - number of rows and their local indices
2190: .  ncol, icol - number of columns and their local indices
2191: .  y -  a logically two-dimensional array of values
2192: -  addv - either INSERT_VALUES or ADD_VALUES, where
2193:    ADD_VALUES adds values to any existing entries, and
2194:    INSERT_VALUES replaces existing entries with new values

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

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

2203:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2204:    options cannot be mixed without intervening calls to the assembly
2205:    routines.

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

2210:    Level: intermediate

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

2216: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2217:            MatSetValuesLocal(),  MatSetValuesBlocked()
2218: @*/
2219: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2220: {

2226:   MatCheckPreallocated(mat,1);
2227:   if (!nrow || !ncol) return(0); /* no values to insert */
2231:   if (mat->insertmode == NOT_SET_VALUES) {
2232:     mat->insertmode = addv;
2233:   }
2234: #if defined(PETSC_USE_DEBUG)
2235:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2236:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2237:   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);
2238: #endif

2240:   if (mat->assembled) {
2241:     mat->was_assembled = PETSC_TRUE;
2242:     mat->assembled     = PETSC_FALSE;
2243:   }
2244: #if defined(PETSC_USE_DEBUG)
2245:   /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2246:   if (mat->rmap->mapping) {
2247:     PetscInt irbs, rbs;
2248:     MatGetBlockSizes(mat, &rbs, NULL);
2249:     ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2250:     if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2251:   }
2252:   if (mat->cmap->mapping) {
2253:     PetscInt icbs, cbs;
2254:     MatGetBlockSizes(mat,NULL,&cbs);
2255:     ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2256:     if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2257:   }
2258: #endif
2259:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2260:   if (mat->ops->setvaluesblockedlocal) {
2261:     (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2262:   } else {
2263:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2264:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2265:       irowm = buf; icolm = buf + nrow;
2266:     } else {
2267:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2268:       irowm = bufr; icolm = bufc;
2269:     }
2270:     ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2271:     ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2272:     MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2273:     PetscFree2(bufr,bufc);
2274:   }
2275:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2276: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2277:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2278:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2279:   }
2280: #endif
2281:   return(0);
2282: }

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

2287:    Collective on Mat

2289:    Input Parameters:
2290: +  mat - the matrix
2291: -  x   - the vector to be multiplied

2293:    Output Parameters:
2294: .  y - the result

2296:    Notes:
2297:    The vectors x and y cannot be the same.  I.e., one cannot
2298:    call MatMult(A,y,y).

2300:    Level: developer

2302: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2303: @*/
2304: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2305: {


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

2319:   if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2320:   (*mat->ops->multdiagonalblock)(mat,x,y);
2321:   PetscObjectStateIncrease((PetscObject)y);
2322:   return(0);
2323: }

2325: /* --------------------------------------------------------*/
2326: /*@
2327:    MatMult - Computes the matrix-vector product, y = Ax.

2329:    Neighbor-wise Collective on Mat

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

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

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

2342:    Level: beginner

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

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

2367:   VecLockReadPush(x);
2368:   if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2369:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2370:   (*mat->ops->mult)(mat,x,y);
2371:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2372:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2373:   VecLockReadPop(x);
2374:   return(0);
2375: }

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

2380:    Neighbor-wise Collective on Mat

2382:    Input Parameters:
2383: +  mat - the matrix
2384: -  x   - the vector to be multiplied

2386:    Output Parameters:
2387: .  y - the result

2389:    Notes:
2390:    The vectors x and y cannot be the same.  I.e., one cannot
2391:    call MatMultTranspose(A,y,y).

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

2396:    Level: beginner

2398: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2399: @*/
2400: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2401: {


2410:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2411:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2412:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2413: #if !defined(PETSC_HAVE_CONSTRAINTS)
2414:   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);
2415:   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);
2416: #endif
2417:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2418:   MatCheckPreallocated(mat,1);

2420:   if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2421:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2422:   VecLockReadPush(x);
2423:   (*mat->ops->multtranspose)(mat,x,y);
2424:   VecLockReadPop(x);
2425:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2426:   PetscObjectStateIncrease((PetscObject)y);
2427:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2428:   return(0);
2429: }

2431: /*@
2432:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2434:    Neighbor-wise Collective on Mat

2436:    Input Parameters:
2437: +  mat - the matrix
2438: -  x   - the vector to be multilplied

2440:    Output Parameters:
2441: .  y - the result

2443:    Notes:
2444:    The vectors x and y cannot be the same.  I.e., one cannot
2445:    call MatMultHermitianTranspose(A,y,y).

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

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

2451:    Level: beginner

2453: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2454: @*/
2455: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2456: {
2458:   Vec            w;


2466:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2467:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2468:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2469: #if !defined(PETSC_HAVE_CONSTRAINTS)
2470:   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);
2471:   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);
2472: #endif
2473:   MatCheckPreallocated(mat,1);

2475:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2476:   if (mat->ops->multhermitiantranspose) {
2477:     VecLockReadPush(x);
2478:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2479:     VecLockReadPop(x);
2480:   } else {
2481:     VecDuplicate(x,&w);
2482:     VecCopy(x,w);
2483:     VecConjugate(w);
2484:     MatMultTranspose(mat,w,y);
2485:     VecDestroy(&w);
2486:     VecConjugate(y);
2487:   }
2488:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2489:   PetscObjectStateIncrease((PetscObject)y);
2490:   return(0);
2491: }

2493: /*@
2494:     MatMultAdd -  Computes v3 = v2 + A * v1.

2496:     Neighbor-wise Collective on Mat

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

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

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

2509:     Level: beginner

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


2524:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2525:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2526:   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);
2527:   /* 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);
2528:      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); */
2529:   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);
2530:   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);
2531:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2532:   MatCheckPreallocated(mat,1);

2534:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2535:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2536:   VecLockReadPush(v1);
2537:   (*mat->ops->multadd)(mat,v1,v2,v3);
2538:   VecLockReadPop(v1);
2539:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2540:   PetscObjectStateIncrease((PetscObject)v3);
2541:   return(0);
2542: }

2544: /*@
2545:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2547:    Neighbor-wise Collective on Mat

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

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

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

2560:    Level: beginner

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


2575:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2576:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2577:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2578:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2579:   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);
2580:   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);
2581:   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);
2582:   MatCheckPreallocated(mat,1);

2584:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2585:   VecLockReadPush(v1);
2586:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2587:   VecLockReadPop(v1);
2588:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2589:   PetscObjectStateIncrease((PetscObject)v3);
2590:   return(0);
2591: }

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

2596:    Neighbor-wise Collective on Mat

2598:    Input Parameters:
2599: +  mat - the matrix
2600: -  v1, v2 - the vectors

2602:    Output Parameters:
2603: .  v3 - the result

2605:    Notes:
2606:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2607:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2609:    Level: beginner

2611: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2612: @*/
2613: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2614: {


2624:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2625:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2626:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2627:   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);
2628:   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);
2629:   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);
2630:   MatCheckPreallocated(mat,1);

2632:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2633:   VecLockReadPush(v1);
2634:   if (mat->ops->multhermitiantransposeadd) {
2635:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2636:   } else {
2637:     Vec w,z;
2638:     VecDuplicate(v1,&w);
2639:     VecCopy(v1,w);
2640:     VecConjugate(w);
2641:     VecDuplicate(v3,&z);
2642:     MatMultTranspose(mat,w,z);
2643:     VecDestroy(&w);
2644:     VecConjugate(z);
2645:     if (v2 != v3) {
2646:       VecWAXPY(v3,1.0,v2,z);
2647:     } else {
2648:       VecAXPY(v3,1.0,z);
2649:     }
2650:     VecDestroy(&z);
2651:   }
2652:   VecLockReadPop(v1);
2653:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2654:   PetscObjectStateIncrease((PetscObject)v3);
2655:   return(0);
2656: }

2658: /*@
2659:    MatMultConstrained - The inner multiplication routine for a
2660:    constrained matrix P^T A P.

2662:    Neighbor-wise Collective on Mat

2664:    Input Parameters:
2665: +  mat - the matrix
2666: -  x   - the vector to be multilplied

2668:    Output Parameters:
2669: .  y - the result

2671:    Notes:
2672:    The vectors x and y cannot be the same.  I.e., one cannot
2673:    call MatMult(A,y,y).

2675:    Level: beginner

2677: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2678: @*/
2679: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2680: {

2687:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2688:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2689:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2690:   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);
2691:   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);
2692:   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);

2694:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2695:   VecLockReadPush(x);
2696:   (*mat->ops->multconstrained)(mat,x,y);
2697:   VecLockReadPop(x);
2698:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2699:   PetscObjectStateIncrease((PetscObject)y);
2700:   return(0);
2701: }

2703: /*@
2704:    MatMultTransposeConstrained - The inner multiplication routine for a
2705:    constrained matrix P^T A^T P.

2707:    Neighbor-wise Collective on Mat

2709:    Input Parameters:
2710: +  mat - the matrix
2711: -  x   - the vector to be multilplied

2713:    Output Parameters:
2714: .  y - the result

2716:    Notes:
2717:    The vectors x and y cannot be the same.  I.e., one cannot
2718:    call MatMult(A,y,y).

2720:    Level: beginner

2722: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2723: @*/
2724: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2725: {

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

2738:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2739:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2740:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2741:   PetscObjectStateIncrease((PetscObject)y);
2742:   return(0);
2743: }

2745: /*@C
2746:    MatGetFactorType - gets the type of factorization it is

2748:    Not Collective

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

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

2756:    Level: intermediate

2758: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2759: @*/
2760: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2761: {
2766:   *t = mat->factortype;
2767:   return(0);
2768: }

2770: /*@C
2771:    MatSetFactorType - sets the type of factorization it is

2773:    Logically Collective on Mat

2775:    Input Parameters:
2776: +  mat - the matrix
2777: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2779:    Level: intermediate

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

2792: /* ------------------------------------------------------------*/
2793: /*@C
2794:    MatGetInfo - Returns information about matrix storage (number of
2795:    nonzeros, memory, etc.).

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

2799:    Input Parameters:
2800: .  mat - the matrix

2802:    Output Parameters:
2803: +  flag - flag indicating the type of parameters to be returned
2804:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2805:    MAT_GLOBAL_SUM - sum over all processors)
2806: -  info - matrix information context

2808:    Notes:
2809:    The MatInfo context contains a variety of matrix data, including
2810:    number of nonzeros allocated and used, number of mallocs during
2811:    matrix assembly, etc.  Additional information for factored matrices
2812:    is provided (such as the fill ratio, number of mallocs during
2813:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2814:    when using the runtime options
2815: $       -info -mat_view ::ascii_info

2817:    Example for C/C++ Users:
2818:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2819:    data within the MatInfo context.  For example,
2820: .vb
2821:       MatInfo info;
2822:       Mat     A;
2823:       double  mal, nz_a, nz_u;

2825:       MatGetInfo(A,MAT_LOCAL,&info);
2826:       mal  = info.mallocs;
2827:       nz_a = info.nz_allocated;
2828: .ve

2830:    Example for Fortran Users:
2831:    Fortran users should declare info as a double precision
2832:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2833:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2834:    a complete list of parameter names.
2835: .vb
2836:       double  precision info(MAT_INFO_SIZE)
2837:       double  precision mal, nz_a
2838:       Mat     A
2839:       integer ierr

2841:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2842:       mal = info(MAT_INFO_MALLOCS)
2843:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2844: .ve

2846:     Level: intermediate

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

2851: .seealso: MatStashGetInfo()

2853: @*/
2854: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2855: {

2862:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2863:   MatCheckPreallocated(mat,1);
2864:   (*mat->ops->getinfo)(mat,flag,info);
2865:   return(0);
2866: }

2868: /*
2869:    This is used by external packages where it is not easy to get the info from the actual
2870:    matrix factorization.
2871: */
2872: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2873: {

2877:   PetscMemzero(info,sizeof(MatInfo));
2878:   return(0);
2879: }

2881: /* ----------------------------------------------------------*/

2883: /*@C
2884:    MatLUFactor - Performs in-place LU factorization of matrix.

2886:    Collective on Mat

2888:    Input Parameters:
2889: +  mat - the matrix
2890: .  row - row permutation
2891: .  col - column permutation
2892: -  info - options for factorization, includes
2893: $          fill - expected fill as ratio of original fill.
2894: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2895: $                   Run with the option -info to determine an optimal value to use

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

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

2905:    Level: developer

2907: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2908:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2913: @*/
2914: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2915: {
2917:   MatFactorInfo  tinfo;

2925:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2926:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2927:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2928:   MatCheckPreallocated(mat,1);
2929:   if (!info) {
2930:     MatFactorInfoInitialize(&tinfo);
2931:     info = &tinfo;
2932:   }

2934:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2935:   (*mat->ops->lufactor)(mat,row,col,info);
2936:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2937:   PetscObjectStateIncrease((PetscObject)mat);
2938:   return(0);
2939: }

2941: /*@C
2942:    MatILUFactor - Performs in-place ILU factorization of matrix.

2944:    Collective on Mat

2946:    Input Parameters:
2947: +  mat - the matrix
2948: .  row - row permutation
2949: .  col - column permutation
2950: -  info - structure containing
2951: $      levels - number of levels of fill.
2952: $      expected fill - as ratio of original fill.
2953: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2954:                 missing diagonal entries)

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

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

2964:    Level: developer

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

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

2971: @*/
2972: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2973: {

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

2988:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
2989:   (*mat->ops->ilufactor)(mat,row,col,info);
2990:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
2991:   PetscObjectStateIncrease((PetscObject)mat);
2992:   return(0);
2993: }

2995: /*@C
2996:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2997:    Call this routine before calling MatLUFactorNumeric().

2999:    Collective on Mat

3001:    Input Parameters:
3002: +  fact - the factor matrix obtained with MatGetFactor()
3003: .  mat - the matrix
3004: .  row, col - row and column permutations
3005: -  info - options for factorization, includes
3006: $          fill - expected fill as ratio of original fill.
3007: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3008: $                   Run with the option -info to determine an optimal value to use


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

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

3018:    Level: developer

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

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

3025: @*/
3026: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3027: {

3037:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3038:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3039:   if (!(fact)->ops->lufactorsymbolic) {
3040:     MatSolverType spackage;
3041:     MatFactorGetSolverType(fact,&spackage);
3042:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3043:   }
3044:   MatCheckPreallocated(mat,2);

3046:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3047:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3048:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3049:   PetscObjectStateIncrease((PetscObject)fact);
3050:   return(0);
3051: }

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

3057:    Collective on Mat

3059:    Input Parameters:
3060: +  fact - the factor matrix obtained with MatGetFactor()
3061: .  mat - the matrix
3062: -  info - options for factorization

3064:    Notes:
3065:    See MatLUFactor() for in-place factorization.  See
3066:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3072:    Level: developer

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

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

3079: @*/
3080: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3081: {

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

3092:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3093:   MatCheckPreallocated(mat,2);
3094:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3095:   (fact->ops->lufactornumeric)(fact,mat,info);
3096:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3097:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3098:   PetscObjectStateIncrease((PetscObject)fact);
3099:   return(0);
3100: }

3102: /*@C
3103:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3104:    symmetric matrix.

3106:    Collective on Mat

3108:    Input Parameters:
3109: +  mat - the matrix
3110: .  perm - row and column permutations
3111: -  f - expected fill as ratio of original fill

3113:    Notes:
3114:    See MatLUFactor() for the nonsymmetric case.  See also
3115:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3121:    Level: developer

3123: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3124:           MatGetOrdering()

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

3129: @*/
3130: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3131: {

3139:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3140:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3141:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3142:   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);
3143:   MatCheckPreallocated(mat,1);

3145:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3146:   (*mat->ops->choleskyfactor)(mat,perm,info);
3147:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3148:   PetscObjectStateIncrease((PetscObject)mat);
3149:   return(0);
3150: }

3152: /*@C
3153:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3154:    of a symmetric matrix.

3156:    Collective on Mat

3158:    Input Parameters:
3159: +  fact - the factor matrix obtained with MatGetFactor()
3160: .  mat - the matrix
3161: .  perm - row and column permutations
3162: -  info - options for factorization, includes
3163: $          fill - expected fill as ratio of original fill.
3164: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3165: $                   Run with the option -info to determine an optimal value to use

3167:    Notes:
3168:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3169:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3175:    Level: developer

3177: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3178:           MatGetOrdering()

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

3183: @*/
3184: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3185: {

3194:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3195:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3196:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3197:   if (!(fact)->ops->choleskyfactorsymbolic) {
3198:     MatSolverType spackage;
3199:     MatFactorGetSolverType(fact,&spackage);
3200:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3201:   }
3202:   MatCheckPreallocated(mat,2);

3204:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3205:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3206:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3207:   PetscObjectStateIncrease((PetscObject)fact);
3208:   return(0);
3209: }

3211: /*@C
3212:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3213:    of a symmetric matrix. Call this routine after first calling
3214:    MatCholeskyFactorSymbolic().

3216:    Collective on Mat

3218:    Input Parameters:
3219: +  fact - the factor matrix obtained with MatGetFactor()
3220: .  mat - the initial matrix
3221: .  info - options for factorization
3222: -  fact - the symbolic factor of mat


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

3230:    Level: developer

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

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

3237: @*/
3238: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3239: {

3247:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3248:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3249:   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);
3250:   MatCheckPreallocated(mat,2);

3252:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3253:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3254:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3255:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3256:   PetscObjectStateIncrease((PetscObject)fact);
3257:   return(0);
3258: }

3260: /* ----------------------------------------------------------------*/
3261: /*@
3262:    MatSolve - Solves A x = b, given a factored matrix.

3264:    Neighbor-wise Collective on Mat

3266:    Input Parameters:
3267: +  mat - the factored matrix
3268: -  b - the right-hand-side vector

3270:    Output Parameter:
3271: .  x - the result vector

3273:    Notes:
3274:    The vectors b and x cannot be the same.  I.e., one cannot
3275:    call MatSolve(A,x,x).

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

3282:    Level: developer

3284: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3285: @*/
3286: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3287: {

3297:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3298:   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);
3299:   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);
3300:   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);
3301:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3302:   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3303:   MatCheckPreallocated(mat,1);

3305:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3306:   if (mat->factorerrortype) {
3307:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3308:     VecSetInf(x);
3309:   } else {
3310:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3311:     (*mat->ops->solve)(mat,b,x);
3312:   }
3313:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3314:   PetscObjectStateIncrease((PetscObject)x);
3315:   return(0);
3316: }

3318: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X, PetscBool trans)
3319: {
3321:   Vec            b,x;
3322:   PetscInt       m,N,i;
3323:   PetscScalar    *bb,*xx;
3324:   PetscBool      flg;

3327:   PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3328:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
3329:   PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3330:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");

3332:   MatDenseGetArray(B,&bb);
3333:   MatDenseGetArray(X,&xx);
3334:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3335:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3336:   MatCreateVecs(A,&x,&b);
3337:   for (i=0; i<N; i++) {
3338:     VecPlaceArray(b,bb + i*m);
3339:     VecPlaceArray(x,xx + i*m);
3340:     if (trans) {
3341:       MatSolveTranspose(A,b,x);
3342:     } else {
3343:       MatSolve(A,b,x);
3344:     }
3345:     VecResetArray(x);
3346:     VecResetArray(b);
3347:   }
3348:   VecDestroy(&b);
3349:   VecDestroy(&x);
3350:   MatDenseRestoreArray(B,&bb);
3351:   MatDenseRestoreArray(X,&xx);
3352:   return(0);
3353: }

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

3358:    Neighbor-wise Collective on Mat

3360:    Input Parameters:
3361: +  A - the factored matrix
3362: -  B - the right-hand-side matrix  (dense matrix)

3364:    Output Parameter:
3365: .  X - the result matrix (dense matrix)

3367:    Notes:
3368:    The matrices b and x cannot be the same.  I.e., one cannot
3369:    call MatMatSolve(A,x,x).

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

3377:    When using SuperLU_Dist as a parallel solver PETSc will use the SuperLU_Dist functionality to solve multiple right hand sides simultaneously. For MUMPS
3378:    it calls a separate solve for each right hand side since MUMPS does not yet support distributed right hand sides.

3380:    Since the resulting matrix X must always be dense we do not support sparse representation of the matrix B.

3382:    Level: developer

3384: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3385: @*/
3386: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3387: {

3397:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3398:   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);
3399:   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);
3400:   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");
3401:   if (!A->rmap->N && !A->cmap->N) return(0);
3402:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3403:   MatCheckPreallocated(A,1);

3405:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3406:   if (!A->ops->matsolve) {
3407:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3408:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3409:   } else {
3410:     (*A->ops->matsolve)(A,B,X);
3411:   }
3412:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3413:   PetscObjectStateIncrease((PetscObject)X);
3414:   return(0);
3415: }

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

3420:    Neighbor-wise Collective on Mat

3422:    Input Parameters:
3423: +  A - the factored matrix
3424: -  B - the right-hand-side matrix  (dense matrix)

3426:    Output Parameter:
3427: .  X - the result matrix (dense matrix)

3429:    Notes:
3430:    The matrices B and X cannot be the same.  I.e., one cannot
3431:    call MatMatSolveTranspose(A,X,X).

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

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

3441:    Level: developer

3443: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3444: @*/
3445: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3446: {

3456:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3457:   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);
3458:   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);
3459:   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);
3460:   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");
3461:   if (!A->rmap->N && !A->cmap->N) return(0);
3462:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3463:   MatCheckPreallocated(A,1);

3465:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3466:   if (!A->ops->matsolvetranspose) {
3467:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3468:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3469:   } else {
3470:     (*A->ops->matsolvetranspose)(A,B,X);
3471:   }
3472:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3473:   PetscObjectStateIncrease((PetscObject)X);
3474:   return(0);
3475: }

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

3480:    Neighbor-wise Collective on Mat

3482:    Input Parameters:
3483: +  A - the factored matrix
3484: -  Bt - the transpose of right-hand-side matrix

3486:    Output Parameter:
3487: .  X - the result matrix (dense matrix)

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

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

3497:    Level: developer

3499: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3500: @*/
3501: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3502: {


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

3521:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3522:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3523:   (*A->ops->mattransposesolve)(A,Bt,X);
3524:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3525:   PetscObjectStateIncrease((PetscObject)X);
3526:   return(0);
3527: }

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

3533:    Neighbor-wise Collective on Mat

3535:    Input Parameters:
3536: +  mat - the factored matrix
3537: -  b - the right-hand-side vector

3539:    Output Parameter:
3540: .  x - the result vector

3542:    Notes:
3543:    MatSolve() should be used for most applications, as it performs
3544:    a forward solve followed by a backward solve.

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

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

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

3559:    Level: developer

3561: .seealso: MatSolve(), MatBackwardSolve()
3562: @*/
3563: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3564: {

3574:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3575:   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);
3576:   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);
3577:   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);
3578:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3579:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3580:   MatCheckPreallocated(mat,1);

3582:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3583:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3584:   (*mat->ops->forwardsolve)(mat,b,x);
3585:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3586:   PetscObjectStateIncrease((PetscObject)x);
3587:   return(0);
3588: }

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

3594:    Neighbor-wise Collective on Mat

3596:    Input Parameters:
3597: +  mat - the factored matrix
3598: -  b - the right-hand-side vector

3600:    Output Parameter:
3601: .  x - the result vector

3603:    Notes:
3604:    MatSolve() should be used for most applications, as it performs
3605:    a forward solve followed by a backward solve.

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

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

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

3620:    Level: developer

3622: .seealso: MatSolve(), MatForwardSolve()
3623: @*/
3624: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3625: {

3635:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3636:   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);
3637:   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);
3638:   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);
3639:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3640:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3641:   MatCheckPreallocated(mat,1);

3643:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3644:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3645:   (*mat->ops->backwardsolve)(mat,b,x);
3646:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3647:   PetscObjectStateIncrease((PetscObject)x);
3648:   return(0);
3649: }

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

3654:    Neighbor-wise Collective on Mat

3656:    Input Parameters:
3657: +  mat - the factored matrix
3658: .  b - the right-hand-side vector
3659: -  y - the vector to be added to

3661:    Output Parameter:
3662: .  x - the result vector

3664:    Notes:
3665:    The vectors b and x cannot be the same.  I.e., one cannot
3666:    call MatSolveAdd(A,x,y,x).

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

3672:    Level: developer

3674: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3675: @*/
3676: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3677: {
3678:   PetscScalar    one = 1.0;
3679:   Vec            tmp;

3691:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3692:   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);
3693:   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);
3694:   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);
3695:   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);
3696:   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);
3697:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3698:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3699:   MatCheckPreallocated(mat,1);

3701:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3702:   if (mat->ops->solveadd) {
3703:     (*mat->ops->solveadd)(mat,b,y,x);
3704:   } else {
3705:     /* do the solve then the add manually */
3706:     if (x != y) {
3707:       MatSolve(mat,b,x);
3708:       VecAXPY(x,one,y);
3709:     } else {
3710:       VecDuplicate(x,&tmp);
3711:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3712:       VecCopy(x,tmp);
3713:       MatSolve(mat,b,x);
3714:       VecAXPY(x,one,tmp);
3715:       VecDestroy(&tmp);
3716:     }
3717:   }
3718:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3719:   PetscObjectStateIncrease((PetscObject)x);
3720:   return(0);
3721: }

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

3726:    Neighbor-wise Collective on Mat

3728:    Input Parameters:
3729: +  mat - the factored matrix
3730: -  b - the right-hand-side vector

3732:    Output Parameter:
3733: .  x - the result vector

3735:    Notes:
3736:    The vectors b and x cannot be the same.  I.e., one cannot
3737:    call MatSolveTranspose(A,x,x).

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

3743:    Level: developer

3745: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3746: @*/
3747: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3748: {

3758:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3759:   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);
3760:   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);
3761:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3762:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3763:   MatCheckPreallocated(mat,1);
3764:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3765:   if (mat->factorerrortype) {
3766:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3767:     VecSetInf(x);
3768:   } else {
3769:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3770:     (*mat->ops->solvetranspose)(mat,b,x);
3771:   }
3772:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3773:   PetscObjectStateIncrease((PetscObject)x);
3774:   return(0);
3775: }

3777: /*@
3778:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3779:                       factored matrix.

3781:    Neighbor-wise Collective on Mat

3783:    Input Parameters:
3784: +  mat - the factored matrix
3785: .  b - the right-hand-side vector
3786: -  y - the vector to be added to

3788:    Output Parameter:
3789: .  x - the result vector

3791:    Notes:
3792:    The vectors b and x cannot be the same.  I.e., one cannot
3793:    call MatSolveTransposeAdd(A,x,y,x).

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

3799:    Level: developer

3801: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3802: @*/
3803: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3804: {
3805:   PetscScalar    one = 1.0;
3807:   Vec            tmp;

3818:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3819:   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);
3820:   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);
3821:   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);
3822:   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);
3823:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3824:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3825:   MatCheckPreallocated(mat,1);

3827:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3828:   if (mat->ops->solvetransposeadd) {
3829:     if (mat->factorerrortype) {
3830:       PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3831:       VecSetInf(x);
3832:     } else {
3833:       (*mat->ops->solvetransposeadd)(mat,b,y,x);
3834:     }
3835:   } else {
3836:     /* do the solve then the add manually */
3837:     if (x != y) {
3838:       MatSolveTranspose(mat,b,x);
3839:       VecAXPY(x,one,y);
3840:     } else {
3841:       VecDuplicate(x,&tmp);
3842:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3843:       VecCopy(x,tmp);
3844:       MatSolveTranspose(mat,b,x);
3845:       VecAXPY(x,one,tmp);
3846:       VecDestroy(&tmp);
3847:     }
3848:   }
3849:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3850:   PetscObjectStateIncrease((PetscObject)x);
3851:   return(0);
3852: }
3853: /* ----------------------------------------------------------------*/

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

3858:    Neighbor-wise Collective on Mat

3860:    Input Parameters:
3861: +  mat - the matrix
3862: .  b - the right hand side
3863: .  omega - the relaxation factor
3864: .  flag - flag indicating the type of SOR (see below)
3865: .  shift -  diagonal shift
3866: .  its - the number of iterations
3867: -  lits - the number of local iterations

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

3872:    SOR Flags:
3873: .     SOR_FORWARD_SWEEP - forward SOR
3874: .     SOR_BACKWARD_SWEEP - backward SOR
3875: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3876: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3877: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3878: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3879: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3880:          upper/lower triangular part of matrix to
3881:          vector (with omega)
3882: .     SOR_ZERO_INITIAL_GUESS - zero initial guess

3884:    Notes:
3885:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3886:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3887:    on each processor.

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

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

3895:    Notes for Advanced Users:
3896:    The flags are implemented as bitwise inclusive or operations.
3897:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3898:    to specify a zero initial guess for SSOR.

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

3904:    Vectors x and b CANNOT be the same

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

3908:    Level: developer

3910: @*/
3911: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3912: {

3922:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3923:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3924:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3925:   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);
3926:   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);
3927:   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);
3928:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3929:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3930:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

3932:   MatCheckPreallocated(mat,1);
3933:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3934:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3935:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3936:   PetscObjectStateIncrease((PetscObject)x);
3937:   return(0);
3938: }

3940: /*
3941:       Default matrix copy routine.
3942: */
3943: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3944: {
3945:   PetscErrorCode    ierr;
3946:   PetscInt          i,rstart = 0,rend = 0,nz;
3947:   const PetscInt    *cwork;
3948:   const PetscScalar *vwork;

3951:   if (B->assembled) {
3952:     MatZeroEntries(B);
3953:   }
3954:   if (str == SAME_NONZERO_PATTERN) {
3955:     MatGetOwnershipRange(A,&rstart,&rend);
3956:     for (i=rstart; i<rend; i++) {
3957:       MatGetRow(A,i,&nz,&cwork,&vwork);
3958:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3959:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
3960:     }
3961:   } else {
3962:     MatAYPX(B,0.0,A,str);
3963:   }
3964:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3965:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3966:   return(0);
3967: }

3969: /*@
3970:    MatCopy - Copies a matrix to another matrix.

3972:    Collective on Mat

3974:    Input Parameters:
3975: +  A - the matrix
3976: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

3978:    Output Parameter:
3979: .  B - where the copy is put

3981:    Notes:
3982:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3983:    same nonzero pattern or the routine will crash.

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

3989:    Level: intermediate

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

3993: @*/
3994: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
3995: {
3997:   PetscInt       i;

4005:   MatCheckPreallocated(B,2);
4006:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4007:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4008:   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);
4009:   MatCheckPreallocated(A,1);
4010:   if (A == B) return(0);

4012:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4013:   if (A->ops->copy) {
4014:     (*A->ops->copy)(A,B,str);
4015:   } else { /* generic conversion */
4016:     MatCopy_Basic(A,B,str);
4017:   }

4019:   B->stencil.dim = A->stencil.dim;
4020:   B->stencil.noc = A->stencil.noc;
4021:   for (i=0; i<=A->stencil.dim; i++) {
4022:     B->stencil.dims[i]   = A->stencil.dims[i];
4023:     B->stencil.starts[i] = A->stencil.starts[i];
4024:   }

4026:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4027:   PetscObjectStateIncrease((PetscObject)B);
4028:   return(0);
4029: }

4031: /*@C
4032:    MatConvert - Converts a matrix to another matrix, either of the same
4033:    or different type.

4035:    Collective on Mat

4037:    Input Parameters:
4038: +  mat - the matrix
4039: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4040:    same type as the original matrix.
4041: -  reuse - denotes if the destination matrix is to be created or reused.
4042:    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
4043:    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).

4045:    Output Parameter:
4046: .  M - pointer to place new matrix

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

4053:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4054:    the MPI communicator of the generated matrix is always the same as the communicator
4055:    of the input matrix.

4057:    Level: intermediate

4059: .seealso: MatCopy(), MatDuplicate()
4060: @*/
4061: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4062: {
4064:   PetscBool      sametype,issame,flg;
4065:   char           convname[256],mtype[256];
4066:   Mat            B;

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

4076:   PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
4077:   if (flg) {
4078:     newtype = mtype;
4079:   }
4080:   PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4081:   PetscStrcmp(newtype,"same",&issame);
4082:   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4083:   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");

4085:   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) return(0);

4087:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4088:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4089:   } else {
4090:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4091:     const char     *prefix[3] = {"seq","mpi",""};
4092:     PetscInt       i;
4093:     /*
4094:        Order of precedence:
4095:        0) See if newtype is a superclass of the current matrix.
4096:        1) See if a specialized converter is known to the current matrix.
4097:        2) See if a specialized converter is known to the desired matrix class.
4098:        3) See if a good general converter is registered for the desired class
4099:           (as of 6/27/03 only MATMPIADJ falls into this category).
4100:        4) See if a good general converter is known for the current matrix.
4101:        5) Use a really basic converter.
4102:     */

4104:     /* 0) See if newtype is a superclass of the current matrix.
4105:           i.e mat is mpiaij and newtype is aij */
4106:     for (i=0; i<2; i++) {
4107:       PetscStrncpy(convname,prefix[i],sizeof(convname));
4108:       PetscStrlcat(convname,newtype,sizeof(convname));
4109:       PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4110:       PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4111:       if (flg) {
4112:         if (reuse == MAT_INPLACE_MATRIX) {
4113:           return(0);
4114:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4115:           (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4116:           return(0);
4117:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4118:           MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4119:           return(0);
4120:         }
4121:       }
4122:     }
4123:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4124:     for (i=0; i<3; i++) {
4125:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4126:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4127:       PetscStrlcat(convname,"_",sizeof(convname));
4128:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4129:       PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4130:       PetscStrlcat(convname,"_C",sizeof(convname));
4131:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4132:       PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4133:       if (conv) goto foundconv;
4134:     }

4136:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4137:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4138:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4139:     MatSetType(B,newtype);
4140:     for (i=0; i<3; i++) {
4141:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4142:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4143:       PetscStrlcat(convname,"_",sizeof(convname));
4144:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4145:       PetscStrlcat(convname,newtype,sizeof(convname));
4146:       PetscStrlcat(convname,"_C",sizeof(convname));
4147:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4148:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4149:       if (conv) {
4150:         MatDestroy(&B);
4151:         goto foundconv;
4152:       }
4153:     }

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

4161:     /* 4) See if a good general converter is known for the current matrix */
4162:     if (mat->ops->convert) {
4163:       conv = mat->ops->convert;
4164:     }
4165:     PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);
4166:     if (conv) goto foundconv;

4168:     /* 5) Use a really basic converter. */
4169:     PetscInfo(mat,"Using MatConvert_Basic\n");
4170:     conv = MatConvert_Basic;

4172: foundconv:
4173:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4174:     (*conv)(mat,newtype,reuse,M);
4175:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4176:       /* the block sizes must be same if the mappings are copied over */
4177:       (*M)->rmap->bs = mat->rmap->bs;
4178:       (*M)->cmap->bs = mat->cmap->bs;
4179:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4180:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4181:       (*M)->rmap->mapping = mat->rmap->mapping;
4182:       (*M)->cmap->mapping = mat->cmap->mapping;
4183:     }
4184:     (*M)->stencil.dim = mat->stencil.dim;
4185:     (*M)->stencil.noc = mat->stencil.noc;
4186:     for (i=0; i<=mat->stencil.dim; i++) {
4187:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4188:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4189:     }
4190:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4191:   }
4192:   PetscObjectStateIncrease((PetscObject)*M);

4194:   /* Copy Mat options */
4195:   if (mat->symmetric) {MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);}
4196:   if (mat->hermitian) {MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);}
4197:   return(0);
4198: }

4200: /*@C
4201:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4203:    Not Collective

4205:    Input Parameter:
4206: .  mat - the matrix, must be a factored matrix

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

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

4215:    Level: intermediate

4217: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4218: @*/
4219: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4220: {
4221:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4226:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4227:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4228:   if (!conv) {
4229:     *type = MATSOLVERPETSC;
4230:   } else {
4231:     (*conv)(mat,type);
4232:   }
4233:   return(0);
4234: }

4236: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4237: struct _MatSolverTypeForSpecifcType {
4238:   MatType                        mtype;
4239:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4240:   MatSolverTypeForSpecifcType next;
4241: };

4243: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4244: struct _MatSolverTypeHolder {
4245:   char                           *name;
4246:   MatSolverTypeForSpecifcType handlers;
4247:   MatSolverTypeHolder         next;
4248: };

4250: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4255:    Input Parameters:
4256: +    package - name of the package, for example petsc or superlu
4257: .    mtype - the matrix type that works with this package
4258: .    ftype - the type of factorization supported by the package
4259: -    getfactor - routine that will create the factored matrix ready to be used

4261:     Level: intermediate

4263: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4264: @*/
4265: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4266: {
4267:   PetscErrorCode              ierr;
4268:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4269:   PetscBool                   flg;
4270:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4273:   MatInitializePackage();
4274:   if (!next) {
4275:     PetscNew(&MatSolverTypeHolders);
4276:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4277:     PetscNew(&MatSolverTypeHolders->handlers);
4278:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4279:     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4280:     return(0);
4281:   }
4282:   while (next) {
4283:     PetscStrcasecmp(package,next->name,&flg);
4284:     if (flg) {
4285:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4286:       inext = next->handlers;
4287:       while (inext) {
4288:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4289:         if (flg) {
4290:           inext->getfactor[(int)ftype-1] = getfactor;
4291:           return(0);
4292:         }
4293:         iprev = inext;
4294:         inext = inext->next;
4295:       }
4296:       PetscNew(&iprev->next);
4297:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4298:       iprev->next->getfactor[(int)ftype-1] = getfactor;
4299:       return(0);
4300:     }
4301:     prev = next;
4302:     next = next->next;
4303:   }
4304:   PetscNew(&prev->next);
4305:   PetscStrallocpy(package,&prev->next->name);
4306:   PetscNew(&prev->next->handlers);
4307:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4308:   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4309:   return(0);
4310: }

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

4315:    Input Parameters:
4316: +    package - name of the package, for example petsc or superlu
4317: .    ftype - the type of factorization supported by the package
4318: -    mtype - the matrix type that works with this package

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

4325:     Level: intermediate

4327: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4328: @*/
4329: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4330: {
4331:   PetscErrorCode                 ierr;
4332:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4333:   PetscBool                      flg;
4334:   MatSolverTypeForSpecifcType inext;

4337:   if (foundpackage) *foundpackage = PETSC_FALSE;
4338:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4339:   if (getfactor)    *getfactor    = NULL;

4341:   if (package) {
4342:     while (next) {
4343:       PetscStrcasecmp(package,next->name,&flg);
4344:       if (flg) {
4345:         if (foundpackage) *foundpackage = PETSC_TRUE;
4346:         inext = next->handlers;
4347:         while (inext) {
4348:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4349:           if (flg) {
4350:             if (foundmtype) *foundmtype = PETSC_TRUE;
4351:             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4352:             return(0);
4353:           }
4354:           inext = inext->next;
4355:         }
4356:       }
4357:       next = next->next;
4358:     }
4359:   } else {
4360:     while (next) {
4361:       inext = next->handlers;
4362:       while (inext) {
4363:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4364:         if (flg && inext->getfactor[(int)ftype-1]) {
4365:           if (foundpackage) *foundpackage = PETSC_TRUE;
4366:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4367:           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
4368:           return(0);
4369:         }
4370:         inext = inext->next;
4371:       }
4372:       next = next->next;
4373:     }
4374:   }
4375:   return(0);
4376: }

4378: PetscErrorCode MatSolverTypeDestroy(void)
4379: {
4380:   PetscErrorCode              ierr;
4381:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4382:   MatSolverTypeForSpecifcType inext,iprev;

4385:   while (next) {
4386:     PetscFree(next->name);
4387:     inext = next->handlers;
4388:     while (inext) {
4389:       PetscFree(inext->mtype);
4390:       iprev = inext;
4391:       inext = inext->next;
4392:       PetscFree(iprev);
4393:     }
4394:     prev = next;
4395:     next = next->next;
4396:     PetscFree(prev);
4397:   }
4398:   MatSolverTypeHolders = NULL;
4399:   return(0);
4400: }

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

4405:    Collective on Mat

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

4412:    Output Parameters:
4413: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4415:    Notes:
4416:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4417:      such as pastix, superlu, mumps etc.

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

4421:    Level: intermediate

4423: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4424: @*/
4425: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4426: {
4427:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4428:   PetscBool      foundpackage,foundmtype;


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

4437:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4438:   if (!foundpackage) {
4439:     if (type) {
4440:       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4441:     } else {
4442:       SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4443:     }
4444:   }

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

4449: #if defined(PETSC_USE_COMPLEX)
4450:   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");
4451: #endif

4453:   (*conv)(mat,ftype,f);
4454:   return(0);
4455: }

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

4460:    Not Collective

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

4467:    Output Parameter:
4468: .    flg - PETSC_TRUE if the factorization is available

4470:    Notes:
4471:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4472:      such as pastix, superlu, mumps etc.

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

4476:    Level: intermediate

4478: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4479: @*/
4480: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4481: {
4482:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4491:   *flg = PETSC_FALSE;
4492:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4493:   if (gconv) {
4494:     *flg = PETSC_TRUE;
4495:   }
4496:   return(0);
4497: }

4499:  #include <petscdmtypes.h>

4501: /*@
4502:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4504:    Collective on Mat

4506:    Input Parameters:
4507: +  mat - the matrix
4508: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4509:         See the manual page for MatDuplicateOption for an explanation of these options.

4511:    Output Parameter:
4512: .  M - pointer to place new matrix

4514:    Level: intermediate

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

4520: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4521: @*/
4522: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4523: {
4525:   Mat            B;
4526:   PetscInt       i;
4527:   DM             dm;
4528:   void           (*viewf)(void);

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

4538:   *M = 0;
4539:   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4540:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4541:   (*mat->ops->duplicate)(mat,op,M);
4542:   B    = *M;

4544:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4545:   if (viewf) {
4546:     MatSetOperation(B,MATOP_VIEW,viewf);
4547:   }

4549:   B->stencil.dim = mat->stencil.dim;
4550:   B->stencil.noc = mat->stencil.noc;
4551:   for (i=0; i<=mat->stencil.dim; i++) {
4552:     B->stencil.dims[i]   = mat->stencil.dims[i];
4553:     B->stencil.starts[i] = mat->stencil.starts[i];
4554:   }

4556:   B->nooffproczerorows = mat->nooffproczerorows;
4557:   B->nooffprocentries  = mat->nooffprocentries;

4559:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4560:   if (dm) {
4561:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4562:   }
4563:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4564:   PetscObjectStateIncrease((PetscObject)B);
4565:   return(0);
4566: }

4568: /*@
4569:    MatGetDiagonal - Gets the diagonal of a matrix.

4571:    Logically Collective on Mat

4573:    Input Parameters:
4574: +  mat - the matrix
4575: -  v - the vector for storing the diagonal

4577:    Output Parameter:
4578: .  v - the diagonal of the matrix

4580:    Level: intermediate

4582:    Note:
4583:    Currently only correct in parallel for square matrices.

4585: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4586: @*/
4587: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4588: {

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

4599:   (*mat->ops->getdiagonal)(mat,v);
4600:   PetscObjectStateIncrease((PetscObject)v);
4601:   return(0);
4602: }

4604: /*@C
4605:    MatGetRowMin - Gets the minimum value (of the real part) of each
4606:         row of the matrix

4608:    Logically Collective on Mat

4610:    Input Parameters:
4611: .  mat - the matrix

4613:    Output Parameter:
4614: +  v - the vector for storing the maximums
4615: -  idx - the indices of the column found for each row (optional)

4617:    Level: intermediate

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

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

4625: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4626:           MatGetRowMax()
4627: @*/
4628: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4629: {

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

4640:   (*mat->ops->getrowmin)(mat,v,idx);
4641:   PetscObjectStateIncrease((PetscObject)v);
4642:   return(0);
4643: }

4645: /*@C
4646:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4647:         row of the matrix

4649:    Logically Collective on Mat

4651:    Input Parameters:
4652: .  mat - the matrix

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

4658:    Level: intermediate

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

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

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

4676:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4677:   if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4678:   MatCheckPreallocated(mat,1);
4679:   if (idx) {PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));}

4681:   (*mat->ops->getrowminabs)(mat,v,idx);
4682:   PetscObjectStateIncrease((PetscObject)v);
4683:   return(0);
4684: }

4686: /*@C
4687:    MatGetRowMax - Gets the maximum value (of the real part) of each
4688:         row of the matrix

4690:    Logically Collective on Mat

4692:    Input Parameters:
4693: .  mat - the matrix

4695:    Output Parameter:
4696: +  v - the vector for storing the maximums
4697: -  idx - the indices of the column found for each row (optional)

4699:    Level: intermediate

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

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

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

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

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

4726: /*@C
4727:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4728:         row of the matrix

4730:    Logically Collective on Mat

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

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

4739:    Level: intermediate

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

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

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

4757:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4758:   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4759:   MatCheckPreallocated(mat,1);
4760:   if (idx) {PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));}

4762:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4763:   PetscObjectStateIncrease((PetscObject)v);
4764:   return(0);
4765: }

4767: /*@
4768:    MatGetRowSum - Gets the sum of each row of the matrix

4770:    Logically or Neighborhood Collective on Mat

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

4775:    Output Parameter:
4776: .  v - the vector for storing the sum of rows

4778:    Level: intermediate

4780:    Notes:
4781:     This code is slow since it is not currently specialized for different formats

4783: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4784: @*/
4785: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4786: {
4787:   Vec            ones;

4794:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4795:   MatCheckPreallocated(mat,1);
4796:   MatCreateVecs(mat,&ones,NULL);
4797:   VecSet(ones,1.);
4798:   MatMult(mat,ones,v);
4799:   VecDestroy(&ones);
4800:   return(0);
4801: }

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

4806:    Collective on Mat

4808:    Input Parameter:
4809: +  mat - the matrix to transpose
4810: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4812:    Output Parameters:
4813: .  B - the transpose

4815:    Notes:
4816:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4822:    Level: intermediate

4824: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4825: @*/
4826: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4827: {

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

4840:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4841:   (*mat->ops->transpose)(mat,reuse,B);
4842:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4843:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4844:   return(0);
4845: }

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

4851:    Collective on Mat

4853:    Input Parameter:
4854: +  A - the matrix to test
4855: -  B - the matrix to test against, this can equal the first parameter

4857:    Output Parameters:
4858: .  flg - the result

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

4865:    Level: intermediate

4867: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4868: @*/
4869: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4870: {
4871:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4877:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4878:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4879:   *flg = PETSC_FALSE;
4880:   if (f && g) {
4881:     if (f == g) {
4882:       (*f)(A,B,tol,flg);
4883:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4884:   } else {
4885:     MatType mattype;
4886:     if (!f) {
4887:       MatGetType(A,&mattype);
4888:     } else {
4889:       MatGetType(B,&mattype);
4890:     }
4891:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4892:   }
4893:   return(0);
4894: }

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

4899:    Collective on Mat

4901:    Input Parameter:
4902: +  mat - the matrix to transpose and complex conjugate
4903: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

4905:    Output Parameters:
4906: .  B - the Hermitian

4908:    Level: intermediate

4910: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4911: @*/
4912: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4913: {

4917:   MatTranspose(mat,reuse,B);
4918: #if defined(PETSC_USE_COMPLEX)
4919:   MatConjugate(*B);
4920: #endif
4921:   return(0);
4922: }

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

4927:    Collective on Mat

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

4933:    Output Parameters:
4934: .  flg - the result

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

4941:    Level: intermediate

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

4953:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4954:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
4955:   if (f && g) {
4956:     if (f==g) {
4957:       (*f)(A,B,tol,flg);
4958:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4959:   }
4960:   return(0);
4961: }

4963: /*@
4964:    MatPermute - Creates a new matrix with rows and columns permuted from the
4965:    original.

4967:    Collective on Mat

4969:    Input Parameters:
4970: +  mat - the matrix to permute
4971: .  row - row permutation, each processor supplies only the permutation for its rows
4972: -  col - column permutation, each processor supplies only the permutation for its columns

4974:    Output Parameters:
4975: .  B - the permuted matrix

4977:    Level: advanced

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

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

4985: @*/
4986: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
4987: {

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

5001:   (*mat->ops->permute)(mat,row,col,B);
5002:   PetscObjectStateIncrease((PetscObject)*B);
5003:   return(0);
5004: }

5006: /*@
5007:    MatEqual - Compares two matrices.

5009:    Collective on Mat

5011:    Input Parameters:
5012: +  A - the first matrix
5013: -  B - the second matrix

5015:    Output Parameter:
5016: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5018:    Level: intermediate

5020: @*/
5021: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5022: {

5032:   MatCheckPreallocated(B,2);
5033:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5034:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5035:   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);
5036:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5037:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5038:   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);
5039:   MatCheckPreallocated(A,1);

5041:   (*A->ops->equal)(A,B,flg);
5042:   return(0);
5043: }

5045: /*@
5046:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5047:    matrices that are stored as vectors.  Either of the two scaling
5048:    matrices can be NULL.

5050:    Collective on Mat

5052:    Input Parameters:
5053: +  mat - the matrix to be scaled
5054: .  l - the left scaling vector (or NULL)
5055: -  r - the right scaling vector (or NULL)

5057:    Notes:
5058:    MatDiagonalScale() computes A = LAR, where
5059:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5060:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5062:    Level: intermediate


5065: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5066: @*/
5067: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5068: {

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

5081:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5082:   (*mat->ops->diagonalscale)(mat,l,r);
5083:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5084:   PetscObjectStateIncrease((PetscObject)mat);
5085: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5086:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5087:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5088:   }
5089: #endif
5090:   return(0);
5091: }

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

5096:     Logically Collective on Mat

5098:     Input Parameters:
5099: +   mat - the matrix to be scaled
5100: -   a  - the scaling value

5102:     Output Parameter:
5103: .   mat - the scaled matrix

5105:     Level: intermediate

5107: .seealso: MatDiagonalScale()
5108: @*/
5109: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5110: {

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

5122:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5123:   if (a != (PetscScalar)1.0) {
5124:     (*mat->ops->scale)(mat,a);
5125:     PetscObjectStateIncrease((PetscObject)mat);
5126: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5127:     if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5128:       mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5129:     }
5130: #endif
5131:   }
5132:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5133:   return(0);
5134: }

5136: /*@
5137:    MatNorm - Calculates various norms of a matrix.

5139:    Collective on Mat

5141:    Input Parameters:
5142: +  mat - the matrix
5143: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5145:    Output Parameters:
5146: .  nrm - the resulting norm

5148:    Level: intermediate

5150: @*/
5151: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5152: {


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

5165:   (*mat->ops->norm)(mat,type,nrm);
5166:   return(0);
5167: }

5169: /*
5170:      This variable is used to prevent counting of MatAssemblyBegin() that
5171:    are called from within a MatAssemblyEnd().
5172: */
5173: static PetscInt MatAssemblyEnd_InUse = 0;
5174: /*@
5175:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5176:    be called after completing all calls to MatSetValues().

5178:    Collective on Mat

5180:    Input Parameters:
5181: +  mat - the matrix
5182: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5184:    Notes:
5185:    MatSetValues() generally caches the values.  The matrix is ready to
5186:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5187:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5188:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5189:    using the matrix.

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

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

5199:    Level: beginner

5201: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5202: @*/
5203: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5204: {

5210:   MatCheckPreallocated(mat,1);
5211:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5212:   if (mat->assembled) {
5213:     mat->was_assembled = PETSC_TRUE;
5214:     mat->assembled     = PETSC_FALSE;
5215:   }
5216:   if (!MatAssemblyEnd_InUse) {
5217:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5218:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5219:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5220:   } else if (mat->ops->assemblybegin) {
5221:     (*mat->ops->assemblybegin)(mat,type);
5222:   }
5223:   return(0);
5224: }

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

5230:    Not Collective

5232:    Input Parameter:
5233: .  mat - the matrix

5235:    Output Parameter:
5236: .  assembled - PETSC_TRUE or PETSC_FALSE

5238:    Level: advanced

5240: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5241: @*/
5242: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5243: {
5247:   *assembled = mat->assembled;
5248:   return(0);
5249: }

5251: /*@
5252:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5253:    be called after MatAssemblyBegin().

5255:    Collective on Mat

5257:    Input Parameters:
5258: +  mat - the matrix
5259: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5261:    Options Database Keys:
5262: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5263: .  -mat_view ::ascii_info_detail - Prints more detailed info
5264: .  -mat_view - Prints matrix in ASCII format
5265: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5266: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5267: .  -display <name> - Sets display name (default is host)
5268: .  -draw_pause <sec> - Sets number of seconds to pause after display
5269: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5270: .  -viewer_socket_machine <machine> - Machine to use for socket
5271: .  -viewer_socket_port <port> - Port number to use for socket
5272: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5274:    Notes:
5275:    MatSetValues() generally caches the values.  The matrix is ready to
5276:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5277:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5278:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5279:    using the matrix.

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

5285:    Level: beginner

5287: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5288: @*/
5289: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5290: {
5291:   PetscErrorCode  ierr;
5292:   static PetscInt inassm = 0;
5293:   PetscBool       flg    = PETSC_FALSE;


5299:   inassm++;
5300:   MatAssemblyEnd_InUse++;
5301:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5302:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5303:     if (mat->ops->assemblyend) {
5304:       (*mat->ops->assemblyend)(mat,type);
5305:     }
5306:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5307:   } else if (mat->ops->assemblyend) {
5308:     (*mat->ops->assemblyend)(mat,type);
5309:   }

5311:   /* Flush assembly is not a true assembly */
5312:   if (type != MAT_FLUSH_ASSEMBLY) {
5313:     mat->assembled = PETSC_TRUE; mat->num_ass++;
5314:   }
5315:   mat->insertmode = NOT_SET_VALUES;
5316:   MatAssemblyEnd_InUse--;
5317:   PetscObjectStateIncrease((PetscObject)mat);
5318:   if (!mat->symmetric_eternal) {
5319:     mat->symmetric_set              = PETSC_FALSE;
5320:     mat->hermitian_set              = PETSC_FALSE;
5321:     mat->structurally_symmetric_set = PETSC_FALSE;
5322:   }
5323: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5324:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5325:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5326:   }
5327: #endif
5328:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5329:     MatViewFromOptions(mat,NULL,"-mat_view");

5331:     if (mat->checksymmetryonassembly) {
5332:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5333:       if (flg) {
5334:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5335:       } else {
5336:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5337:       }
5338:     }
5339:     if (mat->nullsp && mat->checknullspaceonassembly) {
5340:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5341:     }
5342:   }
5343:   inassm--;
5344:   return(0);
5345: }

5347: /*@
5348:    MatSetOption - Sets a parameter option for a matrix. Some options
5349:    may be specific to certain storage formats.  Some options
5350:    determine how values will be inserted (or added). Sorted,
5351:    row-oriented input will generally assemble the fastest. The default
5352:    is row-oriented.

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

5356:    Input Parameters:
5357: +  mat - the matrix
5358: .  option - the option, one of those listed below (and possibly others),
5359: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5361:   Options Describing Matrix Structure:
5362: +    MAT_SPD - symmetric positive definite
5363: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5364: .    MAT_HERMITIAN - transpose is the complex conjugation
5365: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5366: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5367:                             you set to be kept with all future use of the matrix
5368:                             including after MatAssemblyBegin/End() which could
5369:                             potentially change the symmetry structure, i.e. you
5370:                             KNOW the matrix will ALWAYS have the property you set.


5373:    Options For Use with MatSetValues():
5374:    Insert a logically dense subblock, which can be
5375: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5429:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5430:    searches during matrix assembly. When this flag is set, the hash table
5431:    is created during the first Matrix Assembly. This hash table is
5432:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5433:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5434:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5435:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5454:    Level: intermediate

5456: .seealso:  MatOption, Mat

5458: @*/
5459: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5460: {

5466:   if (op > 0) {
5469:   }

5471:   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);
5472:   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()");

5474:   switch (op) {
5475:   case MAT_NO_OFF_PROC_ENTRIES:
5476:     mat->nooffprocentries = flg;
5477:     return(0);
5478:     break;
5479:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5480:     mat->assembly_subset = flg;
5481:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5482: #if !defined(PETSC_HAVE_MPIUNI)
5483:       MatStashScatterDestroy_BTS(&mat->stash);
5484: #endif
5485:       mat->stash.first_assembly_done = PETSC_FALSE;
5486:     }
5487:     return(0);
5488:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5489:     mat->nooffproczerorows = flg;
5490:     return(0);
5491:     break;
5492:   case MAT_SPD:
5493:     mat->spd_set = PETSC_TRUE;
5494:     mat->spd     = flg;
5495:     if (flg) {
5496:       mat->symmetric                  = PETSC_TRUE;
5497:       mat->structurally_symmetric     = PETSC_TRUE;
5498:       mat->symmetric_set              = PETSC_TRUE;
5499:       mat->structurally_symmetric_set = PETSC_TRUE;
5500:     }
5501:     break;
5502:   case MAT_SYMMETRIC:
5503:     mat->symmetric = flg;
5504:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5505:     mat->symmetric_set              = PETSC_TRUE;
5506:     mat->structurally_symmetric_set = flg;
5507: #if !defined(PETSC_USE_COMPLEX)
5508:     mat->hermitian     = flg;
5509:     mat->hermitian_set = PETSC_TRUE;
5510: #endif
5511:     break;
5512:   case MAT_HERMITIAN:
5513:     mat->hermitian = flg;
5514:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5515:     mat->hermitian_set              = PETSC_TRUE;
5516:     mat->structurally_symmetric_set = flg;
5517: #if !defined(PETSC_USE_COMPLEX)
5518:     mat->symmetric     = flg;
5519:     mat->symmetric_set = PETSC_TRUE;
5520: #endif
5521:     break;
5522:   case MAT_STRUCTURALLY_SYMMETRIC:
5523:     mat->structurally_symmetric     = flg;
5524:     mat->structurally_symmetric_set = PETSC_TRUE;
5525:     break;
5526:   case MAT_SYMMETRY_ETERNAL:
5527:     mat->symmetric_eternal = flg;
5528:     break;
5529:   case MAT_STRUCTURE_ONLY:
5530:     mat->structure_only = flg;
5531:     break;
5532:   default:
5533:     break;
5534:   }
5535:   if (mat->ops->setoption) {
5536:     (*mat->ops->setoption)(mat,op,flg);
5537:   }
5538:   return(0);
5539: }

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

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

5546:    Input Parameters:
5547: +  mat - the matrix
5548: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5556:    Level: intermediate

5558: .seealso:  MatOption, MatSetOption()

5560: @*/
5561: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5562: {

5567:   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);
5568:   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()");

5570:   switch (op) {
5571:   case MAT_NO_OFF_PROC_ENTRIES:
5572:     *flg = mat->nooffprocentries;
5573:     break;
5574:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5575:     *flg = mat->nooffproczerorows;
5576:     break;
5577:   case MAT_SYMMETRIC:
5578:     *flg = mat->symmetric;
5579:     break;
5580:   case MAT_HERMITIAN:
5581:     *flg = mat->hermitian;
5582:     break;
5583:   case MAT_STRUCTURALLY_SYMMETRIC:
5584:     *flg = mat->structurally_symmetric;
5585:     break;
5586:   case MAT_SYMMETRY_ETERNAL:
5587:     *flg = mat->symmetric_eternal;
5588:     break;
5589:   case MAT_SPD:
5590:     *flg = mat->spd;
5591:     break;
5592:   default:
5593:     break;
5594:   }
5595:   return(0);
5596: }

5598: /*@
5599:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5600:    this routine retains the old nonzero structure.

5602:    Logically Collective on Mat

5604:    Input Parameters:
5605: .  mat - the matrix

5607:    Level: intermediate

5609:    Notes:
5610:     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.
5611:    See the Performance chapter of the users manual for information on preallocating matrices.

5613: .seealso: MatZeroRows()
5614: @*/
5615: PetscErrorCode MatZeroEntries(Mat mat)
5616: {

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

5627:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5628:   (*mat->ops->zeroentries)(mat);
5629:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5630:   PetscObjectStateIncrease((PetscObject)mat);
5631: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5632:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5633:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5634:   }
5635: #endif
5636:   return(0);
5637: }

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

5643:    Collective on Mat

5645:    Input Parameters:
5646: +  mat - the matrix
5647: .  numRows - the number of rows to remove
5648: .  rows - the global row indices
5649: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5650: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5651: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5670:    Level: intermediate

5672: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5673:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5674: @*/
5675: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5676: {

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

5688:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5689:   MatViewFromOptions(mat,NULL,"-mat_view");
5690:   PetscObjectStateIncrease((PetscObject)mat);
5691: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5692:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5693:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5694:   }
5695: #endif
5696:   return(0);
5697: }

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

5703:    Collective on Mat

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

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

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

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

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

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

5729:    Level: intermediate

5731: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5732:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5733: @*/
5734: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5735: {
5737:   PetscInt       numRows;
5738:   const PetscInt *rows;

5745:   ISGetLocalSize(is,&numRows);
5746:   ISGetIndices(is,&rows);
5747:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5748:   ISRestoreIndices(is,&rows);
5749:   return(0);
5750: }

5752: /*@
5753:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5754:    of a set of rows of a matrix.

5756:    Collective on Mat

5758:    Input Parameters:
5759: +  mat - the matrix
5760: .  numRows - the number of rows to remove
5761: .  rows - the global row indices
5762: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5763: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5764: -  b - optional vector of right hand side, that will be adjusted by provided solution

5766:    Notes:
5767:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5768:    but does not release memory.  For the dense and block diagonal
5769:    formats this does not alter the nonzero structure.

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

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

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

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

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

5790:    Level: intermediate

5792: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5793:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5794: @*/
5795: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5796: {

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

5808:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5809:   MatViewFromOptions(mat,NULL,"-mat_view");
5810:   PetscObjectStateIncrease((PetscObject)mat);
5811: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5812:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5813:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5814:   }
5815: #endif
5816:   return(0);
5817: }

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

5823:    Collective on Mat

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

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

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

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

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

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

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

5856:    Level: intermediate

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

5871:   ISGetLocalSize(is,&numRows);
5872:   ISGetIndices(is,&rows);
5873:   MatZeroRows(mat,numRows,rows,diag,x,b);
5874:   ISRestoreIndices(is,&rows);
5875:   return(0);
5876: }

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

5882:    Collective on Mat

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

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

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

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

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

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

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

5915:    In Fortran idxm and idxn should be declared as
5916: $     MatStencil idxm(4,m)
5917:    and the values inserted using
5918: $    idxm(MatStencil_i,1) = i
5919: $    idxm(MatStencil_j,1) = j
5920: $    idxm(MatStencil_k,1) = k
5921: $    idxm(MatStencil_c,1) = c
5922:    etc

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

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

5932:    Level: intermediate

5934: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5935:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5936: @*/
5937: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5938: {
5939:   PetscInt       dim     = mat->stencil.dim;
5940:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5941:   PetscInt       *dims   = mat->stencil.dims+1;
5942:   PetscInt       *starts = mat->stencil.starts;
5943:   PetscInt       *dxm    = (PetscInt*) rows;
5944:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5952:   PetscMalloc1(numRows, &jdxm);
5953:   for (i = 0; i < numRows; ++i) {
5954:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5955:     for (j = 0; j < 3-sdim; ++j) dxm++;
5956:     /* Local index in X dir */
5957:     tmp = *dxm++ - starts[0];
5958:     /* Loop over remaining dimensions */
5959:     for (j = 0; j < dim-1; ++j) {
5960:       /* If nonlocal, set index to be negative */
5961:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5962:       /* Update local index */
5963:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5964:     }
5965:     /* Skip component slot if necessary */
5966:     if (mat->stencil.noc) dxm++;
5967:     /* Local row number */
5968:     if (tmp >= 0) {
5969:       jdxm[numNewRows++] = tmp;
5970:     }
5971:   }
5972:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5973:   PetscFree(jdxm);
5974:   return(0);
5975: }

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

5981:    Collective on Mat

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

5991:    Notes:
5992:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5993:    but does not release memory.  For the dense and block diagonal
5994:    formats this does not alter the nonzero structure.

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

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

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

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

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

6014:    In Fortran idxm and idxn should be declared as
6015: $     MatStencil idxm(4,m)
6016:    and the values inserted using
6017: $    idxm(MatStencil_i,1) = i
6018: $    idxm(MatStencil_j,1) = j
6019: $    idxm(MatStencil_k,1) = k
6020: $    idxm(MatStencil_c,1) = c
6021:    etc

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

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

6031:    Level: intermediate

6033: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6034:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6035: @*/
6036: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6037: {
6038:   PetscInt       dim     = mat->stencil.dim;
6039:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6040:   PetscInt       *dims   = mat->stencil.dims+1;
6041:   PetscInt       *starts = mat->stencil.starts;
6042:   PetscInt       *dxm    = (PetscInt*) rows;
6043:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6051:   PetscMalloc1(numRows, &jdxm);
6052:   for (i = 0; i < numRows; ++i) {
6053:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6054:     for (j = 0; j < 3-sdim; ++j) dxm++;
6055:     /* Local index in X dir */
6056:     tmp = *dxm++ - starts[0];
6057:     /* Loop over remaining dimensions */
6058:     for (j = 0; j < dim-1; ++j) {
6059:       /* If nonlocal, set index to be negative */
6060:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6061:       /* Update local index */
6062:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6063:     }
6064:     /* Skip component slot if necessary */
6065:     if (mat->stencil.noc) dxm++;
6066:     /* Local row number */
6067:     if (tmp >= 0) {
6068:       jdxm[numNewRows++] = tmp;
6069:     }
6070:   }
6071:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6072:   PetscFree(jdxm);
6073:   return(0);
6074: }

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

6080:    Collective on Mat

6082:    Input Parameters:
6083: +  mat - the matrix
6084: .  numRows - the number of rows to remove
6085: .  rows - the global row indices
6086: .  diag - value put in all diagonals of eliminated rows
6087: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6088: -  b - optional vector of right hand side, that will be adjusted by provided solution

6090:    Notes:
6091:    Before calling MatZeroRowsLocal(), the user must first set the
6092:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6094:    For the AIJ matrix formats this removes the old nonzero structure,
6095:    but does not release memory.  For the dense and block diagonal
6096:    formats this does not alter the nonzero structure.

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

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

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

6109:    Level: intermediate

6111: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6112:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6113: @*/
6114: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6115: {

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

6126:   if (mat->ops->zerorowslocal) {
6127:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6128:   } else {
6129:     IS             is, newis;
6130:     const PetscInt *newRows;

6132:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6133:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6134:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6135:     ISGetIndices(newis,&newRows);
6136:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6137:     ISRestoreIndices(newis,&newRows);
6138:     ISDestroy(&newis);
6139:     ISDestroy(&is);
6140:   }
6141:   PetscObjectStateIncrease((PetscObject)mat);
6142: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6143:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6144:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6145:   }
6146: #endif
6147:   return(0);
6148: }

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

6154:    Collective on Mat

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

6163:    Notes:
6164:    Before calling MatZeroRowsLocalIS(), the user must first set the
6165:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6167:    For the AIJ matrix formats this removes the old nonzero structure,
6168:    but does not release memory.  For the dense and block diagonal
6169:    formats this does not alter the nonzero structure.

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

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

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

6182:    Level: intermediate

6184: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6185:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6186: @*/
6187: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6188: {
6190:   PetscInt       numRows;
6191:   const PetscInt *rows;

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

6201:   ISGetLocalSize(is,&numRows);
6202:   ISGetIndices(is,&rows);
6203:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6204:   ISRestoreIndices(is,&rows);
6205:   return(0);
6206: }

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

6212:    Collective on Mat

6214:    Input Parameters:
6215: +  mat - the matrix
6216: .  numRows - the number of rows to remove
6217: .  rows - the global row indices
6218: .  diag - value put in all diagonals of eliminated rows
6219: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6220: -  b - optional vector of right hand side, that will be adjusted by provided solution

6222:    Notes:
6223:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6224:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6230:    Level: intermediate

6232: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6233:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6234: @*/
6235: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6236: {
6238:   IS             is, newis;
6239:   const PetscInt *newRows;

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

6249:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6250:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6251:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6252:   ISGetIndices(newis,&newRows);
6253:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6254:   ISRestoreIndices(newis,&newRows);
6255:   ISDestroy(&newis);
6256:   ISDestroy(&is);
6257:   PetscObjectStateIncrease((PetscObject)mat);
6258: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6259:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6260:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6261:   }
6262: #endif
6263:   return(0);
6264: }

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

6270:    Collective on Mat

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

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

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

6287:    Level: intermediate

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

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

6306:   ISGetLocalSize(is,&numRows);
6307:   ISGetIndices(is,&rows);
6308:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6309:   ISRestoreIndices(is,&rows);
6310:   return(0);
6311: }

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

6316:    Not Collective

6318:    Input Parameter:
6319: .  mat - the matrix

6321:    Output Parameters:
6322: +  m - the number of global rows
6323: -  n - the number of global columns

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

6327:    Level: beginner

6329: .seealso: MatGetLocalSize()
6330: @*/
6331: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6332: {
6335:   if (m) *m = mat->rmap->N;
6336:   if (n) *n = mat->cmap->N;
6337:   return(0);
6338: }

6340: /*@C
6341:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6342:    stored locally.  This information may be implementation dependent, so
6343:    use with care.

6345:    Not Collective

6347:    Input Parameters:
6348: .  mat - the matrix

6350:    Output Parameters:
6351: +  m - the number of local rows
6352: -  n - the number of local columns

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

6356:    Level: beginner

6358: .seealso: MatGetSize()
6359: @*/
6360: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6361: {
6366:   if (m) *m = mat->rmap->n;
6367:   if (n) *n = mat->cmap->n;
6368:   return(0);
6369: }

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

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

6377:    Input Parameters:
6378: .  mat - the matrix

6380:    Output Parameters:
6381: +  m - the global index of the first local column
6382: -  n - one more than the global index of the last local column

6384:    Notes:
6385:     both output parameters can be NULL on input.

6387:    Level: developer

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

6391: @*/
6392: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6393: {
6399:   MatCheckPreallocated(mat,1);
6400:   if (m) *m = mat->cmap->rstart;
6401:   if (n) *n = mat->cmap->rend;
6402:   return(0);
6403: }

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

6411:    Not Collective

6413:    Input Parameters:
6414: .  mat - the matrix

6416:    Output Parameters:
6417: +  m - the global index of the first local row
6418: -  n - one more than the global index of the last local row

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

6425:    Level: beginner

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

6429: @*/
6430: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6431: {
6437:   MatCheckPreallocated(mat,1);
6438:   if (m) *m = mat->rmap->rstart;
6439:   if (n) *n = mat->rmap->rend;
6440:   return(0);
6441: }

6443: /*@C
6444:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6445:    each process

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

6449:    Input Parameters:
6450: .  mat - the matrix

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

6455:    Level: beginner

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

6459: @*/
6460: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6461: {

6467:   MatCheckPreallocated(mat,1);
6468:   PetscLayoutGetRanges(mat->rmap,ranges);
6469:   return(0);
6470: }

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

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

6478:    Input Parameters:
6479: .  mat - the matrix

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

6484:    Level: beginner

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

6488: @*/
6489: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6490: {

6496:   MatCheckPreallocated(mat,1);
6497:   PetscLayoutGetRanges(mat->cmap,ranges);
6498:   return(0);
6499: }

6501: /*@C
6502:    MatGetOwnershipIS - Get row and column ownership as index sets

6504:    Not Collective

6506:    Input Arguments:
6507: .  A - matrix of type Elemental

6509:    Output Arguments:
6510: +  rows - rows in which this process owns elements
6511: .  cols - columns in which this process owns elements

6513:    Level: intermediate

6515: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6516: @*/
6517: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6518: {
6519:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6522:   MatCheckPreallocated(A,1);
6523:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6524:   if (f) {
6525:     (*f)(A,rows,cols);
6526:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6527:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6528:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6529:   }
6530:   return(0);
6531: }

6533: /*@C
6534:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6535:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6536:    to complete the factorization.

6538:    Collective on Mat

6540:    Input Parameters:
6541: +  mat - the matrix
6542: .  row - row permutation
6543: .  column - column permutation
6544: -  info - structure containing
6545: $      levels - number of levels of fill.
6546: $      expected fill - as ratio of original fill.
6547: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6548:                 missing diagonal entries)

6550:    Output Parameters:
6551: .  fact - new matrix that has been symbolically factored

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

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

6560:    Level: developer

6562: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6563:           MatGetOrdering(), MatFactorInfo

6565:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6570:    References:
6571:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6572: @*/
6573: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6574: {

6584:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6585:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6586:   if (!(fact)->ops->ilufactorsymbolic) {
6587:     MatSolverType spackage;
6588:     MatFactorGetSolverType(fact,&spackage);
6589:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6590:   }
6591:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6592:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6593:   MatCheckPreallocated(mat,2);

6595:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6596:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6597:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6598:   return(0);
6599: }

6601: /*@C
6602:    MatICCFactorSymbolic - Performs symbolic incomplete
6603:    Cholesky factorization for a symmetric matrix.  Use
6604:    MatCholeskyFactorNumeric() to complete the factorization.

6606:    Collective on Mat

6608:    Input Parameters:
6609: +  mat - the matrix
6610: .  perm - row and column permutation
6611: -  info - structure containing
6612: $      levels - number of levels of fill.
6613: $      expected fill - as ratio of original fill.

6615:    Output Parameter:
6616: .  fact - the factored matrix

6618:    Notes:
6619:    Most users should employ the KSP interface for linear solvers
6620:    instead of working directly with matrix algebra routines such as this.
6621:    See, e.g., KSPCreate().

6623:    Level: developer

6625: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6627:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6632:    References:
6633:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6634: @*/
6635: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6636: {

6645:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6646:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6647:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6648:   if (!(fact)->ops->iccfactorsymbolic) {
6649:     MatSolverType spackage;
6650:     MatFactorGetSolverType(fact,&spackage);
6651:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6652:   }
6653:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6654:   MatCheckPreallocated(mat,2);

6656:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6657:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6658:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6659:   return(0);
6660: }

6662: /*@C
6663:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6664:    points to an array of valid matrices, they may be reused to store the new
6665:    submatrices.

6667:    Collective on Mat

6669:    Input Parameters:
6670: +  mat - the matrix
6671: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6672: .  irow, icol - index sets of rows and columns to extract
6673: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6675:    Output Parameter:
6676: .  submat - the array of submatrices

6678:    Notes:
6679:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6680:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6681:    to extract a parallel submatrix.

6683:    Some matrix types place restrictions on the row and column
6684:    indices, such as that they be sorted or that they be equal to each other.

6686:    The index sets may not have duplicate entries.

6688:    When extracting submatrices from a parallel matrix, each processor can
6689:    form a different submatrix by setting the rows and columns of its
6690:    individual index sets according to the local submatrix desired.

6692:    When finished using the submatrices, the user should destroy
6693:    them with MatDestroySubMatrices().

6695:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6696:    original matrix has not changed from that last call to MatCreateSubMatrices().

6698:    This routine creates the matrices in submat; you should NOT create them before
6699:    calling it. It also allocates the array of matrix pointers submat.

6701:    For BAIJ matrices the index sets must respect the block structure, that is if they
6702:    request one row/column in a block, they must request all rows/columns that are in
6703:    that block. For example, if the block size is 2 you cannot request just row 0 and
6704:    column 0.

6706:    Fortran Note:
6707:    The Fortran interface is slightly different from that given below; it
6708:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6710:    Level: advanced


6713: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6714: @*/
6715: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6716: {
6718:   PetscInt       i;
6719:   PetscBool      eq;

6724:   if (n) {
6729:   }
6731:   if (n && scall == MAT_REUSE_MATRIX) {
6734:   }
6735:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6736:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6737:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6738:   MatCheckPreallocated(mat,1);

6740:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6741:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6742:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6743:   for (i=0; i<n; i++) {
6744:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6745:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6746:       ISEqual(irow[i],icol[i],&eq);
6747:       if (eq) {
6748:         if (mat->symmetric) {
6749:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6750:         } else if (mat->hermitian) {
6751:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6752:         } else if (mat->structurally_symmetric) {
6753:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6754:         }
6755:       }
6756:     }
6757:   }
6758:   return(0);
6759: }

6761: /*@C
6762:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6764:    Collective on Mat

6766:    Input Parameters:
6767: +  mat - the matrix
6768: .  n   - the number of submatrixes to be extracted
6769: .  irow, icol - index sets of rows and columns to extract
6770: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6772:    Output Parameter:
6773: .  submat - the array of submatrices

6775:    Level: advanced


6778: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6779: @*/
6780: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6781: {
6783:   PetscInt       i;
6784:   PetscBool      eq;

6789:   if (n) {
6794:   }
6796:   if (n && scall == MAT_REUSE_MATRIX) {
6799:   }
6800:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6801:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6802:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6803:   MatCheckPreallocated(mat,1);

6805:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6806:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6807:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6808:   for (i=0; i<n; i++) {
6809:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6810:       ISEqual(irow[i],icol[i],&eq);
6811:       if (eq) {
6812:         if (mat->symmetric) {
6813:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6814:         } else if (mat->hermitian) {
6815:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6816:         } else if (mat->structurally_symmetric) {
6817:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6818:         }
6819:       }
6820:     }
6821:   }
6822:   return(0);
6823: }

6825: /*@C
6826:    MatDestroyMatrices - Destroys an array of matrices.

6828:    Collective on Mat

6830:    Input Parameters:
6831: +  n - the number of local matrices
6832: -  mat - the matrices (note that this is a pointer to the array of matrices)

6834:    Level: advanced

6836:     Notes:
6837:     Frees not only the matrices, but also the array that contains the matrices
6838:            In Fortran will not free the array.

6840: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6841: @*/
6842: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6843: {
6845:   PetscInt       i;

6848:   if (!*mat) return(0);
6849:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6852:   for (i=0; i<n; i++) {
6853:     MatDestroy(&(*mat)[i]);
6854:   }

6856:   /* memory is allocated even if n = 0 */
6857:   PetscFree(*mat);
6858:   return(0);
6859: }

6861: /*@C
6862:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6864:    Collective on Mat

6866:    Input Parameters:
6867: +  n - the number of local matrices
6868: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6869:                        sequence of MatCreateSubMatrices())

6871:    Level: advanced

6873:     Notes:
6874:     Frees not only the matrices, but also the array that contains the matrices
6875:            In Fortran will not free the array.

6877: .seealso: MatCreateSubMatrices()
6878: @*/
6879: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6880: {
6882:   Mat            mat0;

6885:   if (!*mat) return(0);
6886:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6887:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6890:   mat0 = (*mat)[0];
6891:   if (mat0 && mat0->ops->destroysubmatrices) {
6892:     (mat0->ops->destroysubmatrices)(n,mat);
6893:   } else {
6894:     MatDestroyMatrices(n,mat);
6895:   }
6896:   return(0);
6897: }

6899: /*@C
6900:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6902:    Collective on Mat

6904:    Input Parameters:
6905: .  mat - the matrix

6907:    Output Parameter:
6908: .  matstruct - the sequential matrix with the nonzero structure of mat

6910:   Level: intermediate

6912: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6913: @*/
6914: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6915: {


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

6926:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6927:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6928:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6929:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6930:   return(0);
6931: }

6933: /*@C
6934:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6936:    Collective on Mat

6938:    Input Parameters:
6939: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6940:                        sequence of MatGetSequentialNonzeroStructure())

6942:    Level: advanced

6944:     Notes:
6945:     Frees not only the matrices, but also the array that contains the matrices

6947: .seealso: MatGetSeqNonzeroStructure()
6948: @*/
6949: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6950: {

6955:   MatDestroy(mat);
6956:   return(0);
6957: }

6959: /*@
6960:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6961:    replaces the index sets by larger ones that represent submatrices with
6962:    additional overlap.

6964:    Collective on Mat

6966:    Input Parameters:
6967: +  mat - the matrix
6968: .  n   - the number of index sets
6969: .  is  - the array of index sets (these index sets will changed during the call)
6970: -  ov  - the additional overlap requested

6972:    Options Database:
6973: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

6975:    Level: developer


6978: .seealso: MatCreateSubMatrices()
6979: @*/
6980: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6981: {

6987:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6988:   if (n) {
6991:   }
6992:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6993:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6994:   MatCheckPreallocated(mat,1);

6996:   if (!ov) return(0);
6997:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6998:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6999:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7000:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7001:   return(0);
7002: }


7005: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7007: /*@
7008:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7009:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7010:    additional overlap.

7012:    Collective on Mat

7014:    Input Parameters:
7015: +  mat - the matrix
7016: .  n   - the number of index sets
7017: .  is  - the array of index sets (these index sets will changed during the call)
7018: -  ov  - the additional overlap requested

7020:    Options Database:
7021: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7023:    Level: developer


7026: .seealso: MatCreateSubMatrices()
7027: @*/
7028: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7029: {
7030:   PetscInt       i;

7036:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7037:   if (n) {
7040:   }
7041:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7042:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7043:   MatCheckPreallocated(mat,1);
7044:   if (!ov) return(0);
7045:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7046:   for(i=0; i<n; i++){
7047:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7048:   }
7049:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7050:   return(0);
7051: }




7056: /*@
7057:    MatGetBlockSize - Returns the matrix block size.

7059:    Not Collective

7061:    Input Parameter:
7062: .  mat - the matrix

7064:    Output Parameter:
7065: .  bs - block size

7067:    Notes:
7068:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7070:    If the block size has not been set yet this routine returns 1.

7072:    Level: intermediate

7074: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7075: @*/
7076: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7077: {
7081:   *bs = PetscAbs(mat->rmap->bs);
7082:   return(0);
7083: }

7085: /*@
7086:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7088:    Not Collective

7090:    Input Parameter:
7091: .  mat - the matrix

7093:    Output Parameter:
7094: .  rbs - row block size
7095: .  cbs - column block size

7097:    Notes:
7098:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7099:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7101:    If a block size has not been set yet this routine returns 1.

7103:    Level: intermediate

7105: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7106: @*/
7107: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7108: {
7113:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7114:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7115:   return(0);
7116: }

7118: /*@
7119:    MatSetBlockSize - Sets the matrix block size.

7121:    Logically Collective on Mat

7123:    Input Parameters:
7124: +  mat - the matrix
7125: -  bs - block size

7127:    Notes:
7128:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7129:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7131:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7132:     is compatible with the matrix local sizes.

7134:    Level: intermediate

7136: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7137: @*/
7138: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7139: {

7145:   MatSetBlockSizes(mat,bs,bs);
7146:   return(0);
7147: }

7149: /*@
7150:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7152:    Logically Collective on Mat

7154:    Input Parameters:
7155: +  mat - the matrix
7156: .  nblocks - the number of blocks on this process
7157: -  bsizes - the block sizes

7159:    Notes:
7160:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7162:    Level: intermediate

7164: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7165: @*/
7166: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7167: {
7169:   PetscInt       i,ncnt = 0, nlocal;

7173:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7174:   MatGetLocalSize(mat,&nlocal,NULL);
7175:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7176:   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);
7177:   PetscFree(mat->bsizes);
7178:   mat->nblocks = nblocks;
7179:   PetscMalloc1(nblocks,&mat->bsizes);
7180:   PetscMemcpy(mat->bsizes,bsizes,nblocks*sizeof(PetscInt));
7181:   return(0);
7182: }

7184: /*@C
7185:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7187:    Logically Collective on Mat

7189:    Input Parameters:
7190: .  mat - the matrix

7192:    Output Parameters:
7193: +  nblocks - the number of blocks on this process
7194: -  bsizes - the block sizes

7196:    Notes: Currently not supported from Fortran

7198:    Level: intermediate

7200: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7201: @*/
7202: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7203: {
7206:   *nblocks = mat->nblocks;
7207:   *bsizes  = mat->bsizes;
7208:   return(0);
7209: }

7211: /*@
7212:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7214:    Logically Collective on Mat

7216:    Input Parameters:
7217: +  mat - the matrix
7218: -  rbs - row block size
7219: -  cbs - column block size

7221:    Notes:
7222:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7223:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7224:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later

7226:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7227:     are compatible with the matrix local sizes.

7229:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7231:    Level: intermediate

7233: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7234: @*/
7235: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7236: {

7243:   if (mat->ops->setblocksizes) {
7244:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7245:   }
7246:   if (mat->rmap->refcnt) {
7247:     ISLocalToGlobalMapping l2g = NULL;
7248:     PetscLayout            nmap = NULL;

7250:     PetscLayoutDuplicate(mat->rmap,&nmap);
7251:     if (mat->rmap->mapping) {
7252:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7253:     }
7254:     PetscLayoutDestroy(&mat->rmap);
7255:     mat->rmap = nmap;
7256:     mat->rmap->mapping = l2g;
7257:   }
7258:   if (mat->cmap->refcnt) {
7259:     ISLocalToGlobalMapping l2g = NULL;
7260:     PetscLayout            nmap = NULL;

7262:     PetscLayoutDuplicate(mat->cmap,&nmap);
7263:     if (mat->cmap->mapping) {
7264:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7265:     }
7266:     PetscLayoutDestroy(&mat->cmap);
7267:     mat->cmap = nmap;
7268:     mat->cmap->mapping = l2g;
7269:   }
7270:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7271:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7272:   return(0);
7273: }

7275: /*@
7276:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7278:    Logically Collective on Mat

7280:    Input Parameters:
7281: +  mat - the matrix
7282: .  fromRow - matrix from which to copy row block size
7283: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7285:    Level: developer

7287: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7288: @*/
7289: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7290: {

7297:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7298:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7299:   return(0);
7300: }

7302: /*@
7303:    MatResidual - Default routine to calculate the residual.

7305:    Collective on Mat

7307:    Input Parameters:
7308: +  mat - the matrix
7309: .  b   - the right-hand-side
7310: -  x   - the approximate solution

7312:    Output Parameter:
7313: .  r - location to store the residual

7315:    Level: developer

7317: .seealso: PCMGSetResidual()
7318: @*/
7319: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7320: {

7329:   MatCheckPreallocated(mat,1);
7330:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7331:   if (!mat->ops->residual) {
7332:     MatMult(mat,x,r);
7333:     VecAYPX(r,-1.0,b);
7334:   } else {
7335:     (*mat->ops->residual)(mat,b,x,r);
7336:   }
7337:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7338:   return(0);
7339: }

7341: /*@C
7342:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7344:    Collective on Mat

7346:     Input Parameters:
7347: +   mat - the matrix
7348: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7349: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7350: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7351:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7352:                  always used.

7354:     Output Parameters:
7355: +   n - number of rows in the (possibly compressed) matrix
7356: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7357: .   ja - the column indices
7358: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7359:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7361:     Level: developer

7363:     Notes:
7364:     You CANNOT change any of the ia[] or ja[] values.

7366:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7368:     Fortran Notes:
7369:     In Fortran use
7370: $
7371: $      PetscInt ia(1), ja(1)
7372: $      PetscOffset iia, jja
7373: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7374: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7376:      or
7377: $
7378: $    PetscInt, pointer :: ia(:),ja(:)
7379: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7380: $    ! Access the ith and jth entries via ia(i) and ja(j)

7382: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7383: @*/
7384: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7385: {

7395:   MatCheckPreallocated(mat,1);
7396:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7397:   else {
7398:     *done = PETSC_TRUE;
7399:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7400:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7401:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7402:   }
7403:   return(0);
7404: }

7406: /*@C
7407:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7409:     Collective on Mat

7411:     Input Parameters:
7412: +   mat - the matrix
7413: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7414: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7415:                 symmetrized
7416: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7417:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7418:                  always used.
7419: .   n - number of columns in the (possibly compressed) matrix
7420: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7421: -   ja - the row indices

7423:     Output Parameters:
7424: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7426:     Level: developer

7428: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7429: @*/
7430: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7431: {

7441:   MatCheckPreallocated(mat,1);
7442:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7443:   else {
7444:     *done = PETSC_TRUE;
7445:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7446:   }
7447:   return(0);
7448: }

7450: /*@C
7451:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7452:     MatGetRowIJ().

7454:     Collective on Mat

7456:     Input Parameters:
7457: +   mat - the matrix
7458: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7459: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7460:                 symmetrized
7461: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7462:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7463:                  always used.
7464: .   n - size of (possibly compressed) matrix
7465: .   ia - the row pointers
7466: -   ja - the column indices

7468:     Output Parameters:
7469: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7471:     Note:
7472:     This routine zeros out n, ia, and ja. This is to prevent accidental
7473:     us of the array after it has been restored. If you pass NULL, it will
7474:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7476:     Level: developer

7478: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7479: @*/
7480: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7481: {

7490:   MatCheckPreallocated(mat,1);

7492:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7493:   else {
7494:     *done = PETSC_TRUE;
7495:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7496:     if (n)  *n = 0;
7497:     if (ia) *ia = NULL;
7498:     if (ja) *ja = NULL;
7499:   }
7500:   return(0);
7501: }

7503: /*@C
7504:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7505:     MatGetColumnIJ().

7507:     Collective on Mat

7509:     Input Parameters:
7510: +   mat - the matrix
7511: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7512: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7513:                 symmetrized
7514: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7515:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7516:                  always used.

7518:     Output Parameters:
7519: +   n - size of (possibly compressed) matrix
7520: .   ia - the column pointers
7521: .   ja - the row indices
7522: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7524:     Level: developer

7526: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7527: @*/
7528: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7529: {

7538:   MatCheckPreallocated(mat,1);

7540:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7541:   else {
7542:     *done = PETSC_TRUE;
7543:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7544:     if (n)  *n = 0;
7545:     if (ia) *ia = NULL;
7546:     if (ja) *ja = NULL;
7547:   }
7548:   return(0);
7549: }

7551: /*@C
7552:     MatColoringPatch -Used inside matrix coloring routines that
7553:     use MatGetRowIJ() and/or MatGetColumnIJ().

7555:     Collective on Mat

7557:     Input Parameters:
7558: +   mat - the matrix
7559: .   ncolors - max color value
7560: .   n   - number of entries in colorarray
7561: -   colorarray - array indicating color for each column

7563:     Output Parameters:
7564: .   iscoloring - coloring generated using colorarray information

7566:     Level: developer

7568: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7570: @*/
7571: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7572: {

7580:   MatCheckPreallocated(mat,1);

7582:   if (!mat->ops->coloringpatch) {
7583:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7584:   } else {
7585:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7586:   }
7587:   return(0);
7588: }


7591: /*@
7592:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7594:    Logically Collective on Mat

7596:    Input Parameter:
7597: .  mat - the factored matrix to be reset

7599:    Notes:
7600:    This routine should be used only with factored matrices formed by in-place
7601:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7602:    format).  This option can save memory, for example, when solving nonlinear
7603:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7604:    ILU(0) preconditioner.

7606:    Note that one can specify in-place ILU(0) factorization by calling
7607: .vb
7608:      PCType(pc,PCILU);
7609:      PCFactorSeUseInPlace(pc);
7610: .ve
7611:    or by using the options -pc_type ilu -pc_factor_in_place

7613:    In-place factorization ILU(0) can also be used as a local
7614:    solver for the blocks within the block Jacobi or additive Schwarz
7615:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7616:    for details on setting local solver options.

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

7622:    Level: developer

7624: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7626: @*/
7627: PetscErrorCode MatSetUnfactored(Mat mat)
7628: {

7634:   MatCheckPreallocated(mat,1);
7635:   mat->factortype = MAT_FACTOR_NONE;
7636:   if (!mat->ops->setunfactored) return(0);
7637:   (*mat->ops->setunfactored)(mat);
7638:   return(0);
7639: }

7641: /*MC
7642:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7644:     Synopsis:
7645:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7647:     Not collective

7649:     Input Parameter:
7650: .   x - matrix

7652:     Output Parameters:
7653: +   xx_v - the Fortran90 pointer to the array
7654: -   ierr - error code

7656:     Example of Usage:
7657: .vb
7658:       PetscScalar, pointer xx_v(:,:)
7659:       ....
7660:       call MatDenseGetArrayF90(x,xx_v,ierr)
7661:       a = xx_v(3)
7662:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7663: .ve

7665:     Level: advanced

7667: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7669: M*/

7671: /*MC
7672:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7673:     accessed with MatDenseGetArrayF90().

7675:     Synopsis:
7676:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7678:     Not collective

7680:     Input Parameters:
7681: +   x - matrix
7682: -   xx_v - the Fortran90 pointer to the array

7684:     Output Parameter:
7685: .   ierr - error code

7687:     Example of Usage:
7688: .vb
7689:        PetscScalar, pointer xx_v(:,:)
7690:        ....
7691:        call MatDenseGetArrayF90(x,xx_v,ierr)
7692:        a = xx_v(3)
7693:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7694: .ve

7696:     Level: advanced

7698: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7700: M*/


7703: /*MC
7704:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7706:     Synopsis:
7707:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7709:     Not collective

7711:     Input Parameter:
7712: .   x - matrix

7714:     Output Parameters:
7715: +   xx_v - the Fortran90 pointer to the array
7716: -   ierr - error code

7718:     Example of Usage:
7719: .vb
7720:       PetscScalar, pointer xx_v(:)
7721:       ....
7722:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7723:       a = xx_v(3)
7724:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7725: .ve

7727:     Level: advanced

7729: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7731: M*/

7733: /*MC
7734:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7735:     accessed with MatSeqAIJGetArrayF90().

7737:     Synopsis:
7738:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7740:     Not collective

7742:     Input Parameters:
7743: +   x - matrix
7744: -   xx_v - the Fortran90 pointer to the array

7746:     Output Parameter:
7747: .   ierr - error code

7749:     Example of Usage:
7750: .vb
7751:        PetscScalar, pointer xx_v(:)
7752:        ....
7753:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7754:        a = xx_v(3)
7755:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7756: .ve

7758:     Level: advanced

7760: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7762: M*/


7765: /*@
7766:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7767:                       as the original matrix.

7769:     Collective on Mat

7771:     Input Parameters:
7772: +   mat - the original matrix
7773: .   isrow - parallel IS containing the rows this processor should obtain
7774: .   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.
7775: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7777:     Output Parameter:
7778: .   newmat - the new submatrix, of the same type as the old

7780:     Level: advanced

7782:     Notes:
7783:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7785:     Some matrix types place restrictions on the row and column indices, such
7786:     as that they be sorted or that they be equal to each other.

7788:     The index sets may not have duplicate entries.

7790:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7791:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7792:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7793:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7794:    you are finished using it.

7796:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7797:     the input matrix.

7799:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7801:    Example usage:
7802:    Consider the following 8x8 matrix with 34 non-zero values, that is
7803:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7804:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7805:    as follows:

7807: .vb
7808:             1  2  0  |  0  3  0  |  0  4
7809:     Proc0   0  5  6  |  7  0  0  |  8  0
7810:             9  0 10  | 11  0  0  | 12  0
7811:     -------------------------------------
7812:            13  0 14  | 15 16 17  |  0  0
7813:     Proc1   0 18  0  | 19 20 21  |  0  0
7814:             0  0  0  | 22 23  0  | 24  0
7815:     -------------------------------------
7816:     Proc2  25 26 27  |  0  0 28  | 29  0
7817:            30  0  0  | 31 32 33  |  0 34
7818: .ve

7820:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7822: .vb
7823:             2  0  |  0  3  0  |  0
7824:     Proc0   5  6  |  7  0  0  |  8
7825:     -------------------------------
7826:     Proc1  18  0  | 19 20 21  |  0
7827:     -------------------------------
7828:     Proc2  26 27  |  0  0 28  | 29
7829:             0  0  | 31 32 33  |  0
7830: .ve


7833: .seealso: MatCreateSubMatrices()
7834: @*/
7835: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7836: {
7838:   PetscMPIInt    size;
7839:   Mat            *local;
7840:   IS             iscoltmp;

7849:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7850:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7852:   MatCheckPreallocated(mat,1);
7853:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7855:   if (!iscol || isrow == iscol) {
7856:     PetscBool   stride;
7857:     PetscMPIInt grabentirematrix = 0,grab;
7858:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7859:     if (stride) {
7860:       PetscInt first,step,n,rstart,rend;
7861:       ISStrideGetInfo(isrow,&first,&step);
7862:       if (step == 1) {
7863:         MatGetOwnershipRange(mat,&rstart,&rend);
7864:         if (rstart == first) {
7865:           ISGetLocalSize(isrow,&n);
7866:           if (n == rend-rstart) {
7867:             grabentirematrix = 1;
7868:           }
7869:         }
7870:       }
7871:     }
7872:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7873:     if (grab) {
7874:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7875:       if (cll == MAT_INITIAL_MATRIX) {
7876:         *newmat = mat;
7877:         PetscObjectReference((PetscObject)mat);
7878:       }
7879:       return(0);
7880:     }
7881:   }

7883:   if (!iscol) {
7884:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7885:   } else {
7886:     iscoltmp = iscol;
7887:   }

7889:   /* if original matrix is on just one processor then use submatrix generated */
7890:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7891:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7892:     goto setproperties;
7893:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7894:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7895:     *newmat = *local;
7896:     PetscFree(local);
7897:     goto setproperties;
7898:   } else if (!mat->ops->createsubmatrix) {
7899:     /* Create a new matrix type that implements the operation using the full matrix */
7900:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7901:     switch (cll) {
7902:     case MAT_INITIAL_MATRIX:
7903:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7904:       break;
7905:     case MAT_REUSE_MATRIX:
7906:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7907:       break;
7908:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7909:     }
7910:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7911:     goto setproperties;
7912:   }

7914:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7915:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7916:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7917:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

7919:   /* Propagate symmetry information for diagonal blocks */
7920: setproperties:
7921:   if (isrow == iscoltmp) {
7922:     if (mat->symmetric_set && mat->symmetric) {
7923:       MatSetOption(*newmat,MAT_SYMMETRIC,PETSC_TRUE);
7924:     }
7925:     if (mat->structurally_symmetric_set && mat->structurally_symmetric) {
7926:       MatSetOption(*newmat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
7927:     }
7928:     if (mat->hermitian_set && mat->hermitian) {
7929:       MatSetOption(*newmat,MAT_HERMITIAN,PETSC_TRUE);
7930:     }
7931:     if (mat->spd_set && mat->spd) {
7932:       MatSetOption(*newmat,MAT_SPD,PETSC_TRUE);
7933:     }
7934:   }

7936:   if (!iscol) {ISDestroy(&iscoltmp);}
7937:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7938:   return(0);
7939: }

7941: /*@
7942:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7943:    used during the assembly process to store values that belong to
7944:    other processors.

7946:    Not Collective

7948:    Input Parameters:
7949: +  mat   - the matrix
7950: .  size  - the initial size of the stash.
7951: -  bsize - the initial size of the block-stash(if used).

7953:    Options Database Keys:
7954: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7955: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7957:    Level: intermediate

7959:    Notes:
7960:      The block-stash is used for values set with MatSetValuesBlocked() while
7961:      the stash is used for values set with MatSetValues()

7963:      Run with the option -info and look for output of the form
7964:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7965:      to determine the appropriate value, MM, to use for size and
7966:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7967:      to determine the value, BMM to use for bsize


7970: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

7972: @*/
7973: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7974: {

7980:   MatStashSetInitialSize_Private(&mat->stash,size);
7981:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
7982:   return(0);
7983: }

7985: /*@
7986:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7987:      the matrix

7989:    Neighbor-wise Collective on Mat

7991:    Input Parameters:
7992: +  mat   - the matrix
7993: .  x,y - the vectors
7994: -  w - where the result is stored

7996:    Level: intermediate

7998:    Notes:
7999:     w may be the same vector as y.

8001:     This allows one to use either the restriction or interpolation (its transpose)
8002:     matrix to do the interpolation

8004: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8006: @*/
8007: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8008: {
8010:   PetscInt       M,N,Ny;

8018:   MatCheckPreallocated(A,1);
8019:   MatGetSize(A,&M,&N);
8020:   VecGetSize(y,&Ny);
8021:   if (M == Ny) {
8022:     MatMultAdd(A,x,y,w);
8023:   } else {
8024:     MatMultTransposeAdd(A,x,y,w);
8025:   }
8026:   return(0);
8027: }

8029: /*@
8030:    MatInterpolate - y = A*x or A'*x depending on the shape of
8031:      the matrix

8033:    Neighbor-wise Collective on Mat

8035:    Input Parameters:
8036: +  mat   - the matrix
8037: -  x,y - the vectors

8039:    Level: intermediate

8041:    Notes:
8042:     This allows one to use either the restriction or interpolation (its transpose)
8043:     matrix to do the interpolation

8045: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8047: @*/
8048: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8049: {
8051:   PetscInt       M,N,Ny;

8058:   MatCheckPreallocated(A,1);
8059:   MatGetSize(A,&M,&N);
8060:   VecGetSize(y,&Ny);
8061:   if (M == Ny) {
8062:     MatMult(A,x,y);
8063:   } else {
8064:     MatMultTranspose(A,x,y);
8065:   }
8066:   return(0);
8067: }

8069: /*@
8070:    MatRestrict - y = A*x or A'*x

8072:    Neighbor-wise Collective on Mat

8074:    Input Parameters:
8075: +  mat   - the matrix
8076: -  x,y - the vectors

8078:    Level: intermediate

8080:    Notes:
8081:     This allows one to use either the restriction or interpolation (its transpose)
8082:     matrix to do the restriction

8084: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8086: @*/
8087: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8088: {
8090:   PetscInt       M,N,Ny;

8097:   MatCheckPreallocated(A,1);

8099:   MatGetSize(A,&M,&N);
8100:   VecGetSize(y,&Ny);
8101:   if (M == Ny) {
8102:     MatMult(A,x,y);
8103:   } else {
8104:     MatMultTranspose(A,x,y);
8105:   }
8106:   return(0);
8107: }

8109: /*@
8110:    MatGetNullSpace - retrieves the null space of a matrix.

8112:    Logically Collective on Mat

8114:    Input Parameters:
8115: +  mat - the matrix
8116: -  nullsp - the null space object

8118:    Level: developer

8120: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8121: @*/
8122: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8123: {
8127:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8128:   return(0);
8129: }

8131: /*@
8132:    MatSetNullSpace - attaches a null space to a matrix.

8134:    Logically Collective on Mat

8136:    Input Parameters:
8137: +  mat - the matrix
8138: -  nullsp - the null space object

8140:    Level: advanced

8142:    Notes:
8143:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8145:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8146:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8148:       You can remove the null space by calling this routine with an nullsp of NULL


8151:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8152:    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).
8153:    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
8154:    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
8155:    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).

8157:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8159:     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
8160:     routine also automatically calls MatSetTransposeNullSpace().

8162: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8163: @*/
8164: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8165: {

8171:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8172:   MatNullSpaceDestroy(&mat->nullsp);
8173:   mat->nullsp = nullsp;
8174:   if (mat->symmetric_set && mat->symmetric) {
8175:     MatSetTransposeNullSpace(mat,nullsp);
8176:   }
8177:   return(0);
8178: }

8180: /*@
8181:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8183:    Logically Collective on Mat

8185:    Input Parameters:
8186: +  mat - the matrix
8187: -  nullsp - the null space object

8189:    Level: developer

8191: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8192: @*/
8193: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8194: {
8199:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8200:   return(0);
8201: }

8203: /*@
8204:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8206:    Logically Collective on Mat

8208:    Input Parameters:
8209: +  mat - the matrix
8210: -  nullsp - the null space object

8212:    Level: advanced

8214:    Notes:
8215:       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.
8216:       You must also call MatSetNullSpace()


8219:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8220:    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).
8221:    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
8222:    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
8223:    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).

8225:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8227: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8228: @*/
8229: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8230: {

8236:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8237:   MatNullSpaceDestroy(&mat->transnullsp);
8238:   mat->transnullsp = nullsp;
8239:   return(0);
8240: }

8242: /*@
8243:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8244:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8246:    Logically Collective on Mat

8248:    Input Parameters:
8249: +  mat - the matrix
8250: -  nullsp - the null space object

8252:    Level: advanced

8254:    Notes:
8255:       Overwrites any previous near null space that may have been attached

8257:       You can remove the null space by calling this routine with an nullsp of NULL

8259: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8260: @*/
8261: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8262: {

8269:   MatCheckPreallocated(mat,1);
8270:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8271:   MatNullSpaceDestroy(&mat->nearnullsp);
8272:   mat->nearnullsp = nullsp;
8273:   return(0);
8274: }

8276: /*@
8277:    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()

8279:    Not Collective

8281:    Input Parameters:
8282: .  mat - the matrix

8284:    Output Parameters:
8285: .  nullsp - the null space object, NULL if not set

8287:    Level: developer

8289: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8290: @*/
8291: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8292: {
8297:   MatCheckPreallocated(mat,1);
8298:   *nullsp = mat->nearnullsp;
8299:   return(0);
8300: }

8302: /*@C
8303:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8305:    Collective on Mat

8307:    Input Parameters:
8308: +  mat - the matrix
8309: .  row - row/column permutation
8310: .  fill - expected fill factor >= 1.0
8311: -  level - level of fill, for ICC(k)

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

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

8321:    Level: developer


8324: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8329: @*/
8330: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8331: {

8339:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8340:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8341:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8342:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8343:   MatCheckPreallocated(mat,1);
8344:   (*mat->ops->iccfactor)(mat,row,info);
8345:   PetscObjectStateIncrease((PetscObject)mat);
8346:   return(0);
8347: }

8349: /*@
8350:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8351:          ghosted ones.

8353:    Not Collective

8355:    Input Parameters:
8356: +  mat - the matrix
8357: -  diag = the diagonal values, including ghost ones

8359:    Level: developer

8361:    Notes:
8362:     Works only for MPIAIJ and MPIBAIJ matrices

8364: .seealso: MatDiagonalScale()
8365: @*/
8366: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8367: {
8369:   PetscMPIInt    size;


8376:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8377:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8378:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8379:   if (size == 1) {
8380:     PetscInt n,m;
8381:     VecGetSize(diag,&n);
8382:     MatGetSize(mat,0,&m);
8383:     if (m == n) {
8384:       MatDiagonalScale(mat,0,diag);
8385:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8386:   } else {
8387:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8388:   }
8389:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8390:   PetscObjectStateIncrease((PetscObject)mat);
8391:   return(0);
8392: }

8394: /*@
8395:    MatGetInertia - Gets the inertia from a factored matrix

8397:    Collective on Mat

8399:    Input Parameter:
8400: .  mat - the matrix

8402:    Output Parameters:
8403: +   nneg - number of negative eigenvalues
8404: .   nzero - number of zero eigenvalues
8405: -   npos - number of positive eigenvalues

8407:    Level: advanced

8409:    Notes:
8410:     Matrix must have been factored by MatCholeskyFactor()


8413: @*/
8414: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8415: {

8421:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8422:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8423:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8424:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8425:   return(0);
8426: }

8428: /* ----------------------------------------------------------------*/
8429: /*@C
8430:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8432:    Neighbor-wise Collective on Mats

8434:    Input Parameters:
8435: +  mat - the factored matrix
8436: -  b - the right-hand-side vectors

8438:    Output Parameter:
8439: .  x - the result vectors

8441:    Notes:
8442:    The vectors b and x cannot be the same.  I.e., one cannot
8443:    call MatSolves(A,x,x).

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

8450:    Level: developer

8452: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8453: @*/
8454: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8455: {

8461:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8462:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8463:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8465:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8466:   MatCheckPreallocated(mat,1);
8467:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8468:   (*mat->ops->solves)(mat,b,x);
8469:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8470:   return(0);
8471: }

8473: /*@
8474:    MatIsSymmetric - Test whether a matrix is symmetric

8476:    Collective on Mat

8478:    Input Parameter:
8479: +  A - the matrix to test
8480: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8482:    Output Parameters:
8483: .  flg - the result

8485:    Notes:
8486:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8488:    Level: intermediate

8490: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8491: @*/
8492: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8493: {


8500:   if (!A->symmetric_set) {
8501:     if (!A->ops->issymmetric) {
8502:       MatType mattype;
8503:       MatGetType(A,&mattype);
8504:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8505:     }
8506:     (*A->ops->issymmetric)(A,tol,flg);
8507:     if (!tol) {
8508:       A->symmetric_set = PETSC_TRUE;
8509:       A->symmetric     = *flg;
8510:       if (A->symmetric) {
8511:         A->structurally_symmetric_set = PETSC_TRUE;
8512:         A->structurally_symmetric     = PETSC_TRUE;
8513:       }
8514:     }
8515:   } else if (A->symmetric) {
8516:     *flg = PETSC_TRUE;
8517:   } else if (!tol) {
8518:     *flg = PETSC_FALSE;
8519:   } else {
8520:     if (!A->ops->issymmetric) {
8521:       MatType mattype;
8522:       MatGetType(A,&mattype);
8523:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8524:     }
8525:     (*A->ops->issymmetric)(A,tol,flg);
8526:   }
8527:   return(0);
8528: }

8530: /*@
8531:    MatIsHermitian - Test whether a matrix is Hermitian

8533:    Collective on Mat

8535:    Input Parameter:
8536: +  A - the matrix to test
8537: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8539:    Output Parameters:
8540: .  flg - the result

8542:    Level: intermediate

8544: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8545:           MatIsSymmetricKnown(), MatIsSymmetric()
8546: @*/
8547: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8548: {


8555:   if (!A->hermitian_set) {
8556:     if (!A->ops->ishermitian) {
8557:       MatType mattype;
8558:       MatGetType(A,&mattype);
8559:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8560:     }
8561:     (*A->ops->ishermitian)(A,tol,flg);
8562:     if (!tol) {
8563:       A->hermitian_set = PETSC_TRUE;
8564:       A->hermitian     = *flg;
8565:       if (A->hermitian) {
8566:         A->structurally_symmetric_set = PETSC_TRUE;
8567:         A->structurally_symmetric     = PETSC_TRUE;
8568:       }
8569:     }
8570:   } else if (A->hermitian) {
8571:     *flg = PETSC_TRUE;
8572:   } else if (!tol) {
8573:     *flg = PETSC_FALSE;
8574:   } else {
8575:     if (!A->ops->ishermitian) {
8576:       MatType mattype;
8577:       MatGetType(A,&mattype);
8578:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8579:     }
8580:     (*A->ops->ishermitian)(A,tol,flg);
8581:   }
8582:   return(0);
8583: }

8585: /*@
8586:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8588:    Not Collective

8590:    Input Parameter:
8591: .  A - the matrix to check

8593:    Output Parameters:
8594: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8595: -  flg - the result

8597:    Level: advanced

8599:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8600:          if you want it explicitly checked

8602: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8603: @*/
8604: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8605: {
8610:   if (A->symmetric_set) {
8611:     *set = PETSC_TRUE;
8612:     *flg = A->symmetric;
8613:   } else {
8614:     *set = PETSC_FALSE;
8615:   }
8616:   return(0);
8617: }

8619: /*@
8620:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8622:    Not Collective

8624:    Input Parameter:
8625: .  A - the matrix to check

8627:    Output Parameters:
8628: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8629: -  flg - the result

8631:    Level: advanced

8633:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8634:          if you want it explicitly checked

8636: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8637: @*/
8638: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8639: {
8644:   if (A->hermitian_set) {
8645:     *set = PETSC_TRUE;
8646:     *flg = A->hermitian;
8647:   } else {
8648:     *set = PETSC_FALSE;
8649:   }
8650:   return(0);
8651: }

8653: /*@
8654:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8656:    Collective on Mat

8658:    Input Parameter:
8659: .  A - the matrix to test

8661:    Output Parameters:
8662: .  flg - the result

8664:    Level: intermediate

8666: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8667: @*/
8668: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool  *flg)
8669: {

8675:   if (!A->structurally_symmetric_set) {
8676:     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8677:     (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);

8679:     A->structurally_symmetric_set = PETSC_TRUE;
8680:   }
8681:   *flg = A->structurally_symmetric;
8682:   return(0);
8683: }

8685: /*@
8686:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8687:        to be communicated to other processors during the MatAssemblyBegin/End() process

8689:     Not collective

8691:    Input Parameter:
8692: .   vec - the vector

8694:    Output Parameters:
8695: +   nstash   - the size of the stash
8696: .   reallocs - the number of additional mallocs incurred.
8697: .   bnstash   - the size of the block stash
8698: -   breallocs - the number of additional mallocs incurred.in the block stash

8700:    Level: advanced

8702: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8704: @*/
8705: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8706: {

8710:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8711:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8712:   return(0);
8713: }

8715: /*@C
8716:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8717:      parallel layout

8719:    Collective on Mat

8721:    Input Parameter:
8722: .  mat - the matrix

8724:    Output Parameter:
8725: +   right - (optional) vector that the matrix can be multiplied against
8726: -   left - (optional) vector that the matrix vector product can be stored in

8728:    Notes:
8729:     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().

8731:   Notes:
8732:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8734:   Level: advanced

8736: .seealso: MatCreate(), VecDestroy()
8737: @*/
8738: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8739: {

8745:   if (mat->ops->getvecs) {
8746:     (*mat->ops->getvecs)(mat,right,left);
8747:   } else {
8748:     PetscInt rbs,cbs;
8749:     MatGetBlockSizes(mat,&rbs,&cbs);
8750:     if (right) {
8751:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8752:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8753:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8754:       VecSetBlockSize(*right,cbs);
8755:       VecSetType(*right,mat->defaultvectype);
8756:       PetscLayoutReference(mat->cmap,&(*right)->map);
8757:     }
8758:     if (left) {
8759:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8760:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8761:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8762:       VecSetBlockSize(*left,rbs);
8763:       VecSetType(*left,mat->defaultvectype);
8764:       PetscLayoutReference(mat->rmap,&(*left)->map);
8765:     }
8766:   }
8767:   return(0);
8768: }

8770: /*@C
8771:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8772:      with default values.

8774:    Not Collective

8776:    Input Parameters:
8777: .    info - the MatFactorInfo data structure


8780:    Notes:
8781:     The solvers are generally used through the KSP and PC objects, for example
8782:           PCLU, PCILU, PCCHOLESKY, PCICC

8784:    Level: developer

8786: .seealso: MatFactorInfo

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

8791: @*/

8793: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8794: {

8798:   PetscMemzero(info,sizeof(MatFactorInfo));
8799:   return(0);
8800: }

8802: /*@
8803:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8805:    Collective on Mat

8807:    Input Parameters:
8808: +  mat - the factored matrix
8809: -  is - the index set defining the Schur indices (0-based)

8811:    Notes:
8812:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8814:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8816:    Level: developer

8818: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8819:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8821: @*/
8822: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8823: {
8824:   PetscErrorCode ierr,(*f)(Mat,IS);

8832:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8833:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8834:   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");
8835:   if (mat->schur) {
8836:     MatDestroy(&mat->schur);
8837:   }
8838:   (*f)(mat,is);
8839:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8840:   MatFactorSetUpInPlaceSchur_Private(mat);
8841:   return(0);
8842: }

8844: /*@
8845:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8847:    Logically Collective on Mat

8849:    Input Parameters:
8850: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8851: .  S - location where to return the Schur complement, can be NULL
8852: -  status - the status of the Schur complement matrix, can be NULL

8854:    Notes:
8855:    You must call MatFactorSetSchurIS() before calling this routine.

8857:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8858:    The caller must destroy the object when it is no longer needed.
8859:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8861:    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)

8863:    Developer Notes:
8864:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8865:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8867:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8869:    Level: advanced

8871:    References:

8873: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8874: @*/
8875: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8876: {

8883:   if (S) {
8884:     PetscErrorCode (*f)(Mat,Mat*);

8886:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8887:     if (f) {
8888:       (*f)(F,S);
8889:     } else {
8890:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8891:     }
8892:   }
8893:   if (status) *status = F->schur_status;
8894:   return(0);
8895: }

8897: /*@
8898:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

8900:    Logically Collective on Mat

8902:    Input Parameters:
8903: +  F - the factored matrix obtained by calling MatGetFactor()
8904: .  *S - location where to return the Schur complement, can be NULL
8905: -  status - the status of the Schur complement matrix, can be NULL

8907:    Notes:
8908:    You must call MatFactorSetSchurIS() before calling this routine.

8910:    Schur complement mode is currently implemented for sequential matrices.
8911:    The routine returns a the Schur Complement stored within the data strutures of the solver.
8912:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8913:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

8915:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

8917:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8919:    Level: advanced

8921:    References:

8923: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8924: @*/
8925: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8926: {
8931:   if (S) *S = F->schur;
8932:   if (status) *status = F->schur_status;
8933:   return(0);
8934: }

8936: /*@
8937:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

8939:    Logically Collective on Mat

8941:    Input Parameters:
8942: +  F - the factored matrix obtained by calling MatGetFactor()
8943: .  *S - location where the Schur complement is stored
8944: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

8946:    Notes:

8948:    Level: advanced

8950:    References:

8952: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8953: @*/
8954: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8955: {

8960:   if (S) {
8962:     *S = NULL;
8963:   }
8964:   F->schur_status = status;
8965:   MatFactorUpdateSchurStatus_Private(F);
8966:   return(0);
8967: }

8969: /*@
8970:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

8972:    Logically Collective on Mat

8974:    Input Parameters:
8975: +  F - the factored matrix obtained by calling MatGetFactor()
8976: .  rhs - location where the right hand side of the Schur complement system is stored
8977: -  sol - location where the solution of the Schur complement system has to be returned

8979:    Notes:
8980:    The sizes of the vectors should match the size of the Schur complement

8982:    Must be called after MatFactorSetSchurIS()

8984:    Level: advanced

8986:    References:

8988: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
8989: @*/
8990: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
8991: {

9003:   MatFactorFactorizeSchurComplement(F);
9004:   switch (F->schur_status) {
9005:   case MAT_FACTOR_SCHUR_FACTORED:
9006:     MatSolveTranspose(F->schur,rhs,sol);
9007:     break;
9008:   case MAT_FACTOR_SCHUR_INVERTED:
9009:     MatMultTranspose(F->schur,rhs,sol);
9010:     break;
9011:   default:
9012:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9013:     break;
9014:   }
9015:   return(0);
9016: }

9018: /*@
9019:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9021:    Logically Collective on Mat

9023:    Input Parameters:
9024: +  F - the factored matrix obtained by calling MatGetFactor()
9025: .  rhs - location where the right hand side of the Schur complement system is stored
9026: -  sol - location where the solution of the Schur complement system has to be returned

9028:    Notes:
9029:    The sizes of the vectors should match the size of the Schur complement

9031:    Must be called after MatFactorSetSchurIS()

9033:    Level: advanced

9035:    References:

9037: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9038: @*/
9039: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9040: {

9052:   MatFactorFactorizeSchurComplement(F);
9053:   switch (F->schur_status) {
9054:   case MAT_FACTOR_SCHUR_FACTORED:
9055:     MatSolve(F->schur,rhs,sol);
9056:     break;
9057:   case MAT_FACTOR_SCHUR_INVERTED:
9058:     MatMult(F->schur,rhs,sol);
9059:     break;
9060:   default:
9061:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9062:     break;
9063:   }
9064:   return(0);
9065: }

9067: /*@
9068:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9070:    Logically Collective on Mat

9072:    Input Parameters:
9073: +  F - the factored matrix obtained by calling MatGetFactor()

9075:    Notes:
9076:     Must be called after MatFactorSetSchurIS().

9078:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9080:    Level: advanced

9082:    References:

9084: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9085: @*/
9086: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9087: {

9093:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9094:   MatFactorFactorizeSchurComplement(F);
9095:   MatFactorInvertSchurComplement_Private(F);
9096:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9097:   return(0);
9098: }

9100: /*@
9101:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9103:    Logically Collective on Mat

9105:    Input Parameters:
9106: +  F - the factored matrix obtained by calling MatGetFactor()

9108:    Notes:
9109:     Must be called after MatFactorSetSchurIS().

9111:    Level: advanced

9113:    References:

9115: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9116: @*/
9117: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9118: {

9124:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9125:   MatFactorFactorizeSchurComplement_Private(F);
9126:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9127:   return(0);
9128: }

9130: static PetscErrorCode MatPtAP_Basic(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9131: {
9132:   Mat            AP;

9136:   PetscInfo2(A,"Mat types %s and %s using basic PtAP\n",((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9137:   MatMatMult(A,P,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&AP);
9138:   MatTransposeMatMult(P,AP,scall,fill,C);
9139:   MatDestroy(&AP);
9140:   return(0);
9141: }

9143: /*@
9144:    MatPtAP - Creates the matrix product C = P^T * A * P

9146:    Neighbor-wise Collective on Mat

9148:    Input Parameters:
9149: +  A - the matrix
9150: .  P - the projection matrix
9151: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9152: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9153:           if the result is a dense matrix this is irrelevent

9155:    Output Parameters:
9156: .  C - the product matrix

9158:    Notes:
9159:    C will be created and must be destroyed by the user with MatDestroy().

9161:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9163:    Level: intermediate

9165: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9166: @*/
9167: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9168: {
9170:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9171:   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9172:   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9173:   PetscBool      sametype;

9178:   MatCheckPreallocated(A,1);
9179:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9180:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9181:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9184:   MatCheckPreallocated(P,2);
9185:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9186:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9188:   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);
9189:   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);
9190:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9191:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9193:   if (scall == MAT_REUSE_MATRIX) {

9197:     PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9198:     PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9199:     if ((*C)->ops->ptapnumeric) {
9200:       (*(*C)->ops->ptapnumeric)(A,P,*C);
9201:     } else {
9202:       MatPtAP_Basic(A,P,scall,fill,C);
9203:     }
9204:     PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9205:     PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9206:     return(0);
9207:   }

9209:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9210:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9212:   fA = A->ops->ptap;
9213:   fP = P->ops->ptap;
9214:   PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);
9215:   if (fP == fA && sametype) {
9216:     ptap = fA;
9217:   } else {
9218:     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9219:     char ptapname[256];
9220:     PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));
9221:     PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));
9222:     PetscStrlcat(ptapname,"_",sizeof(ptapname));
9223:     PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));
9224:     PetscStrlcat(ptapname,"_C",sizeof(ptapname)); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9225:     PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
9226:   }

9228:   if (!ptap) ptap = MatPtAP_Basic;
9229:   PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9230:   (*ptap)(A,P,scall,fill,C);
9231:   PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9232:   if (A->symmetric_set && A->symmetric) {
9233:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9234:   }
9235:   return(0);
9236: }

9238: /*@
9239:    MatPtAPNumeric - Computes the matrix product C = P^T * A * P

9241:    Neighbor-wise Collective on Mat

9243:    Input Parameters:
9244: +  A - the matrix
9245: -  P - the projection matrix

9247:    Output Parameters:
9248: .  C - the product matrix

9250:    Notes:
9251:    C must have been created by calling MatPtAPSymbolic and must be destroyed by
9252:    the user using MatDeatroy().

9254:    This routine is currently only implemented for pairs of AIJ matrices and classes
9255:    which inherit from AIJ.  C will be of type MATAIJ.

9257:    Level: intermediate

9259: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9260: @*/
9261: PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9262: {

9268:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9269:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9272:   MatCheckPreallocated(P,2);
9273:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9274:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9277:   MatCheckPreallocated(C,3);
9278:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9279:   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);
9280:   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);
9281:   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);
9282:   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);
9283:   MatCheckPreallocated(A,1);

9285:   if (!C->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You should call MatPtAPSymbolic first");
9286:   PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9287:   (*C->ops->ptapnumeric)(A,P,C);
9288:   PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9289:   return(0);