Actual source code: matrix.c

petsc-3.14.4 2021-02-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:     In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).

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

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

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

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

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

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

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

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

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

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

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

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

1095:    Collective on PetscViewer

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

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

1107:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1192:    Corresponding MatView() is not yet implemented.

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

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

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

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


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

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

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

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

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

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

1269: /*@
1270:    MatDestroy - Frees space taken by a matrix.

1272:    Collective on Mat

1274:    Input Parameter:
1275: .  A - the matrix

1277:    Level: beginner

1279: @*/
1280: PetscErrorCode MatDestroy(Mat *A)
1281: {

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

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

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

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

1315:    Not Collective

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

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

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

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

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

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

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

1348:    Level: beginner

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

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

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

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

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

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

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


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

1405:    Not Collective

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

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

1415:    All the nonzeros in the row must be provided

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

1419:    The row must belong to this process

1421:    Level: intermediate

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

1435:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1436:   MatSetValuesRow(mat,globalrow,v);
1437:   return(0);
1438: }

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

1444:    Not Collective

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

1451:    Notes:
1452:    The values, v, are column-oriented for the block version.

1454:    All the nonzeros in the row must be provided

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

1458:    The row must belong to this process

1460:    Level: advanced

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

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

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

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

1493:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

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

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

1553:    Level: beginner

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

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

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

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

1607:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

1660:    Level: beginner

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

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

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

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

1716:    Not Collective

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


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

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

1732:    Level: beginner

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


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

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

1760:    Not Collective

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

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

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

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

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

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

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

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

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

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

1820:    Level: intermediate

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

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

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

1878: /*@C
1879:    MatGetValues - Gets a block of values from a matrix.

1881:    Not Collective; can only return values that are owned by the give process

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

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

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

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

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

1905:      For the standard row-based matrix formats, idxm[] can only contain rows owned by the requesting MPI rank.
1906:      That is, rows with global index greater than or equal to restart and less than rend where restart and rend are obtainable
1907:      from MatGetOwnershipRange(mat,&rstart,&rend).

1909:    Level: advanced

1911: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues(), MatGetOwnershipRange(), MatGetValuesLocal()
1912: @*/
1913: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1914: {

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

1929:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1930:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1931:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1932:   return(0);
1933: }

1935: /*@C
1936:    MatGetValuesLocal - retrieves values from certain locations in a matrix using the local numbering of the indices
1937:      defined previously by MatSetLocalToGlobalMapping()

1939:    Not Collective

1941:    Input Parameters:
1942: +  mat - the matrix
1943: .  nrow, irow - number of rows and their local indices
1944: -  ncol, icol - number of columns and their local indices

1946:    Output Parameter:
1947: .  y -  a logically two-dimensional array of values

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

1952:      This routine can only return values that are owned by the requesting MPI rank. That is, for standard matrix formats, rows that, in the global numbering,
1953:      are greater than or equal to restart and less than rend where restart and rend are obtainable from MatGetOwnershipRange(mat,&rstart,&rend). One can
1954:      determine if the resulting global row associated with the local row r is owned by the requesting MPI rank by applying the ISLocalToGlobalMapping set
1955:      with MatSetLocalToGlobalMapping().

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

1961:    Level: advanced

1963: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1964:            MatSetValuesLocal(), MatGetValues()
1965: @*/
1966: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1967: {

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

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

2008:   Not Collective

2010:   Input Parameters:
2011: + mat - the matrix
2012: . nb - the number of blocks
2013: . bs - the number of rows (and columns) in each block
2014: . rows - a concatenation of the rows for each block
2015: - v - a concatenation of logically two-dimensional arrays of values

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

2020:   Level: advanced

2022: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2023:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2024: @*/
2025: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2026: {

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

2036:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2037:   if (mat->ops->setvaluesbatch) {
2038:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2039:   } else {
2040:     PetscInt b;
2041:     for (b = 0; b < nb; ++b) {
2042:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2043:     }
2044:   }
2045:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2046:   return(0);
2047: }

2049: /*@
2050:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2051:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2052:    using a local (per-processor) numbering.

2054:    Not Collective

2056:    Input Parameters:
2057: +  x - the matrix
2058: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2059: - cmapping - column mapping

2061:    Level: intermediate


2064: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal(), MatGetValuesLocal()
2065: @*/
2066: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2067: {


2076:   if (x->ops->setlocaltoglobalmapping) {
2077:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2078:   } else {
2079:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2080:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2081:   }
2082:   return(0);
2083: }


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

2089:    Not Collective

2091:    Input Parameters:
2092: .  A - the matrix

2094:    Output Parameters:
2095: + rmapping - row mapping
2096: - cmapping - column mapping

2098:    Level: advanced


2101: .seealso:  MatSetValuesLocal()
2102: @*/
2103: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2104: {
2110:   if (rmapping) *rmapping = A->rmap->mapping;
2111:   if (cmapping) *cmapping = A->cmap->mapping;
2112:   return(0);
2113: }

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

2118:    Logically Collective on A

2120:    Input Parameters:
2121: +  A - the matrix
2122: . rmap - row layout
2123: - cmap - column layout

2125:    Level: advanced

2127: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatGetLayouts()
2128: @*/
2129: PetscErrorCode MatSetLayouts(Mat A,PetscLayout rmap,PetscLayout cmap)
2130: {


2136:   PetscLayoutReference(rmap,&A->rmap);
2137:   PetscLayoutReference(cmap,&A->cmap);
2138:   return(0);
2139: }

2141: /*@
2142:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2144:    Not Collective

2146:    Input Parameters:
2147: .  A - the matrix

2149:    Output Parameters:
2150: + rmap - row layout
2151: - cmap - column layout

2153:    Level: advanced

2155: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatSetLayouts()
2156: @*/
2157: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2158: {
2164:   if (rmap) *rmap = A->rmap;
2165:   if (cmap) *cmap = A->cmap;
2166:   return(0);
2167: }

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

2173:    Not Collective

2175:    Input Parameters:
2176: +  mat - the matrix
2177: .  nrow, irow - number of rows and their local indices
2178: .  ncol, icol - number of columns and their local indices
2179: .  y -  a logically two-dimensional array of values
2180: -  addv - either INSERT_VALUES or ADD_VALUES, where
2181:    ADD_VALUES adds values to any existing entries, and
2182:    INSERT_VALUES replaces existing entries with new values

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

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

2190:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2191:    options cannot be mixed without intervening calls to the assembly
2192:    routines.

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

2197:    Level: intermediate

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

2203: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2204:            MatSetValueLocal(), MatGetValuesLocal()
2205: @*/
2206: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2207: {

2213:   MatCheckPreallocated(mat,1);
2214:   if (!nrow || !ncol) return(0); /* no values to insert */
2217:   if (mat->insertmode == NOT_SET_VALUES) {
2218:     mat->insertmode = addv;
2219:   }
2220:   else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2221:   if (PetscDefined(USE_DEBUG)) {
2222:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2223:     if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2224:   }

2226:   if (mat->assembled) {
2227:     mat->was_assembled = PETSC_TRUE;
2228:     mat->assembled     = PETSC_FALSE;
2229:   }
2230:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2231:   if (mat->ops->setvalueslocal) {
2232:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2233:   } else {
2234:     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*irowm,*icolm;
2235:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2236:       irowm = buf; icolm = buf+nrow;
2237:     } else {
2238:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2239:       irowm = bufr; icolm = bufc;
2240:     }
2241:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2242:     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2243:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2244:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2245:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2246:     PetscFree2(bufr,bufc);
2247:   }
2248:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2249:   return(0);
2250: }

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

2256:    Not Collective

2258:    Input Parameters:
2259: +  x - the matrix
2260: .  nrow, irow - number of rows and their local indices
2261: .  ncol, icol - number of columns and their local indices
2262: .  y -  a logically two-dimensional array of values
2263: -  addv - either INSERT_VALUES or ADD_VALUES, where
2264:    ADD_VALUES adds values to any existing entries, and
2265:    INSERT_VALUES replaces existing entries with new values

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

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

2274:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2275:    options cannot be mixed without intervening calls to the assembly
2276:    routines.

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

2281:    Level: intermediate

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

2287: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2288:            MatSetValuesLocal(),  MatSetValuesBlocked()
2289: @*/
2290: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2291: {

2297:   MatCheckPreallocated(mat,1);
2298:   if (!nrow || !ncol) return(0); /* no values to insert */
2302:   if (mat->insertmode == NOT_SET_VALUES) {
2303:     mat->insertmode = addv;
2304:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2305:   if (PetscDefined(USE_DEBUG)) {
2306:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2307:     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);
2308:   }

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

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

2349:    Collective on Mat

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

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

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

2362:    Level: developer

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


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

2381:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2382:   (*mat->ops->multdiagonalblock)(mat,x,y);
2383:   PetscObjectStateIncrease((PetscObject)y);
2384:   return(0);
2385: }

2387: /* --------------------------------------------------------*/
2388: /*@
2389:    MatMult - Computes the matrix-vector product, y = Ax.

2391:    Neighbor-wise Collective on Mat

2393:    Input Parameters:
2394: +  mat - the matrix
2395: -  x   - the vector to be multiplied

2397:    Output Parameters:
2398: .  y - the result

2400:    Notes:
2401:    The vectors x and y cannot be the same.  I.e., one cannot
2402:    call MatMult(A,y,y).

2404:    Level: beginner

2406: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2407: @*/
2408: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2409: {

2417:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2418:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2419:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2420: #if !defined(PETSC_HAVE_CONSTRAINTS)
2421:   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);
2422:   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);
2423:   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);
2424: #endif
2425:   VecSetErrorIfLocked(y,3);
2426:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2427:   MatCheckPreallocated(mat,1);

2429:   VecLockReadPush(x);
2430:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2431:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2432:   (*mat->ops->mult)(mat,x,y);
2433:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2434:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2435:   VecLockReadPop(x);
2436:   return(0);
2437: }

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

2442:    Neighbor-wise Collective on Mat

2444:    Input Parameters:
2445: +  mat - the matrix
2446: -  x   - the vector to be multiplied

2448:    Output Parameters:
2449: .  y - the result

2451:    Notes:
2452:    The vectors x and y cannot be the same.  I.e., one cannot
2453:    call MatMultTranspose(A,y,y).

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

2458:    Level: beginner

2460: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2461: @*/
2462: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2463: {
2464:   PetscErrorCode (*op)(Mat,Vec,Vec)=NULL,ierr;


2472:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2473:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2474:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2475: #if !defined(PETSC_HAVE_CONSTRAINTS)
2476:   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);
2477:   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);
2478: #endif
2479:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2480:   MatCheckPreallocated(mat,1);

2482:   if (!mat->ops->multtranspose) {
2483:     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
2484:     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);
2485:   } else op = mat->ops->multtranspose;
2486:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2487:   VecLockReadPush(x);
2488:   (*op)(mat,x,y);
2489:   VecLockReadPop(x);
2490:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2491:   PetscObjectStateIncrease((PetscObject)y);
2492:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2493:   return(0);
2494: }

2496: /*@
2497:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2499:    Neighbor-wise Collective on Mat

2501:    Input Parameters:
2502: +  mat - the matrix
2503: -  x   - the vector to be multilplied

2505:    Output Parameters:
2506: .  y - the result

2508:    Notes:
2509:    The vectors x and y cannot be the same.  I.e., one cannot
2510:    call MatMultHermitianTranspose(A,y,y).

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

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

2516:    Level: beginner

2518: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2519: @*/
2520: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2521: {


2530:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2531:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2532:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2533: #if !defined(PETSC_HAVE_CONSTRAINTS)
2534:   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);
2535:   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);
2536: #endif
2537:   MatCheckPreallocated(mat,1);

2539:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2540: #if defined(PETSC_USE_COMPLEX)
2541:   if (mat->ops->multhermitiantranspose || (mat->hermitian && mat->ops->mult)) {
2542:     VecLockReadPush(x);
2543:     if (mat->ops->multhermitiantranspose) {
2544:       (*mat->ops->multhermitiantranspose)(mat,x,y);
2545:     } else {
2546:       (*mat->ops->mult)(mat,x,y);
2547:     }
2548:     VecLockReadPop(x);
2549:   } else {
2550:     Vec w;
2551:     VecDuplicate(x,&w);
2552:     VecCopy(x,w);
2553:     VecConjugate(w);
2554:     MatMultTranspose(mat,w,y);
2555:     VecDestroy(&w);
2556:     VecConjugate(y);
2557:   }
2558:   PetscObjectStateIncrease((PetscObject)y);
2559: #else
2560:   MatMultTranspose(mat,x,y);
2561: #endif
2562:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2563:   return(0);
2564: }

2566: /*@
2567:     MatMultAdd -  Computes v3 = v2 + A * v1.

2569:     Neighbor-wise Collective on Mat

2571:     Input Parameters:
2572: +   mat - the matrix
2573: -   v1, v2 - the vectors

2575:     Output Parameters:
2576: .   v3 - the result

2578:     Notes:
2579:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2580:     call MatMultAdd(A,v1,v2,v1).

2582:     Level: beginner

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


2597:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2598:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2599:   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);
2600:   /* 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);
2601:      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); */
2602:   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);
2603:   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);
2604:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2605:   MatCheckPreallocated(mat,1);

2607:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2608:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2609:   VecLockReadPush(v1);
2610:   (*mat->ops->multadd)(mat,v1,v2,v3);
2611:   VecLockReadPop(v1);
2612:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2613:   PetscObjectStateIncrease((PetscObject)v3);
2614:   return(0);
2615: }

2617: /*@
2618:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2620:    Neighbor-wise Collective on Mat

2622:    Input Parameters:
2623: +  mat - the matrix
2624: -  v1, v2 - the vectors

2626:    Output Parameters:
2627: .  v3 - the result

2629:    Notes:
2630:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2631:    call MatMultTransposeAdd(A,v1,v2,v1).

2633:    Level: beginner

2635: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2636: @*/
2637: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2638: {


2648:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2649:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2650:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2651:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2652:   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);
2653:   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);
2654:   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);
2655:   MatCheckPreallocated(mat,1);

2657:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2658:   VecLockReadPush(v1);
2659:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2660:   VecLockReadPop(v1);
2661:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2662:   PetscObjectStateIncrease((PetscObject)v3);
2663:   return(0);
2664: }

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

2669:    Neighbor-wise Collective on Mat

2671:    Input Parameters:
2672: +  mat - the matrix
2673: -  v1, v2 - the vectors

2675:    Output Parameters:
2676: .  v3 - the result

2678:    Notes:
2679:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2680:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2682:    Level: beginner

2684: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2685: @*/
2686: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2687: {


2697:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2698:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2699:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2700:   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);
2701:   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);
2702:   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);
2703:   MatCheckPreallocated(mat,1);

2705:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2706:   VecLockReadPush(v1);
2707:   if (mat->ops->multhermitiantransposeadd) {
2708:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2709:   } else {
2710:     Vec w,z;
2711:     VecDuplicate(v1,&w);
2712:     VecCopy(v1,w);
2713:     VecConjugate(w);
2714:     VecDuplicate(v3,&z);
2715:     MatMultTranspose(mat,w,z);
2716:     VecDestroy(&w);
2717:     VecConjugate(z);
2718:     if (v2 != v3) {
2719:       VecWAXPY(v3,1.0,v2,z);
2720:     } else {
2721:       VecAXPY(v3,1.0,z);
2722:     }
2723:     VecDestroy(&z);
2724:   }
2725:   VecLockReadPop(v1);
2726:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2727:   PetscObjectStateIncrease((PetscObject)v3);
2728:   return(0);
2729: }

2731: /*@
2732:    MatMultConstrained - The inner multiplication routine for a
2733:    constrained matrix P^T A P.

2735:    Neighbor-wise Collective on Mat

2737:    Input Parameters:
2738: +  mat - the matrix
2739: -  x   - the vector to be multilplied

2741:    Output Parameters:
2742: .  y - the result

2744:    Notes:
2745:    The vectors x and y cannot be the same.  I.e., one cannot
2746:    call MatMult(A,y,y).

2748:    Level: beginner

2750: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2751: @*/
2752: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2753: {

2760:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2761:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2762:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2763:   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);
2764:   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);
2765:   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);

2767:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2768:   VecLockReadPush(x);
2769:   (*mat->ops->multconstrained)(mat,x,y);
2770:   VecLockReadPop(x);
2771:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2772:   PetscObjectStateIncrease((PetscObject)y);
2773:   return(0);
2774: }

2776: /*@
2777:    MatMultTransposeConstrained - The inner multiplication routine for a
2778:    constrained matrix P^T A^T P.

2780:    Neighbor-wise Collective on Mat

2782:    Input Parameters:
2783: +  mat - the matrix
2784: -  x   - the vector to be multilplied

2786:    Output Parameters:
2787: .  y - the result

2789:    Notes:
2790:    The vectors x and y cannot be the same.  I.e., one cannot
2791:    call MatMult(A,y,y).

2793:    Level: beginner

2795: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2796: @*/
2797: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2798: {

2805:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2806:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2807:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2808:   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);
2809:   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);

2811:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2812:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2813:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2814:   PetscObjectStateIncrease((PetscObject)y);
2815:   return(0);
2816: }

2818: /*@C
2819:    MatGetFactorType - gets the type of factorization it is

2821:    Not Collective

2823:    Input Parameters:
2824: .  mat - the matrix

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

2829:    Level: intermediate

2831: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2832: @*/
2833: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2834: {
2839:   *t = mat->factortype;
2840:   return(0);
2841: }

2843: /*@C
2844:    MatSetFactorType - sets the type of factorization it is

2846:    Logically Collective on Mat

2848:    Input Parameters:
2849: +  mat - the matrix
2850: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2852:    Level: intermediate

2854: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2855: @*/
2856: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2857: {
2861:   mat->factortype = t;
2862:   return(0);
2863: }

2865: /* ------------------------------------------------------------*/
2866: /*@C
2867:    MatGetInfo - Returns information about matrix storage (number of
2868:    nonzeros, memory, etc.).

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

2872:    Input Parameters:
2873: .  mat - the matrix

2875:    Output Parameters:
2876: +  flag - flag indicating the type of parameters to be returned
2877:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2878:    MAT_GLOBAL_SUM - sum over all processors)
2879: -  info - matrix information context

2881:    Notes:
2882:    The MatInfo context contains a variety of matrix data, including
2883:    number of nonzeros allocated and used, number of mallocs during
2884:    matrix assembly, etc.  Additional information for factored matrices
2885:    is provided (such as the fill ratio, number of mallocs during
2886:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2887:    when using the runtime options
2888: $       -info -mat_view ::ascii_info

2890:    Example for C/C++ Users:
2891:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2892:    data within the MatInfo context.  For example,
2893: .vb
2894:       MatInfo info;
2895:       Mat     A;
2896:       double  mal, nz_a, nz_u;

2898:       MatGetInfo(A,MAT_LOCAL,&info);
2899:       mal  = info.mallocs;
2900:       nz_a = info.nz_allocated;
2901: .ve

2903:    Example for Fortran Users:
2904:    Fortran users should declare info as a double precision
2905:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2906:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2907:    a complete list of parameter names.
2908: .vb
2909:       double  precision info(MAT_INFO_SIZE)
2910:       double  precision mal, nz_a
2911:       Mat     A
2912:       integer ierr

2914:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2915:       mal = info(MAT_INFO_MALLOCS)
2916:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2917: .ve

2919:     Level: intermediate

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

2924: .seealso: MatStashGetInfo()

2926: @*/
2927: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2928: {

2935:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2936:   MatCheckPreallocated(mat,1);
2937:   (*mat->ops->getinfo)(mat,flag,info);
2938:   return(0);
2939: }

2941: /*
2942:    This is used by external packages where it is not easy to get the info from the actual
2943:    matrix factorization.
2944: */
2945: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2946: {

2950:   PetscMemzero(info,sizeof(MatInfo));
2951:   return(0);
2952: }

2954: /* ----------------------------------------------------------*/

2956: /*@C
2957:    MatLUFactor - Performs in-place LU factorization of matrix.

2959:    Collective on Mat

2961:    Input Parameters:
2962: +  mat - the matrix
2963: .  row - row permutation
2964: .  col - column permutation
2965: -  info - options for factorization, includes
2966: $          fill - expected fill as ratio of original fill.
2967: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2968: $                   Run with the option -info to determine an optimal value to use

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

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

2978:    Level: developer

2980: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2981:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2986: @*/
2987: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2988: {
2990:   MatFactorInfo  tinfo;

2998:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2999:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3000:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3001:   MatCheckPreallocated(mat,1);
3002:   if (!info) {
3003:     MatFactorInfoInitialize(&tinfo);
3004:     info = &tinfo;
3005:   }

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

3014: /*@C
3015:    MatILUFactor - Performs in-place ILU factorization of matrix.

3017:    Collective on Mat

3019:    Input Parameters:
3020: +  mat - the matrix
3021: .  row - row permutation
3022: .  col - column permutation
3023: -  info - structure containing
3024: $      levels - number of levels of fill.
3025: $      expected fill - as ratio of original fill.
3026: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3027:                 missing diagonal entries)

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

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

3037:    Level: developer

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

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

3044: @*/
3045: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3046: {

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

3061:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3062:   (*mat->ops->ilufactor)(mat,row,col,info);
3063:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3064:   PetscObjectStateIncrease((PetscObject)mat);
3065:   return(0);
3066: }

3068: /*@C
3069:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3070:    Call this routine before calling MatLUFactorNumeric().

3072:    Collective on Mat

3074:    Input Parameters:
3075: +  fact - the factor matrix obtained with MatGetFactor()
3076: .  mat - the matrix
3077: .  row, col - row and column permutations
3078: -  info - options for factorization, includes
3079: $          fill - expected fill as ratio of original fill.
3080: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3081: $                   Run with the option -info to determine an optimal value to use


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

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

3091:    Level: developer

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

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

3098: @*/
3099: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3100: {
3102:   MatFactorInfo  tinfo;

3111:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3112:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3113:   if (!(fact)->ops->lufactorsymbolic) {
3114:     MatSolverType stype;
3115:     MatFactorGetSolverType(fact,&stype);
3116:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,stype);
3117:   }
3118:   MatCheckPreallocated(mat,2);
3119:   if (!info) {
3120:     MatFactorInfoInitialize(&tinfo);
3121:     info = &tinfo;
3122:   }

3124:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3125:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3126:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3127:   PetscObjectStateIncrease((PetscObject)fact);
3128:   return(0);
3129: }

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

3135:    Collective on Mat

3137:    Input Parameters:
3138: +  fact - the factor matrix obtained with MatGetFactor()
3139: .  mat - the matrix
3140: -  info - options for factorization

3142:    Notes:
3143:    See MatLUFactor() for in-place factorization.  See
3144:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3150:    Level: developer

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

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

3157: @*/
3158: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3159: {
3160:   MatFactorInfo  tinfo;

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

3171:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3172:   MatCheckPreallocated(mat,2);
3173:   if (!info) {
3174:     MatFactorInfoInitialize(&tinfo);
3175:     info = &tinfo;
3176:   }

3178:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3179:   (fact->ops->lufactornumeric)(fact,mat,info);
3180:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3181:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3182:   PetscObjectStateIncrease((PetscObject)fact);
3183:   return(0);
3184: }

3186: /*@C
3187:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3188:    symmetric matrix.

3190:    Collective on Mat

3192:    Input Parameters:
3193: +  mat - the matrix
3194: .  perm - row and column permutations
3195: -  f - expected fill as ratio of original fill

3197:    Notes:
3198:    See MatLUFactor() for the nonsymmetric case.  See also
3199:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3205:    Level: developer

3207: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3208:           MatGetOrdering()

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

3213: @*/
3214: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3215: {
3217:   MatFactorInfo  tinfo;

3224:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3225:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3226:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3227:   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);
3228:   MatCheckPreallocated(mat,1);
3229:   if (!info) {
3230:     MatFactorInfoInitialize(&tinfo);
3231:     info = &tinfo;
3232:   }

3234:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3235:   (*mat->ops->choleskyfactor)(mat,perm,info);
3236:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3237:   PetscObjectStateIncrease((PetscObject)mat);
3238:   return(0);
3239: }

3241: /*@C
3242:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3243:    of a symmetric matrix.

3245:    Collective on Mat

3247:    Input Parameters:
3248: +  fact - the factor matrix obtained with MatGetFactor()
3249: .  mat - the matrix
3250: .  perm - row and column permutations
3251: -  info - options for factorization, includes
3252: $          fill - expected fill as ratio of original fill.
3253: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3254: $                   Run with the option -info to determine an optimal value to use

3256:    Notes:
3257:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3258:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3264:    Level: developer

3266: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3267:           MatGetOrdering()

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

3272: @*/
3273: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3274: {
3276:   MatFactorInfo  tinfo;

3284:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3285:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3286:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3287:   if (!(fact)->ops->choleskyfactorsymbolic) {
3288:     MatSolverType stype;
3289:     MatFactorGetSolverType(fact,&stype);
3290:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,stype);
3291:   }
3292:   MatCheckPreallocated(mat,2);
3293:   if (!info) {
3294:     MatFactorInfoInitialize(&tinfo);
3295:     info = &tinfo;
3296:   }

3298:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3299:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3300:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3301:   PetscObjectStateIncrease((PetscObject)fact);
3302:   return(0);
3303: }

3305: /*@C
3306:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3307:    of a symmetric matrix. Call this routine after first calling
3308:    MatCholeskyFactorSymbolic().

3310:    Collective on Mat

3312:    Input Parameters:
3313: +  fact - the factor matrix obtained with MatGetFactor()
3314: .  mat - the initial matrix
3315: .  info - options for factorization
3316: -  fact - the symbolic factor of mat


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

3324:    Level: developer

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

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

3331: @*/
3332: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3333: {
3334:   MatFactorInfo  tinfo;

3342:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3343:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3344:   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);
3345:   MatCheckPreallocated(mat,2);
3346:   if (!info) {
3347:     MatFactorInfoInitialize(&tinfo);
3348:     info = &tinfo;
3349:   }

3351:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3352:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3353:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3354:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3355:   PetscObjectStateIncrease((PetscObject)fact);
3356:   return(0);
3357: }

3359: /* ----------------------------------------------------------------*/
3360: /*@
3361:    MatSolve - Solves A x = b, given a factored matrix.

3363:    Neighbor-wise Collective on Mat

3365:    Input Parameters:
3366: +  mat - the factored matrix
3367: -  b - the right-hand-side vector

3369:    Output Parameter:
3370: .  x - the result vector

3372:    Notes:
3373:    The vectors b and x cannot be the same.  I.e., one cannot
3374:    call MatSolve(A,x,x).

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

3381:    Level: developer

3383: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3384: @*/
3385: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3386: {

3396:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3397:   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);
3398:   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);
3399:   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);
3400:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3401:   MatCheckPreallocated(mat,1);

3403:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3404:   if (mat->factorerrortype) {
3405:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3406:     VecSetInf(x);
3407:   } else {
3408:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3409:     (*mat->ops->solve)(mat,b,x);
3410:   }
3411:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3412:   PetscObjectStateIncrease((PetscObject)x);
3413:   return(0);
3414: }

3416: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3417: {
3419:   Vec            b,x;
3420:   PetscInt       m,N,i;
3421:   PetscScalar    *bb,*xx;

3424:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3425:   MatDenseGetArray(X,&xx);
3426:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3427:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3428:   MatCreateVecs(A,&x,&b);
3429:   for (i=0; i<N; i++) {
3430:     VecPlaceArray(b,bb + i*m);
3431:     VecPlaceArray(x,xx + i*m);
3432:     if (trans) {
3433:       MatSolveTranspose(A,b,x);
3434:     } else {
3435:       MatSolve(A,b,x);
3436:     }
3437:     VecResetArray(x);
3438:     VecResetArray(b);
3439:   }
3440:   VecDestroy(&b);
3441:   VecDestroy(&x);
3442:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3443:   MatDenseRestoreArray(X,&xx);
3444:   return(0);
3445: }

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

3450:    Neighbor-wise Collective on Mat

3452:    Input Parameters:
3453: +  A - the factored matrix
3454: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3456:    Output Parameter:
3457: .  X - the result matrix (dense matrix)

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

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

3469:    Level: developer

3471: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3472: @*/
3473: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3474: {

3484:   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);
3485:   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);
3486:   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");
3487:   if (!A->rmap->N && !A->cmap->N) return(0);
3488:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3489:   MatCheckPreallocated(A,1);

3491:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3492:   if (!A->ops->matsolve) {
3493:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3494:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3495:   } else {
3496:     (*A->ops->matsolve)(A,B,X);
3497:   }
3498:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3499:   PetscObjectStateIncrease((PetscObject)X);
3500:   return(0);
3501: }

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

3506:    Neighbor-wise Collective on Mat

3508:    Input Parameters:
3509: +  A - the factored matrix
3510: -  B - the right-hand-side matrix  (dense matrix)

3512:    Output Parameter:
3513: .  X - the result matrix (dense matrix)

3515:    Notes:
3516:    The matrices B and X cannot be the same.  I.e., one cannot
3517:    call MatMatSolveTranspose(A,X,X).

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

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

3527:    Level: developer

3529: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3530: @*/
3531: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3532: {

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

3551:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3552:   if (!A->ops->matsolvetranspose) {
3553:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3554:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3555:   } else {
3556:     (*A->ops->matsolvetranspose)(A,B,X);
3557:   }
3558:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3559:   PetscObjectStateIncrease((PetscObject)X);
3560:   return(0);
3561: }

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

3566:    Neighbor-wise Collective on Mat

3568:    Input Parameters:
3569: +  A - the factored matrix
3570: -  Bt - the transpose of right-hand-side matrix

3572:    Output Parameter:
3573: .  X - the result matrix (dense matrix)

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

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

3583:    Level: developer

3585: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3586: @*/
3587: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3588: {


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

3607:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3608:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3609:   (*A->ops->mattransposesolve)(A,Bt,X);
3610:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3611:   PetscObjectStateIncrease((PetscObject)X);
3612:   return(0);
3613: }

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

3619:    Neighbor-wise Collective on Mat

3621:    Input Parameters:
3622: +  mat - the factored matrix
3623: -  b - the right-hand-side vector

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

3628:    Notes:
3629:    MatSolve() should be used for most applications, as it performs
3630:    a forward solve followed by a backward solve.

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

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

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

3645:    Level: developer

3647: .seealso: MatSolve(), MatBackwardSolve()
3648: @*/
3649: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3650: {

3660:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3661:   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);
3662:   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);
3663:   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);
3664:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3665:   MatCheckPreallocated(mat,1);

3667:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3668:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3669:   (*mat->ops->forwardsolve)(mat,b,x);
3670:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3671:   PetscObjectStateIncrease((PetscObject)x);
3672:   return(0);
3673: }

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

3679:    Neighbor-wise Collective on Mat

3681:    Input Parameters:
3682: +  mat - the factored matrix
3683: -  b - the right-hand-side vector

3685:    Output Parameter:
3686: .  x - the result vector

3688:    Notes:
3689:    MatSolve() should be used for most applications, as it performs
3690:    a forward solve followed by a backward solve.

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

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

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

3705:    Level: developer

3707: .seealso: MatSolve(), MatForwardSolve()
3708: @*/
3709: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3710: {

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

3727:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3728:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3729:   (*mat->ops->backwardsolve)(mat,b,x);
3730:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3731:   PetscObjectStateIncrease((PetscObject)x);
3732:   return(0);
3733: }

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

3738:    Neighbor-wise Collective on Mat

3740:    Input Parameters:
3741: +  mat - the factored matrix
3742: .  b - the right-hand-side vector
3743: -  y - the vector to be added to

3745:    Output Parameter:
3746: .  x - the result vector

3748:    Notes:
3749:    The vectors b and x cannot be the same.  I.e., one cannot
3750:    call MatSolveAdd(A,x,y,x).

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

3756:    Level: developer

3758: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3759: @*/
3760: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3761: {
3762:   PetscScalar    one = 1.0;
3763:   Vec            tmp;

3775:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3776:   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);
3777:   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);
3778:   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);
3779:   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);
3780:   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);
3781:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3782:    MatCheckPreallocated(mat,1);

3784:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3785:   if (mat->factorerrortype) {
3786:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3787:     VecSetInf(x);
3788:   } else if (mat->ops->solveadd) {
3789:     (*mat->ops->solveadd)(mat,b,y,x);
3790:   } else {
3791:     /* do the solve then the add manually */
3792:     if (x != y) {
3793:       MatSolve(mat,b,x);
3794:       VecAXPY(x,one,y);
3795:     } else {
3796:       VecDuplicate(x,&tmp);
3797:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3798:       VecCopy(x,tmp);
3799:       MatSolve(mat,b,x);
3800:       VecAXPY(x,one,tmp);
3801:       VecDestroy(&tmp);
3802:     }
3803:   }
3804:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3805:   PetscObjectStateIncrease((PetscObject)x);
3806:   return(0);
3807: }

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

3812:    Neighbor-wise Collective on Mat

3814:    Input Parameters:
3815: +  mat - the factored matrix
3816: -  b - the right-hand-side vector

3818:    Output Parameter:
3819: .  x - the result vector

3821:    Notes:
3822:    The vectors b and x cannot be the same.  I.e., one cannot
3823:    call MatSolveTranspose(A,x,x).

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

3829:    Level: developer

3831: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3832: @*/
3833: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3834: {

3844:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3845:   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);
3846:   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);
3847:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3848:   MatCheckPreallocated(mat,1);
3849:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3850:   if (mat->factorerrortype) {
3851:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3852:     VecSetInf(x);
3853:   } else {
3854:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3855:     (*mat->ops->solvetranspose)(mat,b,x);
3856:   }
3857:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3858:   PetscObjectStateIncrease((PetscObject)x);
3859:   return(0);
3860: }

3862: /*@
3863:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3864:                       factored matrix.

3866:    Neighbor-wise Collective on Mat

3868:    Input Parameters:
3869: +  mat - the factored matrix
3870: .  b - the right-hand-side vector
3871: -  y - the vector to be added to

3873:    Output Parameter:
3874: .  x - the result vector

3876:    Notes:
3877:    The vectors b and x cannot be the same.  I.e., one cannot
3878:    call MatSolveTransposeAdd(A,x,y,x).

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

3884:    Level: developer

3886: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3887: @*/
3888: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3889: {
3890:   PetscScalar    one = 1.0;
3892:   Vec            tmp;

3903:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3904:   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);
3905:   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);
3906:   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);
3907:   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);
3908:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3909:    MatCheckPreallocated(mat,1);

3911:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3912:   if (mat->factorerrortype) {
3913:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3914:     VecSetInf(x);
3915:   } else if (mat->ops->solvetransposeadd){
3916:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
3917:   } else {
3918:     /* do the solve then the add manually */
3919:     if (x != y) {
3920:       MatSolveTranspose(mat,b,x);
3921:       VecAXPY(x,one,y);
3922:     } else {
3923:       VecDuplicate(x,&tmp);
3924:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3925:       VecCopy(x,tmp);
3926:       MatSolveTranspose(mat,b,x);
3927:       VecAXPY(x,one,tmp);
3928:       VecDestroy(&tmp);
3929:     }
3930:   }
3931:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3932:   PetscObjectStateIncrease((PetscObject)x);
3933:   return(0);
3934: }
3935: /* ----------------------------------------------------------------*/

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

3940:    Neighbor-wise Collective on Mat

3942:    Input Parameters:
3943: +  mat - the matrix
3944: .  b - the right hand side
3945: .  omega - the relaxation factor
3946: .  flag - flag indicating the type of SOR (see below)
3947: .  shift -  diagonal shift
3948: .  its - the number of iterations
3949: -  lits - the number of local iterations

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

3954:    SOR Flags:
3955: +     SOR_FORWARD_SWEEP - forward SOR
3956: .     SOR_BACKWARD_SWEEP - backward SOR
3957: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3958: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3959: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3960: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3961: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3962:          upper/lower triangular part of matrix to
3963:          vector (with omega)
3964: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

3966:    Notes:
3967:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3968:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3969:    on each processor.

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

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

3977:    Notes for Advanced Users:
3978:    The flags are implemented as bitwise inclusive or operations.
3979:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3980:    to specify a zero initial guess for SSOR.

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

3986:    Vectors x and b CANNOT be the same

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

3990:    Level: developer

3992: @*/
3993: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3994: {

4004:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4005:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4006:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4007:   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);
4008:   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);
4009:   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);
4010:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
4011:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
4012:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

4014:   MatCheckPreallocated(mat,1);
4015:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
4016:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
4017:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
4018:   PetscObjectStateIncrease((PetscObject)x);
4019:   return(0);
4020: }

4022: /*
4023:       Default matrix copy routine.
4024: */
4025: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4026: {
4027:   PetscErrorCode    ierr;
4028:   PetscInt          i,rstart = 0,rend = 0,nz;
4029:   const PetscInt    *cwork;
4030:   const PetscScalar *vwork;

4033:   if (B->assembled) {
4034:     MatZeroEntries(B);
4035:   }
4036:   if (str == SAME_NONZERO_PATTERN) {
4037:     MatGetOwnershipRange(A,&rstart,&rend);
4038:     for (i=rstart; i<rend; i++) {
4039:       MatGetRow(A,i,&nz,&cwork,&vwork);
4040:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
4041:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
4042:     }
4043:   } else {
4044:     MatAYPX(B,0.0,A,str);
4045:   }
4046:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4047:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4048:   return(0);
4049: }

4051: /*@
4052:    MatCopy - Copies a matrix to another matrix.

4054:    Collective on Mat

4056:    Input Parameters:
4057: +  A - the matrix
4058: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4060:    Output Parameter:
4061: .  B - where the copy is put

4063:    Notes:
4064:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4065:    same nonzero pattern or the routine will crash.

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

4071:    Level: intermediate

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

4075: @*/
4076: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4077: {
4079:   PetscInt       i;

4087:   MatCheckPreallocated(B,2);
4088:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4089:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4090:   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);
4091:   MatCheckPreallocated(A,1);
4092:   if (A == B) return(0);

4094:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4095:   if (A->ops->copy) {
4096:     (*A->ops->copy)(A,B,str);
4097:   } else { /* generic conversion */
4098:     MatCopy_Basic(A,B,str);
4099:   }

4101:   B->stencil.dim = A->stencil.dim;
4102:   B->stencil.noc = A->stencil.noc;
4103:   for (i=0; i<=A->stencil.dim; i++) {
4104:     B->stencil.dims[i]   = A->stencil.dims[i];
4105:     B->stencil.starts[i] = A->stencil.starts[i];
4106:   }

4108:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4109:   PetscObjectStateIncrease((PetscObject)B);
4110:   return(0);
4111: }

4113: /*@C
4114:    MatConvert - Converts a matrix to another matrix, either of the same
4115:    or different type.

4117:    Collective on Mat

4119:    Input Parameters:
4120: +  mat - the matrix
4121: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4122:    same type as the original matrix.
4123: -  reuse - denotes if the destination matrix is to be created or reused.
4124:    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
4125:    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).

4127:    Output Parameter:
4128: .  M - pointer to place new matrix

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

4135:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4136:    the MPI communicator of the generated matrix is always the same as the communicator
4137:    of the input matrix.

4139:    Level: intermediate

4141: .seealso: MatCopy(), MatDuplicate()
4142: @*/
4143: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4144: {
4146:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4147:   char           convname[256],mtype[256];
4148:   Mat            B;

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

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

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

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

4171:   /* Cache Mat options because some converter use MatHeaderReplace  */
4172:   issymmetric = mat->symmetric;
4173:   ishermitian = mat->hermitian;

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

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

4228:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4229:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4230:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4231:     MatSetType(B,newtype);
4232:     for (i=0; i<3; i++) {
4233:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4234:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4235:       PetscStrlcat(convname,"_",sizeof(convname));
4236:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4237:       PetscStrlcat(convname,newtype,sizeof(convname));
4238:       PetscStrlcat(convname,"_C",sizeof(convname));
4239:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4240:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4241:       if (conv) {
4242:         MatDestroy(&B);
4243:         goto foundconv;
4244:       }
4245:     }

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

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

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

4259:     /* 5) Use a really basic converter. */
4260:     PetscInfo(mat,"Using MatConvert_Basic\n");
4261:     conv = MatConvert_Basic;

4263: foundconv:
4264:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4265:     (*conv)(mat,newtype,reuse,M);
4266:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4267:       /* the block sizes must be same if the mappings are copied over */
4268:       (*M)->rmap->bs = mat->rmap->bs;
4269:       (*M)->cmap->bs = mat->cmap->bs;
4270:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4271:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4272:       (*M)->rmap->mapping = mat->rmap->mapping;
4273:       (*M)->cmap->mapping = mat->cmap->mapping;
4274:     }
4275:     (*M)->stencil.dim = mat->stencil.dim;
4276:     (*M)->stencil.noc = mat->stencil.noc;
4277:     for (i=0; i<=mat->stencil.dim; i++) {
4278:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4279:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4280:     }
4281:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4282:   }
4283:   PetscObjectStateIncrease((PetscObject)*M);

4285:   /* Copy Mat options */
4286:   if (issymmetric) {
4287:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4288:   }
4289:   if (ishermitian) {
4290:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4291:   }
4292:   return(0);
4293: }

4295: /*@C
4296:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4298:    Not Collective

4300:    Input Parameter:
4301: .  mat - the matrix, must be a factored matrix

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

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

4310:    Level: intermediate

4312: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4313: @*/
4314: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4315: {
4316:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4321:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4322:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4323:   if (!conv) {
4324:     *type = MATSOLVERPETSC;
4325:   } else {
4326:     (*conv)(mat,type);
4327:   }
4328:   return(0);
4329: }

4331: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4332: struct _MatSolverTypeForSpecifcType {
4333:   MatType                        mtype;
4334:   PetscErrorCode                 (*createfactor[4])(Mat,MatFactorType,Mat*);
4335:   MatSolverTypeForSpecifcType next;
4336: };

4338: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4339: struct _MatSolverTypeHolder {
4340:   char                        *name;
4341:   MatSolverTypeForSpecifcType handlers;
4342:   MatSolverTypeHolder         next;
4343: };

4345: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4350:    Input Parameters:
4351: +    package - name of the package, for example petsc or superlu
4352: .    mtype - the matrix type that works with this package
4353: .    ftype - the type of factorization supported by the package
4354: -    createfactor - routine that will create the factored matrix ready to be used

4356:     Level: intermediate

4358: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4359: @*/
4360: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*createfactor)(Mat,MatFactorType,Mat*))
4361: {
4362:   PetscErrorCode              ierr;
4363:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4364:   PetscBool                   flg;
4365:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4368:   MatInitializePackage();
4369:   if (!next) {
4370:     PetscNew(&MatSolverTypeHolders);
4371:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4372:     PetscNew(&MatSolverTypeHolders->handlers);
4373:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4374:     MatSolverTypeHolders->handlers->createfactor[(int)ftype-1] = createfactor;
4375:     return(0);
4376:   }
4377:   while (next) {
4378:     PetscStrcasecmp(package,next->name,&flg);
4379:     if (flg) {
4380:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4381:       inext = next->handlers;
4382:       while (inext) {
4383:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4384:         if (flg) {
4385:           inext->createfactor[(int)ftype-1] = createfactor;
4386:           return(0);
4387:         }
4388:         iprev = inext;
4389:         inext = inext->next;
4390:       }
4391:       PetscNew(&iprev->next);
4392:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4393:       iprev->next->createfactor[(int)ftype-1] = createfactor;
4394:       return(0);
4395:     }
4396:     prev = next;
4397:     next = next->next;
4398:   }
4399:   PetscNew(&prev->next);
4400:   PetscStrallocpy(package,&prev->next->name);
4401:   PetscNew(&prev->next->handlers);
4402:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4403:   prev->next->handlers->createfactor[(int)ftype-1] = createfactor;
4404:   return(0);
4405: }

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

4410:    Input Parameters:
4411: +    type - name of the package, for example petsc or superlu
4412: .    ftype - the type of factorization supported by the type
4413: -    mtype - the matrix type that works with this type

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

4420:     Level: intermediate

4422: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatSolvePackageRegister), MatGetFactor()
4423: @*/
4424: PetscErrorCode MatSolverTypeGet(MatSolverType type,MatType mtype,MatFactorType ftype,PetscBool *foundtype,PetscBool *foundmtype,PetscErrorCode (**createfactor)(Mat,MatFactorType,Mat*))
4425: {
4426:   PetscErrorCode              ierr;
4427:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4428:   PetscBool                   flg;
4429:   MatSolverTypeForSpecifcType inext;

4432:   if (foundtype) *foundtype = PETSC_FALSE;
4433:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4434:   if (createfactor) *createfactor    = NULL;

4436:   if (type) {
4437:     while (next) {
4438:       PetscStrcasecmp(type,next->name,&flg);
4439:       if (flg) {
4440:         if (foundtype) *foundtype = PETSC_TRUE;
4441:         inext = next->handlers;
4442:         while (inext) {
4443:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4444:           if (flg) {
4445:             if (foundmtype) *foundmtype = PETSC_TRUE;
4446:             if (createfactor)  *createfactor  = inext->createfactor[(int)ftype-1];
4447:             return(0);
4448:           }
4449:           inext = inext->next;
4450:         }
4451:       }
4452:       next = next->next;
4453:     }
4454:   } else {
4455:     while (next) {
4456:       inext = next->handlers;
4457:       while (inext) {
4458:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4459:         if (flg && inext->createfactor[(int)ftype-1]) {
4460:           if (foundtype) *foundtype = PETSC_TRUE;
4461:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4462:           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4463:           return(0);
4464:         }
4465:         inext = inext->next;
4466:       }
4467:       next = next->next;
4468:     }
4469:   }
4470:   return(0);
4471: }

4473: PetscErrorCode MatSolverTypeDestroy(void)
4474: {
4475:   PetscErrorCode              ierr;
4476:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4477:   MatSolverTypeForSpecifcType inext,iprev;

4480:   while (next) {
4481:     PetscFree(next->name);
4482:     inext = next->handlers;
4483:     while (inext) {
4484:       PetscFree(inext->mtype);
4485:       iprev = inext;
4486:       inext = inext->next;
4487:       PetscFree(iprev);
4488:     }
4489:     prev = next;
4490:     next = next->next;
4491:     PetscFree(prev);
4492:   }
4493:   MatSolverTypeHolders = NULL;
4494:   return(0);
4495: }

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

4500:    Logically Collective on Mat

4502:    Input Parameters:
4503: .  mat - the matrix

4505:    Output Parameters:
4506: .  flg - PETSC_TRUE if uses the ordering

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

4512:    Level: developer

4514: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4515: @*/
4516: PetscErrorCode MatFactorGetUseOrdering(Mat mat, PetscBool *flg)
4517: {
4519:   *flg = mat->useordering;
4520:   return(0);
4521: }

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

4526:    Collective on Mat

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

4533:    Output Parameters:
4534: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4536:    Notes:
4537:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4538:      such as pastix, superlu, mumps etc.

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

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

4545:    Level: intermediate

4547: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetUseOrdering(), MatSolverTypeRegister()
4548: @*/
4549: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4550: {
4551:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4552:   PetscBool      foundtype,foundmtype;


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

4561:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundtype,&foundmtype,&conv);
4562:   if (!foundtype) {
4563:     if (type) {
4564:       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);
4565:     } else {
4566:       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);
4567:     }
4568:   }
4569:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4570:   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);

4572:   (*conv)(mat,ftype,f);
4573:   return(0);
4574: }

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

4579:    Not Collective

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

4586:    Output Parameter:
4587: .    flg - PETSC_TRUE if the factorization is available

4589:    Notes:
4590:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4591:      such as pastix, superlu, mumps etc.

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

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

4598:    Level: intermediate

4600: .seealso: MatCopy(), MatDuplicate(), MatGetFactor(), MatSolverTypeRegister()
4601: @*/
4602: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4603: {
4604:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4613:   *flg = PETSC_FALSE;
4614:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4615:   if (gconv) {
4616:     *flg = PETSC_TRUE;
4617:   }
4618:   return(0);
4619: }

4621: #include <petscdmtypes.h>

4623: /*@
4624:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4626:    Collective on Mat

4628:    Input Parameters:
4629: +  mat - the matrix
4630: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4631:         See the manual page for MatDuplicateOption for an explanation of these options.

4633:    Output Parameter:
4634: .  M - pointer to place new matrix

4636:    Level: intermediate

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

4642: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4643: @*/
4644: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4645: {
4647:   Mat            B;
4648:   PetscInt       i;
4649:   DM             dm;
4650:   void           (*viewf)(void);

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

4660:   *M = NULL;
4661:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4662:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4663:   (*mat->ops->duplicate)(mat,op,M);
4664:   B    = *M;

4666:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4667:   if (viewf) {
4668:     MatSetOperation(B,MATOP_VIEW,viewf);
4669:   }

4671:   B->stencil.dim = mat->stencil.dim;
4672:   B->stencil.noc = mat->stencil.noc;
4673:   for (i=0; i<=mat->stencil.dim; i++) {
4674:     B->stencil.dims[i]   = mat->stencil.dims[i];
4675:     B->stencil.starts[i] = mat->stencil.starts[i];
4676:   }

4678:   B->nooffproczerorows = mat->nooffproczerorows;
4679:   B->nooffprocentries  = mat->nooffprocentries;

4681:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4682:   if (dm) {
4683:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4684:   }
4685:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4686:   PetscObjectStateIncrease((PetscObject)B);
4687:   return(0);
4688: }

4690: /*@
4691:    MatGetDiagonal - Gets the diagonal of a matrix.

4693:    Logically Collective on Mat

4695:    Input Parameters:
4696: +  mat - the matrix
4697: -  v - the vector for storing the diagonal

4699:    Output Parameter:
4700: .  v - the diagonal of the matrix

4702:    Level: intermediate

4704:    Note:
4705:    Currently only correct in parallel for square matrices.

4707: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4708: @*/
4709: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4710: {

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

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

4726: /*@C
4727:    MatGetRowMin - Gets the minimum value (of the real part) of each
4728:         row of the matrix

4730:    Logically Collective on Mat

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

4735:    Output Parameter:
4736: +  v - the vector for storing the maximums
4737: -  idx - the indices of the column found for each row (optional)

4739:    Level: intermediate

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

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

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

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

4760:   if (!mat->cmap->N) {
4761:     VecSet(v,PETSC_MAX_REAL);
4762:     if (idx) {
4763:       PetscInt i,m = mat->rmap->n;
4764:       for (i=0; i<m; i++) idx[i] = -1;
4765:     }
4766:   } else {
4767:     if (!mat->ops->getrowmin) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4768:     MatCheckPreallocated(mat,1);
4769:   }
4770:   (*mat->ops->getrowmin)(mat,v,idx);
4771:   PetscObjectStateIncrease((PetscObject)v);
4772:   return(0);
4773: }

4775: /*@C
4776:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4777:         row of the matrix

4779:    Logically Collective on Mat

4781:    Input Parameters:
4782: .  mat - the matrix

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

4788:    Level: intermediate

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

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

4796: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4797: @*/
4798: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4799: {

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

4809:   if (!mat->cmap->N) {
4810:     VecSet(v,0.0);
4811:     if (idx) {
4812:       PetscInt i,m = mat->rmap->n;
4813:       for (i=0; i<m; i++) idx[i] = -1;
4814:     }
4815:   } else {
4816:     if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4817:     MatCheckPreallocated(mat,1);
4818:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4819:     (*mat->ops->getrowminabs)(mat,v,idx);
4820:   }
4821:   PetscObjectStateIncrease((PetscObject)v);
4822:   return(0);
4823: }

4825: /*@C
4826:    MatGetRowMax - Gets the maximum value (of the real part) of each
4827:         row of the matrix

4829:    Logically Collective on Mat

4831:    Input Parameters:
4832: .  mat - the matrix

4834:    Output Parameter:
4835: +  v - the vector for storing the maximums
4836: -  idx - the indices of the column found for each row (optional)

4838:    Level: intermediate

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

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

4846: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4847: @*/
4848: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4849: {

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

4858:   if (!mat->cmap->N) {
4859:     VecSet(v,PETSC_MIN_REAL);
4860:     if (idx) {
4861:       PetscInt i,m = mat->rmap->n;
4862:       for (i=0; i<m; i++) idx[i] = -1;
4863:     }
4864:   } else {
4865:     if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4866:     MatCheckPreallocated(mat,1);
4867:     (*mat->ops->getrowmax)(mat,v,idx);
4868:   }
4869:   PetscObjectStateIncrease((PetscObject)v);
4870:   return(0);
4871: }

4873: /*@C
4874:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4875:         row of the matrix

4877:    Logically Collective on Mat

4879:    Input Parameters:
4880: .  mat - the matrix

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

4886:    Level: intermediate

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

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

4894: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4895: @*/
4896: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4897: {

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

4906:   if (!mat->cmap->N) {
4907:     VecSet(v,0.0);
4908:     if (idx) {
4909:       PetscInt i,m = mat->rmap->n;
4910:       for (i=0; i<m; i++) idx[i] = -1;
4911:     }
4912:   } else {
4913:     if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4914:     MatCheckPreallocated(mat,1);
4915:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4916:     (*mat->ops->getrowmaxabs)(mat,v,idx);
4917:   }
4918:   PetscObjectStateIncrease((PetscObject)v);
4919:   return(0);
4920: }

4922: /*@
4923:    MatGetRowSum - Gets the sum of each row of the matrix

4925:    Logically or Neighborhood Collective on Mat

4927:    Input Parameters:
4928: .  mat - the matrix

4930:    Output Parameter:
4931: .  v - the vector for storing the sum of rows

4933:    Level: intermediate

4935:    Notes:
4936:     This code is slow since it is not currently specialized for different formats

4938: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4939: @*/
4940: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4941: {
4942:   Vec            ones;

4949:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4950:   MatCheckPreallocated(mat,1);
4951:   MatCreateVecs(mat,&ones,NULL);
4952:   VecSet(ones,1.);
4953:   MatMult(mat,ones,v);
4954:   VecDestroy(&ones);
4955:   return(0);
4956: }

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

4961:    Collective on Mat

4963:    Input Parameter:
4964: +  mat - the matrix to transpose
4965: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4967:    Output Parameters:
4968: .  B - the transpose

4970:    Notes:
4971:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4977:    Level: intermediate

4979: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4980: @*/
4981: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4982: {

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

4995:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4996:   (*mat->ops->transpose)(mat,reuse,B);
4997:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4998:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4999:   return(0);
5000: }

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

5006:    Collective on Mat

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

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

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

5020:    Level: intermediate

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

5032:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
5033:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
5034:   *flg = PETSC_FALSE;
5035:   if (f && g) {
5036:     if (f == g) {
5037:       (*f)(A,B,tol,flg);
5038:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
5039:   } else {
5040:     MatType mattype;
5041:     if (!f) {
5042:       MatGetType(A,&mattype);
5043:     } else {
5044:       MatGetType(B,&mattype);
5045:     }
5046:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
5047:   }
5048:   return(0);
5049: }

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

5054:    Collective on Mat

5056:    Input Parameter:
5057: +  mat - the matrix to transpose and complex conjugate
5058: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

5060:    Output Parameters:
5061: .  B - the Hermitian

5063:    Level: intermediate

5065: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5066: @*/
5067: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5068: {

5072:   MatTranspose(mat,reuse,B);
5073: #if defined(PETSC_USE_COMPLEX)
5074:   MatConjugate(*B);
5075: #endif
5076:   return(0);
5077: }

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

5082:    Collective on Mat

5084:    Input Parameter:
5085: +  A - the matrix to test
5086: -  B - the matrix to test against, this can equal the first parameter

5088:    Output Parameters:
5089: .  flg - the result

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

5096:    Level: intermediate

5098: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5099: @*/
5100: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5101: {
5102:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5108:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5109:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5110:   if (f && g) {
5111:     if (f==g) {
5112:       (*f)(A,B,tol,flg);
5113:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5114:   }
5115:   return(0);
5116: }

5118: /*@
5119:    MatPermute - Creates a new matrix with rows and columns permuted from the
5120:    original.

5122:    Collective on Mat

5124:    Input Parameters:
5125: +  mat - the matrix to permute
5126: .  row - row permutation, each processor supplies only the permutation for its rows
5127: -  col - column permutation, each processor supplies only the permutation for its columns

5129:    Output Parameters:
5130: .  B - the permuted matrix

5132:    Level: advanced

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

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

5140: @*/
5141: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5142: {

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

5156:   (*mat->ops->permute)(mat,row,col,B);
5157:   PetscObjectStateIncrease((PetscObject)*B);
5158:   return(0);
5159: }

5161: /*@
5162:    MatEqual - Compares two matrices.

5164:    Collective on Mat

5166:    Input Parameters:
5167: +  A - the first matrix
5168: -  B - the second matrix

5170:    Output Parameter:
5171: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5173:    Level: intermediate

5175: @*/
5176: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5177: {

5187:   MatCheckPreallocated(B,2);
5188:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5189:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5190:   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);
5191:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5192:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5193:   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);
5194:   MatCheckPreallocated(A,1);

5196:   (*A->ops->equal)(A,B,flg);
5197:   return(0);
5198: }

5200: /*@
5201:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5202:    matrices that are stored as vectors.  Either of the two scaling
5203:    matrices can be NULL.

5205:    Collective on Mat

5207:    Input Parameters:
5208: +  mat - the matrix to be scaled
5209: .  l - the left scaling vector (or NULL)
5210: -  r - the right scaling vector (or NULL)

5212:    Notes:
5213:    MatDiagonalScale() computes A = LAR, where
5214:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5215:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5217:    Level: intermediate


5220: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5221: @*/
5222: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5223: {

5231:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5232:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5233:   MatCheckPreallocated(mat,1);
5234:   if (!l && !r) return(0);

5236:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5237:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5238:   (*mat->ops->diagonalscale)(mat,l,r);
5239:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5240:   PetscObjectStateIncrease((PetscObject)mat);
5241:   return(0);
5242: }

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

5247:     Logically Collective on Mat

5249:     Input Parameters:
5250: +   mat - the matrix to be scaled
5251: -   a  - the scaling value

5253:     Output Parameter:
5254: .   mat - the scaled matrix

5256:     Level: intermediate

5258: .seealso: MatDiagonalScale()
5259: @*/
5260: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5261: {

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

5273:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5274:   if (a != (PetscScalar)1.0) {
5275:     (*mat->ops->scale)(mat,a);
5276:     PetscObjectStateIncrease((PetscObject)mat);
5277:   }
5278:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5279:   return(0);
5280: }

5282: /*@
5283:    MatNorm - Calculates various norms of a matrix.

5285:    Collective on Mat

5287:    Input Parameters:
5288: +  mat - the matrix
5289: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5291:    Output Parameters:
5292: .  nrm - the resulting norm

5294:    Level: intermediate

5296: @*/
5297: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5298: {


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

5311:   (*mat->ops->norm)(mat,type,nrm);
5312:   return(0);
5313: }

5315: /*
5316:      This variable is used to prevent counting of MatAssemblyBegin() that
5317:    are called from within a MatAssemblyEnd().
5318: */
5319: static PetscInt MatAssemblyEnd_InUse = 0;
5320: /*@
5321:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5322:    be called after completing all calls to MatSetValues().

5324:    Collective on Mat

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

5330:    Notes:
5331:    MatSetValues() generally caches the values.  The matrix is ready to
5332:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5333:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5334:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5335:    using the matrix.

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

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

5345:    Level: beginner

5347: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5348: @*/
5349: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5350: {

5356:   MatCheckPreallocated(mat,1);
5357:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5358:   if (mat->assembled) {
5359:     mat->was_assembled = PETSC_TRUE;
5360:     mat->assembled     = PETSC_FALSE;
5361:   }

5363:   if (!MatAssemblyEnd_InUse) {
5364:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5365:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5366:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5367:   } else if (mat->ops->assemblybegin) {
5368:     (*mat->ops->assemblybegin)(mat,type);
5369:   }
5370:   return(0);
5371: }

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

5377:    Not Collective

5379:    Input Parameter:
5380: .  mat - the matrix

5382:    Output Parameter:
5383: .  assembled - PETSC_TRUE or PETSC_FALSE

5385:    Level: advanced

5387: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5388: @*/
5389: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5390: {
5394:   *assembled = mat->assembled;
5395:   return(0);
5396: }

5398: /*@
5399:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5400:    be called after MatAssemblyBegin().

5402:    Collective on Mat

5404:    Input Parameters:
5405: +  mat - the matrix
5406: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5408:    Options Database Keys:
5409: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5410: .  -mat_view ::ascii_info_detail - Prints more detailed info
5411: .  -mat_view - Prints matrix in ASCII format
5412: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5413: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5414: .  -display <name> - Sets display name (default is host)
5415: .  -draw_pause <sec> - Sets number of seconds to pause after display
5416: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab)
5417: .  -viewer_socket_machine <machine> - Machine to use for socket
5418: .  -viewer_socket_port <port> - Port number to use for socket
5419: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5421:    Notes:
5422:    MatSetValues() generally caches the values.  The matrix is ready to
5423:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5424:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5425:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5426:    using the matrix.

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

5432:    Level: beginner

5434: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5435: @*/
5436: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5437: {
5438:   PetscErrorCode  ierr;
5439:   static PetscInt inassm = 0;
5440:   PetscBool       flg    = PETSC_FALSE;


5446:   inassm++;
5447:   MatAssemblyEnd_InUse++;
5448:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5449:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5450:     if (mat->ops->assemblyend) {
5451:       (*mat->ops->assemblyend)(mat,type);
5452:     }
5453:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5454:   } else if (mat->ops->assemblyend) {
5455:     (*mat->ops->assemblyend)(mat,type);
5456:   }

5458:   /* Flush assembly is not a true assembly */
5459:   if (type != MAT_FLUSH_ASSEMBLY) {
5460:     mat->num_ass++;
5461:     mat->assembled        = PETSC_TRUE;
5462:     mat->ass_nonzerostate = mat->nonzerostate;
5463:   }

5465:   mat->insertmode = NOT_SET_VALUES;
5466:   MatAssemblyEnd_InUse--;
5467:   PetscObjectStateIncrease((PetscObject)mat);
5468:   if (!mat->symmetric_eternal) {
5469:     mat->symmetric_set              = PETSC_FALSE;
5470:     mat->hermitian_set              = PETSC_FALSE;
5471:     mat->structurally_symmetric_set = PETSC_FALSE;
5472:   }
5473:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5474:     MatViewFromOptions(mat,NULL,"-mat_view");

5476:     if (mat->checksymmetryonassembly) {
5477:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5478:       if (flg) {
5479:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5480:       } else {
5481:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5482:       }
5483:     }
5484:     if (mat->nullsp && mat->checknullspaceonassembly) {
5485:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5486:     }
5487:   }
5488:   inassm--;
5489:   return(0);
5490: }

5492: /*@
5493:    MatSetOption - Sets a parameter option for a matrix. Some options
5494:    may be specific to certain storage formats.  Some options
5495:    determine how values will be inserted (or added). Sorted,
5496:    row-oriented input will generally assemble the fastest. The default
5497:    is row-oriented.

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

5501:    Input Parameters:
5502: +  mat - the matrix
5503: .  option - the option, one of those listed below (and possibly others),
5504: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5506:   Options Describing Matrix Structure:
5507: +    MAT_SPD - symmetric positive definite
5508: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5509: .    MAT_HERMITIAN - transpose is the complex conjugation
5510: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5511: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5512:                             you set to be kept with all future use of the matrix
5513:                             including after MatAssemblyBegin/End() which could
5514:                             potentially change the symmetry structure, i.e. you
5515:                             KNOW the matrix will ALWAYS have the property you set.
5516:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5517:                             the relevant flags must be set independently.


5520:    Options For Use with MatSetValues():
5521:    Insert a logically dense subblock, which can be
5522: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5576:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5577:    searches during matrix assembly. When this flag is set, the hash table
5578:    is created during the first Matrix Assembly. This hash table is
5579:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5580:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5581:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5582:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5604:    Level: intermediate

5606: .seealso:  MatOption, Mat

5608: @*/
5609: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5610: {

5616:   if (op > 0) {
5619:   }

5621:   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);
5622:   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()");

5624:   switch (op) {
5625:   case MAT_NO_OFF_PROC_ENTRIES:
5626:     mat->nooffprocentries = flg;
5627:     return(0);
5628:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5629:     mat->assembly_subset = flg;
5630:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5631: #if !defined(PETSC_HAVE_MPIUNI)
5632:       MatStashScatterDestroy_BTS(&mat->stash);
5633: #endif
5634:       mat->stash.first_assembly_done = PETSC_FALSE;
5635:     }
5636:     return(0);
5637:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5638:     mat->nooffproczerorows = flg;
5639:     return(0);
5640:   case MAT_SPD:
5641:     mat->spd_set = PETSC_TRUE;
5642:     mat->spd     = flg;
5643:     if (flg) {
5644:       mat->symmetric                  = PETSC_TRUE;
5645:       mat->structurally_symmetric     = PETSC_TRUE;
5646:       mat->symmetric_set              = PETSC_TRUE;
5647:       mat->structurally_symmetric_set = PETSC_TRUE;
5648:     }
5649:     break;
5650:   case MAT_SYMMETRIC:
5651:     mat->symmetric = flg;
5652:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5653:     mat->symmetric_set              = PETSC_TRUE;
5654:     mat->structurally_symmetric_set = flg;
5655: #if !defined(PETSC_USE_COMPLEX)
5656:     mat->hermitian     = flg;
5657:     mat->hermitian_set = PETSC_TRUE;
5658: #endif
5659:     break;
5660:   case MAT_HERMITIAN:
5661:     mat->hermitian = flg;
5662:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5663:     mat->hermitian_set              = PETSC_TRUE;
5664:     mat->structurally_symmetric_set = flg;
5665: #if !defined(PETSC_USE_COMPLEX)
5666:     mat->symmetric     = flg;
5667:     mat->symmetric_set = PETSC_TRUE;
5668: #endif
5669:     break;
5670:   case MAT_STRUCTURALLY_SYMMETRIC:
5671:     mat->structurally_symmetric     = flg;
5672:     mat->structurally_symmetric_set = PETSC_TRUE;
5673:     break;
5674:   case MAT_SYMMETRY_ETERNAL:
5675:     mat->symmetric_eternal = flg;
5676:     break;
5677:   case MAT_STRUCTURE_ONLY:
5678:     mat->structure_only = flg;
5679:     break;
5680:   case MAT_SORTED_FULL:
5681:     mat->sortedfull = flg;
5682:     break;
5683:   default:
5684:     break;
5685:   }
5686:   if (mat->ops->setoption) {
5687:     (*mat->ops->setoption)(mat,op,flg);
5688:   }
5689:   return(0);
5690: }

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

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

5697:    Input Parameters:
5698: +  mat - the matrix
5699: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5707:    Level: intermediate

5709: .seealso:  MatOption, MatSetOption()

5711: @*/
5712: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5713: {

5718:   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);
5719:   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()");

5721:   switch (op) {
5722:   case MAT_NO_OFF_PROC_ENTRIES:
5723:     *flg = mat->nooffprocentries;
5724:     break;
5725:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5726:     *flg = mat->nooffproczerorows;
5727:     break;
5728:   case MAT_SYMMETRIC:
5729:     *flg = mat->symmetric;
5730:     break;
5731:   case MAT_HERMITIAN:
5732:     *flg = mat->hermitian;
5733:     break;
5734:   case MAT_STRUCTURALLY_SYMMETRIC:
5735:     *flg = mat->structurally_symmetric;
5736:     break;
5737:   case MAT_SYMMETRY_ETERNAL:
5738:     *flg = mat->symmetric_eternal;
5739:     break;
5740:   case MAT_SPD:
5741:     *flg = mat->spd;
5742:     break;
5743:   default:
5744:     break;
5745:   }
5746:   return(0);
5747: }

5749: /*@
5750:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5751:    this routine retains the old nonzero structure.

5753:    Logically Collective on Mat

5755:    Input Parameters:
5756: .  mat - the matrix

5758:    Level: intermediate

5760:    Notes:
5761:     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.
5762:    See the Performance chapter of the users manual for information on preallocating matrices.

5764: .seealso: MatZeroRows()
5765: @*/
5766: PetscErrorCode MatZeroEntries(Mat mat)
5767: {

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

5778:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5779:   (*mat->ops->zeroentries)(mat);
5780:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5781:   PetscObjectStateIncrease((PetscObject)mat);
5782:   return(0);
5783: }

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

5789:    Collective on Mat

5791:    Input Parameters:
5792: +  mat - the matrix
5793: .  numRows - the number of rows to remove
5794: .  rows - the global row indices
5795: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5796: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5797: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5816:    Level: intermediate

5818: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5819:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5820: @*/
5821: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5822: {

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

5834:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5835:   MatViewFromOptions(mat,NULL,"-mat_view");
5836:   PetscObjectStateIncrease((PetscObject)mat);
5837:   return(0);
5838: }

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

5844:    Collective on Mat

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

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

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

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

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

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

5870:    Level: intermediate

5872: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5873:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5874: @*/
5875: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5876: {
5878:   PetscInt       numRows;
5879:   const PetscInt *rows;

5886:   ISGetLocalSize(is,&numRows);
5887:   ISGetIndices(is,&rows);
5888:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5889:   ISRestoreIndices(is,&rows);
5890:   return(0);
5891: }

5893: /*@
5894:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5895:    of a set of rows of a matrix.

5897:    Collective on Mat

5899:    Input Parameters:
5900: +  mat - the matrix
5901: .  numRows - the number of rows to remove
5902: .  rows - the global row indices
5903: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5904: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5905: -  b - optional vector of right hand side, that will be adjusted by provided solution

5907:    Notes:
5908:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5909:    but does not release memory.  For the dense and block diagonal
5910:    formats this does not alter the nonzero structure.

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

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

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

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

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

5931:    Level: intermediate

5933: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5934:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5935: @*/
5936: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5937: {

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

5949:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5950:   MatViewFromOptions(mat,NULL,"-mat_view");
5951:   PetscObjectStateIncrease((PetscObject)mat);
5952:   return(0);
5953: }

5955: /*@
5956:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5957:    of a set of rows of a matrix.

5959:    Collective on Mat

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

5968:    Notes:
5969:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5970:    but does not release memory.  For the dense and block diagonal
5971:    formats this does not alter the nonzero structure.

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

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

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

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

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

5992:    Level: intermediate

5994: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5995:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5996: @*/
5997: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5998: {
5999:   PetscInt       numRows;
6000:   const PetscInt *rows;

6007:   ISGetLocalSize(is,&numRows);
6008:   ISGetIndices(is,&rows);
6009:   MatZeroRows(mat,numRows,rows,diag,x,b);
6010:   ISRestoreIndices(is,&rows);
6011:   return(0);
6012: }

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

6018:    Collective on Mat

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

6028:    Notes:
6029:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6030:    but does not release memory.  For the dense and block diagonal
6031:    formats this does not alter the nonzero structure.

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

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

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

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

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

6051:    In Fortran idxm and idxn should be declared as
6052: $     MatStencil idxm(4,m)
6053:    and the values inserted using
6054: $    idxm(MatStencil_i,1) = i
6055: $    idxm(MatStencil_j,1) = j
6056: $    idxm(MatStencil_k,1) = k
6057: $    idxm(MatStencil_c,1) = c
6058:    etc

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

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

6068:    Level: intermediate

6070: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6071:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6072: @*/
6073: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6074: {
6075:   PetscInt       dim     = mat->stencil.dim;
6076:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6077:   PetscInt       *dims   = mat->stencil.dims+1;
6078:   PetscInt       *starts = mat->stencil.starts;
6079:   PetscInt       *dxm    = (PetscInt*) rows;
6080:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6088:   PetscMalloc1(numRows, &jdxm);
6089:   for (i = 0; i < numRows; ++i) {
6090:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6091:     for (j = 0; j < 3-sdim; ++j) dxm++;
6092:     /* Local index in X dir */
6093:     tmp = *dxm++ - starts[0];
6094:     /* Loop over remaining dimensions */
6095:     for (j = 0; j < dim-1; ++j) {
6096:       /* If nonlocal, set index to be negative */
6097:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6098:       /* Update local index */
6099:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6100:     }
6101:     /* Skip component slot if necessary */
6102:     if (mat->stencil.noc) dxm++;
6103:     /* Local row number */
6104:     if (tmp >= 0) {
6105:       jdxm[numNewRows++] = tmp;
6106:     }
6107:   }
6108:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6109:   PetscFree(jdxm);
6110:   return(0);
6111: }

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

6117:    Collective on Mat

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

6127:    Notes:
6128:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6129:    but does not release memory.  For the dense and block diagonal
6130:    formats this does not alter the nonzero structure.

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

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

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

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

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

6150:    In Fortran idxm and idxn should be declared as
6151: $     MatStencil idxm(4,m)
6152:    and the values inserted using
6153: $    idxm(MatStencil_i,1) = i
6154: $    idxm(MatStencil_j,1) = j
6155: $    idxm(MatStencil_k,1) = k
6156: $    idxm(MatStencil_c,1) = c
6157:    etc

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

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

6167:    Level: intermediate

6169: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6170:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6171: @*/
6172: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6173: {
6174:   PetscInt       dim     = mat->stencil.dim;
6175:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6176:   PetscInt       *dims   = mat->stencil.dims+1;
6177:   PetscInt       *starts = mat->stencil.starts;
6178:   PetscInt       *dxm    = (PetscInt*) rows;
6179:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6187:   PetscMalloc1(numRows, &jdxm);
6188:   for (i = 0; i < numRows; ++i) {
6189:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6190:     for (j = 0; j < 3-sdim; ++j) dxm++;
6191:     /* Local index in X dir */
6192:     tmp = *dxm++ - starts[0];
6193:     /* Loop over remaining dimensions */
6194:     for (j = 0; j < dim-1; ++j) {
6195:       /* If nonlocal, set index to be negative */
6196:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6197:       /* Update local index */
6198:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6199:     }
6200:     /* Skip component slot if necessary */
6201:     if (mat->stencil.noc) dxm++;
6202:     /* Local row number */
6203:     if (tmp >= 0) {
6204:       jdxm[numNewRows++] = tmp;
6205:     }
6206:   }
6207:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6208:   PetscFree(jdxm);
6209:   return(0);
6210: }

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

6216:    Collective on Mat

6218:    Input Parameters:
6219: +  mat - the matrix
6220: .  numRows - the number of rows to remove
6221: .  rows - the global row indices
6222: .  diag - value put in all diagonals of eliminated rows
6223: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6224: -  b - optional vector of right hand side, that will be adjusted by provided solution

6226:    Notes:
6227:    Before calling MatZeroRowsLocal(), the user must first set the
6228:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6230:    For the AIJ matrix formats this removes the old nonzero structure,
6231:    but does not release memory.  For the dense and block diagonal
6232:    formats this does not alter the nonzero structure.

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

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

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

6245:    Level: intermediate

6247: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6248:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6249: @*/
6250: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6251: {

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

6262:   if (mat->ops->zerorowslocal) {
6263:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6264:   } else {
6265:     IS             is, newis;
6266:     const PetscInt *newRows;

6268:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6269:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6270:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6271:     ISGetIndices(newis,&newRows);
6272:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6273:     ISRestoreIndices(newis,&newRows);
6274:     ISDestroy(&newis);
6275:     ISDestroy(&is);
6276:   }
6277:   PetscObjectStateIncrease((PetscObject)mat);
6278:   return(0);
6279: }

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

6285:    Collective on Mat

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

6294:    Notes:
6295:    Before calling MatZeroRowsLocalIS(), the user must first set the
6296:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6298:    For the AIJ matrix formats this removes the old nonzero structure,
6299:    but does not release memory.  For the dense and block diagonal
6300:    formats this does not alter the nonzero structure.

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

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

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

6313:    Level: intermediate

6315: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6316:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6317: @*/
6318: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6319: {
6321:   PetscInt       numRows;
6322:   const PetscInt *rows;

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

6332:   ISGetLocalSize(is,&numRows);
6333:   ISGetIndices(is,&rows);
6334:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6335:   ISRestoreIndices(is,&rows);
6336:   return(0);
6337: }

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

6343:    Collective on Mat

6345:    Input Parameters:
6346: +  mat - the matrix
6347: .  numRows - the number of rows to remove
6348: .  rows - the global row indices
6349: .  diag - value put in all diagonals of eliminated rows
6350: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6351: -  b - optional vector of right hand side, that will be adjusted by provided solution

6353:    Notes:
6354:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6355:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6361:    Level: intermediate

6363: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6364:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6365: @*/
6366: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6367: {
6369:   IS             is, newis;
6370:   const PetscInt *newRows;

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

6380:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6381:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6382:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6383:   ISGetIndices(newis,&newRows);
6384:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6385:   ISRestoreIndices(newis,&newRows);
6386:   ISDestroy(&newis);
6387:   ISDestroy(&is);
6388:   PetscObjectStateIncrease((PetscObject)mat);
6389:   return(0);
6390: }

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

6396:    Collective on Mat

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

6405:    Notes:
6406:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6407:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6413:    Level: intermediate

6415: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6416:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6417: @*/
6418: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6419: {
6421:   PetscInt       numRows;
6422:   const PetscInt *rows;

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

6432:   ISGetLocalSize(is,&numRows);
6433:   ISGetIndices(is,&rows);
6434:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6435:   ISRestoreIndices(is,&rows);
6436:   return(0);
6437: }

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

6442:    Not Collective

6444:    Input Parameter:
6445: .  mat - the matrix

6447:    Output Parameters:
6448: +  m - the number of global rows
6449: -  n - the number of global columns

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

6453:    Level: beginner

6455: .seealso: MatGetLocalSize()
6456: @*/
6457: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6458: {
6461:   if (m) *m = mat->rmap->N;
6462:   if (n) *n = mat->cmap->N;
6463:   return(0);
6464: }

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

6470:    Not Collective

6472:    Input Parameters:
6473: .  mat - the matrix

6475:    Output Parameters:
6476: +  m - the number of local rows
6477: -  n - the number of local columns

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

6481:    Level: beginner

6483: .seealso: MatGetSize()
6484: @*/
6485: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6486: {
6491:   if (m) *m = mat->rmap->n;
6492:   if (n) *n = mat->cmap->n;
6493:   return(0);
6494: }

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

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

6502:    Input Parameters:
6503: .  mat - the matrix

6505:    Output Parameters:
6506: +  m - the global index of the first local column
6507: -  n - one more than the global index of the last local column

6509:    Notes:
6510:     both output parameters can be NULL on input.

6512:    Level: developer

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

6516: @*/
6517: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6518: {
6524:   MatCheckPreallocated(mat,1);
6525:   if (m) *m = mat->cmap->rstart;
6526:   if (n) *n = mat->cmap->rend;
6527:   return(0);
6528: }

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

6536:    Not Collective

6538:    Input Parameters:
6539: .  mat - the matrix

6541:    Output Parameters:
6542: +  m - the global index of the first local row
6543: -  n - one more than the global index of the last local row

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

6550:    Level: beginner

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

6554: @*/
6555: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6556: {
6562:   MatCheckPreallocated(mat,1);
6563:   if (m) *m = mat->rmap->rstart;
6564:   if (n) *n = mat->rmap->rend;
6565:   return(0);
6566: }

6568: /*@C
6569:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6570:    each process

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

6574:    Input Parameters:
6575: .  mat - the matrix

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

6580:    Level: beginner

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

6584: @*/
6585: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6586: {

6592:   MatCheckPreallocated(mat,1);
6593:   PetscLayoutGetRanges(mat->rmap,ranges);
6594:   return(0);
6595: }

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

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

6603:    Input Parameters:
6604: .  mat - the matrix

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

6609:    Level: beginner

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

6613: @*/
6614: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6615: {

6621:   MatCheckPreallocated(mat,1);
6622:   PetscLayoutGetRanges(mat->cmap,ranges);
6623:   return(0);
6624: }

6626: /*@C
6627:    MatGetOwnershipIS - Get row and column ownership as index sets

6629:    Not Collective

6631:    Input Arguments:
6632: .  A - matrix of type Elemental or ScaLAPACK

6634:    Output Arguments:
6635: +  rows - rows in which this process owns elements
6636: -  cols - columns in which this process owns elements

6638:    Level: intermediate

6640: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6641: @*/
6642: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6643: {
6644:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6647:   MatCheckPreallocated(A,1);
6648:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6649:   if (f) {
6650:     (*f)(A,rows,cols);
6651:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6652:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6653:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6654:   }
6655:   return(0);
6656: }

6658: /*@C
6659:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6660:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6661:    to complete the factorization.

6663:    Collective on Mat

6665:    Input Parameters:
6666: +  mat - the matrix
6667: .  row - row permutation
6668: .  column - column permutation
6669: -  info - structure containing
6670: $      levels - number of levels of fill.
6671: $      expected fill - as ratio of original fill.
6672: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6673:                 missing diagonal entries)

6675:    Output Parameters:
6676: .  fact - new matrix that has been symbolically factored

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

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

6685:    Level: developer

6687: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6688:           MatGetOrdering(), MatFactorInfo

6690:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6695:    References:
6696:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6697: @*/
6698: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6699: {

6709:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6710:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6711:   if (!fact->ops->ilufactorsymbolic) {
6712:     MatSolverType stype;
6713:     MatFactorGetSolverType(fact,&stype);
6714:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver type %s",((PetscObject)mat)->type_name,stype);
6715:   }
6716:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6717:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6718:   MatCheckPreallocated(mat,2);

6720:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6721:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6722:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6723:   return(0);
6724: }

6726: /*@C
6727:    MatICCFactorSymbolic - Performs symbolic incomplete
6728:    Cholesky factorization for a symmetric matrix.  Use
6729:    MatCholeskyFactorNumeric() to complete the factorization.

6731:    Collective on Mat

6733:    Input Parameters:
6734: +  mat - the matrix
6735: .  perm - row and column permutation
6736: -  info - structure containing
6737: $      levels - number of levels of fill.
6738: $      expected fill - as ratio of original fill.

6740:    Output Parameter:
6741: .  fact - the factored matrix

6743:    Notes:
6744:    Most users should employ the KSP interface for linear solvers
6745:    instead of working directly with matrix algebra routines such as this.
6746:    See, e.g., KSPCreate().

6748:    Level: developer

6750: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6752:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6757:    References:
6758:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6759: @*/
6760: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6761: {

6770:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6771:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6772:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6773:   if (!(fact)->ops->iccfactorsymbolic) {
6774:     MatSolverType stype;
6775:     MatFactorGetSolverType(fact,&stype);
6776:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver type %s",((PetscObject)mat)->type_name,stype);
6777:   }
6778:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6779:   MatCheckPreallocated(mat,2);

6781:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6782:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6783:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6784:   return(0);
6785: }

6787: /*@C
6788:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6789:    points to an array of valid matrices, they may be reused to store the new
6790:    submatrices.

6792:    Collective on Mat

6794:    Input Parameters:
6795: +  mat - the matrix
6796: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6797: .  irow, icol - index sets of rows and columns to extract
6798: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6800:    Output Parameter:
6801: .  submat - the array of submatrices

6803:    Notes:
6804:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6805:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6806:    to extract a parallel submatrix.

6808:    Some matrix types place restrictions on the row and column
6809:    indices, such as that they be sorted or that they be equal to each other.

6811:    The index sets may not have duplicate entries.

6813:    When extracting submatrices from a parallel matrix, each processor can
6814:    form a different submatrix by setting the rows and columns of its
6815:    individual index sets according to the local submatrix desired.

6817:    When finished using the submatrices, the user should destroy
6818:    them with MatDestroySubMatrices().

6820:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6821:    original matrix has not changed from that last call to MatCreateSubMatrices().

6823:    This routine creates the matrices in submat; you should NOT create them before
6824:    calling it. It also allocates the array of matrix pointers submat.

6826:    For BAIJ matrices the index sets must respect the block structure, that is if they
6827:    request one row/column in a block, they must request all rows/columns that are in
6828:    that block. For example, if the block size is 2 you cannot request just row 0 and
6829:    column 0.

6831:    Fortran Note:
6832:    The Fortran interface is slightly different from that given below; it
6833:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6835:    Level: advanced


6838: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6839: @*/
6840: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6841: {
6843:   PetscInt       i;
6844:   PetscBool      eq;

6849:   if (n) {
6854:   }
6856:   if (n && scall == MAT_REUSE_MATRIX) {
6859:   }
6860:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6861:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6862:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6863:   MatCheckPreallocated(mat,1);

6865:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6866:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6867:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6868:   for (i=0; i<n; i++) {
6869:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6870:     ISEqualUnsorted(irow[i],icol[i],&eq);
6871:     if (eq) {
6872:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6873:     }
6874:   }
6875:   return(0);
6876: }

6878: /*@C
6879:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6881:    Collective on Mat

6883:    Input Parameters:
6884: +  mat - the matrix
6885: .  n   - the number of submatrixes to be extracted
6886: .  irow, icol - index sets of rows and columns to extract
6887: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6889:    Output Parameter:
6890: .  submat - the array of submatrices

6892:    Level: advanced


6895: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6896: @*/
6897: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6898: {
6900:   PetscInt       i;
6901:   PetscBool      eq;

6906:   if (n) {
6911:   }
6913:   if (n && scall == MAT_REUSE_MATRIX) {
6916:   }
6917:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6918:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6919:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6920:   MatCheckPreallocated(mat,1);

6922:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6923:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6924:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6925:   for (i=0; i<n; i++) {
6926:     ISEqualUnsorted(irow[i],icol[i],&eq);
6927:     if (eq) {
6928:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6929:     }
6930:   }
6931:   return(0);
6932: }

6934: /*@C
6935:    MatDestroyMatrices - Destroys an array of matrices.

6937:    Collective on Mat

6939:    Input Parameters:
6940: +  n - the number of local matrices
6941: -  mat - the matrices (note that this is a pointer to the array of matrices)

6943:    Level: advanced

6945:     Notes:
6946:     Frees not only the matrices, but also the array that contains the matrices
6947:            In Fortran will not free the array.

6949: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6950: @*/
6951: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6952: {
6954:   PetscInt       i;

6957:   if (!*mat) return(0);
6958:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6961:   for (i=0; i<n; i++) {
6962:     MatDestroy(&(*mat)[i]);
6963:   }

6965:   /* memory is allocated even if n = 0 */
6966:   PetscFree(*mat);
6967:   return(0);
6968: }

6970: /*@C
6971:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6973:    Collective on Mat

6975:    Input Parameters:
6976: +  n - the number of local matrices
6977: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6978:                        sequence of MatCreateSubMatrices())

6980:    Level: advanced

6982:     Notes:
6983:     Frees not only the matrices, but also the array that contains the matrices
6984:            In Fortran will not free the array.

6986: .seealso: MatCreateSubMatrices()
6987: @*/
6988: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6989: {
6991:   Mat            mat0;

6994:   if (!*mat) return(0);
6995:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6996:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6999:   mat0 = (*mat)[0];
7000:   if (mat0 && mat0->ops->destroysubmatrices) {
7001:     (mat0->ops->destroysubmatrices)(n,mat);
7002:   } else {
7003:     MatDestroyMatrices(n,mat);
7004:   }
7005:   return(0);
7006: }

7008: /*@C
7009:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

7011:    Collective on Mat

7013:    Input Parameters:
7014: .  mat - the matrix

7016:    Output Parameter:
7017: .  matstruct - the sequential matrix with the nonzero structure of mat

7019:   Level: intermediate

7021: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7022: @*/
7023: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7024: {


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

7035:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7036:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7037:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
7038:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7039:   return(0);
7040: }

7042: /*@C
7043:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

7045:    Collective on Mat

7047:    Input Parameters:
7048: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
7049:                        sequence of MatGetSequentialNonzeroStructure())

7051:    Level: advanced

7053:     Notes:
7054:     Frees not only the matrices, but also the array that contains the matrices

7056: .seealso: MatGetSeqNonzeroStructure()
7057: @*/
7058: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7059: {

7064:   MatDestroy(mat);
7065:   return(0);
7066: }

7068: /*@
7069:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7070:    replaces the index sets by larger ones that represent submatrices with
7071:    additional overlap.

7073:    Collective on Mat

7075:    Input Parameters:
7076: +  mat - the matrix
7077: .  n   - the number of index sets
7078: .  is  - the array of index sets (these index sets will changed during the call)
7079: -  ov  - the additional overlap requested

7081:    Options Database:
7082: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7084:    Level: developer


7087: .seealso: MatCreateSubMatrices()
7088: @*/
7089: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7090: {

7096:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7097:   if (n) {
7100:   }
7101:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7102:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7103:   MatCheckPreallocated(mat,1);

7105:   if (!ov) return(0);
7106:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7107:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7108:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7109:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7110:   return(0);
7111: }


7114: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7116: /*@
7117:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7118:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7119:    additional overlap.

7121:    Collective on Mat

7123:    Input Parameters:
7124: +  mat - the matrix
7125: .  n   - the number of index sets
7126: .  is  - the array of index sets (these index sets will changed during the call)
7127: -  ov  - the additional overlap requested

7129:    Options Database:
7130: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7132:    Level: developer


7135: .seealso: MatCreateSubMatrices()
7136: @*/
7137: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7138: {
7139:   PetscInt       i;

7145:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7146:   if (n) {
7149:   }
7150:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7151:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7152:   MatCheckPreallocated(mat,1);
7153:   if (!ov) return(0);
7154:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7155:   for (i=0; i<n; i++){
7156:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7157:   }
7158:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7159:   return(0);
7160: }




7165: /*@
7166:    MatGetBlockSize - Returns the matrix block size.

7168:    Not Collective

7170:    Input Parameter:
7171: .  mat - the matrix

7173:    Output Parameter:
7174: .  bs - block size

7176:    Notes:
7177:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7179:    If the block size has not been set yet this routine returns 1.

7181:    Level: intermediate

7183: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7184: @*/
7185: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7186: {
7190:   *bs = PetscAbs(mat->rmap->bs);
7191:   return(0);
7192: }

7194: /*@
7195:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7197:    Not Collective

7199:    Input Parameter:
7200: .  mat - the matrix

7202:    Output Parameter:
7203: +  rbs - row block size
7204: -  cbs - column block size

7206:    Notes:
7207:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7208:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7210:    If a block size has not been set yet this routine returns 1.

7212:    Level: intermediate

7214: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7215: @*/
7216: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7217: {
7222:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7223:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7224:   return(0);
7225: }

7227: /*@
7228:    MatSetBlockSize - Sets the matrix block size.

7230:    Logically Collective on Mat

7232:    Input Parameters:
7233: +  mat - the matrix
7234: -  bs - block size

7236:    Notes:
7237:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7238:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7240:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7241:     is compatible with the matrix local sizes.

7243:    Level: intermediate

7245: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7246: @*/
7247: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7248: {

7254:   MatSetBlockSizes(mat,bs,bs);
7255:   return(0);
7256: }

7258: /*@
7259:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7261:    Logically Collective on Mat

7263:    Input Parameters:
7264: +  mat - the matrix
7265: .  nblocks - the number of blocks on this process
7266: -  bsizes - the block sizes

7268:    Notes:
7269:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7271:    Level: intermediate

7273: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7274: @*/
7275: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7276: {
7278:   PetscInt       i,ncnt = 0, nlocal;

7282:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7283:   MatGetLocalSize(mat,&nlocal,NULL);
7284:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7285:   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);
7286:   PetscFree(mat->bsizes);
7287:   mat->nblocks = nblocks;
7288:   PetscMalloc1(nblocks,&mat->bsizes);
7289:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7290:   return(0);
7291: }

7293: /*@C
7294:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7296:    Logically Collective on Mat

7298:    Input Parameters:
7299: .  mat - the matrix

7301:    Output Parameters:
7302: +  nblocks - the number of blocks on this process
7303: -  bsizes - the block sizes

7305:    Notes: Currently not supported from Fortran

7307:    Level: intermediate

7309: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7310: @*/
7311: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7312: {
7315:   *nblocks = mat->nblocks;
7316:   *bsizes  = mat->bsizes;
7317:   return(0);
7318: }

7320: /*@
7321:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7323:    Logically Collective on Mat

7325:    Input Parameters:
7326: +  mat - the matrix
7327: .  rbs - row block size
7328: -  cbs - column block size

7330:    Notes:
7331:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7332:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7333:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7335:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7336:     are compatible with the matrix local sizes.

7338:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7340:    Level: intermediate

7342: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7343: @*/
7344: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7345: {

7352:   if (mat->ops->setblocksizes) {
7353:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7354:   }
7355:   if (mat->rmap->refcnt) {
7356:     ISLocalToGlobalMapping l2g = NULL;
7357:     PetscLayout            nmap = NULL;

7359:     PetscLayoutDuplicate(mat->rmap,&nmap);
7360:     if (mat->rmap->mapping) {
7361:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7362:     }
7363:     PetscLayoutDestroy(&mat->rmap);
7364:     mat->rmap = nmap;
7365:     mat->rmap->mapping = l2g;
7366:   }
7367:   if (mat->cmap->refcnt) {
7368:     ISLocalToGlobalMapping l2g = NULL;
7369:     PetscLayout            nmap = NULL;

7371:     PetscLayoutDuplicate(mat->cmap,&nmap);
7372:     if (mat->cmap->mapping) {
7373:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7374:     }
7375:     PetscLayoutDestroy(&mat->cmap);
7376:     mat->cmap = nmap;
7377:     mat->cmap->mapping = l2g;
7378:   }
7379:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7380:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7381:   return(0);
7382: }

7384: /*@
7385:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7387:    Logically Collective on Mat

7389:    Input Parameters:
7390: +  mat - the matrix
7391: .  fromRow - matrix from which to copy row block size
7392: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7394:    Level: developer

7396: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7397: @*/
7398: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7399: {

7406:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7407:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7408:   return(0);
7409: }

7411: /*@
7412:    MatResidual - Default routine to calculate the residual.

7414:    Collective on Mat

7416:    Input Parameters:
7417: +  mat - the matrix
7418: .  b   - the right-hand-side
7419: -  x   - the approximate solution

7421:    Output Parameter:
7422: .  r - location to store the residual

7424:    Level: developer

7426: .seealso: PCMGSetResidual()
7427: @*/
7428: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7429: {

7438:   MatCheckPreallocated(mat,1);
7439:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7440:   if (!mat->ops->residual) {
7441:     MatMult(mat,x,r);
7442:     VecAYPX(r,-1.0,b);
7443:   } else {
7444:     (*mat->ops->residual)(mat,b,x,r);
7445:   }
7446:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7447:   return(0);
7448: }

7450: /*@C
7451:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7453:    Collective on Mat

7455:     Input Parameters:
7456: +   mat - the matrix
7457: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7458: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7459: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7460:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7461:                  always used.

7463:     Output Parameters:
7464: +   n - number of rows in the (possibly compressed) matrix
7465: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7466: .   ja - the column indices
7467: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7468:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7470:     Level: developer

7472:     Notes:
7473:     You CANNOT change any of the ia[] or ja[] values.

7475:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7477:     Fortran Notes:
7478:     In Fortran use
7479: $
7480: $      PetscInt ia(1), ja(1)
7481: $      PetscOffset iia, jja
7482: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7483: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7485:      or
7486: $
7487: $    PetscInt, pointer :: ia(:),ja(:)
7488: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7489: $    ! Access the ith and jth entries via ia(i) and ja(j)

7491: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7492: @*/
7493: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7494: {

7504:   MatCheckPreallocated(mat,1);
7505:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7506:   else {
7507:     *done = PETSC_TRUE;
7508:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7509:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7510:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7511:   }
7512:   return(0);
7513: }

7515: /*@C
7516:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7518:     Collective on Mat

7520:     Input Parameters:
7521: +   mat - the matrix
7522: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7523: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7524:                 symmetrized
7525: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7526:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7527:                  always used.
7528: .   n - number of columns in the (possibly compressed) matrix
7529: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7530: -   ja - the row indices

7532:     Output Parameters:
7533: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7535:     Level: developer

7537: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7538: @*/
7539: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7540: {

7550:   MatCheckPreallocated(mat,1);
7551:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7552:   else {
7553:     *done = PETSC_TRUE;
7554:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7555:   }
7556:   return(0);
7557: }

7559: /*@C
7560:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7561:     MatGetRowIJ().

7563:     Collective on Mat

7565:     Input Parameters:
7566: +   mat - the matrix
7567: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7568: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7569:                 symmetrized
7570: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7571:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7572:                  always used.
7573: .   n - size of (possibly compressed) matrix
7574: .   ia - the row pointers
7575: -   ja - the column indices

7577:     Output Parameters:
7578: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7580:     Note:
7581:     This routine zeros out n, ia, and ja. This is to prevent accidental
7582:     us of the array after it has been restored. If you pass NULL, it will
7583:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7585:     Level: developer

7587: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7588: @*/
7589: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7590: {

7599:   MatCheckPreallocated(mat,1);

7601:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7602:   else {
7603:     *done = PETSC_TRUE;
7604:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7605:     if (n)  *n = 0;
7606:     if (ia) *ia = NULL;
7607:     if (ja) *ja = NULL;
7608:   }
7609:   return(0);
7610: }

7612: /*@C
7613:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7614:     MatGetColumnIJ().

7616:     Collective on Mat

7618:     Input Parameters:
7619: +   mat - the matrix
7620: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7621: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7622:                 symmetrized
7623: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7624:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7625:                  always used.

7627:     Output Parameters:
7628: +   n - size of (possibly compressed) matrix
7629: .   ia - the column pointers
7630: .   ja - the row indices
7631: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7633:     Level: developer

7635: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7636: @*/
7637: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7638: {

7647:   MatCheckPreallocated(mat,1);

7649:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7650:   else {
7651:     *done = PETSC_TRUE;
7652:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7653:     if (n)  *n = 0;
7654:     if (ia) *ia = NULL;
7655:     if (ja) *ja = NULL;
7656:   }
7657:   return(0);
7658: }

7660: /*@C
7661:     MatColoringPatch -Used inside matrix coloring routines that
7662:     use MatGetRowIJ() and/or MatGetColumnIJ().

7664:     Collective on Mat

7666:     Input Parameters:
7667: +   mat - the matrix
7668: .   ncolors - max color value
7669: .   n   - number of entries in colorarray
7670: -   colorarray - array indicating color for each column

7672:     Output Parameters:
7673: .   iscoloring - coloring generated using colorarray information

7675:     Level: developer

7677: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7679: @*/
7680: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7681: {

7689:   MatCheckPreallocated(mat,1);

7691:   if (!mat->ops->coloringpatch) {
7692:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7693:   } else {
7694:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7695:   }
7696:   return(0);
7697: }


7700: /*@
7701:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7703:    Logically Collective on Mat

7705:    Input Parameter:
7706: .  mat - the factored matrix to be reset

7708:    Notes:
7709:    This routine should be used only with factored matrices formed by in-place
7710:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7711:    format).  This option can save memory, for example, when solving nonlinear
7712:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7713:    ILU(0) preconditioner.

7715:    Note that one can specify in-place ILU(0) factorization by calling
7716: .vb
7717:      PCType(pc,PCILU);
7718:      PCFactorSeUseInPlace(pc);
7719: .ve
7720:    or by using the options -pc_type ilu -pc_factor_in_place

7722:    In-place factorization ILU(0) can also be used as a local
7723:    solver for the blocks within the block Jacobi or additive Schwarz
7724:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7725:    for details on setting local solver options.

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

7731:    Level: developer

7733: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7735: @*/
7736: PetscErrorCode MatSetUnfactored(Mat mat)
7737: {

7743:   MatCheckPreallocated(mat,1);
7744:   mat->factortype = MAT_FACTOR_NONE;
7745:   if (!mat->ops->setunfactored) return(0);
7746:   (*mat->ops->setunfactored)(mat);
7747:   return(0);
7748: }

7750: /*MC
7751:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7753:     Synopsis:
7754:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7756:     Not collective

7758:     Input Parameter:
7759: .   x - matrix

7761:     Output Parameters:
7762: +   xx_v - the Fortran90 pointer to the array
7763: -   ierr - error code

7765:     Example of Usage:
7766: .vb
7767:       PetscScalar, pointer xx_v(:,:)
7768:       ....
7769:       call MatDenseGetArrayF90(x,xx_v,ierr)
7770:       a = xx_v(3)
7771:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7772: .ve

7774:     Level: advanced

7776: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7778: M*/

7780: /*MC
7781:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7782:     accessed with MatDenseGetArrayF90().

7784:     Synopsis:
7785:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7787:     Not collective

7789:     Input Parameters:
7790: +   x - matrix
7791: -   xx_v - the Fortran90 pointer to the array

7793:     Output Parameter:
7794: .   ierr - error code

7796:     Example of Usage:
7797: .vb
7798:        PetscScalar, pointer xx_v(:,:)
7799:        ....
7800:        call MatDenseGetArrayF90(x,xx_v,ierr)
7801:        a = xx_v(3)
7802:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7803: .ve

7805:     Level: advanced

7807: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7809: M*/


7812: /*MC
7813:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7815:     Synopsis:
7816:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7818:     Not collective

7820:     Input Parameter:
7821: .   x - matrix

7823:     Output Parameters:
7824: +   xx_v - the Fortran90 pointer to the array
7825: -   ierr - error code

7827:     Example of Usage:
7828: .vb
7829:       PetscScalar, pointer xx_v(:)
7830:       ....
7831:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7832:       a = xx_v(3)
7833:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7834: .ve

7836:     Level: advanced

7838: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7840: M*/

7842: /*MC
7843:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7844:     accessed with MatSeqAIJGetArrayF90().

7846:     Synopsis:
7847:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7849:     Not collective

7851:     Input Parameters:
7852: +   x - matrix
7853: -   xx_v - the Fortran90 pointer to the array

7855:     Output Parameter:
7856: .   ierr - error code

7858:     Example of Usage:
7859: .vb
7860:        PetscScalar, pointer xx_v(:)
7861:        ....
7862:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7863:        a = xx_v(3)
7864:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7865: .ve

7867:     Level: advanced

7869: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7871: M*/


7874: /*@
7875:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7876:                       as the original matrix.

7878:     Collective on Mat

7880:     Input Parameters:
7881: +   mat - the original matrix
7882: .   isrow - parallel IS containing the rows this processor should obtain
7883: .   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.
7884: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7886:     Output Parameter:
7887: .   newmat - the new submatrix, of the same type as the old

7889:     Level: advanced

7891:     Notes:
7892:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7894:     Some matrix types place restrictions on the row and column indices, such
7895:     as that they be sorted or that they be equal to each other.

7897:     The index sets may not have duplicate entries.

7899:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7900:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7901:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7902:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7903:    you are finished using it.

7905:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7906:     the input matrix.

7908:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7910:    Example usage:
7911:    Consider the following 8x8 matrix with 34 non-zero values, that is
7912:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7913:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7914:    as follows:

7916: .vb
7917:             1  2  0  |  0  3  0  |  0  4
7918:     Proc0   0  5  6  |  7  0  0  |  8  0
7919:             9  0 10  | 11  0  0  | 12  0
7920:     -------------------------------------
7921:            13  0 14  | 15 16 17  |  0  0
7922:     Proc1   0 18  0  | 19 20 21  |  0  0
7923:             0  0  0  | 22 23  0  | 24  0
7924:     -------------------------------------
7925:     Proc2  25 26 27  |  0  0 28  | 29  0
7926:            30  0  0  | 31 32 33  |  0 34
7927: .ve

7929:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7931: .vb
7932:             2  0  |  0  3  0  |  0
7933:     Proc0   5  6  |  7  0  0  |  8
7934:     -------------------------------
7935:     Proc1  18  0  | 19 20 21  |  0
7936:     -------------------------------
7937:     Proc2  26 27  |  0  0 28  | 29
7938:             0  0  | 31 32 33  |  0
7939: .ve


7942: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7943: @*/
7944: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7945: {
7947:   PetscMPIInt    size;
7948:   Mat            *local;
7949:   IS             iscoltmp;
7950:   PetscBool      flg;

7959:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7960:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7962:   MatCheckPreallocated(mat,1);
7963:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7965:   if (!iscol || isrow == iscol) {
7966:     PetscBool   stride;
7967:     PetscMPIInt grabentirematrix = 0,grab;
7968:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7969:     if (stride) {
7970:       PetscInt first,step,n,rstart,rend;
7971:       ISStrideGetInfo(isrow,&first,&step);
7972:       if (step == 1) {
7973:         MatGetOwnershipRange(mat,&rstart,&rend);
7974:         if (rstart == first) {
7975:           ISGetLocalSize(isrow,&n);
7976:           if (n == rend-rstart) {
7977:             grabentirematrix = 1;
7978:           }
7979:         }
7980:       }
7981:     }
7982:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7983:     if (grab) {
7984:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7985:       if (cll == MAT_INITIAL_MATRIX) {
7986:         *newmat = mat;
7987:         PetscObjectReference((PetscObject)mat);
7988:       }
7989:       return(0);
7990:     }
7991:   }

7993:   if (!iscol) {
7994:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7995:   } else {
7996:     iscoltmp = iscol;
7997:   }

7999:   /* if original matrix is on just one processor then use submatrix generated */
8000:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8001:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
8002:     goto setproperties;
8003:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8004:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
8005:     *newmat = *local;
8006:     PetscFree(local);
8007:     goto setproperties;
8008:   } else if (!mat->ops->createsubmatrix) {
8009:     /* Create a new matrix type that implements the operation using the full matrix */
8010:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8011:     switch (cll) {
8012:     case MAT_INITIAL_MATRIX:
8013:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
8014:       break;
8015:     case MAT_REUSE_MATRIX:
8016:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
8017:       break;
8018:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8019:     }
8020:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8021:     goto setproperties;
8022:   }

8024:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8025:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8026:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
8027:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

8029: setproperties:
8030:   ISEqualUnsorted(isrow,iscoltmp,&flg);
8031:   if (flg) {
8032:     MatPropagateSymmetryOptions(mat,*newmat);
8033:   }
8034:   if (!iscol) {ISDestroy(&iscoltmp);}
8035:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
8036:   return(0);
8037: }

8039: /*@
8040:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8042:    Not Collective

8044:    Input Parameters:
8045: +  A - the matrix we wish to propagate options from
8046: -  B - the matrix we wish to propagate options to

8048:    Level: beginner

8050:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

8052: .seealso: MatSetOption()
8053: @*/
8054: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8055: {

8061:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
8062:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
8063:   }
8064:   if (A->structurally_symmetric_set) {
8065:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
8066:   }
8067:   if (A->hermitian_set) {
8068:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
8069:   }
8070:   if (A->spd_set) {
8071:     MatSetOption(B,MAT_SPD,A->spd);
8072:   }
8073:   if (A->symmetric_set) {
8074:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
8075:   }
8076:   return(0);
8077: }

8079: /*@
8080:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8081:    used during the assembly process to store values that belong to
8082:    other processors.

8084:    Not Collective

8086:    Input Parameters:
8087: +  mat   - the matrix
8088: .  size  - the initial size of the stash.
8089: -  bsize - the initial size of the block-stash(if used).

8091:    Options Database Keys:
8092: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8093: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

8095:    Level: intermediate

8097:    Notes:
8098:      The block-stash is used for values set with MatSetValuesBlocked() while
8099:      the stash is used for values set with MatSetValues()

8101:      Run with the option -info and look for output of the form
8102:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8103:      to determine the appropriate value, MM, to use for size and
8104:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8105:      to determine the value, BMM to use for bsize


8108: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

8110: @*/
8111: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8112: {

8118:   MatStashSetInitialSize_Private(&mat->stash,size);
8119:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8120:   return(0);
8121: }

8123: /*@
8124:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8125:      the matrix

8127:    Neighbor-wise Collective on Mat

8129:    Input Parameters:
8130: +  mat   - the matrix
8131: .  x,y - the vectors
8132: -  w - where the result is stored

8134:    Level: intermediate

8136:    Notes:
8137:     w may be the same vector as y.

8139:     This allows one to use either the restriction or interpolation (its transpose)
8140:     matrix to do the interpolation

8142: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8144: @*/
8145: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8146: {
8148:   PetscInt       M,N,Ny;

8156:   MatCheckPreallocated(A,1);
8157:   MatGetSize(A,&M,&N);
8158:   VecGetSize(y,&Ny);
8159:   if (M == Ny) {
8160:     MatMultAdd(A,x,y,w);
8161:   } else {
8162:     MatMultTransposeAdd(A,x,y,w);
8163:   }
8164:   return(0);
8165: }

8167: /*@
8168:    MatInterpolate - y = A*x or A'*x depending on the shape of
8169:      the matrix

8171:    Neighbor-wise Collective on Mat

8173:    Input Parameters:
8174: +  mat   - the matrix
8175: -  x,y - the vectors

8177:    Level: intermediate

8179:    Notes:
8180:     This allows one to use either the restriction or interpolation (its transpose)
8181:     matrix to do the interpolation

8183: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8185: @*/
8186: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8187: {
8189:   PetscInt       M,N,Ny;

8196:   MatCheckPreallocated(A,1);
8197:   MatGetSize(A,&M,&N);
8198:   VecGetSize(y,&Ny);
8199:   if (M == Ny) {
8200:     MatMult(A,x,y);
8201:   } else {
8202:     MatMultTranspose(A,x,y);
8203:   }
8204:   return(0);
8205: }

8207: /*@
8208:    MatRestrict - y = A*x or A'*x

8210:    Neighbor-wise Collective on Mat

8212:    Input Parameters:
8213: +  mat   - the matrix
8214: -  x,y - the vectors

8216:    Level: intermediate

8218:    Notes:
8219:     This allows one to use either the restriction or interpolation (its transpose)
8220:     matrix to do the restriction

8222: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8224: @*/
8225: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8226: {
8228:   PetscInt       M,N,Ny;

8235:   MatCheckPreallocated(A,1);

8237:   MatGetSize(A,&M,&N);
8238:   VecGetSize(y,&Ny);
8239:   if (M == Ny) {
8240:     MatMult(A,x,y);
8241:   } else {
8242:     MatMultTranspose(A,x,y);
8243:   }
8244:   return(0);
8245: }

8247: /*@
8248:    MatGetNullSpace - retrieves the null space of a matrix.

8250:    Logically Collective on Mat

8252:    Input Parameters:
8253: +  mat - the matrix
8254: -  nullsp - the null space object

8256:    Level: developer

8258: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8259: @*/
8260: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8261: {
8265:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8266:   return(0);
8267: }

8269: /*@
8270:    MatSetNullSpace - attaches a null space to a matrix.

8272:    Logically Collective on Mat

8274:    Input Parameters:
8275: +  mat - the matrix
8276: -  nullsp - the null space object

8278:    Level: advanced

8280:    Notes:
8281:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8283:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8284:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8286:       You can remove the null space by calling this routine with an nullsp of NULL


8289:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8290:    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).
8291:    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
8292:    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
8293:    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).

8295:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8297:     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
8298:     routine also automatically calls MatSetTransposeNullSpace().

8300: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8301: @*/
8302: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8303: {

8309:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8310:   MatNullSpaceDestroy(&mat->nullsp);
8311:   mat->nullsp = nullsp;
8312:   if (mat->symmetric_set && mat->symmetric) {
8313:     MatSetTransposeNullSpace(mat,nullsp);
8314:   }
8315:   return(0);
8316: }

8318: /*@
8319:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8321:    Logically Collective on Mat

8323:    Input Parameters:
8324: +  mat - the matrix
8325: -  nullsp - the null space object

8327:    Level: developer

8329: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8330: @*/
8331: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8332: {
8337:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8338:   return(0);
8339: }

8341: /*@
8342:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8344:    Logically Collective on Mat

8346:    Input Parameters:
8347: +  mat - the matrix
8348: -  nullsp - the null space object

8350:    Level: advanced

8352:    Notes:
8353:       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.
8354:       You must also call MatSetNullSpace()


8357:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8358:    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).
8359:    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
8360:    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
8361:    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).

8363:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8365: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8366: @*/
8367: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8368: {

8374:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8375:   MatNullSpaceDestroy(&mat->transnullsp);
8376:   mat->transnullsp = nullsp;
8377:   return(0);
8378: }

8380: /*@
8381:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8382:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8384:    Logically Collective on Mat

8386:    Input Parameters:
8387: +  mat - the matrix
8388: -  nullsp - the null space object

8390:    Level: advanced

8392:    Notes:
8393:       Overwrites any previous near null space that may have been attached

8395:       You can remove the null space by calling this routine with an nullsp of NULL

8397: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8398: @*/
8399: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8400: {

8407:   MatCheckPreallocated(mat,1);
8408:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8409:   MatNullSpaceDestroy(&mat->nearnullsp);
8410:   mat->nearnullsp = nullsp;
8411:   return(0);
8412: }

8414: /*@
8415:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8417:    Not Collective

8419:    Input Parameter:
8420: .  mat - the matrix

8422:    Output Parameter:
8423: .  nullsp - the null space object, NULL if not set

8425:    Level: developer

8427: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8428: @*/
8429: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8430: {
8435:   MatCheckPreallocated(mat,1);
8436:   *nullsp = mat->nearnullsp;
8437:   return(0);
8438: }

8440: /*@C
8441:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8443:    Collective on Mat

8445:    Input Parameters:
8446: +  mat - the matrix
8447: .  row - row/column permutation
8448: .  fill - expected fill factor >= 1.0
8449: -  level - level of fill, for ICC(k)

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

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

8459:    Level: developer


8462: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8467: @*/
8468: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8469: {

8477:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8478:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8479:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8480:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8481:   MatCheckPreallocated(mat,1);
8482:   (*mat->ops->iccfactor)(mat,row,info);
8483:   PetscObjectStateIncrease((PetscObject)mat);
8484:   return(0);
8485: }

8487: /*@
8488:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8489:          ghosted ones.

8491:    Not Collective

8493:    Input Parameters:
8494: +  mat - the matrix
8495: -  diag = the diagonal values, including ghost ones

8497:    Level: developer

8499:    Notes:
8500:     Works only for MPIAIJ and MPIBAIJ matrices

8502: .seealso: MatDiagonalScale()
8503: @*/
8504: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8505: {
8507:   PetscMPIInt    size;


8514:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8515:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8516:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8517:   if (size == 1) {
8518:     PetscInt n,m;
8519:     VecGetSize(diag,&n);
8520:     MatGetSize(mat,NULL,&m);
8521:     if (m == n) {
8522:       MatDiagonalScale(mat,NULL,diag);
8523:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8524:   } else {
8525:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8526:   }
8527:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8528:   PetscObjectStateIncrease((PetscObject)mat);
8529:   return(0);
8530: }

8532: /*@
8533:    MatGetInertia - Gets the inertia from a factored matrix

8535:    Collective on Mat

8537:    Input Parameter:
8538: .  mat - the matrix

8540:    Output Parameters:
8541: +   nneg - number of negative eigenvalues
8542: .   nzero - number of zero eigenvalues
8543: -   npos - number of positive eigenvalues

8545:    Level: advanced

8547:    Notes:
8548:     Matrix must have been factored by MatCholeskyFactor()


8551: @*/
8552: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8553: {

8559:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8560:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8561:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8562:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8563:   return(0);
8564: }

8566: /* ----------------------------------------------------------------*/
8567: /*@C
8568:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8570:    Neighbor-wise Collective on Mats

8572:    Input Parameters:
8573: +  mat - the factored matrix
8574: -  b - the right-hand-side vectors

8576:    Output Parameter:
8577: .  x - the result vectors

8579:    Notes:
8580:    The vectors b and x cannot be the same.  I.e., one cannot
8581:    call MatSolves(A,x,x).

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

8588:    Level: developer

8590: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8591: @*/
8592: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8593: {

8599:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8600:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8601:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8603:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8604:   MatCheckPreallocated(mat,1);
8605:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8606:   (*mat->ops->solves)(mat,b,x);
8607:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8608:   return(0);
8609: }

8611: /*@
8612:    MatIsSymmetric - Test whether a matrix is symmetric

8614:    Collective on Mat

8616:    Input Parameter:
8617: +  A - the matrix to test
8618: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8620:    Output Parameters:
8621: .  flg - the result

8623:    Notes:
8624:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8626:    Level: intermediate

8628: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8629: @*/
8630: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8631: {


8638:   if (!A->symmetric_set) {
8639:     if (!A->ops->issymmetric) {
8640:       MatType mattype;
8641:       MatGetType(A,&mattype);
8642:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8643:     }
8644:     (*A->ops->issymmetric)(A,tol,flg);
8645:     if (!tol) {
8646:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8647:     }
8648:   } else if (A->symmetric) {
8649:     *flg = PETSC_TRUE;
8650:   } else if (!tol) {
8651:     *flg = PETSC_FALSE;
8652:   } else {
8653:     if (!A->ops->issymmetric) {
8654:       MatType mattype;
8655:       MatGetType(A,&mattype);
8656:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8657:     }
8658:     (*A->ops->issymmetric)(A,tol,flg);
8659:   }
8660:   return(0);
8661: }

8663: /*@
8664:    MatIsHermitian - Test whether a matrix is Hermitian

8666:    Collective on Mat

8668:    Input Parameter:
8669: +  A - the matrix to test
8670: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8672:    Output Parameters:
8673: .  flg - the result

8675:    Level: intermediate

8677: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8678:           MatIsSymmetricKnown(), MatIsSymmetric()
8679: @*/
8680: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8681: {


8688:   if (!A->hermitian_set) {
8689:     if (!A->ops->ishermitian) {
8690:       MatType mattype;
8691:       MatGetType(A,&mattype);
8692:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8693:     }
8694:     (*A->ops->ishermitian)(A,tol,flg);
8695:     if (!tol) {
8696:       MatSetOption(A,MAT_HERMITIAN,*flg);
8697:     }
8698:   } else if (A->hermitian) {
8699:     *flg = PETSC_TRUE;
8700:   } else if (!tol) {
8701:     *flg = PETSC_FALSE;
8702:   } else {
8703:     if (!A->ops->ishermitian) {
8704:       MatType mattype;
8705:       MatGetType(A,&mattype);
8706:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8707:     }
8708:     (*A->ops->ishermitian)(A,tol,flg);
8709:   }
8710:   return(0);
8711: }

8713: /*@
8714:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8716:    Not Collective

8718:    Input Parameter:
8719: .  A - the matrix to check

8721:    Output Parameters:
8722: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8723: -  flg - the result

8725:    Level: advanced

8727:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8728:          if you want it explicitly checked

8730: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8731: @*/
8732: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8733: {
8738:   if (A->symmetric_set) {
8739:     *set = PETSC_TRUE;
8740:     *flg = A->symmetric;
8741:   } else {
8742:     *set = PETSC_FALSE;
8743:   }
8744:   return(0);
8745: }

8747: /*@
8748:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8750:    Not Collective

8752:    Input Parameter:
8753: .  A - the matrix to check

8755:    Output Parameters:
8756: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8757: -  flg - the result

8759:    Level: advanced

8761:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8762:          if you want it explicitly checked

8764: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8765: @*/
8766: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8767: {
8772:   if (A->hermitian_set) {
8773:     *set = PETSC_TRUE;
8774:     *flg = A->hermitian;
8775:   } else {
8776:     *set = PETSC_FALSE;
8777:   }
8778:   return(0);
8779: }

8781: /*@
8782:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8784:    Collective on Mat

8786:    Input Parameter:
8787: .  A - the matrix to test

8789:    Output Parameters:
8790: .  flg - the result

8792:    Level: intermediate

8794: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8795: @*/
8796: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8797: {

8803:   if (!A->structurally_symmetric_set) {
8804:     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);
8805:     (*A->ops->isstructurallysymmetric)(A,flg);
8806:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8807:   } else *flg = A->structurally_symmetric;
8808:   return(0);
8809: }

8811: /*@
8812:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8813:        to be communicated to other processors during the MatAssemblyBegin/End() process

8815:     Not collective

8817:    Input Parameter:
8818: .   vec - the vector

8820:    Output Parameters:
8821: +   nstash   - the size of the stash
8822: .   reallocs - the number of additional mallocs incurred.
8823: .   bnstash   - the size of the block stash
8824: -   breallocs - the number of additional mallocs incurred.in the block stash

8826:    Level: advanced

8828: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8830: @*/
8831: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8832: {

8836:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8837:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8838:   return(0);
8839: }

8841: /*@C
8842:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8843:      parallel layout

8845:    Collective on Mat

8847:    Input Parameter:
8848: .  mat - the matrix

8850:    Output Parameter:
8851: +   right - (optional) vector that the matrix can be multiplied against
8852: -   left - (optional) vector that the matrix vector product can be stored in

8854:    Notes:
8855:     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().

8857:   Notes:
8858:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8860:   Level: advanced

8862: .seealso: MatCreate(), VecDestroy()
8863: @*/
8864: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8865: {

8871:   if (mat->ops->getvecs) {
8872:     (*mat->ops->getvecs)(mat,right,left);
8873:   } else {
8874:     PetscInt rbs,cbs;
8875:     MatGetBlockSizes(mat,&rbs,&cbs);
8876:     if (right) {
8877:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8878:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8879:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8880:       VecSetBlockSize(*right,cbs);
8881:       VecSetType(*right,mat->defaultvectype);
8882:       PetscLayoutReference(mat->cmap,&(*right)->map);
8883:     }
8884:     if (left) {
8885:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8886:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8887:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8888:       VecSetBlockSize(*left,rbs);
8889:       VecSetType(*left,mat->defaultvectype);
8890:       PetscLayoutReference(mat->rmap,&(*left)->map);
8891:     }
8892:   }
8893:   return(0);
8894: }

8896: /*@C
8897:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8898:      with default values.

8900:    Not Collective

8902:    Input Parameters:
8903: .    info - the MatFactorInfo data structure


8906:    Notes:
8907:     The solvers are generally used through the KSP and PC objects, for example
8908:           PCLU, PCILU, PCCHOLESKY, PCICC

8910:    Level: developer

8912: .seealso: MatFactorInfo

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

8917: @*/

8919: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8920: {

8924:   PetscMemzero(info,sizeof(MatFactorInfo));
8925:   return(0);
8926: }

8928: /*@
8929:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8931:    Collective on Mat

8933:    Input Parameters:
8934: +  mat - the factored matrix
8935: -  is - the index set defining the Schur indices (0-based)

8937:    Notes:
8938:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8940:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8942:    Level: developer

8944: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8945:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8947: @*/
8948: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8949: {
8950:   PetscErrorCode ierr,(*f)(Mat,IS);

8958:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8959:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8960:   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");
8961:   MatDestroy(&mat->schur);
8962:   (*f)(mat,is);
8963:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8964:   return(0);
8965: }

8967: /*@
8968:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8970:    Logically Collective on Mat

8972:    Input Parameters:
8973: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8974: .  S - location where to return the Schur complement, can be NULL
8975: -  status - the status of the Schur complement matrix, can be NULL

8977:    Notes:
8978:    You must call MatFactorSetSchurIS() before calling this routine.

8980:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8981:    The caller must destroy the object when it is no longer needed.
8982:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8984:    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)

8986:    Developer Notes:
8987:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8988:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8990:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8992:    Level: advanced

8994:    References:

8996: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8997: @*/
8998: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8999: {

9006:   if (S) {
9007:     PetscErrorCode (*f)(Mat,Mat*);

9009:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
9010:     if (f) {
9011:       (*f)(F,S);
9012:     } else {
9013:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
9014:     }
9015:   }
9016:   if (status) *status = F->schur_status;
9017:   return(0);
9018: }

9020: /*@
9021:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

9023:    Logically Collective on Mat

9025:    Input Parameters:
9026: +  F - the factored matrix obtained by calling MatGetFactor()
9027: .  *S - location where to return the Schur complement, can be NULL
9028: -  status - the status of the Schur complement matrix, can be NULL

9030:    Notes:
9031:    You must call MatFactorSetSchurIS() before calling this routine.

9033:    Schur complement mode is currently implemented for sequential matrices.
9034:    The routine returns a the Schur Complement stored within the data strutures of the solver.
9035:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
9036:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

9038:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

9040:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

9042:    Level: advanced

9044:    References:

9046: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9047: @*/
9048: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9049: {
9054:   if (S) *S = F->schur;
9055:   if (status) *status = F->schur_status;
9056:   return(0);
9057: }

9059: /*@
9060:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

9062:    Logically Collective on Mat

9064:    Input Parameters:
9065: +  F - the factored matrix obtained by calling MatGetFactor()
9066: .  *S - location where the Schur complement is stored
9067: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

9069:    Notes:

9071:    Level: advanced

9073:    References:

9075: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9076: @*/
9077: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9078: {

9083:   if (S) {
9085:     *S = NULL;
9086:   }
9087:   F->schur_status = status;
9088:   MatFactorUpdateSchurStatus_Private(F);
9089:   return(0);
9090: }

9092: /*@
9093:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9095:    Logically Collective on Mat

9097:    Input Parameters:
9098: +  F - the factored matrix obtained by calling MatGetFactor()
9099: .  rhs - location where the right hand side of the Schur complement system is stored
9100: -  sol - location where the solution of the Schur complement system has to be returned

9102:    Notes:
9103:    The sizes of the vectors should match the size of the Schur complement

9105:    Must be called after MatFactorSetSchurIS()

9107:    Level: advanced

9109:    References:

9111: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9112: @*/
9113: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9114: {

9126:   MatFactorFactorizeSchurComplement(F);
9127:   switch (F->schur_status) {
9128:   case MAT_FACTOR_SCHUR_FACTORED:
9129:     MatSolveTranspose(F->schur,rhs,sol);
9130:     break;
9131:   case MAT_FACTOR_SCHUR_INVERTED:
9132:     MatMultTranspose(F->schur,rhs,sol);
9133:     break;
9134:   default:
9135:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9136:   }
9137:   return(0);
9138: }

9140: /*@
9141:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9143:    Logically Collective on Mat

9145:    Input Parameters:
9146: +  F - the factored matrix obtained by calling MatGetFactor()
9147: .  rhs - location where the right hand side of the Schur complement system is stored
9148: -  sol - location where the solution of the Schur complement system has to be returned

9150:    Notes:
9151:    The sizes of the vectors should match the size of the Schur complement

9153:    Must be called after MatFactorSetSchurIS()

9155:    Level: advanced

9157:    References:

9159: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9160: @*/
9161: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9162: {

9174:   MatFactorFactorizeSchurComplement(F);
9175:   switch (F->schur_status) {
9176:   case MAT_FACTOR_SCHUR_FACTORED:
9177:     MatSolve(F->schur,rhs,sol);
9178:     break;
9179:   case MAT_FACTOR_SCHUR_INVERTED:
9180:     MatMult(F->schur,rhs,sol);
9181:     break;
9182:   default:
9183:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9184:   }
9185:   return(0);
9186: }

9188: /*@
9189:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9191:    Logically Collective on Mat

9193:    Input Parameters:
9194: .  F - the factored matrix obtained by calling MatGetFactor()

9196:    Notes:
9197:     Must be called after MatFactorSetSchurIS().

9199:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9201:    Level: advanced

9203:    References:

9205: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9206: @*/
9207: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9208: {

9214:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9215:   MatFactorFactorizeSchurComplement(F);
9216:   MatFactorInvertSchurComplement_Private(F);
9217:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9218:   return(0);
9219: }

9221: /*@
9222:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9224:    Logically Collective on Mat

9226:    Input Parameters:
9227: .  F - the factored matrix obtained by calling MatGetFactor()

9229:    Notes:
9230:     Must be called after MatFactorSetSchurIS().

9232:    Level: advanced

9234:    References:

9236: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9237: @*/
9238: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9239: {

9245:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9246:   MatFactorFactorizeSchurComplement_Private(F);
9247:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9248:   return(0);
9249: }

9251: /*@
9252:    MatPtAP - Creates the matrix product C = P^T * A * P

9254:    Neighbor-wise Collective on Mat

9256:    Input Parameters:
9257: +  A - the matrix
9258: .  P - the projection matrix
9259: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9260: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9261:           if the result is a dense matrix this is irrelevent

9263:    Output Parameters:
9264: .  C - the product matrix

9266:    Notes:
9267:    C will be created and must be destroyed by the user with MatDestroy().

9269:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9271:    Level: intermediate

9273: .seealso: MatMatMult(), MatRARt()
9274: @*/
9275: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9276: {

9280:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9281:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9283:   if (scall == MAT_INITIAL_MATRIX) {
9284:     MatProductCreate(A,P,NULL,C);
9285:     MatProductSetType(*C,MATPRODUCT_PtAP);
9286:     MatProductSetAlgorithm(*C,"default");
9287:     MatProductSetFill(*C,fill);

9289:     (*C)->product->api_user = PETSC_TRUE;
9290:     MatProductSetFromOptions(*C);
9291:     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);
9292:     MatProductSymbolic(*C);
9293:   } else { /* scall == MAT_REUSE_MATRIX */
9294:     MatProductReplaceMats(A,P,NULL,*C);
9295:   }

9297:   MatProductNumeric(*C);
9298:   if (A->symmetric_set && A->symmetric) {
9299:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9300:   }
9301:   return(0);
9302: }

9304: /*@
9305:    MatRARt - Creates the matrix product C = R * A * R^T

9307: