Actual source code: matrix.c

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

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

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

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

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

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

 47:    Logically Collective on Mat

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

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

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

 64:    Level: intermediate


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


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

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

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

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

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

102:    Logically Collective on Mat

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

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

112:    Level: advanced

114:    Notes:
115:     This routine does not work for factorizations done with external packages.

117:     This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT

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

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

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

135:    Logically Collective on Mat

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

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

143:    Level: advanced

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

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

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

161:    Logically Collective on Mat

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

166:    Level: developer

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

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

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

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

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

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

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

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

241:   Level: intermediate

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

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

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

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

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

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

274:   Level: intermediate

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


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

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

303:    Not Collective

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

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

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

316:    Level: advanced

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

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

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

343:    Collective on Mat

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

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

351:    Level: advanced

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

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

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

370:    Logically Collective on Mat

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

375:    Level: advanced


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

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

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

398:    Collective on Mat

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

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

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

410:    Level: advanced

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

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


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

435:    Logically Collective on Mat

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

440:    Level: advanced


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

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

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

463:    Not Collective

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

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

472:    Level: advanced


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

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

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

497:    Not Collective

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

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

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

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

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

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

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

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


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

547:    Level: advanced

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

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

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

573:    Logically Collective on Mat

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

578:    Level: advanced

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

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

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

601:    Not Collective

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

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

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

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

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

631:    Level: advanced

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

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

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

655:    Not Collective

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

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

663:    Level: advanced

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

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

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

685:    Not Collective

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

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


694:    Level: advanced

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

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

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

717:    Logically Collective on Mat

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

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

727:    Level: advanced

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

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

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

745:    Logically Collective on Mat

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

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

755:    Level: advanced

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

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

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

773:    Not Collective

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

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

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

785:    Level: advanced

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

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

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

802:    Collective on Mat

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

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

811:    Level: beginner

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

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


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

830:    Collective on Mat

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

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

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

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

842:    Level: beginner

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

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

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

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

878:    Collective on Mat

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

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

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

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

901:    Collective on Mat

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

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

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

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

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

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

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

961:       See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
962:       viewer is used and lib/petsc/bin/PetscBinaryIO.py for loading them into Python.

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

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

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

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

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

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

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

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

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

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

1093:    Collective on PetscViewer

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

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

1105:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1190:    Corresponding MatView() is not yet implemented.

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

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

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

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


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

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

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

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

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

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

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

1270:    Collective on Mat

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

1275:    Level: beginner

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

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

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

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

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

1313:    Not Collective

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

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

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

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

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

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

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

1346:    Level: beginner

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

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

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

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

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

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

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

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

1442:    Not Collective

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

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

1452:    All the nonzeros in the row must be provided

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

1456:    The row must belong to this process

1458:    Level: advanced

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

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

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

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

1491:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

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

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

1551:    Level: beginner

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

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

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

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

1605:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

1658:    Level: beginner

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

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

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

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

1714:    Not Collective

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


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

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

1730:    Level: beginner

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


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

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

1758:    Not Collective

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

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

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

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

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

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

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

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

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

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

1818:    Level: intermediate

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

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

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

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

1879:    Not Collective; currently only returns a local block

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

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

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

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

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

1903:    Level: advanced

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

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

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

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

1933:    Not Collective

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

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

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

1946:    Level: advanced

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

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

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

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

1997:   Not Collective

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

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

2009:   Level: advanced

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

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

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

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

2043:    Not Collective

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

2050:    Level: intermediate


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


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


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

2078:    Not Collective

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

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

2087:    Level: advanced


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

2104: /*@
2105:    MatSetLayouts - Sets the PetscLayout objects for rows and columns of a matrix

2107:    Logically Collective on A

2109:    Input Parameters:
2110: +  A - the matrix
2111: . rmap - row layout
2112: - cmap - column layout

2114:    Level: advanced

2116: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatGetLayouts()
2117: @*/
2118: PetscErrorCode MatSetLayouts(Mat A,PetscLayout rmap,PetscLayout cmap)
2119: {


2125:   PetscLayoutReference(rmap,&A->rmap);
2126:   PetscLayoutReference(cmap,&A->cmap);
2127:   return(0);
2128: }

2130: /*@
2131:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2133:    Not Collective

2135:    Input Parameters:
2136: .  A - the matrix

2138:    Output Parameters:
2139: + rmap - row layout
2140: - cmap - column layout

2142:    Level: advanced

2144: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatSetLayouts()
2145: @*/
2146: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2147: {
2153:   if (rmap) *rmap = A->rmap;
2154:   if (cmap) *cmap = A->cmap;
2155:   return(0);
2156: }

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

2162:    Not Collective

2164:    Input Parameters:
2165: +  mat - the matrix
2166: .  nrow, irow - number of rows and their local indices
2167: .  ncol, icol - number of columns and their local indices
2168: .  y -  a logically two-dimensional array of values
2169: -  addv - either INSERT_VALUES or ADD_VALUES, where
2170:    ADD_VALUES adds values to any existing entries, and
2171:    INSERT_VALUES replaces existing entries with new values

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

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

2179:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2180:    options cannot be mixed without intervening calls to the assembly
2181:    routines.

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

2186:    Level: intermediate

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

2192: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2193:            MatSetValueLocal(), MatGetValuesLocal()
2194: @*/
2195: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2196: {

2202:   MatCheckPreallocated(mat,1);
2203:   if (!nrow || !ncol) return(0); /* no values to insert */
2206:   if (mat->insertmode == NOT_SET_VALUES) {
2207:     mat->insertmode = addv;
2208:   }
2209:   else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2210:   if (PetscDefined(USE_DEBUG)) {
2211:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2212:     if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2213:   }

2215:   if (mat->assembled) {
2216:     mat->was_assembled = PETSC_TRUE;
2217:     mat->assembled     = PETSC_FALSE;
2218:   }
2219:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2220:   if (mat->ops->setvalueslocal) {
2221:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2222:   } else {
2223:     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*irowm,*icolm;
2224:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2225:       irowm = buf; icolm = buf+nrow;
2226:     } else {
2227:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2228:       irowm = bufr; icolm = bufc;
2229:     }
2230:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2231:     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2232:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2233:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2234:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2235:     PetscFree2(bufr,bufc);
2236:   }
2237:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2238:   return(0);
2239: }

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

2245:    Not Collective

2247:    Input Parameters:
2248: +  x - the matrix
2249: .  nrow, irow - number of rows and their local indices
2250: .  ncol, icol - number of columns and their local indices
2251: .  y -  a logically two-dimensional array of values
2252: -  addv - either INSERT_VALUES or ADD_VALUES, where
2253:    ADD_VALUES adds values to any existing entries, and
2254:    INSERT_VALUES replaces existing entries with new values

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

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

2263:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2264:    options cannot be mixed without intervening calls to the assembly
2265:    routines.

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

2270:    Level: intermediate

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

2276: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2277:            MatSetValuesLocal(),  MatSetValuesBlocked()
2278: @*/
2279: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2280: {

2286:   MatCheckPreallocated(mat,1);
2287:   if (!nrow || !ncol) return(0); /* no values to insert */
2291:   if (mat->insertmode == NOT_SET_VALUES) {
2292:     mat->insertmode = addv;
2293:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2294:   if (PetscDefined(USE_DEBUG)) {
2295:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2296:     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);
2297:   }

2299:   if (mat->assembled) {
2300:     mat->was_assembled = PETSC_TRUE;
2301:     mat->assembled     = PETSC_FALSE;
2302:   }
2303:   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2304:     PetscInt irbs, rbs;
2305:     MatGetBlockSizes(mat, &rbs, NULL);
2306:     ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2307:     if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2308:   }
2309:   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2310:     PetscInt icbs, cbs;
2311:     MatGetBlockSizes(mat,NULL,&cbs);
2312:     ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2313:     if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2314:   }
2315:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2316:   if (mat->ops->setvaluesblockedlocal) {
2317:     (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2318:   } else {
2319:     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*irowm,*icolm;
2320:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2321:       irowm = buf; icolm = buf + nrow;
2322:     } else {
2323:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2324:       irowm = bufr; icolm = bufc;
2325:     }
2326:     ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2327:     ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2328:     MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2329:     PetscFree2(bufr,bufc);
2330:   }
2331:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2332:   return(0);
2333: }

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

2338:    Collective on Mat

2340:    Input Parameters:
2341: +  mat - the matrix
2342: -  x   - the vector to be multiplied

2344:    Output Parameters:
2345: .  y - the result

2347:    Notes:
2348:    The vectors x and y cannot be the same.  I.e., one cannot
2349:    call MatMult(A,y,y).

2351:    Level: developer

2353: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2354: @*/
2355: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2356: {


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

2370:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2371:   (*mat->ops->multdiagonalblock)(mat,x,y);
2372:   PetscObjectStateIncrease((PetscObject)y);
2373:   return(0);
2374: }

2376: /* --------------------------------------------------------*/
2377: /*@
2378:    MatMult - Computes the matrix-vector product, y = Ax.

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 MatMult(A,y,y).

2393:    Level: beginner

2395: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2396: @*/
2397: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2398: {

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

2418:   VecLockReadPush(x);
2419:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2420:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2421:   (*mat->ops->mult)(mat,x,y);
2422:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2423:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2424:   VecLockReadPop(x);
2425:   return(0);
2426: }

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

2431:    Neighbor-wise Collective on Mat

2433:    Input Parameters:
2434: +  mat - the matrix
2435: -  x   - the vector to be multiplied

2437:    Output Parameters:
2438: .  y - the result

2440:    Notes:
2441:    The vectors x and y cannot be the same.  I.e., one cannot
2442:    call MatMultTranspose(A,y,y).

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

2447:    Level: beginner

2449: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2450: @*/
2451: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2452: {
2453:   PetscErrorCode (*op)(Mat,Vec,Vec)=NULL,ierr;


2461:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2462:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2463:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2464: #if !defined(PETSC_HAVE_CONSTRAINTS)
2465:   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);
2466:   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);
2467: #endif
2468:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2469:   MatCheckPreallocated(mat,1);

2471:   if (!mat->ops->multtranspose) {
2472:     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
2473:     if (!op) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined or is symmetric and does not have a multiply defined",((PetscObject)mat)->type_name);
2474:   } else op = mat->ops->multtranspose;
2475:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2476:   VecLockReadPush(x);
2477:   (*op)(mat,x,y);
2478:   VecLockReadPop(x);
2479:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2480:   PetscObjectStateIncrease((PetscObject)y);
2481:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2482:   return(0);
2483: }

2485: /*@
2486:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2488:    Neighbor-wise Collective on Mat

2490:    Input Parameters:
2491: +  mat - the matrix
2492: -  x   - the vector to be multilplied

2494:    Output Parameters:
2495: .  y - the result

2497:    Notes:
2498:    The vectors x and y cannot be the same.  I.e., one cannot
2499:    call MatMultHermitianTranspose(A,y,y).

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

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

2505:    Level: beginner

2507: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2508: @*/
2509: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2510: {


2519:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2520:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2521:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2522: #if !defined(PETSC_HAVE_CONSTRAINTS)
2523:   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);
2524:   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);
2525: #endif
2526:   MatCheckPreallocated(mat,1);

2528:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2529: #if defined(PETSC_USE_COMPLEX)
2530:   if (mat->ops->multhermitiantranspose || (mat->hermitian && mat->ops->mult)) {
2531:     VecLockReadPush(x);
2532:     if (mat->ops->multhermitiantranspose) {
2533:       (*mat->ops->multhermitiantranspose)(mat,x,y);
2534:     } else {
2535:       (*mat->ops->mult)(mat,x,y);
2536:     }
2537:     VecLockReadPop(x);
2538:   } else {
2539:     Vec w;
2540:     VecDuplicate(x,&w);
2541:     VecCopy(x,w);
2542:     VecConjugate(w);
2543:     MatMultTranspose(mat,w,y);
2544:     VecDestroy(&w);
2545:     VecConjugate(y);
2546:   }
2547:   PetscObjectStateIncrease((PetscObject)y);
2548: #else
2549:   MatMultTranspose(mat,x,y);
2550: #endif
2551:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2552:   return(0);
2553: }

2555: /*@
2556:     MatMultAdd -  Computes v3 = v2 + A * v1.

2558:     Neighbor-wise Collective on Mat

2560:     Input Parameters:
2561: +   mat - the matrix
2562: -   v1, v2 - the vectors

2564:     Output Parameters:
2565: .   v3 - the result

2567:     Notes:
2568:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2569:     call MatMultAdd(A,v1,v2,v1).

2571:     Level: beginner

2573: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2574: @*/
2575: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2576: {


2586:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2587:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2588:   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);
2589:   /* 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);
2590:      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); */
2591:   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);
2592:   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);
2593:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2594:   MatCheckPreallocated(mat,1);

2596:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2597:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2598:   VecLockReadPush(v1);
2599:   (*mat->ops->multadd)(mat,v1,v2,v3);
2600:   VecLockReadPop(v1);
2601:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2602:   PetscObjectStateIncrease((PetscObject)v3);
2603:   return(0);
2604: }

2606: /*@
2607:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2609:    Neighbor-wise Collective on Mat

2611:    Input Parameters:
2612: +  mat - the matrix
2613: -  v1, v2 - the vectors

2615:    Output Parameters:
2616: .  v3 - the result

2618:    Notes:
2619:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2620:    call MatMultTransposeAdd(A,v1,v2,v1).

2622:    Level: beginner

2624: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2625: @*/
2626: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2627: {


2637:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2638:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2639:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2640:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2641:   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);
2642:   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);
2643:   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);
2644:   MatCheckPreallocated(mat,1);

2646:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2647:   VecLockReadPush(v1);
2648:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2649:   VecLockReadPop(v1);
2650:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2651:   PetscObjectStateIncrease((PetscObject)v3);
2652:   return(0);
2653: }

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

2658:    Neighbor-wise Collective on Mat

2660:    Input Parameters:
2661: +  mat - the matrix
2662: -  v1, v2 - the vectors

2664:    Output Parameters:
2665: .  v3 - the result

2667:    Notes:
2668:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2669:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2671:    Level: beginner

2673: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2674: @*/
2675: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2676: {


2686:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2687:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2688:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2689:   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);
2690:   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);
2691:   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);
2692:   MatCheckPreallocated(mat,1);

2694:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2695:   VecLockReadPush(v1);
2696:   if (mat->ops->multhermitiantransposeadd) {
2697:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2698:   } else {
2699:     Vec w,z;
2700:     VecDuplicate(v1,&w);
2701:     VecCopy(v1,w);
2702:     VecConjugate(w);
2703:     VecDuplicate(v3,&z);
2704:     MatMultTranspose(mat,w,z);
2705:     VecDestroy(&w);
2706:     VecConjugate(z);
2707:     if (v2 != v3) {
2708:       VecWAXPY(v3,1.0,v2,z);
2709:     } else {
2710:       VecAXPY(v3,1.0,z);
2711:     }
2712:     VecDestroy(&z);
2713:   }
2714:   VecLockReadPop(v1);
2715:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2716:   PetscObjectStateIncrease((PetscObject)v3);
2717:   return(0);
2718: }

2720: /*@
2721:    MatMultConstrained - The inner multiplication routine for a
2722:    constrained matrix P^T A P.

2724:    Neighbor-wise Collective on Mat

2726:    Input Parameters:
2727: +  mat - the matrix
2728: -  x   - the vector to be multilplied

2730:    Output Parameters:
2731: .  y - the result

2733:    Notes:
2734:    The vectors x and y cannot be the same.  I.e., one cannot
2735:    call MatMult(A,y,y).

2737:    Level: beginner

2739: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2740: @*/
2741: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2742: {

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

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

2765: /*@
2766:    MatMultTransposeConstrained - The inner multiplication routine for a
2767:    constrained matrix P^T A^T P.

2769:    Neighbor-wise Collective on Mat

2771:    Input Parameters:
2772: +  mat - the matrix
2773: -  x   - the vector to be multilplied

2775:    Output Parameters:
2776: .  y - the result

2778:    Notes:
2779:    The vectors x and y cannot be the same.  I.e., one cannot
2780:    call MatMult(A,y,y).

2782:    Level: beginner

2784: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2785: @*/
2786: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2787: {

2794:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2795:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2796:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2797:   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);
2798:   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);

2800:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2801:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2802:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2803:   PetscObjectStateIncrease((PetscObject)y);
2804:   return(0);
2805: }

2807: /*@C
2808:    MatGetFactorType - gets the type of factorization it is

2810:    Not Collective

2812:    Input Parameters:
2813: .  mat - the matrix

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

2818:    Level: intermediate

2820: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2821: @*/
2822: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2823: {
2828:   *t = mat->factortype;
2829:   return(0);
2830: }

2832: /*@C
2833:    MatSetFactorType - sets the type of factorization it is

2835:    Logically Collective on Mat

2837:    Input Parameters:
2838: +  mat - the matrix
2839: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2841:    Level: intermediate

2843: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2844: @*/
2845: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2846: {
2850:   mat->factortype = t;
2851:   return(0);
2852: }

2854: /* ------------------------------------------------------------*/
2855: /*@C
2856:    MatGetInfo - Returns information about matrix storage (number of
2857:    nonzeros, memory, etc.).

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

2861:    Input Parameters:
2862: .  mat - the matrix

2864:    Output Parameters:
2865: +  flag - flag indicating the type of parameters to be returned
2866:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2867:    MAT_GLOBAL_SUM - sum over all processors)
2868: -  info - matrix information context

2870:    Notes:
2871:    The MatInfo context contains a variety of matrix data, including
2872:    number of nonzeros allocated and used, number of mallocs during
2873:    matrix assembly, etc.  Additional information for factored matrices
2874:    is provided (such as the fill ratio, number of mallocs during
2875:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2876:    when using the runtime options
2877: $       -info -mat_view ::ascii_info

2879:    Example for C/C++ Users:
2880:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2881:    data within the MatInfo context.  For example,
2882: .vb
2883:       MatInfo info;
2884:       Mat     A;
2885:       double  mal, nz_a, nz_u;

2887:       MatGetInfo(A,MAT_LOCAL,&info);
2888:       mal  = info.mallocs;
2889:       nz_a = info.nz_allocated;
2890: .ve

2892:    Example for Fortran Users:
2893:    Fortran users should declare info as a double precision
2894:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2895:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2896:    a complete list of parameter names.
2897: .vb
2898:       double  precision info(MAT_INFO_SIZE)
2899:       double  precision mal, nz_a
2900:       Mat     A
2901:       integer ierr

2903:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2904:       mal = info(MAT_INFO_MALLOCS)
2905:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2906: .ve

2908:     Level: intermediate

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

2913: .seealso: MatStashGetInfo()

2915: @*/
2916: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2917: {

2924:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2925:   MatCheckPreallocated(mat,1);
2926:   (*mat->ops->getinfo)(mat,flag,info);
2927:   return(0);
2928: }

2930: /*
2931:    This is used by external packages where it is not easy to get the info from the actual
2932:    matrix factorization.
2933: */
2934: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2935: {

2939:   PetscMemzero(info,sizeof(MatInfo));
2940:   return(0);
2941: }

2943: /* ----------------------------------------------------------*/

2945: /*@C
2946:    MatLUFactor - Performs in-place LU factorization of matrix.

2948:    Collective on Mat

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

2959:    Notes:
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:    This changes the state of the matrix to a factored matrix; it cannot be used
2965:    for example with MatSetValues() unless one first calls MatSetUnfactored().

2967:    Level: developer

2969: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2970:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

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

2987:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2988:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2989:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2990:   MatCheckPreallocated(mat,1);
2991:   if (!info) {
2992:     MatFactorInfoInitialize(&tinfo);
2993:     info = &tinfo;
2994:   }

2996:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2997:   (*mat->ops->lufactor)(mat,row,col,info);
2998:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2999:   PetscObjectStateIncrease((PetscObject)mat);
3000:   return(0);
3001: }

3003: /*@C
3004:    MatILUFactor - Performs in-place ILU factorization of matrix.

3006:    Collective on Mat

3008:    Input Parameters:
3009: +  mat - the matrix
3010: .  row - row permutation
3011: .  col - column permutation
3012: -  info - structure containing
3013: $      levels - number of levels of fill.
3014: $      expected fill - as ratio of original fill.
3015: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3016:                 missing diagonal entries)

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

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

3026:    Level: developer

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

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

3033: @*/
3034: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3035: {

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

3050:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3051:   (*mat->ops->ilufactor)(mat,row,col,info);
3052:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3053:   PetscObjectStateIncrease((PetscObject)mat);
3054:   return(0);
3055: }

3057: /*@C
3058:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3059:    Call this routine before calling MatLUFactorNumeric().

3061:    Collective on Mat

3063:    Input Parameters:
3064: +  fact - the factor matrix obtained with MatGetFactor()
3065: .  mat - the matrix
3066: .  row, col - row and column permutations
3067: -  info - options for factorization, includes
3068: $          fill - expected fill as ratio of original fill.
3069: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3070: $                   Run with the option -info to determine an optimal value to use


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

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

3080:    Level: developer

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

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

3087: @*/
3088: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3089: {
3091:   MatFactorInfo  tinfo;

3100:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3101:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3102:   if (!(fact)->ops->lufactorsymbolic) {
3103:     MatSolverType stype;
3104:     MatFactorGetSolverType(fact,&stype);
3105:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,stype);
3106:   }
3107:   MatCheckPreallocated(mat,2);
3108:   if (!info) {
3109:     MatFactorInfoInitialize(&tinfo);
3110:     info = &tinfo;
3111:   }

3113:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3114:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3115:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3116:   PetscObjectStateIncrease((PetscObject)fact);
3117:   return(0);
3118: }

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

3124:    Collective on Mat

3126:    Input Parameters:
3127: +  fact - the factor matrix obtained with MatGetFactor()
3128: .  mat - the matrix
3129: -  info - options for factorization

3131:    Notes:
3132:    See MatLUFactor() for in-place factorization.  See
3133:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3139:    Level: developer

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

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

3146: @*/
3147: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3148: {
3149:   MatFactorInfo  tinfo;

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

3160:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3161:   MatCheckPreallocated(mat,2);
3162:   if (!info) {
3163:     MatFactorInfoInitialize(&tinfo);
3164:     info = &tinfo;
3165:   }

3167:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3168:   (fact->ops->lufactornumeric)(fact,mat,info);
3169:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3170:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3171:   PetscObjectStateIncrease((PetscObject)fact);
3172:   return(0);
3173: }

3175: /*@C
3176:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3177:    symmetric matrix.

3179:    Collective on Mat

3181:    Input Parameters:
3182: +  mat - the matrix
3183: .  perm - row and column permutations
3184: -  f - expected fill as ratio of original fill

3186:    Notes:
3187:    See MatLUFactor() for the nonsymmetric case.  See also
3188:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3194:    Level: developer

3196: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3197:           MatGetOrdering()

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

3202: @*/
3203: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3204: {
3206:   MatFactorInfo  tinfo;

3213:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3214:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3215:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3216:   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);
3217:   MatCheckPreallocated(mat,1);
3218:   if (!info) {
3219:     MatFactorInfoInitialize(&tinfo);
3220:     info = &tinfo;
3221:   }

3223:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3224:   (*mat->ops->choleskyfactor)(mat,perm,info);
3225:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3226:   PetscObjectStateIncrease((PetscObject)mat);
3227:   return(0);
3228: }

3230: /*@C
3231:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3232:    of a symmetric matrix.

3234:    Collective on Mat

3236:    Input Parameters:
3237: +  fact - the factor matrix obtained with MatGetFactor()
3238: .  mat - the matrix
3239: .  perm - row and column permutations
3240: -  info - options for factorization, includes
3241: $          fill - expected fill as ratio of original fill.
3242: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3243: $                   Run with the option -info to determine an optimal value to use

3245:    Notes:
3246:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3247:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3253:    Level: developer

3255: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3256:           MatGetOrdering()

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

3261: @*/
3262: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3263: {
3265:   MatFactorInfo  tinfo;

3273:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3274:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3275:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3276:   if (!(fact)->ops->choleskyfactorsymbolic) {
3277:     MatSolverType stype;
3278:     MatFactorGetSolverType(fact,&stype);
3279:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,stype);
3280:   }
3281:   MatCheckPreallocated(mat,2);
3282:   if (!info) {
3283:     MatFactorInfoInitialize(&tinfo);
3284:     info = &tinfo;
3285:   }

3287:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3288:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3289:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3290:   PetscObjectStateIncrease((PetscObject)fact);
3291:   return(0);
3292: }

3294: /*@C
3295:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3296:    of a symmetric matrix. Call this routine after first calling
3297:    MatCholeskyFactorSymbolic().

3299:    Collective on Mat

3301:    Input Parameters:
3302: +  fact - the factor matrix obtained with MatGetFactor()
3303: .  mat - the initial matrix
3304: .  info - options for factorization
3305: -  fact - the symbolic factor of mat


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

3313:    Level: developer

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

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

3320: @*/
3321: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3322: {
3323:   MatFactorInfo  tinfo;

3331:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3332:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3333:   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);
3334:   MatCheckPreallocated(mat,2);
3335:   if (!info) {
3336:     MatFactorInfoInitialize(&tinfo);
3337:     info = &tinfo;
3338:   }

3340:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3341:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3342:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3343:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3344:   PetscObjectStateIncrease((PetscObject)fact);
3345:   return(0);
3346: }

3348: /* ----------------------------------------------------------------*/
3349: /*@
3350:    MatSolve - Solves A x = b, given a factored matrix.

3352:    Neighbor-wise Collective on Mat

3354:    Input Parameters:
3355: +  mat - the factored matrix
3356: -  b - the right-hand-side vector

3358:    Output Parameter:
3359: .  x - the result vector

3361:    Notes:
3362:    The vectors b and x cannot be the same.  I.e., one cannot
3363:    call MatSolve(A,x,x).

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

3370:    Level: developer

3372: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3373: @*/
3374: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3375: {

3385:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3386:   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);
3387:   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);
3388:   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);
3389:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3390:   MatCheckPreallocated(mat,1);

3392:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3393:   if (mat->factorerrortype) {
3394:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3395:     VecSetInf(x);
3396:   } else {
3397:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3398:     (*mat->ops->solve)(mat,b,x);
3399:   }
3400:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3401:   PetscObjectStateIncrease((PetscObject)x);
3402:   return(0);
3403: }

3405: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3406: {
3408:   Vec            b,x;
3409:   PetscInt       m,N,i;
3410:   PetscScalar    *bb,*xx;

3413:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3414:   MatDenseGetArray(X,&xx);
3415:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3416:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3417:   MatCreateVecs(A,&x,&b);
3418:   for (i=0; i<N; i++) {
3419:     VecPlaceArray(b,bb + i*m);
3420:     VecPlaceArray(x,xx + i*m);
3421:     if (trans) {
3422:       MatSolveTranspose(A,b,x);
3423:     } else {
3424:       MatSolve(A,b,x);
3425:     }
3426:     VecResetArray(x);
3427:     VecResetArray(b);
3428:   }
3429:   VecDestroy(&b);
3430:   VecDestroy(&x);
3431:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3432:   MatDenseRestoreArray(X,&xx);
3433:   return(0);
3434: }

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

3439:    Neighbor-wise Collective on Mat

3441:    Input Parameters:
3442: +  A - the factored matrix
3443: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3445:    Output Parameter:
3446: .  X - the result matrix (dense matrix)

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

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

3458:    Level: developer

3460: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3461: @*/
3462: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3463: {

3473:   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);
3474:   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);
3475:   if (X->cmap->N != B->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3476:   if (!A->rmap->N && !A->cmap->N) return(0);
3477:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3478:   MatCheckPreallocated(A,1);

3480:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3481:   if (!A->ops->matsolve) {
3482:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3483:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3484:   } else {
3485:     (*A->ops->matsolve)(A,B,X);
3486:   }
3487:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3488:   PetscObjectStateIncrease((PetscObject)X);
3489:   return(0);
3490: }

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

3495:    Neighbor-wise Collective on Mat

3497:    Input Parameters:
3498: +  A - the factored matrix
3499: -  B - the right-hand-side matrix  (dense matrix)

3501:    Output Parameter:
3502: .  X - the result matrix (dense matrix)

3504:    Notes:
3505:    The matrices B and X cannot be the same.  I.e., one cannot
3506:    call MatMatSolveTranspose(A,X,X).

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

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

3516:    Level: developer

3518: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3519: @*/
3520: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3521: {

3531:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3532:   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);
3533:   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);
3534:   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);
3535:   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");
3536:   if (!A->rmap->N && !A->cmap->N) return(0);
3537:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3538:   MatCheckPreallocated(A,1);

3540:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3541:   if (!A->ops->matsolvetranspose) {
3542:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3543:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3544:   } else {
3545:     (*A->ops->matsolvetranspose)(A,B,X);
3546:   }
3547:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3548:   PetscObjectStateIncrease((PetscObject)X);
3549:   return(0);
3550: }

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

3555:    Neighbor-wise Collective on Mat

3557:    Input Parameters:
3558: +  A - the factored matrix
3559: -  Bt - the transpose of right-hand-side matrix

3561:    Output Parameter:
3562: .  X - the result matrix (dense matrix)

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

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

3572:    Level: developer

3574: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3575: @*/
3576: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3577: {


3588:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3589:   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);
3590:   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);
3591:   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");
3592:   if (!A->rmap->N && !A->cmap->N) return(0);
3593:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3594:   MatCheckPreallocated(A,1);

3596:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3597:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3598:   (*A->ops->mattransposesolve)(A,Bt,X);
3599:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3600:   PetscObjectStateIncrease((PetscObject)X);
3601:   return(0);
3602: }

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

3608:    Neighbor-wise Collective on Mat

3610:    Input Parameters:
3611: +  mat - the factored matrix
3612: -  b - the right-hand-side vector

3614:    Output Parameter:
3615: .  x - the result vector

3617:    Notes:
3618:    MatSolve() should be used for most applications, as it performs
3619:    a forward solve followed by a backward solve.

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

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

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

3634:    Level: developer

3636: .seealso: MatSolve(), MatBackwardSolve()
3637: @*/
3638: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3639: {

3649:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3650:   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);
3651:   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);
3652:   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);
3653:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3654:   MatCheckPreallocated(mat,1);

3656:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3657:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3658:   (*mat->ops->forwardsolve)(mat,b,x);
3659:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3660:   PetscObjectStateIncrease((PetscObject)x);
3661:   return(0);
3662: }

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

3668:    Neighbor-wise Collective on Mat

3670:    Input Parameters:
3671: +  mat - the factored matrix
3672: -  b - the right-hand-side vector

3674:    Output Parameter:
3675: .  x - the result vector

3677:    Notes:
3678:    MatSolve() should be used for most applications, as it performs
3679:    a forward solve followed by a backward solve.

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

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

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

3694:    Level: developer

3696: .seealso: MatSolve(), MatForwardSolve()
3697: @*/
3698: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3699: {

3709:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3710:   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);
3711:   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);
3712:   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);
3713:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3714:   MatCheckPreallocated(mat,1);

3716:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3717:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3718:   (*mat->ops->backwardsolve)(mat,b,x);
3719:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3720:   PetscObjectStateIncrease((PetscObject)x);
3721:   return(0);
3722: }

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

3727:    Neighbor-wise Collective on Mat

3729:    Input Parameters:
3730: +  mat - the factored matrix
3731: .  b - the right-hand-side vector
3732: -  y - the vector to be added to

3734:    Output Parameter:
3735: .  x - the result vector

3737:    Notes:
3738:    The vectors b and x cannot be the same.  I.e., one cannot
3739:    call MatSolveAdd(A,x,y,x).

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

3745:    Level: developer

3747: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3748: @*/
3749: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3750: {
3751:   PetscScalar    one = 1.0;
3752:   Vec            tmp;

3764:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3765:   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);
3766:   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);
3767:   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);
3768:   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);
3769:   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);
3770:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3771:    MatCheckPreallocated(mat,1);

3773:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3774:   if (mat->factorerrortype) {
3775:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3776:     VecSetInf(x);
3777:   } else if (mat->ops->solveadd) {
3778:     (*mat->ops->solveadd)(mat,b,y,x);
3779:   } else {
3780:     /* do the solve then the add manually */
3781:     if (x != y) {
3782:       MatSolve(mat,b,x);
3783:       VecAXPY(x,one,y);
3784:     } else {
3785:       VecDuplicate(x,&tmp);
3786:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3787:       VecCopy(x,tmp);
3788:       MatSolve(mat,b,x);
3789:       VecAXPY(x,one,tmp);
3790:       VecDestroy(&tmp);
3791:     }
3792:   }
3793:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3794:   PetscObjectStateIncrease((PetscObject)x);
3795:   return(0);
3796: }

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

3801:    Neighbor-wise Collective on Mat

3803:    Input Parameters:
3804: +  mat - the factored matrix
3805: -  b - the right-hand-side vector

3807:    Output Parameter:
3808: .  x - the result vector

3810:    Notes:
3811:    The vectors b and x cannot be the same.  I.e., one cannot
3812:    call MatSolveTranspose(A,x,x).

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

3818:    Level: developer

3820: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3821: @*/
3822: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3823: {

3833:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3834:   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);
3835:   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);
3836:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3837:   MatCheckPreallocated(mat,1);
3838:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3839:   if (mat->factorerrortype) {
3840:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3841:     VecSetInf(x);
3842:   } else {
3843:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3844:     (*mat->ops->solvetranspose)(mat,b,x);
3845:   }
3846:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3847:   PetscObjectStateIncrease((PetscObject)x);
3848:   return(0);
3849: }

3851: /*@
3852:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3853:                       factored matrix.

3855:    Neighbor-wise Collective on Mat

3857:    Input Parameters:
3858: +  mat - the factored matrix
3859: .  b - the right-hand-side vector
3860: -  y - the vector to be added to

3862:    Output Parameter:
3863: .  x - the result vector

3865:    Notes:
3866:    The vectors b and x cannot be the same.  I.e., one cannot
3867:    call MatSolveTransposeAdd(A,x,y,x).

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

3873:    Level: developer

3875: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3876: @*/
3877: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3878: {
3879:   PetscScalar    one = 1.0;
3881:   Vec            tmp;

3892:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3893:   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);
3894:   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);
3895:   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);
3896:   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);
3897:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3898:    MatCheckPreallocated(mat,1);

3900:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3901:   if (mat->factorerrortype) {
3902:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3903:     VecSetInf(x);
3904:   } else if (mat->ops->solvetransposeadd){
3905:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
3906:   } else {
3907:     /* do the solve then the add manually */
3908:     if (x != y) {
3909:       MatSolveTranspose(mat,b,x);
3910:       VecAXPY(x,one,y);
3911:     } else {
3912:       VecDuplicate(x,&tmp);
3913:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3914:       VecCopy(x,tmp);
3915:       MatSolveTranspose(mat,b,x);
3916:       VecAXPY(x,one,tmp);
3917:       VecDestroy(&tmp);
3918:     }
3919:   }
3920:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3921:   PetscObjectStateIncrease((PetscObject)x);
3922:   return(0);
3923: }
3924: /* ----------------------------------------------------------------*/

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

3929:    Neighbor-wise Collective on Mat

3931:    Input Parameters:
3932: +  mat - the matrix
3933: .  b - the right hand side
3934: .  omega - the relaxation factor
3935: .  flag - flag indicating the type of SOR (see below)
3936: .  shift -  diagonal shift
3937: .  its - the number of iterations
3938: -  lits - the number of local iterations

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

3943:    SOR Flags:
3944: +     SOR_FORWARD_SWEEP - forward SOR
3945: .     SOR_BACKWARD_SWEEP - backward SOR
3946: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3947: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3948: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3949: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3950: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3951:          upper/lower triangular part of matrix to
3952:          vector (with omega)
3953: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

3955:    Notes:
3956:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3957:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3958:    on each processor.

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

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

3966:    Notes for Advanced Users:
3967:    The flags are implemented as bitwise inclusive or operations.
3968:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3969:    to specify a zero initial guess for SSOR.

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

3975:    Vectors x and b CANNOT be the same

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

3979:    Level: developer

3981: @*/
3982: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3983: {

3993:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3994:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3995:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3996:   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);
3997:   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);
3998:   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);
3999:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
4000:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
4001:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

4003:   MatCheckPreallocated(mat,1);
4004:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
4005:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
4006:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
4007:   PetscObjectStateIncrease((PetscObject)x);
4008:   return(0);
4009: }

4011: /*
4012:       Default matrix copy routine.
4013: */
4014: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4015: {
4016:   PetscErrorCode    ierr;
4017:   PetscInt          i,rstart = 0,rend = 0,nz;
4018:   const PetscInt    *cwork;
4019:   const PetscScalar *vwork;

4022:   if (B->assembled) {
4023:     MatZeroEntries(B);
4024:   }
4025:   if (str == SAME_NONZERO_PATTERN) {
4026:     MatGetOwnershipRange(A,&rstart,&rend);
4027:     for (i=rstart; i<rend; i++) {
4028:       MatGetRow(A,i,&nz,&cwork,&vwork);
4029:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
4030:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
4031:     }
4032:   } else {
4033:     MatAYPX(B,0.0,A,str);
4034:   }
4035:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4036:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4037:   return(0);
4038: }

4040: /*@
4041:    MatCopy - Copies a matrix to another matrix.

4043:    Collective on Mat

4045:    Input Parameters:
4046: +  A - the matrix
4047: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4049:    Output Parameter:
4050: .  B - where the copy is put

4052:    Notes:
4053:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4054:    same nonzero pattern or the routine will crash.

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

4060:    Level: intermediate

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

4064: @*/
4065: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4066: {
4068:   PetscInt       i;

4076:   MatCheckPreallocated(B,2);
4077:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4078:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4079:   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);
4080:   MatCheckPreallocated(A,1);
4081:   if (A == B) return(0);

4083:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4084:   if (A->ops->copy) {
4085:     (*A->ops->copy)(A,B,str);
4086:   } else { /* generic conversion */
4087:     MatCopy_Basic(A,B,str);
4088:   }

4090:   B->stencil.dim = A->stencil.dim;
4091:   B->stencil.noc = A->stencil.noc;
4092:   for (i=0; i<=A->stencil.dim; i++) {
4093:     B->stencil.dims[i]   = A->stencil.dims[i];
4094:     B->stencil.starts[i] = A->stencil.starts[i];
4095:   }

4097:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4098:   PetscObjectStateIncrease((PetscObject)B);
4099:   return(0);
4100: }

4102: /*@C
4103:    MatConvert - Converts a matrix to another matrix, either of the same
4104:    or different type.

4106:    Collective on Mat

4108:    Input Parameters:
4109: +  mat - the matrix
4110: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4111:    same type as the original matrix.
4112: -  reuse - denotes if the destination matrix is to be created or reused.
4113:    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
4114:    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).

4116:    Output Parameter:
4117: .  M - pointer to place new matrix

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

4124:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4125:    the MPI communicator of the generated matrix is always the same as the communicator
4126:    of the input matrix.

4128:    Level: intermediate

4130: .seealso: MatCopy(), MatDuplicate()
4131: @*/
4132: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4133: {
4135:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4136:   char           convname[256],mtype[256];
4137:   Mat            B;

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

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

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

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

4160:   /* Cache Mat options because some converter use MatHeaderReplace  */
4161:   issymmetric = mat->symmetric;
4162:   ishermitian = mat->hermitian;

4164:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4165:     PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4166:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4167:   } else {
4168:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4169:     const char     *prefix[3] = {"seq","mpi",""};
4170:     PetscInt       i;
4171:     /*
4172:        Order of precedence:
4173:        0) See if newtype is a superclass of the current matrix.
4174:        1) See if a specialized converter is known to the current matrix.
4175:        2) See if a specialized converter is known to the desired matrix class.
4176:        3) See if a good general converter is registered for the desired class
4177:           (as of 6/27/03 only MATMPIADJ falls into this category).
4178:        4) See if a good general converter is known for the current matrix.
4179:        5) Use a really basic converter.
4180:     */

4182:     /* 0) See if newtype is a superclass of the current matrix.
4183:           i.e mat is mpiaij and newtype is aij */
4184:     for (i=0; i<2; i++) {
4185:       PetscStrncpy(convname,prefix[i],sizeof(convname));
4186:       PetscStrlcat(convname,newtype,sizeof(convname));
4187:       PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4188:       PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4189:       if (flg) {
4190:         if (reuse == MAT_INPLACE_MATRIX) {
4191:           PetscInfo(mat,"Early return\n");
4192:           return(0);
4193:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4194:           PetscInfo(mat,"Calling MatDuplicate\n");
4195:           (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4196:           return(0);
4197:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4198:           PetscInfo(mat,"Calling MatCopy\n");
4199:           MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4200:           return(0);
4201:         }
4202:       }
4203:     }
4204:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4205:     for (i=0; i<3; i++) {
4206:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4207:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4208:       PetscStrlcat(convname,"_",sizeof(convname));
4209:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4210:       PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4211:       PetscStrlcat(convname,"_C",sizeof(convname));
4212:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4213:       PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4214:       if (conv) goto foundconv;
4215:     }

4217:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4218:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4219:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4220:     MatSetType(B,newtype);
4221:     for (i=0; i<3; i++) {
4222:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4223:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4224:       PetscStrlcat(convname,"_",sizeof(convname));
4225:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4226:       PetscStrlcat(convname,newtype,sizeof(convname));
4227:       PetscStrlcat(convname,"_C",sizeof(convname));
4228:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4229:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4230:       if (conv) {
4231:         MatDestroy(&B);
4232:         goto foundconv;
4233:       }
4234:     }

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

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

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

4248:     /* 5) Use a really basic converter. */
4249:     PetscInfo(mat,"Using MatConvert_Basic\n");
4250:     conv = MatConvert_Basic;

4252: foundconv:
4253:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4254:     (*conv)(mat,newtype,reuse,M);
4255:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4256:       /* the block sizes must be same if the mappings are copied over */
4257:       (*M)->rmap->bs = mat->rmap->bs;
4258:       (*M)->cmap->bs = mat->cmap->bs;
4259:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4260:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4261:       (*M)->rmap->mapping = mat->rmap->mapping;
4262:       (*M)->cmap->mapping = mat->cmap->mapping;
4263:     }
4264:     (*M)->stencil.dim = mat->stencil.dim;
4265:     (*M)->stencil.noc = mat->stencil.noc;
4266:     for (i=0; i<=mat->stencil.dim; i++) {
4267:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4268:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4269:     }
4270:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4271:   }
4272:   PetscObjectStateIncrease((PetscObject)*M);

4274:   /* Copy Mat options */
4275:   if (issymmetric) {
4276:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4277:   }
4278:   if (ishermitian) {
4279:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4280:   }
4281:   return(0);
4282: }

4284: /*@C
4285:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4287:    Not Collective

4289:    Input Parameter:
4290: .  mat - the matrix, must be a factored matrix

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

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

4299:    Level: intermediate

4301: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4302: @*/
4303: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4304: {
4305:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4310:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4311:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4312:   if (!conv) {
4313:     *type = MATSOLVERPETSC;
4314:   } else {
4315:     (*conv)(mat,type);
4316:   }
4317:   return(0);
4318: }

4320: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4321: struct _MatSolverTypeForSpecifcType {
4322:   MatType                        mtype;
4323:   PetscErrorCode                 (*createfactor[4])(Mat,MatFactorType,Mat*);
4324:   MatSolverTypeForSpecifcType next;
4325: };

4327: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4328: struct _MatSolverTypeHolder {
4329:   char                        *name;
4330:   MatSolverTypeForSpecifcType handlers;
4331:   MatSolverTypeHolder         next;
4332: };

4334: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

4336: /*@C
4337:    MatSolveTypeRegister - Registers a MatSolverType that works for a particular matrix type

4339:    Input Parameters:
4340: +    package - name of the package, for example petsc or superlu
4341: .    mtype - the matrix type that works with this package
4342: .    ftype - the type of factorization supported by the package
4343: -    createfactor - routine that will create the factored matrix ready to be used

4345:     Level: intermediate

4347: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4348: @*/
4349: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*createfactor)(Mat,MatFactorType,Mat*))
4350: {
4351:   PetscErrorCode              ierr;
4352:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4353:   PetscBool                   flg;
4354:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4357:   MatInitializePackage();
4358:   if (!next) {
4359:     PetscNew(&MatSolverTypeHolders);
4360:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4361:     PetscNew(&MatSolverTypeHolders->handlers);
4362:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4363:     MatSolverTypeHolders->handlers->createfactor[(int)ftype-1] = createfactor;
4364:     return(0);
4365:   }
4366:   while (next) {
4367:     PetscStrcasecmp(package,next->name,&flg);
4368:     if (flg) {
4369:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4370:       inext = next->handlers;
4371:       while (inext) {
4372:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4373:         if (flg) {
4374:           inext->createfactor[(int)ftype-1] = createfactor;
4375:           return(0);
4376:         }
4377:         iprev = inext;
4378:         inext = inext->next;
4379:       }
4380:       PetscNew(&iprev->next);
4381:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4382:       iprev->next->createfactor[(int)ftype-1] = createfactor;
4383:       return(0);
4384:     }
4385:     prev = next;
4386:     next = next->next;
4387:   }
4388:   PetscNew(&prev->next);
4389:   PetscStrallocpy(package,&prev->next->name);
4390:   PetscNew(&prev->next->handlers);
4391:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4392:   prev->next->handlers->createfactor[(int)ftype-1] = createfactor;
4393:   return(0);
4394: }

4396: /*@C
4397:    MatSolveTypeGet - Gets the function that creates the factor matrix if it exist

4399:    Input Parameters:
4400: +    type - name of the package, for example petsc or superlu
4401: .    ftype - the type of factorization supported by the type
4402: -    mtype - the matrix type that works with this type

4404:    Output Parameters:
4405: +   foundtype - PETSC_TRUE if the type was registered
4406: .   foundmtype - PETSC_TRUE if the type supports the requested mtype
4407: -   createfactor - routine that will create the factored matrix ready to be used or NULL if not found

4409:     Level: intermediate

4411: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatSolvePackageRegister), MatGetFactor()
4412: @*/
4413: PetscErrorCode MatSolverTypeGet(MatSolverType type,MatType mtype,MatFactorType ftype,PetscBool *foundtype,PetscBool *foundmtype,PetscErrorCode (**createfactor)(Mat,MatFactorType,Mat*))
4414: {
4415:   PetscErrorCode              ierr;
4416:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4417:   PetscBool                   flg;
4418:   MatSolverTypeForSpecifcType inext;

4421:   if (foundtype) *foundtype = PETSC_FALSE;
4422:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4423:   if (createfactor) *createfactor    = NULL;

4425:   if (type) {
4426:     while (next) {
4427:       PetscStrcasecmp(type,next->name,&flg);
4428:       if (flg) {
4429:         if (foundtype) *foundtype = PETSC_TRUE;
4430:         inext = next->handlers;
4431:         while (inext) {
4432:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4433:           if (flg) {
4434:             if (foundmtype) *foundmtype = PETSC_TRUE;
4435:             if (createfactor)  *createfactor  = inext->createfactor[(int)ftype-1];
4436:             return(0);
4437:           }
4438:           inext = inext->next;
4439:         }
4440:       }
4441:       next = next->next;
4442:     }
4443:   } else {
4444:     while (next) {
4445:       inext = next->handlers;
4446:       while (inext) {
4447:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4448:         if (flg && inext->createfactor[(int)ftype-1]) {
4449:           if (foundtype) *foundtype = PETSC_TRUE;
4450:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4451:           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4452:           return(0);
4453:         }
4454:         inext = inext->next;
4455:       }
4456:       next = next->next;
4457:     }
4458:   }
4459:   return(0);
4460: }

4462: PetscErrorCode MatSolverTypeDestroy(void)
4463: {
4464:   PetscErrorCode              ierr;
4465:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4466:   MatSolverTypeForSpecifcType inext,iprev;

4469:   while (next) {
4470:     PetscFree(next->name);
4471:     inext = next->handlers;
4472:     while (inext) {
4473:       PetscFree(inext->mtype);
4474:       iprev = inext;
4475:       inext = inext->next;
4476:       PetscFree(iprev);
4477:     }
4478:     prev = next;
4479:     next = next->next;
4480:     PetscFree(prev);
4481:   }
4482:   MatSolverTypeHolders = NULL;
4483:   return(0);
4484: }

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

4489:    Logically Collective on Mat

4491:    Input Parameters:
4492: .  mat - the matrix

4494:    Output Parameters:
4495: .  flg - PETSC_TRUE if uses the ordering

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

4501:    Level: developer

4503: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4504: @*/
4505: PetscErrorCode MatFactorGetUseOrdering(Mat mat, PetscBool *flg)
4506: {
4508:   *flg = mat->useordering;
4509:   return(0);
4510: }

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

4515:    Collective on Mat

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

4522:    Output Parameters:
4523: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4525:    Notes:
4526:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4527:      such as pastix, superlu, mumps etc.

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

4531:    Developer Notes:
4532:       This should actually be called MatCreateFactor() since it creates a new factor object

4534:    Level: intermediate

4536: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetUseOrdering(), MatSolverTypeRegister()
4537: @*/
4538: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4539: {
4540:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4541:   PetscBool      foundtype,foundmtype;


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

4550:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundtype,&foundmtype,&conv);
4551:   if (!foundtype) {
4552:     if (type) {
4553:       SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver type %s for factorization type %s and matrix type %s. Perhaps you must ./configure with --download-%s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name,type);
4554:     } else {
4555:       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver type for factorization type %s and matrix type %s.",MatFactorTypes[ftype],((PetscObject)mat)->type_name);
4556:     }
4557:   }
4558:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4559:   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);

4561:   (*conv)(mat,ftype,f);
4562:   return(0);
4563: }

4565: /*@C
4566:    MatGetFactorAvailable - Returns a a flag if matrix supports particular type and factor type

4568:    Not Collective

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

4575:    Output Parameter:
4576: .    flg - PETSC_TRUE if the factorization is available

4578:    Notes:
4579:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4580:      such as pastix, superlu, mumps etc.

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

4584:    Developer Notes:
4585:       This should actually be called MatCreateFactorAvailable() since MatGetFactor() creates a new factor object

4587:    Level: intermediate

4589: .seealso: MatCopy(), MatDuplicate(), MatGetFactor(), MatSolverTypeRegister()
4590: @*/
4591: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4592: {
4593:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4602:   *flg = PETSC_FALSE;
4603:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4604:   if (gconv) {
4605:     *flg = PETSC_TRUE;
4606:   }
4607:   return(0);
4608: }

4610: #include <petscdmtypes.h>

4612: /*@
4613:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4615:    Collective on Mat

4617:    Input Parameters:
4618: +  mat - the matrix
4619: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4620:         See the manual page for MatDuplicateOption for an explanation of these options.

4622:    Output Parameter:
4623: .  M - pointer to place new matrix

4625:    Level: intermediate

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

4631: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4632: @*/
4633: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4634: {
4636:   Mat            B;
4637:   PetscInt       i;
4638:   DM             dm;
4639:   void           (*viewf)(void);

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

4649:   *M = NULL;
4650:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4651:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4652:   (*mat->ops->duplicate)(mat,op,M);
4653:   B    = *M;

4655:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4656:   if (viewf) {
4657:     MatSetOperation(B,MATOP_VIEW,viewf);
4658:   }

4660:   B->stencil.dim = mat->stencil.dim;
4661:   B->stencil.noc = mat->stencil.noc;
4662:   for (i=0; i<=mat->stencil.dim; i++) {
4663:     B->stencil.dims[i]   = mat->stencil.dims[i];
4664:     B->stencil.starts[i] = mat->stencil.starts[i];
4665:   }

4667:   B->nooffproczerorows = mat->nooffproczerorows;
4668:   B->nooffprocentries  = mat->nooffprocentries;

4670:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4671:   if (dm) {
4672:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4673:   }
4674:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4675:   PetscObjectStateIncrease((PetscObject)B);
4676:   return(0);
4677: }

4679: /*@
4680:    MatGetDiagonal - Gets the diagonal of a matrix.

4682:    Logically Collective on Mat

4684:    Input Parameters:
4685: +  mat - the matrix
4686: -  v - the vector for storing the diagonal

4688:    Output Parameter:
4689: .  v - the diagonal of the matrix

4691:    Level: intermediate

4693:    Note:
4694:    Currently only correct in parallel for square matrices.

4696: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4697: @*/
4698: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4699: {

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

4710:   (*mat->ops->getdiagonal)(mat,v);
4711:   PetscObjectStateIncrease((PetscObject)v);
4712:   return(0);
4713: }

4715: /*@C
4716:    MatGetRowMin - Gets the minimum value (of the real part) of each
4717:         row of the matrix

4719:    Logically Collective on Mat

4721:    Input Parameters:
4722: .  mat - the matrix

4724:    Output Parameter:
4725: +  v - the vector for storing the maximums
4726: -  idx - the indices of the column found for each row (optional)

4728:    Level: intermediate

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

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

4736: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4737:           MatGetRowMax()
4738: @*/
4739: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4740: {

4747:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");

4749:   if (!mat->cmap->N) {
4750:     VecSet(v,PETSC_MAX_REAL);
4751:     if (idx) {
4752:       PetscInt i,m = mat->rmap->n;
4753:       for (i=0; i<m; i++) idx[i] = -1;
4754:     }
4755:   } else {
4756:     if (!mat->ops->getrowmin) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4757:     MatCheckPreallocated(mat,1);
4758:   }
4759:   (*mat->ops->getrowmin)(mat,v,idx);
4760:   PetscObjectStateIncrease((PetscObject)v);
4761:   return(0);
4762: }

4764: /*@C
4765:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4766:         row of the matrix

4768:    Logically Collective on Mat

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

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

4777:    Level: intermediate

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

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

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

4795:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4796:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

4798:   if (!mat->cmap->N) {
4799:     VecSet(v,0.0);
4800:     if (idx) {
4801:       PetscInt i,m = mat->rmap->n;
4802:       for (i=0; i<m; i++) idx[i] = -1;
4803:     }
4804:   } else {
4805:     if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4806:     MatCheckPreallocated(mat,1);
4807:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4808:     (*mat->ops->getrowminabs)(mat,v,idx);
4809:   }
4810:   PetscObjectStateIncrease((PetscObject)v);
4811:   return(0);
4812: }

4814: /*@C
4815:    MatGetRowMax - Gets the maximum value (of the real part) of each
4816:         row of the matrix

4818:    Logically Collective on Mat

4820:    Input Parameters:
4821: .  mat - the matrix

4823:    Output Parameter:
4824: +  v - the vector for storing the maximums
4825: -  idx - the indices of the column found for each row (optional)

4827:    Level: intermediate

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

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

4835: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4836: @*/
4837: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4838: {

4845:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");

4847:   if (!mat->cmap->N) {
4848:     VecSet(v,PETSC_MIN_REAL);
4849:     if (idx) {
4850:       PetscInt i,m = mat->rmap->n;
4851:       for (i=0; i<m; i++) idx[i] = -1;
4852:     }
4853:   } else {
4854:     if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4855:     MatCheckPreallocated(mat,1);
4856:     (*mat->ops->getrowmax)(mat,v,idx);
4857:   }
4858:   PetscObjectStateIncrease((PetscObject)v);
4859:   return(0);
4860: }

4862: /*@C
4863:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4864:         row of the matrix

4866:    Logically Collective on Mat

4868:    Input Parameters:
4869: .  mat - the matrix

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

4875:    Level: intermediate

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

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

4883: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4884: @*/
4885: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4886: {

4893:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");

4895:   if (!mat->cmap->N) {
4896:     VecSet(v,0.0);
4897:     if (idx) {
4898:       PetscInt i,m = mat->rmap->n;
4899:       for (i=0; i<m; i++) idx[i] = -1;
4900:     }
4901:   } else {
4902:     if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4903:     MatCheckPreallocated(mat,1);
4904:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4905:     (*mat->ops->getrowmaxabs)(mat,v,idx);
4906:   }
4907:   PetscObjectStateIncrease((PetscObject)v);
4908:   return(0);
4909: }

4911: /*@
4912:    MatGetRowSum - Gets the sum of each row of the matrix

4914:    Logically or Neighborhood Collective on Mat

4916:    Input Parameters:
4917: .  mat - the matrix

4919:    Output Parameter:
4920: .  v - the vector for storing the sum of rows

4922:    Level: intermediate

4924:    Notes:
4925:     This code is slow since it is not currently specialized for different formats

4927: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4928: @*/
4929: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4930: {
4931:   Vec            ones;

4938:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4939:   MatCheckPreallocated(mat,1);
4940:   MatCreateVecs(mat,&ones,NULL);
4941:   VecSet(ones,1.);
4942:   MatMult(mat,ones,v);
4943:   VecDestroy(&ones);
4944:   return(0);
4945: }

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

4950:    Collective on Mat

4952:    Input Parameter:
4953: +  mat - the matrix to transpose
4954: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4956:    Output Parameters:
4957: .  B - the transpose

4959:    Notes:
4960:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4966:    Level: intermediate

4968: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4969: @*/
4970: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4971: {

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

4984:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4985:   (*mat->ops->transpose)(mat,reuse,B);
4986:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4987:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4988:   return(0);
4989: }

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

4995:    Collective on Mat

4997:    Input Parameter:
4998: +  A - the matrix to test
4999: -  B - the matrix to test against, this can equal the first parameter

5001:    Output Parameters:
5002: .  flg - the result

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

5009:    Level: intermediate

5011: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
5012: @*/
5013: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5014: {
5015:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5021:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
5022:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
5023:   *flg = PETSC_FALSE;
5024:   if (f && g) {
5025:     if (f == g) {
5026:       (*f)(A,B,tol,flg);
5027:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
5028:   } else {
5029:     MatType mattype;
5030:     if (!f) {
5031:       MatGetType(A,&mattype);
5032:     } else {
5033:       MatGetType(B,&mattype);
5034:     }
5035:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
5036:   }
5037:   return(0);
5038: }

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

5043:    Collective on Mat

5045:    Input Parameter:
5046: +  mat - the matrix to transpose and complex conjugate
5047: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

5049:    Output Parameters:
5050: .  B - the Hermitian

5052:    Level: intermediate

5054: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5055: @*/
5056: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5057: {

5061:   MatTranspose(mat,reuse,B);
5062: #if defined(PETSC_USE_COMPLEX)
5063:   MatConjugate(*B);
5064: #endif
5065:   return(0);
5066: }

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

5071:    Collective on Mat

5073:    Input Parameter:
5074: +  A - the matrix to test
5075: -  B - the matrix to test against, this can equal the first parameter

5077:    Output Parameters:
5078: .  flg - the result

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

5085:    Level: intermediate

5087: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5088: @*/
5089: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5090: {
5091:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5097:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5098:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5099:   if (f && g) {
5100:     if (f==g) {
5101:       (*f)(A,B,tol,flg);
5102:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5103:   }
5104:   return(0);
5105: }

5107: /*@
5108:    MatPermute - Creates a new matrix with rows and columns permuted from the
5109:    original.

5111:    Collective on Mat

5113:    Input Parameters:
5114: +  mat - the matrix to permute
5115: .  row - row permutation, each processor supplies only the permutation for its rows
5116: -  col - column permutation, each processor supplies only the permutation for its columns

5118:    Output Parameters:
5119: .  B - the permuted matrix

5121:    Level: advanced

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

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

5129: @*/
5130: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5131: {

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

5145:   (*mat->ops->permute)(mat,row,col,B);
5146:   PetscObjectStateIncrease((PetscObject)*B);
5147:   return(0);
5148: }

5150: /*@
5151:    MatEqual - Compares two matrices.

5153:    Collective on Mat

5155:    Input Parameters:
5156: +  A - the first matrix
5157: -  B - the second matrix

5159:    Output Parameter:
5160: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5162:    Level: intermediate

5164: @*/
5165: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5166: {

5176:   MatCheckPreallocated(B,2);
5177:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5178:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5179:   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);
5180:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5181:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5182:   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);
5183:   MatCheckPreallocated(A,1);

5185:   (*A->ops->equal)(A,B,flg);
5186:   return(0);
5187: }

5189: /*@
5190:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5191:    matrices that are stored as vectors.  Either of the two scaling
5192:    matrices can be NULL.

5194:    Collective on Mat

5196:    Input Parameters:
5197: +  mat - the matrix to be scaled
5198: .  l - the left scaling vector (or NULL)
5199: -  r - the right scaling vector (or NULL)

5201:    Notes:
5202:    MatDiagonalScale() computes A = LAR, where
5203:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5204:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5206:    Level: intermediate


5209: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5210: @*/
5211: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5212: {

5220:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5221:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5222:   MatCheckPreallocated(mat,1);
5223:   if (!l && !r) return(0);

5225:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5226:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5227:   (*mat->ops->diagonalscale)(mat,l,r);
5228:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5229:   PetscObjectStateIncrease((PetscObject)mat);
5230:   return(0);
5231: }

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

5236:     Logically Collective on Mat

5238:     Input Parameters:
5239: +   mat - the matrix to be scaled
5240: -   a  - the scaling value

5242:     Output Parameter:
5243: .   mat - the scaled matrix

5245:     Level: intermediate

5247: .seealso: MatDiagonalScale()
5248: @*/
5249: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5250: {

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

5262:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5263:   if (a != (PetscScalar)1.0) {
5264:     (*mat->ops->scale)(mat,a);
5265:     PetscObjectStateIncrease((PetscObject)mat);
5266:   }
5267:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5268:   return(0);
5269: }

5271: /*@
5272:    MatNorm - Calculates various norms of a matrix.

5274:    Collective on Mat

5276:    Input Parameters:
5277: +  mat - the matrix
5278: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5280:    Output Parameters:
5281: .  nrm - the resulting norm

5283:    Level: intermediate

5285: @*/
5286: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5287: {


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

5300:   (*mat->ops->norm)(mat,type,nrm);
5301:   return(0);
5302: }

5304: /*
5305:      This variable is used to prevent counting of MatAssemblyBegin() that
5306:    are called from within a MatAssemblyEnd().
5307: */
5308: static PetscInt MatAssemblyEnd_InUse = 0;
5309: /*@
5310:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5311:    be called after completing all calls to MatSetValues().

5313:    Collective on Mat

5315:    Input Parameters:
5316: +  mat - the matrix
5317: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5319:    Notes:
5320:    MatSetValues() generally caches the values.  The matrix is ready to
5321:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5322:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5323:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5324:    using the matrix.

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

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

5334:    Level: beginner

5336: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5337: @*/
5338: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5339: {

5345:   MatCheckPreallocated(mat,1);
5346:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5347:   if (mat->assembled) {
5348:     mat->was_assembled = PETSC_TRUE;
5349:     mat->assembled     = PETSC_FALSE;
5350:   }

5352:   if (!MatAssemblyEnd_InUse) {
5353:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5354:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5355:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5356:   } else if (mat->ops->assemblybegin) {
5357:     (*mat->ops->assemblybegin)(mat,type);
5358:   }
5359:   return(0);
5360: }

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

5366:    Not Collective

5368:    Input Parameter:
5369: .  mat - the matrix

5371:    Output Parameter:
5372: .  assembled - PETSC_TRUE or PETSC_FALSE

5374:    Level: advanced

5376: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5377: @*/
5378: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5379: {
5383:   *assembled = mat->assembled;
5384:   return(0);
5385: }

5387: /*@
5388:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5389:    be called after MatAssemblyBegin().

5391:    Collective on Mat

5393:    Input Parameters:
5394: +  mat - the matrix
5395: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5397:    Options Database Keys:
5398: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5399: .  -mat_view ::ascii_info_detail - Prints more detailed info
5400: .  -mat_view - Prints matrix in ASCII format
5401: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5402: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5403: .  -display <name> - Sets display name (default is host)
5404: .  -draw_pause <sec> - Sets number of seconds to pause after display
5405: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab)
5406: .  -viewer_socket_machine <machine> - Machine to use for socket
5407: .  -viewer_socket_port <port> - Port number to use for socket
5408: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5410:    Notes:
5411:    MatSetValues() generally caches the values.  The matrix is ready to
5412:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5413:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5414:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5415:    using the matrix.

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

5421:    Level: beginner

5423: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5424: @*/
5425: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5426: {
5427:   PetscErrorCode  ierr;
5428:   static PetscInt inassm = 0;
5429:   PetscBool       flg    = PETSC_FALSE;


5435:   inassm++;
5436:   MatAssemblyEnd_InUse++;
5437:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5438:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5439:     if (mat->ops->assemblyend) {
5440:       (*mat->ops->assemblyend)(mat,type);
5441:     }
5442:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5443:   } else if (mat->ops->assemblyend) {
5444:     (*mat->ops->assemblyend)(mat,type);
5445:   }

5447:   /* Flush assembly is not a true assembly */
5448:   if (type != MAT_FLUSH_ASSEMBLY) {
5449:     mat->num_ass++;
5450:     mat->assembled        = PETSC_TRUE;
5451:     mat->ass_nonzerostate = mat->nonzerostate;
5452:   }

5454:   mat->insertmode = NOT_SET_VALUES;
5455:   MatAssemblyEnd_InUse--;
5456:   PetscObjectStateIncrease((PetscObject)mat);
5457:   if (!mat->symmetric_eternal) {
5458:     mat->symmetric_set              = PETSC_FALSE;
5459:     mat->hermitian_set              = PETSC_FALSE;
5460:     mat->structurally_symmetric_set = PETSC_FALSE;
5461:   }
5462:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5463:     MatViewFromOptions(mat,NULL,"-mat_view");

5465:     if (mat->checksymmetryonassembly) {
5466:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5467:       if (flg) {
5468:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5469:       } else {
5470:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5471:       }
5472:     }
5473:     if (mat->nullsp && mat->checknullspaceonassembly) {
5474:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5475:     }
5476:   }
5477:   inassm--;
5478:   return(0);
5479: }

5481: /*@
5482:    MatSetOption - Sets a parameter option for a matrix. Some options
5483:    may be specific to certain storage formats.  Some options
5484:    determine how values will be inserted (or added). Sorted,
5485:    row-oriented input will generally assemble the fastest. The default
5486:    is row-oriented.

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

5490:    Input Parameters:
5491: +  mat - the matrix
5492: .  option - the option, one of those listed below (and possibly others),
5493: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5495:   Options Describing Matrix Structure:
5496: +    MAT_SPD - symmetric positive definite
5497: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5498: .    MAT_HERMITIAN - transpose is the complex conjugation
5499: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5500: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5501:                             you set to be kept with all future use of the matrix
5502:                             including after MatAssemblyBegin/End() which could
5503:                             potentially change the symmetry structure, i.e. you
5504:                             KNOW the matrix will ALWAYS have the property you set.
5505:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5506:                             the relevant flags must be set independently.


5509:    Options For Use with MatSetValues():
5510:    Insert a logically dense subblock, which can be
5511: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5565:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5566:    searches during matrix assembly. When this flag is set, the hash table
5567:    is created during the first Matrix Assembly. This hash table is
5568:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5569:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5570:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5571:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5593:    Level: intermediate

5595: .seealso:  MatOption, Mat

5597: @*/
5598: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5599: {

5605:   if (op > 0) {
5608:   }

5610:   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);
5611:   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()");

5613:   switch (op) {
5614:   case MAT_NO_OFF_PROC_ENTRIES:
5615:     mat->nooffprocentries = flg;
5616:     return(0);
5617:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5618:     mat->assembly_subset = flg;
5619:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5620: #if !defined(PETSC_HAVE_MPIUNI)
5621:       MatStashScatterDestroy_BTS(&mat->stash);
5622: #endif
5623:       mat->stash.first_assembly_done = PETSC_FALSE;
5624:     }
5625:     return(0);
5626:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5627:     mat->nooffproczerorows = flg;
5628:     return(0);
5629:   case MAT_SPD:
5630:     mat->spd_set = PETSC_TRUE;
5631:     mat->spd     = flg;
5632:     if (flg) {
5633:       mat->symmetric                  = PETSC_TRUE;
5634:       mat->structurally_symmetric     = PETSC_TRUE;
5635:       mat->symmetric_set              = PETSC_TRUE;
5636:       mat->structurally_symmetric_set = PETSC_TRUE;
5637:     }
5638:     break;
5639:   case MAT_SYMMETRIC:
5640:     mat->symmetric = flg;
5641:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5642:     mat->symmetric_set              = PETSC_TRUE;
5643:     mat->structurally_symmetric_set = flg;
5644: #if !defined(PETSC_USE_COMPLEX)
5645:     mat->hermitian     = flg;
5646:     mat->hermitian_set = PETSC_TRUE;
5647: #endif
5648:     break;
5649:   case MAT_HERMITIAN:
5650:     mat->hermitian = flg;
5651:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5652:     mat->hermitian_set              = PETSC_TRUE;
5653:     mat->structurally_symmetric_set = flg;
5654: #if !defined(PETSC_USE_COMPLEX)
5655:     mat->symmetric     = flg;
5656:     mat->symmetric_set = PETSC_TRUE;
5657: #endif
5658:     break;
5659:   case MAT_STRUCTURALLY_SYMMETRIC:
5660:     mat->structurally_symmetric     = flg;
5661:     mat->structurally_symmetric_set = PETSC_TRUE;
5662:     break;
5663:   case MAT_SYMMETRY_ETERNAL:
5664:     mat->symmetric_eternal = flg;
5665:     break;
5666:   case MAT_STRUCTURE_ONLY:
5667:     mat->structure_only = flg;
5668:     break;
5669:   case MAT_SORTED_FULL:
5670:     mat->sortedfull = flg;
5671:     break;
5672:   default:
5673:     break;
5674:   }
5675:   if (mat->ops->setoption) {
5676:     (*mat->ops->setoption)(mat,op,flg);
5677:   }
5678:   return(0);
5679: }

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

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

5686:    Input Parameters:
5687: +  mat - the matrix
5688: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5696:    Level: intermediate

5698: .seealso:  MatOption, MatSetOption()

5700: @*/
5701: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5702: {

5707:   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);
5708:   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()");

5710:   switch (op) {
5711:   case MAT_NO_OFF_PROC_ENTRIES:
5712:     *flg = mat->nooffprocentries;
5713:     break;
5714:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5715:     *flg = mat->nooffproczerorows;
5716:     break;
5717:   case MAT_SYMMETRIC:
5718:     *flg = mat->symmetric;
5719:     break;
5720:   case MAT_HERMITIAN:
5721:     *flg = mat->hermitian;
5722:     break;
5723:   case MAT_STRUCTURALLY_SYMMETRIC:
5724:     *flg = mat->structurally_symmetric;
5725:     break;
5726:   case MAT_SYMMETRY_ETERNAL:
5727:     *flg = mat->symmetric_eternal;
5728:     break;
5729:   case MAT_SPD:
5730:     *flg = mat->spd;
5731:     break;
5732:   default:
5733:     break;
5734:   }
5735:   return(0);
5736: }

5738: /*@
5739:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5740:    this routine retains the old nonzero structure.

5742:    Logically Collective on Mat

5744:    Input Parameters:
5745: .  mat - the matrix

5747:    Level: intermediate

5749:    Notes:
5750:     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.
5751:    See the Performance chapter of the users manual for information on preallocating matrices.

5753: .seealso: MatZeroRows()
5754: @*/
5755: PetscErrorCode MatZeroEntries(Mat mat)
5756: {

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

5767:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5768:   (*mat->ops->zeroentries)(mat);
5769:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5770:   PetscObjectStateIncrease((PetscObject)mat);
5771:   return(0);
5772: }

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

5778:    Collective on Mat

5780:    Input Parameters:
5781: +  mat - the matrix
5782: .  numRows - the number of rows to remove
5783: .  rows - the global row indices
5784: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5785: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5786: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5805:    Level: intermediate

5807: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5808:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5809: @*/
5810: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5811: {

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

5823:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5824:   MatViewFromOptions(mat,NULL,"-mat_view");
5825:   PetscObjectStateIncrease((PetscObject)mat);
5826:   return(0);
5827: }

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

5833:    Collective on Mat

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

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

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

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

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

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

5859:    Level: intermediate

5861: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5862:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5863: @*/
5864: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5865: {
5867:   PetscInt       numRows;
5868:   const PetscInt *rows;

5875:   ISGetLocalSize(is,&numRows);
5876:   ISGetIndices(is,&rows);
5877:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5878:   ISRestoreIndices(is,&rows);
5879:   return(0);
5880: }

5882: /*@
5883:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5884:    of a set of rows of a matrix.

5886:    Collective on Mat

5888:    Input Parameters:
5889: +  mat - the matrix
5890: .  numRows - the number of rows to remove
5891: .  rows - the global row indices
5892: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5893: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5894: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

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

5920:    Level: intermediate

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

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

5938:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5939:   MatViewFromOptions(mat,NULL,"-mat_view");
5940:   PetscObjectStateIncrease((PetscObject)mat);
5941:   return(0);
5942: }

5944: /*@
5945:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5946:    of a set of rows of a matrix.

5948:    Collective on Mat

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

5957:    Notes:
5958:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5959:    but does not release memory.  For the dense and block diagonal
5960:    formats this does not alter the nonzero structure.

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

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

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

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

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

5981:    Level: intermediate

5983: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5984:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5985: @*/
5986: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5987: {
5988:   PetscInt       numRows;
5989:   const PetscInt *rows;

5996:   ISGetLocalSize(is,&numRows);
5997:   ISGetIndices(is,&rows);
5998:   MatZeroRows(mat,numRows,rows,diag,x,b);
5999:   ISRestoreIndices(is,&rows);
6000:   return(0);
6001: }

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

6007:    Collective on Mat

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

6017:    Notes:
6018:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6019:    but does not release memory.  For the dense and block diagonal
6020:    formats this does not alter the nonzero structure.

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

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

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

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

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

6040:    In Fortran idxm and idxn should be declared as
6041: $     MatStencil idxm(4,m)
6042:    and the values inserted using
6043: $    idxm(MatStencil_i,1) = i
6044: $    idxm(MatStencil_j,1) = j
6045: $    idxm(MatStencil_k,1) = k
6046: $    idxm(MatStencil_c,1) = c
6047:    etc

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

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

6057:    Level: intermediate

6059: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6060:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6061: @*/
6062: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6063: {
6064:   PetscInt       dim     = mat->stencil.dim;
6065:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6066:   PetscInt       *dims   = mat->stencil.dims+1;
6067:   PetscInt       *starts = mat->stencil.starts;
6068:   PetscInt       *dxm    = (PetscInt*) rows;
6069:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6077:   PetscMalloc1(numRows, &jdxm);
6078:   for (i = 0; i < numRows; ++i) {
6079:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6080:     for (j = 0; j < 3-sdim; ++j) dxm++;
6081:     /* Local index in X dir */
6082:     tmp = *dxm++ - starts[0];
6083:     /* Loop over remaining dimensions */
6084:     for (j = 0; j < dim-1; ++j) {
6085:       /* If nonlocal, set index to be negative */
6086:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6087:       /* Update local index */
6088:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6089:     }
6090:     /* Skip component slot if necessary */
6091:     if (mat->stencil.noc) dxm++;
6092:     /* Local row number */
6093:     if (tmp >= 0) {
6094:       jdxm[numNewRows++] = tmp;
6095:     }
6096:   }
6097:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6098:   PetscFree(jdxm);
6099:   return(0);
6100: }

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

6106:    Collective on Mat

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

6116:    Notes:
6117:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6118:    but does not release memory.  For the dense and block diagonal
6119:    formats this does not alter the nonzero structure.

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

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

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

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

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

6139:    In Fortran idxm and idxn should be declared as
6140: $     MatStencil idxm(4,m)
6141:    and the values inserted using
6142: $    idxm(MatStencil_i,1) = i
6143: $    idxm(MatStencil_j,1) = j
6144: $    idxm(MatStencil_k,1) = k
6145: $    idxm(MatStencil_c,1) = c
6146:    etc

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

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

6156:    Level: intermediate

6158: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6159:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6160: @*/
6161: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6162: {
6163:   PetscInt       dim     = mat->stencil.dim;
6164:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6165:   PetscInt       *dims   = mat->stencil.dims+1;
6166:   PetscInt       *starts = mat->stencil.starts;
6167:   PetscInt       *dxm    = (PetscInt*) rows;
6168:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6176:   PetscMalloc1(numRows, &jdxm);
6177:   for (i = 0; i < numRows; ++i) {
6178:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6179:     for (j = 0; j < 3-sdim; ++j) dxm++;
6180:     /* Local index in X dir */
6181:     tmp = *dxm++ - starts[0];
6182:     /* Loop over remaining dimensions */
6183:     for (j = 0; j < dim-1; ++j) {
6184:       /* If nonlocal, set index to be negative */
6185:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6186:       /* Update local index */
6187:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6188:     }
6189:     /* Skip component slot if necessary */
6190:     if (mat->stencil.noc) dxm++;
6191:     /* Local row number */
6192:     if (tmp >= 0) {
6193:       jdxm[numNewRows++] = tmp;
6194:     }
6195:   }
6196:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6197:   PetscFree(jdxm);
6198:   return(0);
6199: }

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

6205:    Collective on Mat

6207:    Input Parameters:
6208: +  mat - the matrix
6209: .  numRows - the number of rows to remove
6210: .  rows - the global row indices
6211: .  diag - value put in all diagonals of eliminated rows
6212: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6213: -  b - optional vector of right hand side, that will be adjusted by provided solution

6215:    Notes:
6216:    Before calling MatZeroRowsLocal(), the user must first set the
6217:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6219:    For the AIJ matrix formats this removes the old nonzero structure,
6220:    but does not release memory.  For the dense and block diagonal
6221:    formats this does not alter the nonzero structure.

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

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

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

6234:    Level: intermediate

6236: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6237:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6238: @*/
6239: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6240: {

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

6251:   if (mat->ops->zerorowslocal) {
6252:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6253:   } else {
6254:     IS             is, newis;
6255:     const PetscInt *newRows;

6257:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6258:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6259:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6260:     ISGetIndices(newis,&newRows);
6261:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6262:     ISRestoreIndices(newis,&newRows);
6263:     ISDestroy(&newis);
6264:     ISDestroy(&is);
6265:   }
6266:   PetscObjectStateIncrease((PetscObject)mat);
6267:   return(0);
6268: }

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

6274:    Collective on Mat

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

6283:    Notes:
6284:    Before calling MatZeroRowsLocalIS(), the user must first set the
6285:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6287:    For the AIJ matrix formats this removes the old nonzero structure,
6288:    but does not release memory.  For the dense and block diagonal
6289:    formats this does not alter the nonzero structure.

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

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

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

6302:    Level: intermediate

6304: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6305:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6306: @*/
6307: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6308: {
6310:   PetscInt       numRows;
6311:   const PetscInt *rows;

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

6321:   ISGetLocalSize(is,&numRows);
6322:   ISGetIndices(is,&rows);
6323:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6324:   ISRestoreIndices(is,&rows);
6325:   return(0);
6326: }

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

6332:    Collective on Mat

6334:    Input Parameters:
6335: +  mat - the matrix
6336: .  numRows - the number of rows to remove
6337: .  rows - the global row indices
6338: .  diag - value put in all diagonals of eliminated rows
6339: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6340: -  b - optional vector of right hand side, that will be adjusted by provided solution

6342:    Notes:
6343:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6344:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6350:    Level: intermediate

6352: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6353:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6354: @*/
6355: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6356: {
6358:   IS             is, newis;
6359:   const PetscInt *newRows;

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

6369:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6370:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6371:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6372:   ISGetIndices(newis,&newRows);
6373:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6374:   ISRestoreIndices(newis,&newRows);
6375:   ISDestroy(&newis);
6376:   ISDestroy(&is);
6377:   PetscObjectStateIncrease((PetscObject)mat);
6378:   return(0);
6379: }

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

6385:    Collective on Mat

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

6394:    Notes:
6395:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6396:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6402:    Level: intermediate

6404: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6405:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6406: @*/
6407: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6408: {
6410:   PetscInt       numRows;
6411:   const PetscInt *rows;

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

6421:   ISGetLocalSize(is,&numRows);
6422:   ISGetIndices(is,&rows);
6423:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6424:   ISRestoreIndices(is,&rows);
6425:   return(0);
6426: }

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

6431:    Not Collective

6433:    Input Parameter:
6434: .  mat - the matrix

6436:    Output Parameters:
6437: +  m - the number of global rows
6438: -  n - the number of global columns

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

6442:    Level: beginner

6444: .seealso: MatGetLocalSize()
6445: @*/
6446: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6447: {
6450:   if (m) *m = mat->rmap->N;
6451:   if (n) *n = mat->cmap->N;
6452:   return(0);
6453: }

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

6459:    Not Collective

6461:    Input Parameters:
6462: .  mat - the matrix

6464:    Output Parameters:
6465: +  m - the number of local rows
6466: -  n - the number of local columns

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

6470:    Level: beginner

6472: .seealso: MatGetSize()
6473: @*/
6474: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6475: {
6480:   if (m) *m = mat->rmap->n;
6481:   if (n) *n = mat->cmap->n;
6482:   return(0);
6483: }

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

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

6491:    Input Parameters:
6492: .  mat - the matrix

6494:    Output Parameters:
6495: +  m - the global index of the first local column
6496: -  n - one more than the global index of the last local column

6498:    Notes:
6499:     both output parameters can be NULL on input.

6501:    Level: developer

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

6505: @*/
6506: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6507: {
6513:   MatCheckPreallocated(mat,1);
6514:   if (m) *m = mat->cmap->rstart;
6515:   if (n) *n = mat->cmap->rend;
6516:   return(0);
6517: }

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

6525:    Not Collective

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

6530:    Output Parameters:
6531: +  m - the global index of the first local row
6532: -  n - one more than the global index of the last local row

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

6539:    Level: beginner

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

6543: @*/
6544: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6545: {
6551:   MatCheckPreallocated(mat,1);
6552:   if (m) *m = mat->rmap->rstart;
6553:   if (n) *n = mat->rmap->rend;
6554:   return(0);
6555: }

6557: /*@C
6558:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6559:    each process

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

6563:    Input Parameters:
6564: .  mat - the matrix

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

6569:    Level: beginner

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

6573: @*/
6574: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6575: {

6581:   MatCheckPreallocated(mat,1);
6582:   PetscLayoutGetRanges(mat->rmap,ranges);
6583:   return(0);
6584: }

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

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

6592:    Input Parameters:
6593: .  mat - the matrix

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

6598:    Level: beginner

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

6602: @*/
6603: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6604: {

6610:   MatCheckPreallocated(mat,1);
6611:   PetscLayoutGetRanges(mat->cmap,ranges);
6612:   return(0);
6613: }

6615: /*@C
6616:    MatGetOwnershipIS - Get row and column ownership as index sets

6618:    Not Collective

6620:    Input Arguments:
6621: .  A - matrix of type Elemental or ScaLAPACK

6623:    Output Arguments:
6624: +  rows - rows in which this process owns elements
6625: -  cols - columns in which this process owns elements

6627:    Level: intermediate

6629: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6630: @*/
6631: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6632: {
6633:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6636:   MatCheckPreallocated(A,1);
6637:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6638:   if (f) {
6639:     (*f)(A,rows,cols);
6640:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6641:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6642:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6643:   }
6644:   return(0);
6645: }

6647: /*@C
6648:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6649:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6650:    to complete the factorization.

6652:    Collective on Mat

6654:    Input Parameters:
6655: +  mat - the matrix
6656: .  row - row permutation
6657: .  column - column permutation
6658: -  info - structure containing
6659: $      levels - number of levels of fill.
6660: $      expected fill - as ratio of original fill.
6661: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6662:                 missing diagonal entries)

6664:    Output Parameters:
6665: .  fact - new matrix that has been symbolically factored

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

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

6674:    Level: developer

6676: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6677:           MatGetOrdering(), MatFactorInfo

6679:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6684:    References:
6685:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6686: @*/
6687: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6688: {

6698:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6699:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6700:   if (!fact->ops->ilufactorsymbolic) {
6701:     MatSolverType stype;
6702:     MatFactorGetSolverType(fact,&stype);
6703:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver type %s",((PetscObject)mat)->type_name,stype);
6704:   }
6705:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6706:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6707:   MatCheckPreallocated(mat,2);

6709:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6710:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6711:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6712:   return(0);
6713: }

6715: /*@C
6716:    MatICCFactorSymbolic - Performs symbolic incomplete
6717:    Cholesky factorization for a symmetric matrix.  Use
6718:    MatCholeskyFactorNumeric() to complete the factorization.

6720:    Collective on Mat

6722:    Input Parameters:
6723: +  mat - the matrix
6724: .  perm - row and column permutation
6725: -  info - structure containing
6726: $      levels - number of levels of fill.
6727: $      expected fill - as ratio of original fill.

6729:    Output Parameter:
6730: .  fact - the factored matrix

6732:    Notes:
6733:    Most users should employ the KSP interface for linear solvers
6734:    instead of working directly with matrix algebra routines such as this.
6735:    See, e.g., KSPCreate().

6737:    Level: developer

6739: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6741:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6746:    References:
6747:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6748: @*/
6749: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6750: {

6759:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6760:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6761:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6762:   if (!(fact)->ops->iccfactorsymbolic) {
6763:     MatSolverType stype;
6764:     MatFactorGetSolverType(fact,&stype);
6765:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver type %s",((PetscObject)mat)->type_name,stype);
6766:   }
6767:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6768:   MatCheckPreallocated(mat,2);

6770:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6771:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6772:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6773:   return(0);
6774: }

6776: /*@C
6777:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6778:    points to an array of valid matrices, they may be reused to store the new
6779:    submatrices.

6781:    Collective on Mat

6783:    Input Parameters:
6784: +  mat - the matrix
6785: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6786: .  irow, icol - index sets of rows and columns to extract
6787: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6789:    Output Parameter:
6790: .  submat - the array of submatrices

6792:    Notes:
6793:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6794:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6795:    to extract a parallel submatrix.

6797:    Some matrix types place restrictions on the row and column
6798:    indices, such as that they be sorted or that they be equal to each other.

6800:    The index sets may not have duplicate entries.

6802:    When extracting submatrices from a parallel matrix, each processor can
6803:    form a different submatrix by setting the rows and columns of its
6804:    individual index sets according to the local submatrix desired.

6806:    When finished using the submatrices, the user should destroy
6807:    them with MatDestroySubMatrices().

6809:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6810:    original matrix has not changed from that last call to MatCreateSubMatrices().

6812:    This routine creates the matrices in submat; you should NOT create them before
6813:    calling it. It also allocates the array of matrix pointers submat.

6815:    For BAIJ matrices the index sets must respect the block structure, that is if they
6816:    request one row/column in a block, they must request all rows/columns that are in
6817:    that block. For example, if the block size is 2 you cannot request just row 0 and
6818:    column 0.

6820:    Fortran Note:
6821:    The Fortran interface is slightly different from that given below; it
6822:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6824:    Level: advanced


6827: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6828: @*/
6829: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6830: {
6832:   PetscInt       i;
6833:   PetscBool      eq;

6838:   if (n) {
6843:   }
6845:   if (n && scall == MAT_REUSE_MATRIX) {
6848:   }
6849:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6850:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6851:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6852:   MatCheckPreallocated(mat,1);

6854:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6855:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6856:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6857:   for (i=0; i<n; i++) {
6858:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6859:     ISEqualUnsorted(irow[i],icol[i],&eq);
6860:     if (eq) {
6861:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6862:     }
6863:   }
6864:   return(0);
6865: }

6867: /*@C
6868:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6870:    Collective on Mat

6872:    Input Parameters:
6873: +  mat - the matrix
6874: .  n   - the number of submatrixes to be extracted
6875: .  irow, icol - index sets of rows and columns to extract
6876: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6878:    Output Parameter:
6879: .  submat - the array of submatrices

6881:    Level: advanced


6884: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6885: @*/
6886: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6887: {
6889:   PetscInt       i;
6890:   PetscBool      eq;

6895:   if (n) {
6900:   }
6902:   if (n && scall == MAT_REUSE_MATRIX) {
6905:   }
6906:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6907:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6908:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6909:   MatCheckPreallocated(mat,1);

6911:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6912:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6913:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6914:   for (i=0; i<n; i++) {
6915:     ISEqualUnsorted(irow[i],icol[i],&eq);
6916:     if (eq) {
6917:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6918:     }
6919:   }
6920:   return(0);
6921: }

6923: /*@C
6924:    MatDestroyMatrices - Destroys an array of matrices.

6926:    Collective on Mat

6928:    Input Parameters:
6929: +  n - the number of local matrices
6930: -  mat - the matrices (note that this is a pointer to the array of matrices)

6932:    Level: advanced

6934:     Notes:
6935:     Frees not only the matrices, but also the array that contains the matrices
6936:            In Fortran will not free the array.

6938: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6939: @*/
6940: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6941: {
6943:   PetscInt       i;

6946:   if (!*mat) return(0);
6947:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6950:   for (i=0; i<n; i++) {
6951:     MatDestroy(&(*mat)[i]);
6952:   }

6954:   /* memory is allocated even if n = 0 */
6955:   PetscFree(*mat);
6956:   return(0);
6957: }

6959: /*@C
6960:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6962:    Collective on Mat

6964:    Input Parameters:
6965: +  n - the number of local matrices
6966: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6967:                        sequence of MatCreateSubMatrices())

6969:    Level: advanced

6971:     Notes:
6972:     Frees not only the matrices, but also the array that contains the matrices
6973:            In Fortran will not free the array.

6975: .seealso: MatCreateSubMatrices()
6976: @*/
6977: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6978: {
6980:   Mat            mat0;

6983:   if (!*mat) return(0);
6984:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6985:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6988:   mat0 = (*mat)[0];
6989:   if (mat0 && mat0->ops->destroysubmatrices) {
6990:     (mat0->ops->destroysubmatrices)(n,mat);
6991:   } else {
6992:     MatDestroyMatrices(n,mat);
6993:   }
6994:   return(0);
6995: }

6997: /*@C
6998:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

7000:    Collective on Mat

7002:    Input Parameters:
7003: .  mat - the matrix

7005:    Output Parameter:
7006: .  matstruct - the sequential matrix with the nonzero structure of mat

7008:   Level: intermediate

7010: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7011: @*/
7012: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7013: {


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

7024:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7025:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7026:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
7027:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7028:   return(0);
7029: }

7031: /*@C
7032:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

7034:    Collective on Mat

7036:    Input Parameters:
7037: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
7038:                        sequence of MatGetSequentialNonzeroStructure())

7040:    Level: advanced

7042:     Notes:
7043:     Frees not only the matrices, but also the array that contains the matrices

7045: .seealso: MatGetSeqNonzeroStructure()
7046: @*/
7047: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7048: {

7053:   MatDestroy(mat);
7054:   return(0);
7055: }

7057: /*@
7058:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7059:    replaces the index sets by larger ones that represent submatrices with
7060:    additional overlap.

7062:    Collective on Mat

7064:    Input Parameters:
7065: +  mat - the matrix
7066: .  n   - the number of index sets
7067: .  is  - the array of index sets (these index sets will changed during the call)
7068: -  ov  - the additional overlap requested

7070:    Options Database:
7071: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7073:    Level: developer


7076: .seealso: MatCreateSubMatrices()
7077: @*/
7078: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7079: {

7085:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7086:   if (n) {
7089:   }
7090:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7091:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7092:   MatCheckPreallocated(mat,1);

7094:   if (!ov) return(0);
7095:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7096:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7097:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7098:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7099:   return(0);
7100: }


7103: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7105: /*@
7106:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7107:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7108:    additional overlap.

7110:    Collective on Mat

7112:    Input Parameters:
7113: +  mat - the matrix
7114: .  n   - the number of index sets
7115: .  is  - the array of index sets (these index sets will changed during the call)
7116: -  ov  - the additional overlap requested

7118:    Options Database:
7119: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7121:    Level: developer


7124: .seealso: MatCreateSubMatrices()
7125: @*/
7126: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7127: {
7128:   PetscInt       i;

7134:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7135:   if (n) {
7138:   }
7139:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7140:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7141:   MatCheckPreallocated(mat,1);
7142:   if (!ov) return(0);
7143:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7144:   for (i=0; i<n; i++){
7145:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7146:   }
7147:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7148:   return(0);
7149: }




7154: /*@
7155:    MatGetBlockSize - Returns the matrix block size.

7157:    Not Collective

7159:    Input Parameter:
7160: .  mat - the matrix

7162:    Output Parameter:
7163: .  bs - block size

7165:    Notes:
7166:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7168:    If the block size has not been set yet this routine returns 1.

7170:    Level: intermediate

7172: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7173: @*/
7174: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7175: {
7179:   *bs = PetscAbs(mat->rmap->bs);
7180:   return(0);
7181: }

7183: /*@
7184:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7186:    Not Collective

7188:    Input Parameter:
7189: .  mat - the matrix

7191:    Output Parameter:
7192: +  rbs - row block size
7193: -  cbs - column block size

7195:    Notes:
7196:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7197:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7199:    If a block size has not been set yet this routine returns 1.

7201:    Level: intermediate

7203: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7204: @*/
7205: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7206: {
7211:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7212:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7213:   return(0);
7214: }

7216: /*@
7217:    MatSetBlockSize - Sets the matrix block size.

7219:    Logically Collective on Mat

7221:    Input Parameters:
7222: +  mat - the matrix
7223: -  bs - block size

7225:    Notes:
7226:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7227:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7229:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7230:     is compatible with the matrix local sizes.

7232:    Level: intermediate

7234: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7235: @*/
7236: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7237: {

7243:   MatSetBlockSizes(mat,bs,bs);
7244:   return(0);
7245: }

7247: /*@
7248:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7250:    Logically Collective on Mat

7252:    Input Parameters:
7253: +  mat - the matrix
7254: .  nblocks - the number of blocks on this process
7255: -  bsizes - the block sizes

7257:    Notes:
7258:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7260:    Level: intermediate

7262: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7263: @*/
7264: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7265: {
7267:   PetscInt       i,ncnt = 0, nlocal;

7271:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7272:   MatGetLocalSize(mat,&nlocal,NULL);
7273:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7274:   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);
7275:   PetscFree(mat->bsizes);
7276:   mat->nblocks = nblocks;
7277:   PetscMalloc1(nblocks,&mat->bsizes);
7278:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7279:   return(0);
7280: }

7282: /*@C
7283:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7285:    Logically Collective on Mat

7287:    Input Parameters:
7288: .  mat - the matrix

7290:    Output Parameters:
7291: +  nblocks - the number of blocks on this process
7292: -  bsizes - the block sizes

7294:    Notes: Currently not supported from Fortran

7296:    Level: intermediate

7298: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7299: @*/
7300: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7301: {
7304:   *nblocks = mat->nblocks;
7305:   *bsizes  = mat->bsizes;
7306:   return(0);
7307: }

7309: /*@
7310:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7312:    Logically Collective on Mat

7314:    Input Parameters:
7315: +  mat - the matrix
7316: .  rbs - row block size
7317: -  cbs - column block size

7319:    Notes:
7320:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7321:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7322:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7324:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7325:     are compatible with the matrix local sizes.

7327:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7329:    Level: intermediate

7331: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7332: @*/
7333: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7334: {

7341:   if (mat->ops->setblocksizes) {
7342:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7343:   }
7344:   if (mat->rmap->refcnt) {
7345:     ISLocalToGlobalMapping l2g = NULL;
7346:     PetscLayout            nmap = NULL;

7348:     PetscLayoutDuplicate(mat->rmap,&nmap);
7349:     if (mat->rmap->mapping) {
7350:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7351:     }
7352:     PetscLayoutDestroy(&mat->rmap);
7353:     mat->rmap = nmap;
7354:     mat->rmap->mapping = l2g;
7355:   }
7356:   if (mat->cmap->refcnt) {
7357:     ISLocalToGlobalMapping l2g = NULL;
7358:     PetscLayout            nmap = NULL;

7360:     PetscLayoutDuplicate(mat->cmap,&nmap);
7361:     if (mat->cmap->mapping) {
7362:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7363:     }
7364:     PetscLayoutDestroy(&mat->cmap);
7365:     mat->cmap = nmap;
7366:     mat->cmap->mapping = l2g;
7367:   }
7368:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7369:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7370:   return(0);
7371: }

7373: /*@
7374:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7376:    Logically Collective on Mat

7378:    Input Parameters:
7379: +  mat - the matrix
7380: .  fromRow - matrix from which to copy row block size
7381: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7383:    Level: developer

7385: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7386: @*/
7387: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7388: {

7395:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7396:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7397:   return(0);
7398: }

7400: /*@
7401:    MatResidual - Default routine to calculate the residual.

7403:    Collective on Mat

7405:    Input Parameters:
7406: +  mat - the matrix
7407: .  b   - the right-hand-side
7408: -  x   - the approximate solution

7410:    Output Parameter:
7411: .  r - location to store the residual

7413:    Level: developer

7415: .seealso: PCMGSetResidual()
7416: @*/
7417: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7418: {

7427:   MatCheckPreallocated(mat,1);
7428:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7429:   if (!mat->ops->residual) {
7430:     MatMult(mat,x,r);
7431:     VecAYPX(r,-1.0,b);
7432:   } else {
7433:     (*mat->ops->residual)(mat,b,x,r);
7434:   }
7435:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7436:   return(0);
7437: }

7439: /*@C
7440:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7442:    Collective on Mat

7444:     Input Parameters:
7445: +   mat - the matrix
7446: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7447: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7448: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7449:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7450:                  always used.

7452:     Output Parameters:
7453: +   n - number of rows in the (possibly compressed) matrix
7454: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7455: .   ja - the column indices
7456: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7457:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7459:     Level: developer

7461:     Notes:
7462:     You CANNOT change any of the ia[] or ja[] values.

7464:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7466:     Fortran Notes:
7467:     In Fortran use
7468: $
7469: $      PetscInt ia(1), ja(1)
7470: $      PetscOffset iia, jja
7471: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7472: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7474:      or
7475: $
7476: $    PetscInt, pointer :: ia(:),ja(:)
7477: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7478: $    ! Access the ith and jth entries via ia(i) and ja(j)

7480: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7481: @*/
7482: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7483: {

7493:   MatCheckPreallocated(mat,1);
7494:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7495:   else {
7496:     *done = PETSC_TRUE;
7497:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7498:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7499:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7500:   }
7501:   return(0);
7502: }

7504: /*@C
7505:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

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.
7517: .   n - number of columns in the (possibly compressed) matrix
7518: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7519: -   ja - the row indices

7521:     Output Parameters:
7522: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7524:     Level: developer

7526: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7527: @*/
7528: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7529: {

7539:   MatCheckPreallocated(mat,1);
7540:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7541:   else {
7542:     *done = PETSC_TRUE;
7543:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7544:   }
7545:   return(0);
7546: }

7548: /*@C
7549:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7550:     MatGetRowIJ().

7552:     Collective on Mat

7554:     Input Parameters:
7555: +   mat - the matrix
7556: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7557: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7558:                 symmetrized
7559: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7560:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7561:                  always used.
7562: .   n - size of (possibly compressed) matrix
7563: .   ia - the row pointers
7564: -   ja - the column indices

7566:     Output Parameters:
7567: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7569:     Note:
7570:     This routine zeros out n, ia, and ja. This is to prevent accidental
7571:     us of the array after it has been restored. If you pass NULL, it will
7572:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7574:     Level: developer

7576: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7577: @*/
7578: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7579: {

7588:   MatCheckPreallocated(mat,1);

7590:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7591:   else {
7592:     *done = PETSC_TRUE;
7593:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7594:     if (n)  *n = 0;
7595:     if (ia) *ia = NULL;
7596:     if (ja) *ja = NULL;
7597:   }
7598:   return(0);
7599: }

7601: /*@C
7602:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7603:     MatGetColumnIJ().

7605:     Collective on Mat

7607:     Input Parameters:
7608: +   mat - the matrix
7609: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7610: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7611:                 symmetrized
7612: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7613:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7614:                  always used.

7616:     Output Parameters:
7617: +   n - size of (possibly compressed) matrix
7618: .   ia - the column pointers
7619: .   ja - the row indices
7620: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7622:     Level: developer

7624: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7625: @*/
7626: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7627: {

7636:   MatCheckPreallocated(mat,1);

7638:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7639:   else {
7640:     *done = PETSC_TRUE;
7641:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7642:     if (n)  *n = 0;
7643:     if (ia) *ia = NULL;
7644:     if (ja) *ja = NULL;
7645:   }
7646:   return(0);
7647: }

7649: /*@C
7650:     MatColoringPatch -Used inside matrix coloring routines that
7651:     use MatGetRowIJ() and/or MatGetColumnIJ().

7653:     Collective on Mat

7655:     Input Parameters:
7656: +   mat - the matrix
7657: .   ncolors - max color value
7658: .   n   - number of entries in colorarray
7659: -   colorarray - array indicating color for each column

7661:     Output Parameters:
7662: .   iscoloring - coloring generated using colorarray information

7664:     Level: developer

7666: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7668: @*/
7669: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7670: {

7678:   MatCheckPreallocated(mat,1);

7680:   if (!mat->ops->coloringpatch) {
7681:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7682:   } else {
7683:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7684:   }
7685:   return(0);
7686: }


7689: /*@
7690:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7692:    Logically Collective on Mat

7694:    Input Parameter:
7695: .  mat - the factored matrix to be reset

7697:    Notes:
7698:    This routine should be used only with factored matrices formed by in-place
7699:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7700:    format).  This option can save memory, for example, when solving nonlinear
7701:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7702:    ILU(0) preconditioner.

7704:    Note that one can specify in-place ILU(0) factorization by calling
7705: .vb
7706:      PCType(pc,PCILU);
7707:      PCFactorSeUseInPlace(pc);
7708: .ve
7709:    or by using the options -pc_type ilu -pc_factor_in_place

7711:    In-place factorization ILU(0) can also be used as a local
7712:    solver for the blocks within the block Jacobi or additive Schwarz
7713:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7714:    for details on setting local solver options.

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

7720:    Level: developer

7722: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7724: @*/
7725: PetscErrorCode MatSetUnfactored(Mat mat)
7726: {

7732:   MatCheckPreallocated(mat,1);
7733:   mat->factortype = MAT_FACTOR_NONE;
7734:   if (!mat->ops->setunfactored) return(0);
7735:   (*mat->ops->setunfactored)(mat);
7736:   return(0);
7737: }

7739: /*MC
7740:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7742:     Synopsis:
7743:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7745:     Not collective

7747:     Input Parameter:
7748: .   x - matrix

7750:     Output Parameters:
7751: +   xx_v - the Fortran90 pointer to the array
7752: -   ierr - error code

7754:     Example of Usage:
7755: .vb
7756:       PetscScalar, pointer xx_v(:,:)
7757:       ....
7758:       call MatDenseGetArrayF90(x,xx_v,ierr)
7759:       a = xx_v(3)
7760:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7761: .ve

7763:     Level: advanced

7765: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7767: M*/

7769: /*MC
7770:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7771:     accessed with MatDenseGetArrayF90().

7773:     Synopsis:
7774:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7776:     Not collective

7778:     Input Parameters:
7779: +   x - matrix
7780: -   xx_v - the Fortran90 pointer to the array

7782:     Output Parameter:
7783: .   ierr - error code

7785:     Example of Usage:
7786: .vb
7787:        PetscScalar, pointer xx_v(:,:)
7788:        ....
7789:        call MatDenseGetArrayF90(x,xx_v,ierr)
7790:        a = xx_v(3)
7791:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7792: .ve

7794:     Level: advanced

7796: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7798: M*/


7801: /*MC
7802:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7804:     Synopsis:
7805:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7807:     Not collective

7809:     Input Parameter:
7810: .   x - matrix

7812:     Output Parameters:
7813: +   xx_v - the Fortran90 pointer to the array
7814: -   ierr - error code

7816:     Example of Usage:
7817: .vb
7818:       PetscScalar, pointer xx_v(:)
7819:       ....
7820:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7821:       a = xx_v(3)
7822:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7823: .ve

7825:     Level: advanced

7827: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7829: M*/

7831: /*MC
7832:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7833:     accessed with MatSeqAIJGetArrayF90().

7835:     Synopsis:
7836:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7838:     Not collective

7840:     Input Parameters:
7841: +   x - matrix
7842: -   xx_v - the Fortran90 pointer to the array

7844:     Output Parameter:
7845: .   ierr - error code

7847:     Example of Usage:
7848: .vb
7849:        PetscScalar, pointer xx_v(:)
7850:        ....
7851:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7852:        a = xx_v(3)
7853:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7854: .ve

7856:     Level: advanced

7858: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7860: M*/


7863: /*@
7864:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7865:                       as the original matrix.

7867:     Collective on Mat

7869:     Input Parameters:
7870: +   mat - the original matrix
7871: .   isrow - parallel IS containing the rows this processor should obtain
7872: .   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.
7873: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7875:     Output Parameter:
7876: .   newmat - the new submatrix, of the same type as the old

7878:     Level: advanced

7880:     Notes:
7881:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7883:     Some matrix types place restrictions on the row and column indices, such
7884:     as that they be sorted or that they be equal to each other.

7886:     The index sets may not have duplicate entries.

7888:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7889:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7890:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7891:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7892:    you are finished using it.

7894:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7895:     the input matrix.

7897:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7899:    Example usage:
7900:    Consider the following 8x8 matrix with 34 non-zero values, that is
7901:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7902:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7903:    as follows:

7905: .vb
7906:             1  2  0  |  0  3  0  |  0  4
7907:     Proc0   0  5  6  |  7  0  0  |  8  0
7908:             9  0 10  | 11  0  0  | 12  0
7909:     -------------------------------------
7910:            13  0 14  | 15 16 17  |  0  0
7911:     Proc1   0 18  0  | 19 20 21  |  0  0
7912:             0  0  0  | 22 23  0  | 24  0
7913:     -------------------------------------
7914:     Proc2  25 26 27  |  0  0 28  | 29  0
7915:            30  0  0  | 31 32 33  |  0 34
7916: .ve

7918:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7920: .vb
7921:             2  0  |  0  3  0  |  0
7922:     Proc0   5  6  |  7  0  0  |  8
7923:     -------------------------------
7924:     Proc1  18  0  | 19 20 21  |  0
7925:     -------------------------------
7926:     Proc2  26 27  |  0  0 28  | 29
7927:             0  0  | 31 32 33  |  0
7928: .ve


7931: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7932: @*/
7933: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7934: {
7936:   PetscMPIInt    size;
7937:   Mat            *local;
7938:   IS             iscoltmp;
7939:   PetscBool      flg;

7948:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7949:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7951:   MatCheckPreallocated(mat,1);
7952:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7954:   if (!iscol || isrow == iscol) {
7955:     PetscBool   stride;
7956:     PetscMPIInt grabentirematrix = 0,grab;
7957:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7958:     if (stride) {
7959:       PetscInt first,step,n,rstart,rend;
7960:       ISStrideGetInfo(isrow,&first,&step);
7961:       if (step == 1) {
7962:         MatGetOwnershipRange(mat,&rstart,&rend);
7963:         if (rstart == first) {
7964:           ISGetLocalSize(isrow,&n);
7965:           if (n == rend-rstart) {
7966:             grabentirematrix = 1;
7967:           }
7968:         }
7969:       }
7970:     }
7971:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7972:     if (grab) {
7973:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7974:       if (cll == MAT_INITIAL_MATRIX) {
7975:         *newmat = mat;
7976:         PetscObjectReference((PetscObject)mat);
7977:       }
7978:       return(0);
7979:     }
7980:   }

7982:   if (!iscol) {
7983:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7984:   } else {
7985:     iscoltmp = iscol;
7986:   }

7988:   /* if original matrix is on just one processor then use submatrix generated */
7989:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7990:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7991:     goto setproperties;
7992:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7993:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7994:     *newmat = *local;
7995:     PetscFree(local);
7996:     goto setproperties;
7997:   } else if (!mat->ops->createsubmatrix) {
7998:     /* Create a new matrix type that implements the operation using the full matrix */
7999:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8000:     switch (cll) {
8001:     case MAT_INITIAL_MATRIX:
8002:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
8003:       break;
8004:     case MAT_REUSE_MATRIX:
8005:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
8006:       break;
8007:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8008:     }
8009:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8010:     goto setproperties;
8011:   }

8013:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8014:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8015:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
8016:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

8018: setproperties:
8019:   ISEqualUnsorted(isrow,iscoltmp,&flg);
8020:   if (flg) {
8021:     MatPropagateSymmetryOptions(mat,*newmat);
8022:   }
8023:   if (!iscol) {ISDestroy(&iscoltmp);}
8024:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
8025:   return(0);
8026: }

8028: /*@
8029:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8031:    Not Collective

8033:    Input Parameters:
8034: +  A - the matrix we wish to propagate options from
8035: -  B - the matrix we wish to propagate options to

8037:    Level: beginner

8039:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

8041: .seealso: MatSetOption()
8042: @*/
8043: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8044: {

8050:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
8051:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
8052:   }
8053:   if (A->structurally_symmetric_set) {
8054:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
8055:   }
8056:   if (A->hermitian_set) {
8057:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
8058:   }
8059:   if (A->spd_set) {
8060:     MatSetOption(B,MAT_SPD,A->spd);
8061:   }
8062:   if (A->symmetric_set) {
8063:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
8064:   }
8065:   return(0);
8066: }

8068: /*@
8069:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8070:    used during the assembly process to store values that belong to
8071:    other processors.

8073:    Not Collective

8075:    Input Parameters:
8076: +  mat   - the matrix
8077: .  size  - the initial size of the stash.
8078: -  bsize - the initial size of the block-stash(if used).

8080:    Options Database Keys:
8081: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8082: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

8084:    Level: intermediate

8086:    Notes:
8087:      The block-stash is used for values set with MatSetValuesBlocked() while
8088:      the stash is used for values set with MatSetValues()

8090:      Run with the option -info and look for output of the form
8091:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8092:      to determine the appropriate value, MM, to use for size and
8093:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8094:      to determine the value, BMM to use for bsize


8097: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

8099: @*/
8100: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8101: {

8107:   MatStashSetInitialSize_Private(&mat->stash,size);
8108:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8109:   return(0);
8110: }

8112: /*@
8113:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8114:      the matrix

8116:    Neighbor-wise Collective on Mat

8118:    Input Parameters:
8119: +  mat   - the matrix
8120: .  x,y - the vectors
8121: -  w - where the result is stored

8123:    Level: intermediate

8125:    Notes:
8126:     w may be the same vector as y.

8128:     This allows one to use either the restriction or interpolation (its transpose)
8129:     matrix to do the interpolation

8131: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8133: @*/
8134: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8135: {
8137:   PetscInt       M,N,Ny;

8145:   MatCheckPreallocated(A,1);
8146:   MatGetSize(A,&M,&N);
8147:   VecGetSize(y,&Ny);
8148:   if (M == Ny) {
8149:     MatMultAdd(A,x,y,w);
8150:   } else {
8151:     MatMultTransposeAdd(A,x,y,w);
8152:   }
8153:   return(0);
8154: }

8156: /*@
8157:    MatInterpolate - y = A*x or A'*x depending on the shape of
8158:      the matrix

8160:    Neighbor-wise Collective on Mat

8162:    Input Parameters:
8163: +  mat   - the matrix
8164: -  x,y - the vectors

8166:    Level: intermediate

8168:    Notes:
8169:     This allows one to use either the restriction or interpolation (its transpose)
8170:     matrix to do the interpolation

8172: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8174: @*/
8175: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8176: {
8178:   PetscInt       M,N,Ny;

8185:   MatCheckPreallocated(A,1);
8186:   MatGetSize(A,&M,&N);
8187:   VecGetSize(y,&Ny);
8188:   if (M == Ny) {
8189:     MatMult(A,x,y);
8190:   } else {
8191:     MatMultTranspose(A,x,y);
8192:   }
8193:   return(0);
8194: }

8196: /*@
8197:    MatRestrict - y = A*x or A'*x

8199:    Neighbor-wise Collective on Mat

8201:    Input Parameters:
8202: +  mat   - the matrix
8203: -  x,y - the vectors

8205:    Level: intermediate

8207:    Notes:
8208:     This allows one to use either the restriction or interpolation (its transpose)
8209:     matrix to do the restriction

8211: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8213: @*/
8214: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8215: {
8217:   PetscInt       M,N,Ny;

8224:   MatCheckPreallocated(A,1);

8226:   MatGetSize(A,&M,&N);
8227:   VecGetSize(y,&Ny);
8228:   if (M == Ny) {
8229:     MatMult(A,x,y);
8230:   } else {
8231:     MatMultTranspose(A,x,y);
8232:   }
8233:   return(0);
8234: }

8236: /*@
8237:    MatGetNullSpace - retrieves the null space of a matrix.

8239:    Logically Collective on Mat

8241:    Input Parameters:
8242: +  mat - the matrix
8243: -  nullsp - the null space object

8245:    Level: developer

8247: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8248: @*/
8249: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8250: {
8254:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8255:   return(0);
8256: }

8258: /*@
8259:    MatSetNullSpace - attaches a null space to a matrix.

8261:    Logically Collective on Mat

8263:    Input Parameters:
8264: +  mat - the matrix
8265: -  nullsp - the null space object

8267:    Level: advanced

8269:    Notes:
8270:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8272:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8273:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8275:       You can remove the null space by calling this routine with an nullsp of NULL


8278:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8279:    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).
8280:    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
8281:    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
8282:    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).

8284:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8286:     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
8287:     routine also automatically calls MatSetTransposeNullSpace().

8289: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8290: @*/
8291: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8292: {

8298:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8299:   MatNullSpaceDestroy(&mat->nullsp);
8300:   mat->nullsp = nullsp;
8301:   if (mat->symmetric_set && mat->symmetric) {
8302:     MatSetTransposeNullSpace(mat,nullsp);
8303:   }
8304:   return(0);
8305: }

8307: /*@
8308:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8310:    Logically Collective on Mat

8312:    Input Parameters:
8313: +  mat - the matrix
8314: -  nullsp - the null space object

8316:    Level: developer

8318: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8319: @*/
8320: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8321: {
8326:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8327:   return(0);
8328: }

8330: /*@
8331:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8333:    Logically Collective on Mat

8335:    Input Parameters:
8336: +  mat - the matrix
8337: -  nullsp - the null space object

8339:    Level: advanced

8341:    Notes:
8342:       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.
8343:       You must also call MatSetNullSpace()


8346:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8347:    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).
8348:    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
8349:    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
8350:    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).

8352:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8354: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8355: @*/
8356: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8357: {

8363:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8364:   MatNullSpaceDestroy(&mat->transnullsp);
8365:   mat->transnullsp = nullsp;
8366:   return(0);
8367: }

8369: /*@
8370:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8371:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8373:    Logically Collective on Mat

8375:    Input Parameters:
8376: +  mat - the matrix
8377: -  nullsp - the null space object

8379:    Level: advanced

8381:    Notes:
8382:       Overwrites any previous near null space that may have been attached

8384:       You can remove the null space by calling this routine with an nullsp of NULL

8386: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8387: @*/
8388: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8389: {

8396:   MatCheckPreallocated(mat,1);
8397:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8398:   MatNullSpaceDestroy(&mat->nearnullsp);
8399:   mat->nearnullsp = nullsp;
8400:   return(0);
8401: }

8403: /*@
8404:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8406:    Not Collective

8408:    Input Parameter:
8409: .  mat - the matrix

8411:    Output Parameter:
8412: .  nullsp - the null space object, NULL if not set

8414:    Level: developer

8416: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8417: @*/
8418: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8419: {
8424:   MatCheckPreallocated(mat,1);
8425:   *nullsp = mat->nearnullsp;
8426:   return(0);
8427: }

8429: /*@C
8430:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8432:    Collective on Mat

8434:    Input Parameters:
8435: +  mat - the matrix
8436: .  row - row/column permutation
8437: .  fill - expected fill factor >= 1.0
8438: -  level - level of fill, for ICC(k)

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

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

8448:    Level: developer


8451: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8456: @*/
8457: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8458: {

8466:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8467:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8468:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8469:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8470:   MatCheckPreallocated(mat,1);
8471:   (*mat->ops->iccfactor)(mat,row,info);
8472:   PetscObjectStateIncrease((PetscObject)mat);
8473:   return(0);
8474: }

8476: /*@
8477:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8478:          ghosted ones.

8480:    Not Collective

8482:    Input Parameters:
8483: +  mat - the matrix
8484: -  diag = the diagonal values, including ghost ones

8486:    Level: developer

8488:    Notes:
8489:     Works only for MPIAIJ and MPIBAIJ matrices

8491: .seealso: MatDiagonalScale()
8492: @*/
8493: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8494: {
8496:   PetscMPIInt    size;


8503:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8504:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8505:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8506:   if (size == 1) {
8507:     PetscInt n,m;
8508:     VecGetSize(diag,&n);
8509:     MatGetSize(mat,NULL,&m);
8510:     if (m == n) {
8511:       MatDiagonalScale(mat,NULL,diag);
8512:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8513:   } else {
8514:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8515:   }
8516:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8517:   PetscObjectStateIncrease((PetscObject)mat);
8518:   return(0);
8519: }

8521: /*@
8522:    MatGetInertia - Gets the inertia from a factored matrix

8524:    Collective on Mat

8526:    Input Parameter:
8527: .  mat - the matrix

8529:    Output Parameters:
8530: +   nneg - number of negative eigenvalues
8531: .   nzero - number of zero eigenvalues
8532: -   npos - number of positive eigenvalues

8534:    Level: advanced

8536:    Notes:
8537:     Matrix must have been factored by MatCholeskyFactor()


8540: @*/
8541: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8542: {

8548:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8549:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8550:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8551:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8552:   return(0);
8553: }

8555: /* ----------------------------------------------------------------*/
8556: /*@C
8557:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8559:    Neighbor-wise Collective on Mats

8561:    Input Parameters:
8562: +  mat - the factored matrix
8563: -  b - the right-hand-side vectors

8565:    Output Parameter:
8566: .  x - the result vectors

8568:    Notes:
8569:    The vectors b and x cannot be the same.  I.e., one cannot
8570:    call MatSolves(A,x,x).

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

8577:    Level: developer

8579: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8580: @*/
8581: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8582: {

8588:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8589:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8590:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8592:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8593:   MatCheckPreallocated(mat,1);
8594:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8595:   (*mat->ops->solves)(mat,b,x);
8596:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8597:   return(0);
8598: }

8600: /*@
8601:    MatIsSymmetric - Test whether a matrix is symmetric

8603:    Collective on Mat

8605:    Input Parameter:
8606: +  A - the matrix to test
8607: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8609:    Output Parameters:
8610: .  flg - the result

8612:    Notes:
8613:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8615:    Level: intermediate

8617: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8618: @*/
8619: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8620: {


8627:   if (!A->symmetric_set) {
8628:     if (!A->ops->issymmetric) {
8629:       MatType mattype;
8630:       MatGetType(A,&mattype);
8631:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8632:     }
8633:     (*A->ops->issymmetric)(A,tol,flg);
8634:     if (!tol) {
8635:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8636:     }
8637:   } else if (A->symmetric) {
8638:     *flg = PETSC_TRUE;
8639:   } else if (!tol) {
8640:     *flg = PETSC_FALSE;
8641:   } else {
8642:     if (!A->ops->issymmetric) {
8643:       MatType mattype;
8644:       MatGetType(A,&mattype);
8645:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8646:     }
8647:     (*A->ops->issymmetric)(A,tol,flg);
8648:   }
8649:   return(0);
8650: }

8652: /*@
8653:    MatIsHermitian - Test whether a matrix is Hermitian

8655:    Collective on Mat

8657:    Input Parameter:
8658: +  A - the matrix to test
8659: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8661:    Output Parameters:
8662: .  flg - the result

8664:    Level: intermediate

8666: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8667:           MatIsSymmetricKnown(), MatIsSymmetric()
8668: @*/
8669: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8670: {


8677:   if (!A->hermitian_set) {
8678:     if (!A->ops->ishermitian) {
8679:       MatType mattype;
8680:       MatGetType(A,&mattype);
8681:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8682:     }
8683:     (*A->ops->ishermitian)(A,tol,flg);
8684:     if (!tol) {
8685:       MatSetOption(A,MAT_HERMITIAN,*flg);
8686:     }
8687:   } else if (A->hermitian) {
8688:     *flg = PETSC_TRUE;
8689:   } else if (!tol) {
8690:     *flg = PETSC_FALSE;
8691:   } else {
8692:     if (!A->ops->ishermitian) {
8693:       MatType mattype;
8694:       MatGetType(A,&mattype);
8695:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8696:     }
8697:     (*A->ops->ishermitian)(A,tol,flg);
8698:   }
8699:   return(0);
8700: }

8702: /*@
8703:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8705:    Not Collective

8707:    Input Parameter:
8708: .  A - the matrix to check

8710:    Output Parameters:
8711: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8712: -  flg - the result

8714:    Level: advanced

8716:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8717:          if you want it explicitly checked

8719: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8720: @*/
8721: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8722: {
8727:   if (A->symmetric_set) {
8728:     *set = PETSC_TRUE;
8729:     *flg = A->symmetric;
8730:   } else {
8731:     *set = PETSC_FALSE;
8732:   }
8733:   return(0);
8734: }

8736: /*@
8737:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8739:    Not Collective

8741:    Input Parameter:
8742: .  A - the matrix to check

8744:    Output Parameters:
8745: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8746: -  flg - the result

8748:    Level: advanced

8750:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8751:          if you want it explicitly checked

8753: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8754: @*/
8755: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8756: {
8761:   if (A->hermitian_set) {
8762:     *set = PETSC_TRUE;
8763:     *flg = A->hermitian;
8764:   } else {
8765:     *set = PETSC_FALSE;
8766:   }
8767:   return(0);
8768: }

8770: /*@
8771:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8773:    Collective on Mat

8775:    Input Parameter:
8776: .  A - the matrix to test

8778:    Output Parameters:
8779: .  flg - the result

8781:    Level: intermediate

8783: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8784: @*/
8785: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8786: {

8792:   if (!A->structurally_symmetric_set) {
8793:     if (!A->ops->isstructurallysymmetric) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type %s does not support checking for structural symmetric",((PetscObject)A)->type_name);
8794:     (*A->ops->isstructurallysymmetric)(A,flg);
8795:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8796:   } else *flg = A->structurally_symmetric;
8797:   return(0);
8798: }

8800: /*@
8801:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8802:        to be communicated to other processors during the MatAssemblyBegin/End() process

8804:     Not collective

8806:    Input Parameter:
8807: .   vec - the vector

8809:    Output Parameters:
8810: +   nstash   - the size of the stash
8811: .   reallocs - the number of additional mallocs incurred.
8812: .   bnstash   - the size of the block stash
8813: -   breallocs - the number of additional mallocs incurred.in the block stash

8815:    Level: advanced

8817: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8819: @*/
8820: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8821: {

8825:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8826:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8827:   return(0);
8828: }

8830: /*@C
8831:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8832:      parallel layout

8834:    Collective on Mat

8836:    Input Parameter:
8837: .  mat - the matrix

8839:    Output Parameter:
8840: +   right - (optional) vector that the matrix can be multiplied against
8841: -   left - (optional) vector that the matrix vector product can be stored in

8843:    Notes:
8844:     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().

8846:   Notes:
8847:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8849:   Level: advanced

8851: .seealso: MatCreate(), VecDestroy()
8852: @*/
8853: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8854: {

8860:   if (mat->ops->getvecs) {
8861:     (*mat->ops->getvecs)(mat,right,left);
8862:   } else {
8863:     PetscInt rbs,cbs;
8864:     MatGetBlockSizes(mat,&rbs,&cbs);
8865:     if (right) {
8866:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8867:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8868:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8869:       VecSetBlockSize(*right,cbs);
8870:       VecSetType(*right,mat->defaultvectype);
8871:       PetscLayoutReference(mat->cmap,&(*right)->map);
8872:     }
8873:     if (left) {
8874:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8875:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8876:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8877:       VecSetBlockSize(*left,rbs);
8878:       VecSetType(*left,mat->defaultvectype);
8879:       PetscLayoutReference(mat->rmap,&(*left)->map);
8880:     }
8881:   }
8882:   return(0);
8883: }

8885: /*@C
8886:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8887:      with default values.

8889:    Not Collective

8891:    Input Parameters:
8892: .    info - the MatFactorInfo data structure


8895:    Notes:
8896:     The solvers are generally used through the KSP and PC objects, for example
8897:           PCLU, PCILU, PCCHOLESKY, PCICC

8899:    Level: developer

8901: .seealso: MatFactorInfo

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

8906: @*/

8908: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8909: {

8913:   PetscMemzero(info,sizeof(MatFactorInfo));
8914:   return(0);
8915: }

8917: /*@
8918:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8920:    Collective on Mat

8922:    Input Parameters:
8923: +  mat - the factored matrix
8924: -  is - the index set defining the Schur indices (0-based)

8926:    Notes:
8927:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8929:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8931:    Level: developer

8933: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8934:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8936: @*/
8937: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8938: {
8939:   PetscErrorCode ierr,(*f)(Mat,IS);

8947:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8948:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8949:   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");
8950:   MatDestroy(&mat->schur);
8951:   (*f)(mat,is);
8952:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8953:   return(0);
8954: }

8956: /*@
8957:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8959:    Logically Collective on Mat

8961:    Input Parameters:
8962: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8963: .  S - location where to return the Schur complement, can be NULL
8964: -  status - the status of the Schur complement matrix, can be NULL

8966:    Notes:
8967:    You must call MatFactorSetSchurIS() before calling this routine.

8969:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8970:    The caller must destroy the object when it is no longer needed.
8971:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8973:    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)

8975:    Developer Notes:
8976:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8977:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8979:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8981:    Level: advanced

8983:    References:

8985: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8986: @*/
8987: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8988: {

8995:   if (S) {
8996:     PetscErrorCode (*f)(Mat,Mat*);

8998:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8999:     if (f) {
9000:       (*f)(F,S);
9001:     } else {
9002:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
9003:     }
9004:   }
9005:   if (status) *status = F->schur_status;
9006:   return(0);
9007: }

9009: /*@
9010:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

9012:    Logically Collective on Mat

9014:    Input Parameters:
9015: +  F - the factored matrix obtained by calling MatGetFactor()
9016: .  *S - location where to return the Schur complement, can be NULL
9017: -  status - the status of the Schur complement matrix, can be NULL

9019:    Notes:
9020:    You must call MatFactorSetSchurIS() before calling this routine.

9022:    Schur complement mode is currently implemented for sequential matrices.
9023:    The routine returns a the Schur Complement stored within the data strutures of the solver.
9024:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
9025:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

9027:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

9029:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

9031:    Level: advanced

9033:    References:

9035: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9036: @*/
9037: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9038: {
9043:   if (S) *S = F->schur;
9044:   if (status) *status = F->schur_status;
9045:   return(0);
9046: }

9048: /*@
9049:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

9051:    Logically Collective on Mat

9053:    Input Parameters:
9054: +  F - the factored matrix obtained by calling MatGetFactor()
9055: .  *S - location where the Schur complement is stored
9056: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

9058:    Notes:

9060:    Level: advanced

9062:    References:

9064: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9065: @*/
9066: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9067: {

9072:   if (S) {
9074:     *S = NULL;
9075:   }
9076:   F->schur_status = status;
9077:   MatFactorUpdateSchurStatus_Private(F);
9078:   return(0);
9079: }

9081: /*@
9082:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9084:    Logically Collective on Mat

9086:    Input Parameters:
9087: +  F - the factored matrix obtained by calling MatGetFactor()
9088: .  rhs - location where the right hand side of the Schur complement system is stored
9089: -  sol - location where the solution of the Schur complement system has to be returned

9091:    Notes:
9092:    The sizes of the vectors should match the size of the Schur complement

9094:    Must be called after MatFactorSetSchurIS()

9096:    Level: advanced

9098:    References:

9100: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9101: @*/
9102: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9103: {

9115:   MatFactorFactorizeSchurComplement(F);
9116:   switch (F->schur_status) {
9117:   case MAT_FACTOR_SCHUR_FACTORED:
9118:     MatSolveTranspose(F->schur,rhs,sol);
9119:     break;
9120:   case MAT_FACTOR_SCHUR_INVERTED:
9121:     MatMultTranspose(F->schur,rhs,sol);
9122:     break;
9123:   default:
9124:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9125:   }
9126:   return(0);
9127: }

9129: /*@
9130:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9132:    Logically Collective on Mat

9134:    Input Parameters:
9135: +  F - the factored matrix obtained by calling MatGetFactor()
9136: .  rhs - location where the right hand side of the Schur complement system is stored
9137: -  sol - location where the solution of the Schur complement system has to be returned

9139:    Notes:
9140:    The sizes of the vectors should match the size of the Schur complement

9142:    Must be called after MatFactorSetSchurIS()

9144:    Level: advanced

9146:    References:

9148: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9149: @*/
9150: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9151: {

9163:   MatFactorFactorizeSchurComplement(F);
9164:   switch (F->schur_status) {
9165:   case MAT_FACTOR_SCHUR_FACTORED:
9166:     MatSolve(F->schur,rhs,sol);
9167:     break;
9168:   case MAT_FACTOR_SCHUR_INVERTED:
9169:     MatMult(F->schur,rhs,sol);
9170:     break;
9171:   default:
9172:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9173:   }
9174:   return(0);
9175: }

9177: /*@
9178:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9180:    Logically Collective on Mat

9182:    Input Parameters:
9183: .  F - the factored matrix obtained by calling MatGetFactor()

9185:    Notes:
9186:     Must be called after MatFactorSetSchurIS().

9188:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9190:    Level: advanced

9192:    References:

9194: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9195: @*/
9196: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9197: {

9203:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9204:   MatFactorFactorizeSchurComplement(F);
9205:   MatFactorInvertSchurComplement_Private(F);
9206:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9207:   return(0);
9208: }

9210: /*@
9211:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9213:    Logically Collective on Mat

9215:    Input Parameters:
9216: .  F - the factored matrix obtained by calling MatGetFactor()

9218:    Notes:
9219:     Must be called after MatFactorSetSchurIS().

9221:    Level: advanced

9223:    References:

9225: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9226: @*/
9227: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9228: {

9234:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9235:   MatFactorFactorizeSchurComplement_Private(F);
9236:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9237:   return(0);
9238: }

9240: /*@
9241:    MatPtAP - Creates the matrix product C = P^T * A * P

9243:    Neighbor-wise Collective on Mat

9245:    Input Parameters:
9246: +  A - the matrix
9247: .  P - the projection matrix
9248: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9249: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9250:           if the result is a dense matrix this is irrelevent

9252:    Output Parameters:
9253: .  C - the product matrix

9255:    Notes:
9256:    C will be created and must be destroyed by the user with MatDestroy().

9258:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9260:    Level: intermediate

9262: .seealso: MatMatMult(), MatRARt()
9263: @*/
9264: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9265: {

9269:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9270:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9272:   if (scall == MAT_INITIAL_MATRIX) {
9273:     MatProductCreate(A,P,NULL,C);
9274:     MatProductSetType(*C,MATPRODUCT_PtAP);
9275:     MatProductSetAlgorithm(*C,"default");
9276:     MatProductSetFill(*C,fill);

9278:     (*C)->product->api_user = PETSC_TRUE;
9279:     MatProductSetFromOptions(*C);
9280:     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and P %s",MatProductTypes[MATPRODUCT_PtAP],((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9281:     MatProductSymbolic(*C);
9282:   } else { /* scall == MAT_REUSE_MATRIX */
9283:     MatProductReplaceMats(A,P,NULL,*C);
9284:   }

9286:   MatProductNumeric(*C);
9287:   if (A->symmetric_set && A->symmetric) {
9288:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9289:   }
9290:   return(0);
9291: }

9293: /*@
9294:    MatRARt - Creates the matrix product C = R * A * R^T

9296:    Neighbor-wise Collective on Mat

9298:    Input Parameters:
9299: +  A - the matrix
9300: .  R - the projection matrix
9301: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9302: -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9303:           if the result is a dense matrix this is irrelevent

9305:    Output Parameters:
9306: .  C - the product matrix

9308:    Notes:
9309:    C will be created and must be destroyed by the user with MatDestroy().

9311:    This routine is currently only implemented for pairs of AIJ matrices and classes
9312:    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9313:    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9314:    We recommend using MatPtAP().

9316:    Level: intermediate

9318: .seealso: MatMatMult(), MatPtAP()
9319: @*/
9320: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9321: {

9325:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9326:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9328:   if (scall == MAT_INITIAL_MATRIX) {
9329:     MatProductCreate(A,R,NULL,C);
9330:     MatProductSetType(*C,MATPRODUCT_RARt);
9331:     MatProductSetAlgorithm(*C,"default");
9332:     MatProductSetFill(*C,fill);

9334:     (*C)->product->api_user = PETSC_TRUE;
9335:     MatProductSetFromOptions(*C);
9336:     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and R %s",MatProductTypes[MATPRODUCT_RARt],((PetscObject)A)->type_name,((PetscObject)R)->type_name);
9337:     MatProductSymbolic(*C);
9338:   } else { /* scall == MAT_REUSE_MATRIX */
9339:     MatProductReplaceMats(A,R,NULL,*C);
9340:   }

9342:   MatProductNumeric(*C);
9343:   if (A->symmetric_set && A->symmetric) {
9344:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9345:   }
9346:   return(0);
9347: }


9350: static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
9351: {

9355:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9357:   if (scall == MAT_INITIAL_MATRIX) {
9358:     PetscInfo1(A,"Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n",MatProductTypes[ptype]);
9359:     MatProductCreate(A,B,NULL,C);
9360:     MatProductSetType(*C,ptype);
9361:     MatProductSetAlgorithm(*C,MATPRODUCTALGORITHM_DEFAULT);
9362:     MatProductSetFill(*C,fill);

9364:     (*C)->product->api_user = PETSC_TRUE;
9365:     MatProductSetFromOptions(*C);
9366:     MatProductSymbolic(*C);
9367:   } else { /* scall == MAT_REUSE_MATRIX */
9368:     Mat_Product *product = (*C)->product;

9370:     PetscInfo2(A,"Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n",product ? "with" : "without",MatProductTypes[ptype]);
9371:     if (!product) {
9372:       /* user provide the dense matrix *C without calling MatProductCreate() */
9373:       PetscBool isdense;

9375:       PetscObjectBaseTypeCompareAny((PetscObject)(*C),&isdense,MATSEQDENSE,MATMPIDENSE,"");
9376:       if (isdense) {
9377:         /* user wants to reuse an assembled dense matrix */
9378:         /* Create product -- see MatCreateProduct() */
9379:         MatProductCreate_Private(A,B,NULL,*C);
9380:         product = (*C)->product;
9381:         product->fill     = fill;
9382:         product->api_user = PETSC_TRUE;
9383:         product->clear    = PETSC_TRUE;

9385:         MatProductSetType(*C,ptype);
9386:         MatProductSetFromOptions(*C);
9387:         if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for %s and %s",MatProductTypes[ptype],((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9388:         MatProductSymbolic(*C);
9389:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
9390:     } else { /* user may change input matrices A or B when REUSE */
9391:       MatProductReplaceMats(A,B,NULL,*C);
9392:     }
9393:   }
9394:   MatProductNumeric(*C);
9395:   return(0);
9396: }

9398: /*@
9399:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

9401:    Neighbor-wise Collective on Mat

9403:    Input Parameters:
9404: +  A - the left matrix
9405: .  B - the right matrix
9406: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9407: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9408:           if the result is a dense matrix this is irrelevent

9410:    Output Parameters:
9411: .  C - the product matrix

9413:    Notes:
9414:    Unless scall is MAT_REUSE_MATRIX C will be created.

9416:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call and C was obtained from a previous
9417:    call to this function with MAT_INITIAL_MATRIX.

9419:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.

9421:    If you have many matrices with the same non-zero structure to multiply, you should use MatProductCreate()/MatProductSymbolic(C)/ReplaceMats(), and call MatProductNumeric() repeatedly.

9423:    In the special case where matrix B (and hence C) are dense you can create the correctly sized matrix C yourself and then call this routine with MAT_REUSE_MATRIX, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.

9425:    Level: intermediate

9427: .seealso: MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
9428: @*/
9429: PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9430: {

9434:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_AB,C);
9435:   return(0);
9436: }

9438: /*@
9439:    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.

9441:    Neighbor-wise Collective on Mat

9443:    Input Parameters:
9444: +  A - the left matrix
9445: .  B - the right matrix
9446: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9447: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9449:    Output Parameters:
9450: .  C - the product matrix

9452:    Notes:
9453:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9455:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

9457:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9458:    actually needed.

9460:    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9461:    and for pairs of MPIDense matrices.

9463:    Options Database Keys:
9464: .  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9465:                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9466:                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.

9468:    Level: intermediate

9470: .seealso: MatMatMult(), MatTransposeMatMult() MatPtAP()
9471: @*/
9472: PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9473: {

9477:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_ABt,C);
9478:   return(0);
9479: }

9481: /*@
9482:    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.

9484:    Neighbor-wise Collective on Mat

9486:    Input Parameters:
9487: +  A - the left matrix
9488: .  B - the right matrix
9489: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9490: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9492:    Output Parameters:
9493: .  C - the product matrix

9495:    Notes:
9496:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9498:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call.

9500:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9501:    actually needed.

9503:    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9504:    which inherit from SeqAIJ.  C will be of same type as the input matrices.

9506:    Level: intermediate

9508: .seealso: MatMatMult(), MatMatTransposeMult(), MatPtAP()
9509: @*/
9510: PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9511: {

9515:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_AtB,C);
9516:   return(0);
9517: }

9519: /*@
9520:    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.

9522:    Neighbor-wise Collective on Mat

9524:    Input Parameters:
9525: +  A - the left matrix
9526: .  B - the middle matrix
9527: .  C - the right matrix
9528: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9529: -  fill - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use PETSC_DEFAULT if you do not have a good estimate
9530:           if the result is a dense matrix this is irrelevent

9532:    Output Parameters:
9533: .  D - the product matrix

9535:    Notes:
9536:    Unless scall is MAT_REUSE_MATRIX D will be created.

9538:    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call

9540:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9541:    actually needed.

9543:    If you have many matrices with the same non-zero structure to multiply, you
9544:    should use MAT_REUSE_MATRIX in all calls but the first or

9546:    Level: intermediate

9548: .seealso: MatMatMult, MatPtAP()
9549: @*/
9550: PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9551: {

9555:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D,6);
9556:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9558:   if (scall == MAT_INITIAL_MATRIX) {
9559:     MatProductCreate(A,B,C,D);
9560:     MatProductSetType(*D,MATPRODUCT_ABC);
9561:     MatProductSetAlgorithm(*D,"default");
9562:     MatProductSetFill(*D,fill);

9564:     (*D)->product->api_user = PETSC_TRUE;
9565:     MatProductSetFromOptions(*D);
9566:     if (!(*D)->ops->productsymbolic) SETERRQ4(PetscObjectComm((PetscObject)(*D)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s, B %s and C %s",MatProductTypes[MATPRODUCT_ABC],((PetscObject)A)->type_name,((PetscObject)B)->type_name,((PetscObject)C)->type_name);
9567:     MatProductSymbolic(*D);
9568:   } else { /* user may change input matrices when REUSE */
9569:     MatProductReplaceMats(A,B,C,*D);
9570:   }
9571:   MatProductNumeric(*D);
9572:   return(0);
9573: }

9575: /*@
9576:    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

9578:    Collective on Mat

9580:    Input Parameters:
9581: +  mat - the matrix
9582: .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9583: .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9584: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9586:    Output Parameter:
9587: .  matredundant - redundant matrix

9589:    Notes:
9590:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9591:    original matrix has not changed from that last call to MatCreateRedundantMatrix().

9593:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9594:    calling it.

9596:    Level: advanced


9599: .seealso: MatDestroy()
9600: @*/
9601: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9602: {
9604:   MPI_Comm       comm;
9605:   PetscMPIInt    size;
9606:   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9607:   Mat_Redundant  *redund=NULL;
9608:   PetscSubcomm   psubcomm=NULL;
9609:   MPI_Comm       subcomm_in=subcomm;
9610:   Mat            *matseq;
9611:   IS             isrow,iscol;
9612:   PetscBool      newsubcomm=PETSC_FALSE;

9616:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9619:   }

9621:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
9622:   if (size == 1 || nsubcomm == 1) {
9623:     if (reuse == MAT_INITIAL_MATRIX) {
9624:       MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
9625:     } else {
9626:       if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9627:       MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
9628:     }
9629:     return(0);
9630:   }

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

9636:   PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
9637:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9638:     /* create psubcomm, then get subcomm */
9639:     PetscObjectGetComm((PetscObject)mat,&comm);
9640:     MPI_Comm_size(comm,&size);
9641:     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);

9643:     PetscSubcommCreate(comm,&psubcomm);
9644:     PetscSubcommSetNumber(psubcomm,nsubcomm);
9645:     PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
9646:     PetscSubcommSetFromOptions(psubcomm);
9647:     PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
9648:     newsubcomm = PETSC_TRUE;
9649:     PetscSubcommDestroy(&psubcomm);
9650:   }

9652:   /* get isrow, iscol and a local sequential matrix matseq[0] */
9653:   if (reuse == MAT_INITIAL_MATRIX) {
9654:     mloc_sub = PETSC_DECIDE;
9655:     nloc_sub = PETSC_DECIDE;
9656:     if (bs < 1) {
9657:       PetscSplitOwnership(subcomm,&mloc_sub,&M);
9658:       PetscSplitOwnership(subcomm,&nloc_sub,&N);
9659:     } else {
9660:       PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
9661:       PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);
9662:     }
9663:     MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
9664:     rstart = rend - mloc_sub;
9665:     ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
9666:     ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
9667:   } else { /* reuse == MAT_REUSE_MATRIX */
9668:     if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9669:     /* retrieve subcomm */
9670:     PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
9671:     redund = (*matredundant)->redundant;
9672:     isrow  = redund->isrow;
9673:     iscol  = redund->iscol;
9674:     matseq = redund->matseq;
9675:   }
9676:   MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);

9678:   /* get matredundant over subcomm */
9679:   if (reuse == MAT_INITIAL_MATRIX) {
9680:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);

9682:     /* create a supporting struct and attach it to C for reuse */
9683:     PetscNewLog(*matredundant,&redund);
9684:     (*matredundant)->redundant = redund;
9685:     redund->isrow              = isrow;
9686:     redund->iscol              = iscol;
9687:     redund->matseq             = matseq;
9688:     if (newsubcomm) {
9689:       redund->subcomm          = subcomm;
9690:     } else {
9691:       redund->subcomm          = MPI_COMM_NULL;
9692:     }
9693:   } else {
9694:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
9695:   }
9696:   PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
9697:   return(0);
9698: }

9700: /*@C
9701:    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
9702:    a given 'mat' object. Each submatrix can span multiple procs.

9704:    Collective on Mat

9706:    Input Parameters:
9707: +  mat - the matrix
9708: .  subcomm - the subcommunicator obtained by com_split(comm)
9709: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9711:    Output Parameter:
9712: .  subMat - 'parallel submatrices each spans a given subcomm

9714:   Notes:
9715:   The submatrix partition across processors is dictated by 'subComm' a
9716:   communicator obtained by com_split(comm). The comm_split
9717:   is not restriced to be grouped with consecutive original ranks.

9719:   Due the comm_split() usage, the parallel layout of the submatrices
9720:   map directly to the layout of the original matrix [wrt the local
9721:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
9722:   into the 'DiagonalMat' of the subMat, hence it is used directly from
9723:   the subMat. However the offDiagMat looses some columns - and this is
9724:   reconstructed with MatSetValues()

9726:   Level: advanced


9729: .seealso: MatCreateSubMatrices()
9730: @*/
9731: PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
9732: {
9734:   PetscMPIInt    commsize,subCommSize;

9737:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
9738:   MPI_Comm_size(subComm,&subCommSize);
9739:   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);

9741:   if (scall == MAT_REUSE_MATRIX && *subMat == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9742:   PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
9743:   (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
9744:   PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
9745:   return(0);
9746: }

9748: /*@
9749:    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

9751:    Not Collective

9753:    Input Arguments:
9754: +  mat - matrix to extract local submatrix from
9755: .  isrow - local row indices for submatrix
9756: -  iscol - local column indices for submatrix

9758:    Output Arguments:
9759: .  submat - the submatrix

9761:    Level: intermediate

9763:    Notes:
9764:    The submat should be returned with MatRestoreLocalSubMatrix().

9766:    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
9767:    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.

9769:    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
9770:    MatSetValuesBlockedLocal() will also be implemented.

9772:    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
9773:    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.

9775: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
9776: @*/
9777: PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9778: {

9787:   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");

9789:   if (mat->ops->getlocalsubmatrix) {
9790:     (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
9791:   } else {
9792:     MatCreateLocalRef(mat,isrow,iscol,submat);
9793:   }
9794:   return(0);
9795: }

9797: /*@
9798:    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering

9800:    Not Collective

9802:    Input Arguments:
9803:    mat - matrix to extract local submatrix from
9804:    isrow - local row indices for submatrix
9805:    iscol - local column indices for submatrix
9806:    submat - the submatrix

9808:    Level: intermediate

9810: .seealso: MatGetLocalSubMatrix()
9811: @*/
9812: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9813: {

9822:   if (*submat) {
9824:   }

9826:   if (mat->ops->restorelocalsubmatrix) {
9827:     (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
9828:   } else {
9829:     MatDestroy(submat);
9830:   }
9831:   *submat = NULL;
9832:   return(0);
9833: }

9835: /* --------------------------------------------------------*/
9836: /*@
9837:    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

9839:    Collective on Mat

9841:    Input Parameter:
9842: .  mat - the matrix

9844:    Output Parameter:
9845: .  is - if any rows have zero diagonals this contains the list of them

9847:    Level: developer

9849: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9850: @*/
9851: PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
9852: {

9858:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9859:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9861:   if (!mat->ops->findzerodiagonals) {
9862:     Vec                diag;
9863:     const PetscScalar *a;
9864:     PetscInt          *rows;
9865:     PetscInt           rStart, rEnd, r, nrow = 0;

9867:     MatCreateVecs(mat, &diag, NULL);
9868:     MatGetDiagonal(mat, diag);
9869:     MatGetOwnershipRange(mat, &rStart, &rEnd);
9870:     VecGetArrayRead(diag, &a);
9871:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
9872:     PetscMalloc1(nrow, &rows);
9873:     nrow = 0;
9874:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
9875:     VecRestoreArrayRead(diag, &a);
9876:     VecDestroy(&diag);
9877:     ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);
9878:   } else {
9879:     (*mat->ops->findzerodiagonals)(mat, is);
9880:   }
9881:   return(0);
9882: }

9884: /*@
9885:    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

9887:    Collective on Mat

9889:    Input Parameter:
9890: .  mat - the matrix

9892:    Output Parameter:
9893: .  is - contains the list of rows with off block diagonal entries

9895:    Level: developer

9897: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9898: @*/
9899: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
9900: {

9906:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9907:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9909:   if (!mat->ops->findoffblockdiagonalentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a find off block diagonal entries defined",((PetscObject)mat)->type_name);
9910:   (*mat->ops->findoffblockdiagonalentries)(mat,is);
9911:   return(0);
9912: }

9914: /*@C
9915:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

9917:   Collective on Mat

9919:   Input Parameters:
9920: . mat - the matrix

9922:   Output Parameters:
9923: . values - the block inverses in column major order (FORTRAN-like)

9925:    Note:
9926:    This routine is not available from Fortran.

9928:   Level: advanced

9930: .seealso: MatInvertBockDiagonalMat
9931: @*/
9932: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
9933: {

9938:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9939:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9940:   if (!mat->ops->invertblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type %s",((PetscObject)mat)->type_name);
9941:   (*mat->ops->invertblockdiagonal)(mat,values);
9942:   return(0);
9943: }

9945: /*@C
9946:   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.

9948:   Collective on Mat

9950:   Input Parameters:
9951: + mat - the matrix
9952: . nblocks - the number of blocks
9953: - bsizes - the size of each block

9955:   Output Parameters:
9956: . values - the block inverses in column major order (FORTRAN-like)

9958:    Note:
9959:    This routine is not available from Fortran.

9961:   Level: advanced

9963: .seealso: MatInvertBockDiagonal()
9964: @*/
9965: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
9966: {

9971:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9972:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9973:   if (!mat->ops->invertvariableblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type",((PetscObject)mat)->type_name);
9974:   (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);
9975:   return(0);
9976: }

9978: /*@
9979:   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A

9981:   Collective on Mat

9983:   Input Parameters:
9984: . A - the matrix

9986:   Output Parameters:
9987: . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.

9989:   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C

9991:   Level: advanced

9993: .seealso: MatInvertBockDiagonal()
9994: @*/
9995: PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
9996: {
9997:   PetscErrorCode     ierr;
9998:   const PetscScalar *vals;
9999:   PetscInt          *dnnz;
10000:   PetscInt           M,N,m,n,rstart,rend,bs,i,j;

10003:   MatInvertBlockDiagonal(A,&vals);
10004:   MatGetBlockSize(A,&bs);
10005:   MatGetSize(A,&M,&N);
10006:   MatGetLocalSize(A,&m,&n);
10007:   MatSetSizes(C,m,n,M,N);
10008:   MatSetBlockSize(C,bs);
10009:   PetscMalloc1(m/bs,&dnnz);
10010:   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
10011:   MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);
10012:   PetscFree(dnnz);
10013:   MatGetOwnershipRange(C,&rstart,&rend);
10014:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);
10015:   for (i = rstart/bs; i < rend/bs; i++) {
10016:     MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);
10017:   }
10018:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
10019:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
10020:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);
10021:   return(0);
10022: }

10024: /*@C
10025:     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
10026:     via MatTransposeColoringCreate().

10028:     Collective on MatTransposeColoring

10030:     Input Parameter:
10031: .   c - coloring context

10033:     Level: intermediate

10035: .seealso: MatTransposeColoringCreate()
10036: @*/
10037: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10038: {
10039:   PetscErrorCode       ierr;
10040:   MatTransposeColoring matcolor=*c;

10043:   if (!matcolor) return(0);
10044:   if (--((PetscObject)matcolor)->refct > 0) {matcolor = NULL; return(0);}

10046:   PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
10047:   PetscFree(matcolor->rows);
10048:   PetscFree(matcolor->den2sp);
10049:   PetscFree(matcolor->colorforcol);
10050:   PetscFree(matcolor->columns);
10051:   if (matcolor->brows>0) {
10052:     PetscFree(matcolor->lstart);
10053:   }
10054:   PetscHeaderDestroy(c);
10055:   return(0);
10056: }

10058: /*@C
10059:     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10060:     a MatTransposeColoring context has been created, computes a dense B^T by Apply
10061:     MatTransposeColoring to sparse B.

10063:     Collective on MatTransposeColoring

10065:     Input Parameters:
10066: +   B - sparse matrix B
10067: .   Btdense - symbolic dense matrix B^T
10068: -   coloring - coloring context created with MatTransposeColoringCreate()

10070:     Output Parameter:
10071: .   Btdense - dense matrix B^T

10073:     Level: advanced

10075:      Notes:
10076:     These are used internally for some implementations of MatRARt()

10078: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()

10080: @*/
10081: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10082: {


10090:   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10091:   (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
10092:   return(0);
10093: }

10095: /*@C
10096:     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10097:     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10098:     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10099:     Csp from Cden.

10101:     Collective on MatTransposeColoring

10103:     Input Parameters:
10104: +   coloring - coloring context created with MatTransposeColoringCreate()
10105: -   Cden - matrix product of a sparse matrix and a dense matrix Btdense

10107:     Output Parameter:
10108: .   Csp - sparse matrix

10110:     Level: advanced

10112:      Notes:
10113:     These are used internally for some implementations of MatRARt()

10115: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()

10117: @*/
10118: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10119: {


10127:   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10128:   (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
10129:   MatAssemblyBegin(Csp,MAT_FINAL_ASSEMBLY);
10130:   MatAssemblyEnd(Csp,MAT_FINAL_ASSEMBLY);
10131:   return(0);
10132: }

10134: /*@C
10135:    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.

10137:    Collective on Mat

10139:    Input Parameters:
10140: +  mat - the matrix product C
10141: -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()

10143:     Output Parameter:
10144: .   color - the new coloring context

10146:     Level: intermediate

10148: .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
10149:            MatTransColoringApplyDenToSp()
10150: @*/
10151: PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10152: {
10153:   MatTransposeColoring c;
10154:   MPI_Comm             comm;
10155:   PetscErrorCode       ierr;

10158:   PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
10159:   PetscObjectGetComm((PetscObject)mat,&comm);
10160:   PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);

10162:   c->ctype = iscoloring->ctype;
10163:   if (mat->ops->transposecoloringcreate) {
10164:     (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
10165:   } else SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for matrix type %s",((PetscObject)mat)->type_name);

10167:   *color = c;
10168:   PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
10169:   return(0);
10170: }

10172: /*@
10173:       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10174:         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10175:         same, otherwise it will be larger

10177:      Not Collective

10179:   Input Parameter:
10180: .    A  - the matrix

10182:   Output Parameter:
10183: .    state - the current state

10185:   Notes:
10186:     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10187:          different matrices

10189:   Level: intermediate

10191: @*/
10192: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10193: {
10196:   *state = mat->nonzerostate;
10197:   return(0);
10198: }

10200: /*@
10201:       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10202:                  matrices from each processor

10204:     Collective

10206:    Input Parameters:
10207: +    comm - the communicators the parallel matrix will live on
10208: .    seqmat - the input sequential matrices
10209: .    n - number of local columns (or PETSC_DECIDE)
10210: -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

10212:    Output Parameter:
10213: .    mpimat - the parallel matrix generated

10215:     Level: advanced

10217:    Notes:
10218:     The number of columns of the matrix in EACH processor MUST be the same.

10220: @*/
10221: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10222: {

10226:   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10227:   if (reuse == MAT_REUSE_MATRIX && seqmat == *mpimat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");

10229:   PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
10230:   (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
10231:   PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
10232:   return(0);
10233: }

10235: /*@
10236:      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10237:                  ranks' ownership ranges.

10239:     Collective on A

10241:    Input Parameters:
10242: +    A   - the matrix to create subdomains from
10243: -    N   - requested number of subdomains


10246:    Output Parameters:
10247: +    n   - number of subdomains resulting on this rank
10248: -    iss - IS list with indices of subdomains on this rank

10250:     Level: advanced

10252:     Notes:
10253:     number of subdomains must be smaller than the communicator size
10254: @*/
10255: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10256: {
10257:   MPI_Comm        comm,subcomm;
10258:   PetscMPIInt     size,rank,color;
10259:   PetscInt        rstart,rend,k;
10260:   PetscErrorCode  ierr;

10263:   PetscObjectGetComm((PetscObject)A,&comm);
10264:   MPI_Comm_size(comm,&size);
10265:   MPI_Comm_rank(comm,&rank);
10266:   if (N < 1 || N >= (PetscInt)size) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"number of subdomains must be > 0 and < %D, got N = %D",size,N);
10267:   *n = 1;
10268:   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10269:   color = rank/k;
10270:   MPI_Comm_split(comm,color,rank,&subcomm);
10271:   PetscMalloc1(1,iss);
10272:   MatGetOwnershipRange(A,&rstart,&rend);
10273:   ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);
10274:   MPI_Comm_free(&subcomm);
10275:   return(0);
10276: }

10278: /*@
10279:    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.

10281:    If the interpolation and restriction operators are the same, uses MatPtAP.
10282:    If they are not the same, use MatMatMatMult.

10284:    Once the coarse grid problem is constructed, correct for interpolation operators
10285:    that are not of full rank, which can legitimately happen in the case of non-nested
10286:    geometric multigrid.

10288:    Input Parameters:
10289: +  restrct - restriction operator
10290: .  dA - fine grid matrix
10291: .  interpolate - interpolation operator
10292: .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10293: -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate

10295:    Output Parameters:
10296: .  A - the Galerkin coarse matrix

10298:    Options Database Key:
10299: .  -pc_mg_galerkin <both,pmat,mat,none>

10301:    Level: developer

10303: .seealso: MatPtAP(), MatMatMatMult()
10304: @*/
10305: PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10306: {
10308:   IS             zerorows;
10309:   Vec            diag;

10312:   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10313:   /* Construct the coarse grid matrix */
10314:   if (interpolate == restrct) {
10315:     MatPtAP(dA,interpolate,reuse,fill,A);
10316:   } else {
10317:     MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);
10318:   }

10320:   /* If the interpolation matrix is not of full rank, A will have zero rows.
10321:      This can legitimately happen in the case of non-nested geometric multigrid.
10322:      In that event, we set the rows of the matrix to the rows of the identity,
10323:      ignoring the equations (as the RHS will also be zero). */

10325:   MatFindZeroRows(*A, &zerorows);

10327:   if (zerorows != NULL) { /* if there are any zero rows */
10328:     MatCreateVecs(*A, &diag, NULL);
10329:     MatGetDiagonal(*A, diag);
10330:     VecISSet(diag, zerorows, 1.0);
10331:     MatDiagonalSet(*A, diag, INSERT_VALUES);
10332:     VecDestroy(&diag);
10333:     ISDestroy(&zerorows);
10334:   }
10335:   return(0);
10336: }

10338: /*@C
10339:     MatSetOperation - Allows user to set a matrix operation for any matrix type

10341:    Logically Collective on Mat

10343:     Input Parameters:
10344: +   mat - the matrix
10345: .   op - the name of the operation
10346: -   f - the function that provides the operation

10348:    Level: developer

10350:     Usage:
10351: $      extern PetscErrorCode usermult(Mat,Vec,Vec);
10352: $      MatCreateXXX(comm,...&A);
10353: $      MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);

10355:     Notes:
10356:     See the file include/petscmat.h for a complete list of matrix
10357:     operations, which all have the form MATOP_<OPERATION>, where
10358:     <OPERATION> is the name (in all capital letters) of the
10359:     user interface routine (e.g., MatMult() -> MATOP_MULT).

10361:     All user-provided functions (except for MATOP_DESTROY) should have the same calling
10362:     sequence as the usual matrix interface routines, since they
10363:     are intended to be accessed via the usual matrix interface
10364:     routines, e.g.,
10365: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

10367:     In particular each function MUST return an error code of 0 on success and
10368:     nonzero on failure.

10370:     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.

10372: .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10373: @*/
10374: PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10375: {
10378:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10379:     mat->ops->viewnative = mat->ops->view;
10380:   }
10381:   (((void(**)(void))mat->ops)[op]) = f;
10382:   return(0);
10383: }

10385: /*@C
10386:     MatGetOperation - Gets a matrix operation for any matrix type.

10388:     Not Collective

10390:     Input Parameters:
10391: +   mat - the matrix
10392: -   op - the name of the operation

10394:     Output Parameter:
10395: .   f - the function that provides the operation

10397:     Level: developer

10399:     Usage:
10400: $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
10401: $      MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);

10403:     Notes:
10404:     See the file include/petscmat.h for a complete list of matrix
10405:     operations, which all have the form MATOP_<OPERATION>, where
10406:     <OPERATION> is the name (in all capital letters) of the
10407:     user interface routine (e.g., MatMult() -> MATOP_MULT).

10409:     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.

10411: .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
10412: @*/
10413: PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
10414: {
10417:   *f = (((void (**)(void))mat->ops)[op]);
10418:   return(0);
10419: }

10421: /*@
10422:     MatHasOperation - Determines whether the given matrix supports the particular
10423:     operation.

10425:    Not Collective

10427:    Input Parameters:
10428: +  mat - the matrix
10429: -  op - the operation, for example, MATOP_GET_DIAGONAL

10431:    Output Parameter:
10432: .  has - either PETSC_TRUE or PETSC_FALSE

10434:    Level: advanced

10436:    Notes:
10437:    See the file include/petscmat.h for a complete list of matrix
10438:    operations, which all have the form MATOP_<OPERATION>, where
10439:    <OPERATION> is the name (in all capital letters) of the
10440:    user-level routine.  E.g., MatNorm() -> MATOP_NORM.

10442: .seealso: MatCreateShell()
10443: @*/
10444: PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
10445: {

10450:   /* symbolic product can be set before matrix type */
10453:   if (mat->ops->hasoperation) {
10454:     (*mat->ops->hasoperation)(mat,op,has);
10455:   } else {
10456:     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
10457:     else {
10458:       *has = PETSC_FALSE;
10459:       if (op == MATOP_CREATE_SUBMATRIX) {
10460:         PetscMPIInt size;

10462:         MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
10463:         if (size == 1) {
10464:           MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);
10465:         }
10466:       }
10467:     }
10468:   }
10469:   return(0);
10470: }

10472: /*@
10473:     MatHasCongruentLayouts - Determines whether the rows and columns layouts
10474:     of the matrix are congruent

10476:    Collective on mat

10478:    Input Parameters:
10479: .  mat - the matrix

10481:    Output Parameter:
10482: .  cong - either PETSC_TRUE or PETSC_FALSE

10484:    Level: beginner

10486:    Notes:

10488: .seealso: MatCreate(), MatSetSizes()
10489: @*/
10490: PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
10491: {

10498:   if (!mat->rmap || !mat->cmap) {
10499:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
10500:     return(0);
10501:   }
10502:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
10503:     PetscLayoutCompare(mat->rmap,mat->cmap,cong);
10504:     if (*cong) mat->congruentlayouts = 1;
10505:     else       mat->congruentlayouts = 0;
10506:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
10507:   return(0);
10508: }

10510: PetscErrorCode MatSetInf(Mat A)
10511: {

10515:   if (!A->ops->setinf) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"No support for this operation for this matrix type");
10516:   (*A->ops->setinf)(A);
10517:   return(0);
10518: }