Actual source code: matrix.c

  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_QRFactorNumeric, MAT_QRFactorSymbolic, MAT_QRFactor;
 21: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
 22: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
 23: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
 24: PetscLogEvent MAT_TransposeColoringCreate;
 25: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
 26: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
 27: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
 28: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
 29: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
 30: PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
 31: PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
 32: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
 33: PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
 34: PetscLogEvent MAT_GetMultiProcBlock;
 35: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_CUSPARSECopyFromGPU, MAT_CUSPARSEGenerateTranspose, MAT_CUSPARSESolveAnalysis;
 36: PetscLogEvent MAT_PreallCOO, MAT_SetVCOO;
 37: PetscLogEvent MAT_SetValuesBatch;
 38: PetscLogEvent MAT_ViennaCLCopyToGPU;
 39: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
 40: PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
 41: PetscLogEvent MAT_FactorFactS,MAT_FactorInvS;
 42: PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;

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

 46: /*@
 47:    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,
 48:                   for sparse matrices that already have locations it fills the locations with random numbers

 50:    Logically Collective on Mat

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

 57:    Output Parameter:
 58: .  x  - the matrix

 60:    Example of Usage:
 61: .vb
 62:      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
 63:      MatSetRandom(x,rctx);
 64:      PetscRandomDestroy(rctx);
 65: .ve

 67:    Level: intermediate

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


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

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

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

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

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

104:    Logically Collective on Mat

106:    Input Parameter:
107: .  mat - the factored matrix

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

114:    Level: advanced

116:    Notes:
117:     This routine does not work for factorizations done with external packages.

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

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

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

134: /*@
135:    MatFactorGetError - gets the error code from a factorization

137:    Logically Collective on Mat

139:    Input Parameters:
140: .  mat - the factored matrix

142:    Output Parameter:
143: .  err  - the error code

145:    Level: advanced

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

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

160: /*@
161:    MatFactorClearError - clears the error code in a factorization

163:    Logically Collective on Mat

165:    Input Parameter:
166: .  mat - the factored matrix

168:    Level: developer

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

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

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

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

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

234:   Input Parameter:
235: .    A  - the matrix

237:   Output Parameter:
238: .    keptrows - the rows that are not completely zero

240:   Notes:
241:     keptrows is set to NULL if all rows are nonzero.

243:   Level: intermediate

245:  @*/
246: PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
247: {

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

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

267:   Input Parameter:
268: .    A  - the matrix

270:   Output Parameter:
271: .    zerorows - the rows that are completely zero

273:   Notes:
274:     zerorows is set to NULL if no rows are zero.

276:   Level: intermediate

278:  @*/
279: PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
280: {
282:   IS             keptrows;
283:   PetscInt       m, n;

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

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

306:    Not Collective

308:    Input Parameters:
309: .   A - the matrix

311:    Output Parameters:
312: .   a - the diagonal part (which is a SEQUENTIAL matrix)

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

319:    Level: advanced

321: @*/
322: PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
323: {

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

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

346:    Collective on Mat

348:    Input Parameters:
349: .  mat - the matrix

351:    Output Parameter:
352: .   trace - the sum of the diagonal entries

354:    Level: advanced

356: @*/
357: PetscErrorCode MatGetTrace(Mat mat,PetscScalar *trace)
358: {
360:   Vec            diag;

363:   MatCreateVecs(mat,&diag,NULL);
364:   MatGetDiagonal(mat,diag);
365:   VecSum(diag,trace);
366:   VecDestroy(&diag);
367:   return(0);
368: }

370: /*@
371:    MatRealPart - Zeros out the imaginary part of the matrix

373:    Logically Collective on Mat

375:    Input Parameters:
376: .  mat - the matrix

378:    Level: advanced

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

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

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

400:    Collective on Mat

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

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

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

412:    Level: advanced

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

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

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

436:    Logically Collective on Mat

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

441:    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

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

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

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

496:    Not Collective

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

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

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

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

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

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

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

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

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

545:    Level: advanced

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

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

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

572:    Logically Collective on Mat

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

577:    Level: advanced

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

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

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

600:    Not Collective

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

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

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

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

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

630:    Level: advanced

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

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

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

654:    Not Collective

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

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

662:    Level: advanced

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

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

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

684:    Not Collective

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

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

692:    Level: advanced

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

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

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

715:    Logically Collective on Mat

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

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

725:    Level: advanced

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

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

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

743:    Logically Collective on Mat

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

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

753:    Level: advanced

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

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

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

771:    Not Collective

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

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

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

783:    Level: advanced

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

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

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

800:    Collective on Mat

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

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

809:    Level: beginner

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

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

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

827:    Collective on Mat

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

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

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

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

839:    Level: beginner

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

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

868: #if defined(PETSC_HAVE_SAWS)
869: #include <petscviewersaws.h>
870: #endif

872: /*@C
873:    MatViewFromOptions - View from Options

875:    Collective on Mat

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

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

891:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
892:   return(0);
893: }

895: /*@C
896:    MatView - Visualizes a matrix object.

898:    Collective on Mat

900:    Input Parameters:
901: +  mat - the matrix
902: -  viewer - visualization context

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

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

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

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

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

955:     In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).

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

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

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

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

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

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

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

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

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

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

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

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

1092:    Collective on PetscViewer

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

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

1104:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1189:    Corresponding MatView() is not yet implemented.

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

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

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

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


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

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

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

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

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

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

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

1269:    Collective on Mat

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

1274:    Level: beginner

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

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

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

1292:   PetscFree((*A)->defaultvectype);
1293:   PetscFree((*A)->bsizes);
1294:   PetscFree((*A)->solvertype);
1295:   for (PetscInt i=0; i<MAT_FACTOR_NUM_TYPES; i++) {
1296:     PetscFree((*A)->preferredordering[i]);
1297:   }
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:     for (i=0; i<m; i++) if (idxm[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot insert in row %D, maximum is %D",idxm[i],mat->rmap->N-1);
1389:     for (i=0; i<n; i++) if (idxn[i] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot insert in column %D, maximum is %D",idxn[i],mat->cmap->N-1);
1390:   }

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

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

1406:    Not Collective

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

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

1416:    All the nonzeros in the row must be provided

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

1420:    The row must belong to this process

1422:    Level: intermediate

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

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

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

1445:    Not Collective

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

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

1455:    All the nonzeros in the row must be provided

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

1459:    The row must belong to this process

1461:    Level: advanced

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

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

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

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

1494:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

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

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

1554:    Level: beginner

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

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

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

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

1608:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

1661:    Level: beginner

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

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

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

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

1717:    Not Collective

1719:    Input Parameters:
1720: +  mat - the matrix
1721: .  dim - dimension of the grid 1, 2, or 3
1722: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1723: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1724: -  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:   }
1843:   if (PetscDefined(USE_DEBUG)) {
1844:     PetscInt rbs,cbs,M,N,i;
1845:     MatGetBlockSizes(mat,&rbs,&cbs);
1846:     MatGetSize(mat,&M,&N);
1847:     for (i=0; i<m; i++) {
1848:       if (idxm[i]*rbs >= M) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row block index %D (index %D) greater than row length %D",i,idxm[i],M);
1849:     }
1850:     for (i=0; i<n; i++) {
1851:       if (idxn[i]*cbs >= N) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column block index %D (index %D) great than column length %D",i,idxn[i],N);
1852:     }
1853:   }
1854:   if (mat->assembled) {
1855:     mat->was_assembled = PETSC_TRUE;
1856:     mat->assembled     = PETSC_FALSE;
1857:   }
1858:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1859:   if (mat->ops->setvaluesblocked) {
1860:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1861:   } else {
1862:     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*iidxm,*iidxn;
1863:     PetscInt i,j,bs,cbs;
1864:     MatGetBlockSizes(mat,&bs,&cbs);
1865:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1866:       iidxm = buf; iidxn = buf + m*bs;
1867:     } else {
1868:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1869:       iidxm = bufr; iidxn = bufc;
1870:     }
1871:     for (i=0; i<m; i++) {
1872:       for (j=0; j<bs; j++) {
1873:         iidxm[i*bs+j] = bs*idxm[i] + j;
1874:       }
1875:     }
1876:     for (i=0; i<n; i++) {
1877:       for (j=0; j<cbs; j++) {
1878:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1879:       }
1880:     }
1881:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1882:     PetscFree2(bufr,bufc);
1883:   }
1884:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1885:   return(0);
1886: }

1888: /*@C
1889:    MatGetValues - Gets a block of values from a matrix.

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

1893:    Input Parameters:
1894: +  mat - the matrix
1895: .  v - a logically two-dimensional array for storing the values
1896: .  m, idxm - the number of rows and their global indices
1897: -  n, idxn - the number of columns and their global indices

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

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

1907:      MatGetValues() requires that the matrix has been assembled
1908:      with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1909:      MatSetValues() and MatGetValues() CANNOT be made in succession
1910:      without intermediate matrix assembly.

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

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

1919:    Level: advanced

1921: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues(), MatGetOwnershipRange(), MatGetValuesLocal()
1922: @*/
1923: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1924: {

1930:   if (!m || !n) return(0);
1934:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1935:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1936:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1937:   MatCheckPreallocated(mat,1);

1939:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1940:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1941:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1942:   return(0);
1943: }

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

1949:    Not Collective

1951:    Input Parameters:
1952: +  mat - the matrix
1953: .  nrow, irow - number of rows and their local indices
1954: -  ncol, icol - number of columns and their local indices

1956:    Output Parameter:
1957: .  y -  a logically two-dimensional array of values

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

1962:      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,
1963:      are greater than or equal to restart and less than rend where restart and rend are obtainable from MatGetOwnershipRange(mat,&rstart,&rend). One can
1964:      determine if the resulting global row associated with the local row r is owned by the requesting MPI rank by applying the ISLocalToGlobalMapping set
1965:      with MatSetLocalToGlobalMapping().

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

1971:    Level: advanced

1973: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1974:            MatSetValuesLocal(), MatGetValues()
1975: @*/
1976: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1977: {

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

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

2018:   Not Collective

2020:   Input Parameters:
2021: + mat - the matrix
2022: . nb - the number of blocks
2023: . bs - the number of rows (and columns) in each block
2024: . rows - a concatenation of the rows for each block
2025: - v - a concatenation of logically two-dimensional arrays of values

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

2030:   Level: advanced

2032: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2033:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2034: @*/
2035: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2036: {

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

2046:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2047:   if (mat->ops->setvaluesbatch) {
2048:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2049:   } else {
2050:     PetscInt b;
2051:     for (b = 0; b < nb; ++b) {
2052:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2053:     }
2054:   }
2055:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2056:   return(0);
2057: }

2059: /*@
2060:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2061:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2062:    using a local (per-processor) numbering.

2064:    Not Collective

2066:    Input Parameters:
2067: +  x - the matrix
2068: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2069: - cmapping - column mapping

2071:    Level: intermediate

2073: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal(), MatGetValuesLocal()
2074: @*/
2075: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2076: {


2085:   if (x->ops->setlocaltoglobalmapping) {
2086:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2087:   } else {
2088:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2089:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2090:   }
2091:   return(0);
2092: }

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

2097:    Not Collective

2099:    Input Parameter:
2100: .  A - the matrix

2102:    Output Parameters:
2103: + rmapping - row mapping
2104: - cmapping - column mapping

2106:    Level: advanced

2108: .seealso:  MatSetValuesLocal()
2109: @*/
2110: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2111: {
2117:   if (rmapping) *rmapping = A->rmap->mapping;
2118:   if (cmapping) *cmapping = A->cmap->mapping;
2119:   return(0);
2120: }

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

2125:    Logically Collective on A

2127:    Input Parameters:
2128: +  A - the matrix
2129: . rmap - row layout
2130: - cmap - column layout

2132:    Level: advanced

2134: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatGetLayouts()
2135: @*/
2136: PetscErrorCode MatSetLayouts(Mat A,PetscLayout rmap,PetscLayout cmap)
2137: {


2143:   PetscLayoutReference(rmap,&A->rmap);
2144:   PetscLayoutReference(cmap,&A->cmap);
2145:   return(0);
2146: }

2148: /*@
2149:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2151:    Not Collective

2153:    Input Parameter:
2154: .  A - the matrix

2156:    Output Parameters:
2157: + rmap - row layout
2158: - cmap - column layout

2160:    Level: advanced

2162: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatSetLayouts()
2163: @*/
2164: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2165: {
2171:   if (rmap) *rmap = A->rmap;
2172:   if (cmap) *cmap = A->cmap;
2173:   return(0);
2174: }

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

2180:    Not Collective

2182:    Input Parameters:
2183: +  mat - the matrix
2184: .  nrow, irow - number of rows and their local indices
2185: .  ncol, icol - number of columns and their local indices
2186: .  y -  a logically two-dimensional array of values
2187: -  addv - either INSERT_VALUES or ADD_VALUES, where
2188:    ADD_VALUES adds values to any existing entries, and
2189:    INSERT_VALUES replaces existing entries with new values

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

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

2197:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2198:    options cannot be mixed without intervening calls to the assembly
2199:    routines.

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

2204:    Level: intermediate

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

2210: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2211:            MatSetValueLocal(), MatGetValuesLocal()
2212: @*/
2213: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2214: {

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

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

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

2263:    Not Collective

2265:    Input Parameters:
2266: +  x - the matrix
2267: .  nrow, irow - number of rows and their local indices
2268: .  ncol, icol - number of columns and their local indices
2269: .  y -  a logically two-dimensional array of values
2270: -  addv - either INSERT_VALUES or ADD_VALUES, where
2271:    ADD_VALUES adds values to any existing entries, and
2272:    INSERT_VALUES replaces existing entries with new values

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

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

2281:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2282:    options cannot be mixed without intervening calls to the assembly
2283:    routines.

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

2288:    Level: intermediate

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

2294: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2295:            MatSetValuesLocal(),  MatSetValuesBlocked()
2296: @*/
2297: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2298: {

2304:   MatCheckPreallocated(mat,1);
2305:   if (!nrow || !ncol) return(0); /* no values to insert */
2309:   if (mat->insertmode == NOT_SET_VALUES) {
2310:     mat->insertmode = addv;
2311:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2312:   if (PetscDefined(USE_DEBUG)) {
2313:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2314:     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);
2315:   }

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

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

2356:    Collective on Mat

2358:    Input Parameters:
2359: +  mat - the matrix
2360: -  x   - the vector to be multiplied

2362:    Output Parameters:
2363: .  y - the result

2365:    Notes:
2366:    The vectors x and y cannot be the same.  I.e., one cannot
2367:    call MatMult(A,y,y).

2369:    Level: developer

2371: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2372: @*/
2373: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2374: {


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

2388:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2389:   (*mat->ops->multdiagonalblock)(mat,x,y);
2390:   PetscObjectStateIncrease((PetscObject)y);
2391:   return(0);
2392: }

2394: /* --------------------------------------------------------*/
2395: /*@
2396:    MatMult - Computes the matrix-vector product, y = Ax.

2398:    Neighbor-wise Collective on Mat

2400:    Input Parameters:
2401: +  mat - the matrix
2402: -  x   - the vector to be multiplied

2404:    Output Parameters:
2405: .  y - the result

2407:    Notes:
2408:    The vectors x and y cannot be the same.  I.e., one cannot
2409:    call MatMult(A,y,y).

2411:    Level: beginner

2413: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2414: @*/
2415: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2416: {

2424:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2425:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2426:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2427:   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);
2428:   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);
2429:   if (mat->cmap->n != x->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: local dim %D %D",mat->cmap->n,x->map->n);
2430:   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);
2431:   VecSetErrorIfLocked(y,3);
2432:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2433:   MatCheckPreallocated(mat,1);

2435:   VecLockReadPush(x);
2436:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2437:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2438:   (*mat->ops->mult)(mat,x,y);
2439:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2440:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2441:   VecLockReadPop(x);
2442:   return(0);
2443: }

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

2448:    Neighbor-wise Collective on Mat

2450:    Input Parameters:
2451: +  mat - the matrix
2452: -  x   - the vector to be multiplied

2454:    Output Parameters:
2455: .  y - the result

2457:    Notes:
2458:    The vectors x and y cannot be the same.  I.e., one cannot
2459:    call MatMultTranspose(A,y,y).

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

2464:    Level: beginner

2466: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2467: @*/
2468: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2469: {
2470:   PetscErrorCode (*op)(Mat,Vec,Vec)=NULL,ierr;


2478:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2479:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2480:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2481:   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);
2482:   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);
2483:   if (mat->cmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->cmap->n,y->map->n);
2484:   if (mat->rmap->n != x->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: local dim %D %D",mat->rmap->n,x->map->n);
2485:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2486:   MatCheckPreallocated(mat,1);

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

2502: /*@
2503:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2505:    Neighbor-wise Collective on Mat

2507:    Input Parameters:
2508: +  mat - the matrix
2509: -  x   - the vector to be multilplied

2511:    Output Parameters:
2512: .  y - the result

2514:    Notes:
2515:    The vectors x and y cannot be the same.  I.e., one cannot
2516:    call MatMultHermitianTranspose(A,y,y).

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

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

2522:    Level: beginner

2524: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2525: @*/
2526: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2527: {


2536:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2537:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2538:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2539:   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);
2540:   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);
2541:   if (mat->cmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->cmap->n,y->map->n);
2542:   if (mat->rmap->n != x->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: local dim %D %D",mat->rmap->n,x->map->n);
2543:   MatCheckPreallocated(mat,1);

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

2572: /*@
2573:     MatMultAdd -  Computes v3 = v2 + A * v1.

2575:     Neighbor-wise Collective on Mat

2577:     Input Parameters:
2578: +   mat - the matrix
2579: -   v1, v2 - the vectors

2581:     Output Parameters:
2582: .   v3 - the result

2584:     Notes:
2585:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2586:     call MatMultAdd(A,v1,v2,v1).

2588:     Level: beginner

2590: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2591: @*/
2592: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2593: {


2603:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2604:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2605:   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);
2606:   /* 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);
2607:      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); */
2608:   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);
2609:   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);
2610:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2611:   MatCheckPreallocated(mat,1);

2613:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2614:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2615:   VecLockReadPush(v1);
2616:   (*mat->ops->multadd)(mat,v1,v2,v3);
2617:   VecLockReadPop(v1);
2618:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2619:   PetscObjectStateIncrease((PetscObject)v3);
2620:   return(0);
2621: }

2623: /*@
2624:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2626:    Neighbor-wise Collective on Mat

2628:    Input Parameters:
2629: +  mat - the matrix
2630: -  v1, v2 - the vectors

2632:    Output Parameters:
2633: .  v3 - the result

2635:    Notes:
2636:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2637:    call MatMultTransposeAdd(A,v1,v2,v1).

2639:    Level: beginner

2641: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2642: @*/
2643: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2644: {


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

2663:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2664:   VecLockReadPush(v1);
2665:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2666:   VecLockReadPop(v1);
2667:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2668:   PetscObjectStateIncrease((PetscObject)v3);
2669:   return(0);
2670: }

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

2675:    Neighbor-wise Collective on Mat

2677:    Input Parameters:
2678: +  mat - the matrix
2679: -  v1, v2 - the vectors

2681:    Output Parameters:
2682: .  v3 - the result

2684:    Notes:
2685:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2686:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2688:    Level: beginner

2690: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2691: @*/
2692: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2693: {


2703:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2704:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2705:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2706:   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);
2707:   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);
2708:   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);
2709:   MatCheckPreallocated(mat,1);

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

2737: /*@
2738:    MatMultConstrained - The inner multiplication routine for a
2739:    constrained matrix P^T A P.

2741:    Neighbor-wise Collective on Mat

2743:    Input Parameters:
2744: +  mat - the matrix
2745: -  x   - the vector to be multilplied

2747:    Output Parameters:
2748: .  y - the result

2750:    Notes:
2751:    The vectors x and y cannot be the same.  I.e., one cannot
2752:    call MatMult(A,y,y).

2754:    Level: beginner

2756: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2757: @*/
2758: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2759: {

2766:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2767:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2768:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2769:   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);
2770:   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);
2771:   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);

2773:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2774:   VecLockReadPush(x);
2775:   (*mat->ops->multconstrained)(mat,x,y);
2776:   VecLockReadPop(x);
2777:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2778:   PetscObjectStateIncrease((PetscObject)y);
2779:   return(0);
2780: }

2782: /*@
2783:    MatMultTransposeConstrained - The inner multiplication routine for a
2784:    constrained matrix P^T A^T P.

2786:    Neighbor-wise Collective on Mat

2788:    Input Parameters:
2789: +  mat - the matrix
2790: -  x   - the vector to be multilplied

2792:    Output Parameters:
2793: .  y - the result

2795:    Notes:
2796:    The vectors x and y cannot be the same.  I.e., one cannot
2797:    call MatMult(A,y,y).

2799:    Level: beginner

2801: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2802: @*/
2803: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2804: {

2811:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2812:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2813:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2814:   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);
2815:   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);

2817:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2818:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2819:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2820:   PetscObjectStateIncrease((PetscObject)y);
2821:   return(0);
2822: }

2824: /*@C
2825:    MatGetFactorType - gets the type of factorization it is

2827:    Not Collective

2829:    Input Parameters:
2830: .  mat - the matrix

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

2835:    Level: intermediate

2837: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2838: @*/
2839: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2840: {
2845:   *t = mat->factortype;
2846:   return(0);
2847: }

2849: /*@C
2850:    MatSetFactorType - sets the type of factorization it is

2852:    Logically Collective on Mat

2854:    Input Parameters:
2855: +  mat - the matrix
2856: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2858:    Level: intermediate

2860: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2861: @*/
2862: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2863: {
2867:   mat->factortype = t;
2868:   return(0);
2869: }

2871: /* ------------------------------------------------------------*/
2872: /*@C
2873:    MatGetInfo - Returns information about matrix storage (number of
2874:    nonzeros, memory, etc.).

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

2878:    Input Parameter:
2879: .  mat - the matrix

2881:    Output Parameters:
2882: +  flag - flag indicating the type of parameters to be returned
2883:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2884:    MAT_GLOBAL_SUM - sum over all processors)
2885: -  info - matrix information context

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

2896:    Example for C/C++ Users:
2897:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2898:    data within the MatInfo context.  For example,
2899: .vb
2900:       MatInfo info;
2901:       Mat     A;
2902:       double  mal, nz_a, nz_u;

2904:       MatGetInfo(A,MAT_LOCAL,&info);
2905:       mal  = info.mallocs;
2906:       nz_a = info.nz_allocated;
2907: .ve

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

2920:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2921:       mal = info(MAT_INFO_MALLOCS)
2922:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2923: .ve

2925:     Level: intermediate

2927:     Developer Note: fortran interface is not autogenerated as the f90
2928:     interface definition cannot be generated correctly [due to MatInfo]

2930: .seealso: MatStashGetInfo()

2932: @*/
2933: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2934: {

2941:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2942:   MatCheckPreallocated(mat,1);
2943:   (*mat->ops->getinfo)(mat,flag,info);
2944:   return(0);
2945: }

2947: /*
2948:    This is used by external packages where it is not easy to get the info from the actual
2949:    matrix factorization.
2950: */
2951: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2952: {

2956:   PetscMemzero(info,sizeof(MatInfo));
2957:   return(0);
2958: }

2960: /* ----------------------------------------------------------*/

2962: /*@C
2963:    MatLUFactor - Performs in-place LU factorization of matrix.

2965:    Collective on Mat

2967:    Input Parameters:
2968: +  mat - the matrix
2969: .  row - row permutation
2970: .  col - column permutation
2971: -  info - options for factorization, includes
2972: $          fill - expected fill as ratio of original fill.
2973: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2974: $                   Run with the option -info to determine an optimal value to use

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

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

2984:    Level: developer

2986: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2987:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2992: @*/
2993: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2994: {
2996:   MatFactorInfo  tinfo;

3004:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3005:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3006:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3007:   MatCheckPreallocated(mat,1);
3008:   if (!info) {
3009:     MatFactorInfoInitialize(&tinfo);
3010:     info = &tinfo;
3011:   }

3013:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
3014:   (*mat->ops->lufactor)(mat,row,col,info);
3015:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
3016:   PetscObjectStateIncrease((PetscObject)mat);
3017:   return(0);
3018: }

3020: /*@C
3021:    MatILUFactor - Performs in-place ILU factorization of matrix.

3023:    Collective on Mat

3025:    Input Parameters:
3026: +  mat - the matrix
3027: .  row - row permutation
3028: .  col - column permutation
3029: -  info - structure containing
3030: $      levels - number of levels of fill.
3031: $      expected fill - as ratio of original fill.
3032: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3033:                 missing diagonal entries)

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

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

3043:    Level: developer

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

3047:     Developer Note: fortran interface is not autogenerated as the f90
3048:     interface definition cannot be generated correctly [due to MatFactorInfo]

3050: @*/
3051: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3052: {

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

3067:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3068:   (*mat->ops->ilufactor)(mat,row,col,info);
3069:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3070:   PetscObjectStateIncrease((PetscObject)mat);
3071:   return(0);
3072: }

3074: /*@C
3075:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3076:    Call this routine before calling MatLUFactorNumeric().

3078:    Collective on Mat

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

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

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

3096:    Level: developer

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

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

3103: @*/
3104: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3105: {
3107:   MatFactorInfo  tinfo;

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

3129:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);}
3130:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3131:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);}
3132:   PetscObjectStateIncrease((PetscObject)fact);
3133:   return(0);
3134: }

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

3140:    Collective on Mat

3142:    Input Parameters:
3143: +  fact - the factor matrix obtained with MatGetFactor()
3144: .  mat - the matrix
3145: -  info - options for factorization

3147:    Notes:
3148:    See MatLUFactor() for in-place factorization.  See
3149:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3155:    Level: developer

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

3159:     Developer Note: fortran interface is not autogenerated as the f90
3160:     interface definition cannot be generated correctly [due to MatFactorInfo]

3162: @*/
3163: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3164: {
3165:   MatFactorInfo  tinfo;

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

3176:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3177:   MatCheckPreallocated(mat,2);
3178:   if (!info) {
3179:     MatFactorInfoInitialize(&tinfo);
3180:     info = &tinfo;
3181:   }

3183:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);}
3184:   else {PetscLogEventBegin(MAT_LUFactor,mat,fact,0,0);}
3185:   (fact->ops->lufactornumeric)(fact,mat,info);
3186:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);}
3187:   else {PetscLogEventEnd(MAT_LUFactor,mat,fact,0,0);}
3188:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3189:   PetscObjectStateIncrease((PetscObject)fact);
3190:   return(0);
3191: }

3193: /*@C
3194:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3195:    symmetric matrix.

3197:    Collective on Mat

3199:    Input Parameters:
3200: +  mat - the matrix
3201: .  perm - row and column permutations
3202: -  f - expected fill as ratio of original fill

3204:    Notes:
3205:    See MatLUFactor() for the nonsymmetric case.  See also
3206:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3212:    Level: developer

3214: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3215:           MatGetOrdering()

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

3220: @*/
3221: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3222: {
3224:   MatFactorInfo  tinfo;

3231:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3232:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3233:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3234:   if (!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);
3235:   MatCheckPreallocated(mat,1);
3236:   if (!info) {
3237:     MatFactorInfoInitialize(&tinfo);
3238:     info = &tinfo;
3239:   }

3241:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3242:   (*mat->ops->choleskyfactor)(mat,perm,info);
3243:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3244:   PetscObjectStateIncrease((PetscObject)mat);
3245:   return(0);
3246: }

3248: /*@C
3249:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3250:    of a symmetric matrix.

3252:    Collective on Mat

3254:    Input Parameters:
3255: +  fact - the factor matrix obtained with MatGetFactor()
3256: .  mat - the matrix
3257: .  perm - row and column permutations
3258: -  info - options for factorization, includes
3259: $          fill - expected fill as ratio of original fill.
3260: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3261: $                   Run with the option -info to determine an optimal value to use

3263:    Notes:
3264:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3265:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3271:    Level: developer

3273: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3274:           MatGetOrdering()

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

3279: @*/
3280: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3281: {
3283:   MatFactorInfo  tinfo;

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

3305:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);}
3306:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3307:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);}
3308:   PetscObjectStateIncrease((PetscObject)fact);
3309:   return(0);
3310: }

3312: /*@C
3313:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3314:    of a symmetric matrix. Call this routine after first calling
3315:    MatCholeskyFactorSymbolic().

3317:    Collective on Mat

3319:    Input Parameters:
3320: +  fact - the factor matrix obtained with MatGetFactor()
3321: .  mat - the initial matrix
3322: .  info - options for factorization
3323: -  fact - the symbolic factor of mat

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

3330:    Level: developer

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

3334:     Developer Note: fortran interface is not autogenerated as the f90
3335:     interface definition cannot be generated correctly [due to MatFactorInfo]

3337: @*/
3338: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3339: {
3340:   MatFactorInfo  tinfo;

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

3357:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);}
3358:   else {PetscLogEventBegin(MAT_CholeskyFactor,mat,fact,0,0);}
3359:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3360:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);}
3361:   else {PetscLogEventEnd(MAT_CholeskyFactor,mat,fact,0,0);}
3362:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3363:   PetscObjectStateIncrease((PetscObject)fact);
3364:   return(0);
3365: }

3367: /*@
3368:    MatQRFactor - Performs in-place QR factorization of matrix.

3370:    Collective on Mat

3372:    Input Parameters:
3373: +  mat - the matrix
3374: .  col - column permutation
3375: -  info - options for factorization, includes
3376: $          fill - expected fill as ratio of original fill.
3377: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3378: $                   Run with the option -info to determine an optimal value to use

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

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

3388:    Level: developer

3390: .seealso: MatQRFactorSymbolic(), MatQRFactorNumeric(), MatLUFactor(),
3391:           MatSetUnfactored(), MatFactorInfo, MatGetFactor()

3393:     Developer Note: fortran interface is not autogenerated as the f90
3394:     interface definition cannot be generated correctly [due to MatFactorInfo]

3396: @*/
3397: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3398: {

3406:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3407:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3408:   MatCheckPreallocated(mat,1);
3409:   PetscLogEventBegin(MAT_QRFactor,mat,col,0,0);
3410:   PetscUseMethod(mat,"MatQRFactor_C", (Mat,IS,const MatFactorInfo*), (mat, col, info));
3411:   PetscLogEventEnd(MAT_QRFactor,mat,col,0,0);
3412:   PetscObjectStateIncrease((PetscObject)mat);
3413:   return(0);
3414: }

3416: /*@
3417:    MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3418:    Call this routine before calling MatQRFactorNumeric().

3420:    Collective on Mat

3422:    Input Parameters:
3423: +  fact - the factor matrix obtained with MatGetFactor()
3424: .  mat - the matrix
3425: .  col - column permutation
3426: -  info - options for factorization, includes
3427: $          fill - expected fill as ratio of original fill.
3428: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3429: $                   Run with the option -info to determine an optimal value to use

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

3435:    Level: developer

3437: .seealso: MatQRFactor(), MatQRFactorNumeric(), MatLUFactor(), MatFactorInfo, MatFactorInfoInitialize()

3439:     Developer Note: fortran interface is not autogenerated as the f90
3440:     interface definition cannot be generated correctly [due to MatFactorInfo]

3442: @*/
3443: PetscErrorCode MatQRFactorSymbolic(Mat fact,Mat mat,IS col,const MatFactorInfo *info)
3444: {
3446:   MatFactorInfo  tinfo;

3454:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3455:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3456:   MatCheckPreallocated(mat,2);
3457:   if (!info) {
3458:     MatFactorInfoInitialize(&tinfo);
3459:     info = &tinfo;
3460:   }

3462:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_QRFactorSymbolic,fact,mat,col,0);}
3463:   PetscUseMethod(fact,"MatQRFactorSymbolic_C", (Mat,Mat,IS,const MatFactorInfo*), (fact, mat, col, info));
3464:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_QRFactorSymbolic,fact,mat,col,0);}
3465:   PetscObjectStateIncrease((PetscObject)fact);
3466:   return(0);
3467: }

3469: /*@
3470:    MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3471:    Call this routine after first calling MatQRFactorSymbolic().

3473:    Collective on Mat

3475:    Input Parameters:
3476: +  fact - the factor matrix obtained with MatGetFactor()
3477: .  mat - the matrix
3478: -  info - options for factorization

3480:    Notes:
3481:    See MatQRFactor() for in-place factorization.

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

3487:    Level: developer

3489: .seealso: MatQRFactorSymbolic(), MatLUFactor()

3491:     Developer Note: fortran interface is not autogenerated as the f90
3492:     interface definition cannot be generated correctly [due to MatFactorInfo]

3494: @*/
3495: PetscErrorCode MatQRFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3496: {
3497:   MatFactorInfo  tinfo;

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

3508:   MatCheckPreallocated(mat,2);
3509:   if (!info) {
3510:     MatFactorInfoInitialize(&tinfo);
3511:     info = &tinfo;
3512:   }

3514:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_QRFactorNumeric,mat,fact,0,0);}
3515:   else  {PetscLogEventBegin(MAT_QRFactor,mat,fact,0,0);}
3516:   PetscUseMethod(fact,"MatQRFactorNumeric_C", (Mat,Mat,const MatFactorInfo*), (fact, mat, info));
3517:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_QRFactorNumeric,mat,fact,0,0);}
3518:   else {PetscLogEventEnd(MAT_QRFactor,mat,fact,0,0);}
3519:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3520:   PetscObjectStateIncrease((PetscObject)fact);
3521:   return(0);
3522: }

3524: /* ----------------------------------------------------------------*/
3525: /*@
3526:    MatSolve - Solves A x = b, given a factored matrix.

3528:    Neighbor-wise Collective on Mat

3530:    Input Parameters:
3531: +  mat - the factored matrix
3532: -  b - the right-hand-side vector

3534:    Output Parameter:
3535: .  x - the result vector

3537:    Notes:
3538:    The vectors b and x cannot be the same.  I.e., one cannot
3539:    call MatSolve(A,x,x).

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

3546:    Level: developer

3548: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3549: @*/
3550: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3551: {

3561:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3562:   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);
3563:   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);
3564:   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);
3565:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3566:   MatCheckPreallocated(mat,1);

3568:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3569:   if (mat->factorerrortype) {
3570:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3571:     VecSetInf(x);
3572:   } else {
3573:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3574:     (*mat->ops->solve)(mat,b,x);
3575:   }
3576:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3577:   PetscObjectStateIncrease((PetscObject)x);
3578:   return(0);
3579: }

3581: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3582: {
3584:   Vec            b,x;
3585:   PetscInt       m,N,i;
3586:   PetscScalar    *bb,*xx;
3587:   PetscErrorCode (*f)(Mat,Vec,Vec);

3590:   if (A->factorerrortype) {
3591:     PetscInfo1(A,"MatFactorError %D\n",A->factorerrortype);
3592:     MatSetInf(X);
3593:     return(0);
3594:   }
3595:   f = trans ? A->ops->solvetranspose : A->ops->solve;
3596:   if (!f) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);

3598:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3599:   MatDenseGetArray(X,&xx);
3600:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3601:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3602:   MatCreateVecs(A,&x,&b);
3603:   for (i=0; i<N; i++) {
3604:     VecPlaceArray(b,bb + i*m);
3605:     VecPlaceArray(x,xx + i*m);
3606:     (*f)(A,b,x);
3607:     VecResetArray(x);
3608:     VecResetArray(b);
3609:   }
3610:   VecDestroy(&b);
3611:   VecDestroy(&x);
3612:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3613:   MatDenseRestoreArray(X,&xx);
3614:   return(0);
3615: }

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

3620:    Neighbor-wise Collective on Mat

3622:    Input Parameters:
3623: +  A - the factored matrix
3624: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3626:    Output Parameter:
3627: .  X - the result matrix (dense matrix)

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

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

3639:    Level: developer

3641: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3642: @*/
3643: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3644: {

3654:   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);
3655:   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);
3656:   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");
3657:   if (!A->rmap->N && !A->cmap->N) return(0);
3658:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3659:   MatCheckPreallocated(A,1);

3661:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3662:   if (!A->ops->matsolve) {
3663:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3664:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3665:   } else {
3666:     (*A->ops->matsolve)(A,B,X);
3667:   }
3668:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3669:   PetscObjectStateIncrease((PetscObject)X);
3670:   return(0);
3671: }

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

3676:    Neighbor-wise Collective on Mat

3678:    Input Parameters:
3679: +  A - the factored matrix
3680: -  B - the right-hand-side matrix  (dense matrix)

3682:    Output Parameter:
3683: .  X - the result matrix (dense matrix)

3685:    Notes:
3686:    The matrices B and X cannot be the same.  I.e., one cannot
3687:    call MatMatSolveTranspose(A,X,X).

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

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

3697:    Level: developer

3699: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3700: @*/
3701: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3702: {

3712:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3713:   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);
3714:   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);
3715:   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);
3716:   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");
3717:   if (!A->rmap->N && !A->cmap->N) return(0);
3718:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3719:   MatCheckPreallocated(A,1);

3721:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3722:   if (!A->ops->matsolvetranspose) {
3723:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3724:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3725:   } else {
3726:     (*A->ops->matsolvetranspose)(A,B,X);
3727:   }
3728:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3729:   PetscObjectStateIncrease((PetscObject)X);
3730:   return(0);
3731: }

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

3736:    Neighbor-wise Collective on Mat

3738:    Input Parameters:
3739: +  A - the factored matrix
3740: -  Bt - the transpose of right-hand-side matrix

3742:    Output Parameter:
3743: .  X - the result matrix (dense matrix)

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

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

3753:    Level: developer

3755: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3756: @*/
3757: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3758: {


3769:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3770:   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);
3771:   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);
3772:   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");
3773:   if (!A->rmap->N && !A->cmap->N) return(0);
3774:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3775:   MatCheckPreallocated(A,1);

3777:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3778:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3779:   (*A->ops->mattransposesolve)(A,Bt,X);
3780:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3781:   PetscObjectStateIncrease((PetscObject)X);
3782:   return(0);
3783: }

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

3789:    Neighbor-wise Collective on Mat

3791:    Input Parameters:
3792: +  mat - the factored matrix
3793: -  b - the right-hand-side vector

3795:    Output Parameter:
3796: .  x - the result vector

3798:    Notes:
3799:    MatSolve() should be used for most applications, as it performs
3800:    a forward solve followed by a backward solve.

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

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

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

3815:    Level: developer

3817: .seealso: MatSolve(), MatBackwardSolve()
3818: @*/
3819: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3820: {

3830:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3831:   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);
3832:   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);
3833:   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);
3834:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3835:   MatCheckPreallocated(mat,1);

3837:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3838:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3839:   (*mat->ops->forwardsolve)(mat,b,x);
3840:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3841:   PetscObjectStateIncrease((PetscObject)x);
3842:   return(0);
3843: }

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

3849:    Neighbor-wise Collective on Mat

3851:    Input Parameters:
3852: +  mat - the factored matrix
3853: -  b - the right-hand-side vector

3855:    Output Parameter:
3856: .  x - the result vector

3858:    Notes:
3859:    MatSolve() should be used for most applications, as it performs
3860:    a forward solve followed by a backward solve.

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

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

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

3875:    Level: developer

3877: .seealso: MatSolve(), MatForwardSolve()
3878: @*/
3879: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3880: {

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

3897:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3898:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3899:   (*mat->ops->backwardsolve)(mat,b,x);
3900:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3901:   PetscObjectStateIncrease((PetscObject)x);
3902:   return(0);
3903: }

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

3908:    Neighbor-wise Collective on Mat

3910:    Input Parameters:
3911: +  mat - the factored matrix
3912: .  b - the right-hand-side vector
3913: -  y - the vector to be added to

3915:    Output Parameter:
3916: .  x - the result vector

3918:    Notes:
3919:    The vectors b and x cannot be the same.  I.e., one cannot
3920:    call MatSolveAdd(A,x,y,x).

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

3926:    Level: developer

3928: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3929: @*/
3930: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3931: {
3932:   PetscScalar    one = 1.0;
3933:   Vec            tmp;

3945:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3946:   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);
3947:   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);
3948:   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);
3949:   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);
3950:   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);
3951:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3952:    MatCheckPreallocated(mat,1);

3954:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3955:   if (mat->factorerrortype) {
3956:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3957:     VecSetInf(x);
3958:   } else if (mat->ops->solveadd) {
3959:     (*mat->ops->solveadd)(mat,b,y,x);
3960:   } else {
3961:     /* do the solve then the add manually */
3962:     if (x != y) {
3963:       MatSolve(mat,b,x);
3964:       VecAXPY(x,one,y);
3965:     } else {
3966:       VecDuplicate(x,&tmp);
3967:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3968:       VecCopy(x,tmp);
3969:       MatSolve(mat,b,x);
3970:       VecAXPY(x,one,tmp);
3971:       VecDestroy(&tmp);
3972:     }
3973:   }
3974:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3975:   PetscObjectStateIncrease((PetscObject)x);
3976:   return(0);
3977: }

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

3982:    Neighbor-wise Collective on Mat

3984:    Input Parameters:
3985: +  mat - the factored matrix
3986: -  b - the right-hand-side vector

3988:    Output Parameter:
3989: .  x - the result vector

3991:    Notes:
3992:    The vectors b and x cannot be the same.  I.e., one cannot
3993:    call MatSolveTranspose(A,x,x).

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

3999:    Level: developer

4001: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
4002: @*/
4003: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
4004: {

4014:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
4015:   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);
4016:   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);
4017:   if (!mat->rmap->N && !mat->cmap->N) return(0);
4018:   MatCheckPreallocated(mat,1);
4019:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
4020:   if (mat->factorerrortype) {
4021:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
4022:     VecSetInf(x);
4023:   } else {
4024:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
4025:     (*mat->ops->solvetranspose)(mat,b,x);
4026:   }
4027:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
4028:   PetscObjectStateIncrease((PetscObject)x);
4029:   return(0);
4030: }

4032: /*@
4033:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
4034:                       factored matrix.

4036:    Neighbor-wise Collective on Mat

4038:    Input Parameters:
4039: +  mat - the factored matrix
4040: .  b - the right-hand-side vector
4041: -  y - the vector to be added to

4043:    Output Parameter:
4044: .  x - the result vector

4046:    Notes:
4047:    The vectors b and x cannot be the same.  I.e., one cannot
4048:    call MatSolveTransposeAdd(A,x,y,x).

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

4054:    Level: developer

4056: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
4057: @*/
4058: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
4059: {
4060:   PetscScalar    one = 1.0;
4062:   Vec            tmp;

4073:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
4074:   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);
4075:   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);
4076:   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);
4077:   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);
4078:   if (!mat->rmap->N && !mat->cmap->N) return(0);
4079:    MatCheckPreallocated(mat,1);

4081:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
4082:   if (mat->factorerrortype) {
4083:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
4084:     VecSetInf(x);
4085:   } else if (mat->ops->solvetransposeadd) {
4086:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
4087:   } else {
4088:     /* do the solve then the add manually */
4089:     if (x != y) {
4090:       MatSolveTranspose(mat,b,x);
4091:       VecAXPY(x,one,y);
4092:     } else {
4093:       VecDuplicate(x,&tmp);
4094:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
4095:       VecCopy(x,tmp);
4096:       MatSolveTranspose(mat,b,x);
4097:       VecAXPY(x,one,tmp);
4098:       VecDestroy(&tmp);
4099:     }
4100:   }
4101:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
4102:   PetscObjectStateIncrease((PetscObject)x);
4103:   return(0);
4104: }
4105: /* ----------------------------------------------------------------*/

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

4110:    Neighbor-wise Collective on Mat

4112:    Input Parameters:
4113: +  mat - the matrix
4114: .  b - the right hand side
4115: .  omega - the relaxation factor
4116: .  flag - flag indicating the type of SOR (see below)
4117: .  shift -  diagonal shift
4118: .  its - the number of iterations
4119: -  lits - the number of local iterations

4121:    Output Parameter:
4122: .  x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)

4124:    SOR Flags:
4125: +     SOR_FORWARD_SWEEP - forward SOR
4126: .     SOR_BACKWARD_SWEEP - backward SOR
4127: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
4128: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
4129: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
4130: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
4131: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
4132:          upper/lower triangular part of matrix to
4133:          vector (with omega)
4134: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

4136:    Notes:
4137:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
4138:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
4139:    on each processor.

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

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

4147:    Notes for Advanced Users:
4148:    The flags are implemented as bitwise inclusive or operations.
4149:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
4150:    to specify a zero initial guess for SSOR.

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

4156:    Vectors x and b CANNOT be the same

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

4160:    Level: developer

4162: @*/
4163: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
4164: {

4174:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4175:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4176:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4177:   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);
4178:   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);
4179:   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);
4180:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
4181:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
4182:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

4184:   MatCheckPreallocated(mat,1);
4185:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
4186:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
4187:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
4188:   PetscObjectStateIncrease((PetscObject)x);
4189:   return(0);
4190: }

4192: /*
4193:       Default matrix copy routine.
4194: */
4195: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4196: {
4197:   PetscErrorCode    ierr;
4198:   PetscInt          i,rstart = 0,rend = 0,nz;
4199:   const PetscInt    *cwork;
4200:   const PetscScalar *vwork;

4203:   if (B->assembled) {
4204:     MatZeroEntries(B);
4205:   }
4206:   if (str == SAME_NONZERO_PATTERN) {
4207:     MatGetOwnershipRange(A,&rstart,&rend);
4208:     for (i=rstart; i<rend; i++) {
4209:       MatGetRow(A,i,&nz,&cwork,&vwork);
4210:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
4211:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
4212:     }
4213:   } else {
4214:     MatAYPX(B,0.0,A,str);
4215:   }
4216:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4217:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4218:   return(0);
4219: }

4221: /*@
4222:    MatCopy - Copies a matrix to another matrix.

4224:    Collective on Mat

4226:    Input Parameters:
4227: +  A - the matrix
4228: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4230:    Output Parameter:
4231: .  B - where the copy is put

4233:    Notes:
4234:    If you use SAME_NONZERO_PATTERN then the two matrices must have the same nonzero pattern or the routine will crash.

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

4240:    Level: intermediate

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

4244: @*/
4245: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4246: {
4248:   PetscInt       i;

4256:   MatCheckPreallocated(B,2);
4257:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4258:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4259:   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);
4260:   MatCheckPreallocated(A,1);
4261:   if (A == B) return(0);

4263:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4264:   if (A->ops->copy) {
4265:     (*A->ops->copy)(A,B,str);
4266:   } else { /* generic conversion */
4267:     MatCopy_Basic(A,B,str);
4268:   }

4270:   B->stencil.dim = A->stencil.dim;
4271:   B->stencil.noc = A->stencil.noc;
4272:   for (i=0; i<=A->stencil.dim; i++) {
4273:     B->stencil.dims[i]   = A->stencil.dims[i];
4274:     B->stencil.starts[i] = A->stencil.starts[i];
4275:   }

4277:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4278:   PetscObjectStateIncrease((PetscObject)B);
4279:   return(0);
4280: }

4282: /*@C
4283:    MatConvert - Converts a matrix to another matrix, either of the same
4284:    or different type.

4286:    Collective on Mat

4288:    Input Parameters:
4289: +  mat - the matrix
4290: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4291:    same type as the original matrix.
4292: -  reuse - denotes if the destination matrix is to be created or reused.
4293:    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
4294:    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).

4296:    Output Parameter:
4297: .  M - pointer to place new matrix

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

4304:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4305:    the MPI communicator of the generated matrix is always the same as the communicator
4306:    of the input matrix.

4308:    Level: intermediate

4310: .seealso: MatCopy(), MatDuplicate()
4311: @*/
4312: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4313: {
4315:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4316:   char           convname[256],mtype[256];
4317:   Mat            B;

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

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

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

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

4340:   /* Cache Mat options because some converter use MatHeaderReplace  */
4341:   issymmetric = mat->symmetric;
4342:   ishermitian = mat->hermitian;

4344:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4345:     PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4346:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4347:   } else {
4348:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4349:     const char     *prefix[3] = {"seq","mpi",""};
4350:     PetscInt       i;
4351:     /*
4352:        Order of precedence:
4353:        0) See if newtype is a superclass of the current matrix.
4354:        1) See if a specialized converter is known to the current matrix.
4355:        2) See if a specialized converter is known to the desired matrix class.
4356:        3) See if a good general converter is registered for the desired class
4357:           (as of 6/27/03 only MATMPIADJ falls into this category).
4358:        4) See if a good general converter is known for the current matrix.
4359:        5) Use a really basic converter.
4360:     */

4362:     /* 0) See if newtype is a superclass of the current matrix.
4363:           i.e mat is mpiaij and newtype is aij */
4364:     for (i=0; i<2; i++) {
4365:       PetscStrncpy(convname,prefix[i],sizeof(convname));
4366:       PetscStrlcat(convname,newtype,sizeof(convname));
4367:       PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4368:       PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4369:       if (flg) {
4370:         if (reuse == MAT_INPLACE_MATRIX) {
4371:           PetscInfo(mat,"Early return\n");
4372:           return(0);
4373:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4374:           PetscInfo(mat,"Calling MatDuplicate\n");
4375:           (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4376:           return(0);
4377:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4378:           PetscInfo(mat,"Calling MatCopy\n");
4379:           MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4380:           return(0);
4381:         }
4382:       }
4383:     }
4384:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4385:     for (i=0; i<3; i++) {
4386:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4387:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4388:       PetscStrlcat(convname,"_",sizeof(convname));
4389:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4390:       PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4391:       PetscStrlcat(convname,"_C",sizeof(convname));
4392:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4393:       PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4394:       if (conv) goto foundconv;
4395:     }

4397:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4398:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4399:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4400:     MatSetType(B,newtype);
4401:     for (i=0; i<3; i++) {
4402:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4403:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4404:       PetscStrlcat(convname,"_",sizeof(convname));
4405:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4406:       PetscStrlcat(convname,newtype,sizeof(convname));
4407:       PetscStrlcat(convname,"_C",sizeof(convname));
4408:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4409:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4410:       if (conv) {
4411:         MatDestroy(&B);
4412:         goto foundconv;
4413:       }
4414:     }

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

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

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

4428:     /* 5) Use a really basic converter. */
4429:     PetscInfo(mat,"Using MatConvert_Basic\n");
4430:     conv = MatConvert_Basic;

4432: foundconv:
4433:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4434:     (*conv)(mat,newtype,reuse,M);
4435:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4436:       /* the block sizes must be same if the mappings are copied over */
4437:       (*M)->rmap->bs = mat->rmap->bs;
4438:       (*M)->cmap->bs = mat->cmap->bs;
4439:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4440:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4441:       (*M)->rmap->mapping = mat->rmap->mapping;
4442:       (*M)->cmap->mapping = mat->cmap->mapping;
4443:     }
4444:     (*M)->stencil.dim = mat->stencil.dim;
4445:     (*M)->stencil.noc = mat->stencil.noc;
4446:     for (i=0; i<=mat->stencil.dim; i++) {
4447:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4448:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4449:     }
4450:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4451:   }
4452:   PetscObjectStateIncrease((PetscObject)*M);

4454:   /* Copy Mat options */
4455:   if (issymmetric) {
4456:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4457:   }
4458:   if (ishermitian) {
4459:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4460:   }
4461:   return(0);
4462: }

4464: /*@C
4465:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4467:    Not Collective

4469:    Input Parameter:
4470: .  mat - the matrix, must be a factored matrix

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

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

4479:    Level: intermediate

4481: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4482: @*/
4483: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4484: {
4485:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4490:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4491:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4492:   if (!conv) {
4493:     *type = MATSOLVERPETSC;
4494:   } else {
4495:     (*conv)(mat,type);
4496:   }
4497:   return(0);
4498: }

4500: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4501: struct _MatSolverTypeForSpecifcType {
4502:   MatType                        mtype;
4503:   /* no entry for MAT_FACTOR_NONE */
4504:   PetscErrorCode                 (*createfactor[MAT_FACTOR_NUM_TYPES-1])(Mat,MatFactorType,Mat*);
4505:   MatSolverTypeForSpecifcType next;
4506: };

4508: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4509: struct _MatSolverTypeHolder {
4510:   char                        *name;
4511:   MatSolverTypeForSpecifcType handlers;
4512:   MatSolverTypeHolder         next;
4513: };

4515: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

4517: /*@C
4518:    MatSolverTypeRegister - Registers a MatSolverType that works for a particular matrix type

4520:    Input Parameters:
4521: +    package - name of the package, for example petsc or superlu
4522: .    mtype - the matrix type that works with this package
4523: .    ftype - the type of factorization supported by the package
4524: -    createfactor - routine that will create the factored matrix ready to be used

4526:     Level: intermediate

4528: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4529: @*/
4530: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*createfactor)(Mat,MatFactorType,Mat*))
4531: {
4532:   PetscErrorCode              ierr;
4533:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4534:   PetscBool                   flg;
4535:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4538:   MatInitializePackage();
4539:   if (!next) {
4540:     PetscNew(&MatSolverTypeHolders);
4541:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4542:     PetscNew(&MatSolverTypeHolders->handlers);
4543:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4544:     MatSolverTypeHolders->handlers->createfactor[(int)ftype-1] = createfactor;
4545:     return(0);
4546:   }
4547:   while (next) {
4548:     PetscStrcasecmp(package,next->name,&flg);
4549:     if (flg) {
4550:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4551:       inext = next->handlers;
4552:       while (inext) {
4553:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4554:         if (flg) {
4555:           inext->createfactor[(int)ftype-1] = createfactor;
4556:           return(0);
4557:         }
4558:         iprev = inext;
4559:         inext = inext->next;
4560:       }
4561:       PetscNew(&iprev->next);
4562:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4563:       iprev->next->createfactor[(int)ftype-1] = createfactor;
4564:       return(0);
4565:     }
4566:     prev = next;
4567:     next = next->next;
4568:   }
4569:   PetscNew(&prev->next);
4570:   PetscStrallocpy(package,&prev->next->name);
4571:   PetscNew(&prev->next->handlers);
4572:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4573:   prev->next->handlers->createfactor[(int)ftype-1] = createfactor;
4574:   return(0);
4575: }

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

4580:    Input Parameters:
4581: +    type - name of the package, for example petsc or superlu
4582: .    ftype - the type of factorization supported by the type
4583: -    mtype - the matrix type that works with this type

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

4590:     Level: intermediate

4592: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatSolverTypeRegister(), MatGetFactor()
4593: @*/
4594: PetscErrorCode MatSolverTypeGet(MatSolverType type,MatType mtype,MatFactorType ftype,PetscBool *foundtype,PetscBool *foundmtype,PetscErrorCode (**createfactor)(Mat,MatFactorType,Mat*))
4595: {
4596:   PetscErrorCode              ierr;
4597:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4598:   PetscBool                   flg;
4599:   MatSolverTypeForSpecifcType inext;

4602:   if (foundtype) *foundtype = PETSC_FALSE;
4603:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4604:   if (createfactor) *createfactor    = NULL;

4606:   if (type) {
4607:     while (next) {
4608:       PetscStrcasecmp(type,next->name,&flg);
4609:       if (flg) {
4610:         if (foundtype) *foundtype = PETSC_TRUE;
4611:         inext = next->handlers;
4612:         while (inext) {
4613:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4614:           if (flg) {
4615:             if (foundmtype) *foundmtype = PETSC_TRUE;
4616:             if (createfactor)  *createfactor  = inext->createfactor[(int)ftype-1];
4617:             return(0);
4618:           }
4619:           inext = inext->next;
4620:         }
4621:       }
4622:       next = next->next;
4623:     }
4624:   } else {
4625:     while (next) {
4626:       inext = next->handlers;
4627:       while (inext) {
4628:         PetscStrcmp(mtype,inext->mtype,&flg);
4629:         if (flg && inext->createfactor[(int)ftype-1]) {
4630:           if (foundtype) *foundtype = PETSC_TRUE;
4631:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4632:           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4633:           return(0);
4634:         }
4635:         inext = inext->next;
4636:       }
4637:       next = next->next;
4638:     }
4639:     /* try with base classes inext->mtype */
4640:     next = MatSolverTypeHolders;
4641:     while (next) {
4642:       inext = next->handlers;
4643:       while (inext) {
4644:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4645:         if (flg && inext->createfactor[(int)ftype-1]) {
4646:           if (foundtype) *foundtype = PETSC_TRUE;
4647:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4648:           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4649:           return(0);
4650:         }
4651:         inext = inext->next;
4652:       }
4653:       next = next->next;
4654:     }
4655:   }
4656:   return(0);
4657: }

4659: PetscErrorCode MatSolverTypeDestroy(void)
4660: {
4661:   PetscErrorCode              ierr;
4662:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4663:   MatSolverTypeForSpecifcType inext,iprev;

4666:   while (next) {
4667:     PetscFree(next->name);
4668:     inext = next->handlers;
4669:     while (inext) {
4670:       PetscFree(inext->mtype);
4671:       iprev = inext;
4672:       inext = inext->next;
4673:       PetscFree(iprev);
4674:     }
4675:     prev = next;
4676:     next = next->next;
4677:     PetscFree(prev);
4678:   }
4679:   MatSolverTypeHolders = NULL;
4680:   return(0);
4681: }

4683: /*@C
4684:    MatFactorGetCanUseOrdering - Indicates if the factorization can use the ordering provided in MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()

4686:    Logically Collective on Mat

4688:    Input Parameters:
4689: .  mat - the matrix

4691:    Output Parameters:
4692: .  flg - PETSC_TRUE if uses the ordering

4694:    Notes:
4695:       Most internal PETSc factorizations use the ordering passed to the factorization routine but external
4696:       packages do not, thus we want to skip generating the ordering when it is not needed or used.

4698:    Level: developer

4700: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4701: @*/
4702: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4703: {
4705:   *flg = mat->canuseordering;
4706:   return(0);
4707: }

4709: /*@C
4710:    MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

4712:    Logically Collective on Mat

4714:    Input Parameters:
4715: .  mat - the matrix

4717:    Output Parameters:
4718: .  otype - the preferred type

4720:    Level: developer

4722: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4723: @*/
4724: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4725: {
4727:   *otype = mat->preferredordering[ftype];
4728:   if (!*otype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatFactor did not have a preferred ordering");
4729:   return(0);
4730: }

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

4735:    Collective on Mat

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

4742:    Output Parameters:
4743: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4745:    Notes:
4746:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4747:      such as pastix, superlu, mumps etc.

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

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

4754:    Level: intermediate

4756: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetCanUseOrdering(), MatSolverTypeRegister()
4757: @*/
4758: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4759: {
4760:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4761:   PetscBool      foundtype,foundmtype;


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

4770:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundtype,&foundmtype,&conv);
4771:   if (!foundtype) {
4772:     if (type) {
4773:       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);
4774:     } else {
4775:       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);
4776:     }
4777:   }
4778:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4779:   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);

4781:   (*conv)(mat,ftype,f);
4782:   return(0);
4783: }

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

4788:    Not Collective

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

4795:    Output Parameter:
4796: .    flg - PETSC_TRUE if the factorization is available

4798:    Notes:
4799:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4800:      such as pastix, superlu, mumps etc.

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

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

4807:    Level: intermediate

4809: .seealso: MatCopy(), MatDuplicate(), MatGetFactor(), MatSolverTypeRegister()
4810: @*/
4811: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4812: {
4813:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4822:   *flg = PETSC_FALSE;
4823:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4824:   if (gconv) {
4825:     *flg = PETSC_TRUE;
4826:   }
4827:   return(0);
4828: }

4830: #include <petscdmtypes.h>

4832: /*@
4833:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4835:    Collective on Mat

4837:    Input Parameters:
4838: +  mat - the matrix
4839: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4840:         See the manual page for MatDuplicateOption for an explanation of these options.

4842:    Output Parameter:
4843: .  M - pointer to place new matrix

4845:    Level: intermediate

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

4851: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4852: @*/
4853: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4854: {
4856:   Mat            B;
4857:   PetscInt       i;
4858:   DM             dm;
4859:   void           (*viewf)(void);

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

4869:   *M = NULL;
4870:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4871:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4872:   (*mat->ops->duplicate)(mat,op,M);
4873:   B    = *M;

4875:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4876:   if (viewf) {
4877:     MatSetOperation(B,MATOP_VIEW,viewf);
4878:   }

4880:   B->stencil.dim = mat->stencil.dim;
4881:   B->stencil.noc = mat->stencil.noc;
4882:   for (i=0; i<=mat->stencil.dim; i++) {
4883:     B->stencil.dims[i]   = mat->stencil.dims[i];
4884:     B->stencil.starts[i] = mat->stencil.starts[i];
4885:   }

4887:   B->nooffproczerorows = mat->nooffproczerorows;
4888:   B->nooffprocentries  = mat->nooffprocentries;

4890:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4891:   if (dm) {
4892:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4893:   }
4894:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4895:   PetscObjectStateIncrease((PetscObject)B);
4896:   return(0);
4897: }

4899: /*@
4900:    MatGetDiagonal - Gets the diagonal of a matrix.

4902:    Logically Collective on Mat

4904:    Input Parameters:
4905: +  mat - the matrix
4906: -  v - the vector for storing the diagonal

4908:    Output Parameter:
4909: .  v - the diagonal of the matrix

4911:    Level: intermediate

4913:    Note:
4914:    Currently only correct in parallel for square matrices.

4916: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4917: @*/
4918: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4919: {

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

4930:   (*mat->ops->getdiagonal)(mat,v);
4931:   PetscObjectStateIncrease((PetscObject)v);
4932:   return(0);
4933: }

4935: /*@C
4936:    MatGetRowMin - Gets the minimum value (of the real part) of each
4937:         row of the matrix

4939:    Logically Collective on Mat

4941:    Input Parameter:
4942: .  mat - the matrix

4944:    Output Parameters:
4945: +  v - the vector for storing the maximums
4946: -  idx - the indices of the column found for each row (optional)

4948:    Level: intermediate

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

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

4956: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4957:           MatGetRowMax()
4958: @*/
4959: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4960: {

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

4969:   if (!mat->cmap->N) {
4970:     VecSet(v,PETSC_MAX_REAL);
4971:     if (idx) {
4972:       PetscInt i,m = mat->rmap->n;
4973:       for (i=0; i<m; i++) idx[i] = -1;
4974:     }
4975:   } else {
4976:     if (!mat->ops->getrowmin) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4977:     MatCheckPreallocated(mat,1);
4978:   }
4979:   (*mat->ops->getrowmin)(mat,v,idx);
4980:   PetscObjectStateIncrease((PetscObject)v);
4981:   return(0);
4982: }

4984: /*@C
4985:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4986:         row of the matrix

4988:    Logically Collective on Mat

4990:    Input Parameter:
4991: .  mat - the matrix

4993:    Output Parameters:
4994: +  v - the vector for storing the minimums
4995: -  idx - the indices of the column found for each row (or NULL if not needed)

4997:    Level: intermediate

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

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

5005: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
5006: @*/
5007: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
5008: {

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

5018:   if (!mat->cmap->N) {
5019:     VecSet(v,0.0);
5020:     if (idx) {
5021:       PetscInt i,m = mat->rmap->n;
5022:       for (i=0; i<m; i++) idx[i] = -1;
5023:     }
5024:   } else {
5025:     if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5026:     MatCheckPreallocated(mat,1);
5027:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
5028:     (*mat->ops->getrowminabs)(mat,v,idx);
5029:   }
5030:   PetscObjectStateIncrease((PetscObject)v);
5031:   return(0);
5032: }

5034: /*@C
5035:    MatGetRowMax - Gets the maximum value (of the real part) of each
5036:         row of the matrix

5038:    Logically Collective on Mat

5040:    Input Parameter:
5041: .  mat - the matrix

5043:    Output Parameters:
5044: +  v - the vector for storing the maximums
5045: -  idx - the indices of the column found for each row (optional)

5047:    Level: intermediate

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

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

5055: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
5056: @*/
5057: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
5058: {

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

5067:   if (!mat->cmap->N) {
5068:     VecSet(v,PETSC_MIN_REAL);
5069:     if (idx) {
5070:       PetscInt i,m = mat->rmap->n;
5071:       for (i=0; i<m; i++) idx[i] = -1;
5072:     }
5073:   } else {
5074:     if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5075:     MatCheckPreallocated(mat,1);
5076:     (*mat->ops->getrowmax)(mat,v,idx);
5077:   }
5078:   PetscObjectStateIncrease((PetscObject)v);
5079:   return(0);
5080: }

5082: /*@C
5083:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5084:         row of the matrix

5086:    Logically Collective on Mat

5088:    Input Parameter:
5089: .  mat - the matrix

5091:    Output Parameters:
5092: +  v - the vector for storing the maximums
5093: -  idx - the indices of the column found for each row (or NULL if not needed)

5095:    Level: intermediate

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

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

5103: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
5104: @*/
5105: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
5106: {

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

5115:   if (!mat->cmap->N) {
5116:     VecSet(v,0.0);
5117:     if (idx) {
5118:       PetscInt i,m = mat->rmap->n;
5119:       for (i=0; i<m; i++) idx[i] = -1;
5120:     }
5121:   } else {
5122:     if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5123:     MatCheckPreallocated(mat,1);
5124:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
5125:     (*mat->ops->getrowmaxabs)(mat,v,idx);
5126:   }
5127:   PetscObjectStateIncrease((PetscObject)v);
5128:   return(0);
5129: }

5131: /*@
5132:    MatGetRowSum - Gets the sum of each row of the matrix

5134:    Logically or Neighborhood Collective on Mat

5136:    Input Parameters:
5137: .  mat - the matrix

5139:    Output Parameter:
5140: .  v - the vector for storing the sum of rows

5142:    Level: intermediate

5144:    Notes:
5145:     This code is slow since it is not currently specialized for different formats

5147: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
5148: @*/
5149: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5150: {
5151:   Vec            ones;

5158:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5159:   MatCheckPreallocated(mat,1);
5160:   MatCreateVecs(mat,&ones,NULL);
5161:   VecSet(ones,1.);
5162:   MatMult(mat,ones,v);
5163:   VecDestroy(&ones);
5164:   return(0);
5165: }

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

5170:    Collective on Mat

5172:    Input Parameters:
5173: +  mat - the matrix to transpose
5174: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

5176:    Output Parameter:
5177: .  B - the transpose

5179:    Notes:
5180:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

5186:    Level: intermediate

5188: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5189: @*/
5190: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
5191: {

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

5204:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
5205:   (*mat->ops->transpose)(mat,reuse,B);
5206:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
5207:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
5208:   return(0);
5209: }

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

5215:    Collective on Mat

5217:    Input Parameters:
5218: +  A - the matrix to test
5219: -  B - the matrix to test against, this can equal the first parameter

5221:    Output Parameters:
5222: .  flg - the result

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

5229:    Level: intermediate

5231: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
5232: @*/
5233: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5234: {
5235:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5241:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
5242:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
5243:   *flg = PETSC_FALSE;
5244:   if (f && g) {
5245:     if (f == g) {
5246:       (*f)(A,B,tol,flg);
5247:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
5248:   } else {
5249:     MatType mattype;
5250:     if (!f) {
5251:       MatGetType(A,&mattype);
5252:     } else {
5253:       MatGetType(B,&mattype);
5254:     }
5255:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
5256:   }
5257:   return(0);
5258: }

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

5263:    Collective on Mat

5265:    Input Parameters:
5266: +  mat - the matrix to transpose and complex conjugate
5267: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

5269:    Output Parameter:
5270: .  B - the Hermitian

5272:    Level: intermediate

5274: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5275: @*/
5276: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5277: {

5281:   MatTranspose(mat,reuse,B);
5282: #if defined(PETSC_USE_COMPLEX)
5283:   MatConjugate(*B);
5284: #endif
5285:   return(0);
5286: }

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

5291:    Collective on Mat

5293:    Input Parameters:
5294: +  A - the matrix to test
5295: -  B - the matrix to test against, this can equal the first parameter

5297:    Output Parameters:
5298: .  flg - the result

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

5305:    Level: intermediate

5307: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5308: @*/
5309: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5310: {
5311:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5317:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5318:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5319:   if (f && g) {
5320:     if (f==g) {
5321:       (*f)(A,B,tol,flg);
5322:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5323:   }
5324:   return(0);
5325: }

5327: /*@
5328:    MatPermute - Creates a new matrix with rows and columns permuted from the
5329:    original.

5331:    Collective on Mat

5333:    Input Parameters:
5334: +  mat - the matrix to permute
5335: .  row - row permutation, each processor supplies only the permutation for its rows
5336: -  col - column permutation, each processor supplies only the permutation for its columns

5338:    Output Parameters:
5339: .  B - the permuted matrix

5341:    Level: advanced

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

5347:    Developer Note:
5348:      If you want to implement MatPermute for a matrix type, and your approach doesn't
5349:      exploit the fact that row and col are permutations, consider implementing the
5350:      more general MatCreateSubMatrix() instead.

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

5354: @*/
5355: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5356: {

5367:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5368:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5369:   if (!mat->ops->permute && !mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
5370:   MatCheckPreallocated(mat,1);

5372:   if (mat->ops->permute) {
5373:     (*mat->ops->permute)(mat,row,col,B);
5374:     PetscObjectStateIncrease((PetscObject)*B);
5375:   } else {
5376:     MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B);
5377:   }
5378:   return(0);
5379: }

5381: /*@
5382:    MatEqual - Compares two matrices.

5384:    Collective on Mat

5386:    Input Parameters:
5387: +  A - the first matrix
5388: -  B - the second matrix

5390:    Output Parameter:
5391: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5393:    Level: intermediate

5395: @*/
5396: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5397: {

5407:   MatCheckPreallocated(B,2);
5408:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5409:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5410:   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);
5411:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5412:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5413:   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);
5414:   MatCheckPreallocated(A,1);

5416:   (*A->ops->equal)(A,B,flg);
5417:   return(0);
5418: }

5420: /*@
5421:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5422:    matrices that are stored as vectors.  Either of the two scaling
5423:    matrices can be NULL.

5425:    Collective on Mat

5427:    Input Parameters:
5428: +  mat - the matrix to be scaled
5429: .  l - the left scaling vector (or NULL)
5430: -  r - the right scaling vector (or NULL)

5432:    Notes:
5433:    MatDiagonalScale() computes A = LAR, where
5434:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5435:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5437:    Level: intermediate

5439: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5440: @*/
5441: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5442: {

5450:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5451:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5452:   MatCheckPreallocated(mat,1);
5453:   if (!l && !r) return(0);

5455:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5456:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5457:   (*mat->ops->diagonalscale)(mat,l,r);
5458:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5459:   PetscObjectStateIncrease((PetscObject)mat);
5460:   return(0);
5461: }

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

5466:     Logically Collective on Mat

5468:     Input Parameters:
5469: +   mat - the matrix to be scaled
5470: -   a  - the scaling value

5472:     Output Parameter:
5473: .   mat - the scaled matrix

5475:     Level: intermediate

5477: .seealso: MatDiagonalScale()
5478: @*/
5479: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5480: {

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

5492:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5493:   if (a != (PetscScalar)1.0) {
5494:     (*mat->ops->scale)(mat,a);
5495:     PetscObjectStateIncrease((PetscObject)mat);
5496:   }
5497:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5498:   return(0);
5499: }

5501: /*@
5502:    MatNorm - Calculates various norms of a matrix.

5504:    Collective on Mat

5506:    Input Parameters:
5507: +  mat - the matrix
5508: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5510:    Output Parameter:
5511: .  nrm - the resulting norm

5513:    Level: intermediate

5515: @*/
5516: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5517: {


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

5530:   (*mat->ops->norm)(mat,type,nrm);
5531:   return(0);
5532: }

5534: /*
5535:      This variable is used to prevent counting of MatAssemblyBegin() that
5536:    are called from within a MatAssemblyEnd().
5537: */
5538: static PetscInt MatAssemblyEnd_InUse = 0;
5539: /*@
5540:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5541:    be called after completing all calls to MatSetValues().

5543:    Collective on Mat

5545:    Input Parameters:
5546: +  mat - the matrix
5547: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5549:    Notes:
5550:    MatSetValues() generally caches the values.  The matrix is ready to
5551:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5552:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5553:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5554:    using the matrix.

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

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

5564:    Level: beginner

5566: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5567: @*/
5568: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5569: {

5575:   MatCheckPreallocated(mat,1);
5576:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5577:   if (mat->assembled) {
5578:     mat->was_assembled = PETSC_TRUE;
5579:     mat->assembled     = PETSC_FALSE;
5580:   }

5582:   if (!MatAssemblyEnd_InUse) {
5583:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5584:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5585:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5586:   } else if (mat->ops->assemblybegin) {
5587:     (*mat->ops->assemblybegin)(mat,type);
5588:   }
5589:   return(0);
5590: }

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

5596:    Not Collective

5598:    Input Parameter:
5599: .  mat - the matrix

5601:    Output Parameter:
5602: .  assembled - PETSC_TRUE or PETSC_FALSE

5604:    Level: advanced

5606: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5607: @*/
5608: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5609: {
5613:   *assembled = mat->assembled;
5614:   return(0);
5615: }

5617: /*@
5618:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5619:    be called after MatAssemblyBegin().

5621:    Collective on Mat

5623:    Input Parameters:
5624: +  mat - the matrix
5625: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5627:    Options Database Keys:
5628: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5629: .  -mat_view ::ascii_info_detail - Prints more detailed info
5630: .  -mat_view - Prints matrix in ASCII format
5631: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5632: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5633: .  -display <name> - Sets display name (default is host)
5634: .  -draw_pause <sec> - Sets number of seconds to pause after display
5635: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab)
5636: .  -viewer_socket_machine <machine> - Machine to use for socket
5637: .  -viewer_socket_port <port> - Port number to use for socket
5638: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5640:    Notes:
5641:    MatSetValues() generally caches the values.  The matrix is ready to
5642:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5643:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5644:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5645:    using the matrix.

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

5651:    Level: beginner

5653: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5654: @*/
5655: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5656: {
5657:   PetscErrorCode  ierr;
5658:   static PetscInt inassm = 0;
5659:   PetscBool       flg    = PETSC_FALSE;


5665:   inassm++;
5666:   MatAssemblyEnd_InUse++;
5667:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5668:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5669:     if (mat->ops->assemblyend) {
5670:       (*mat->ops->assemblyend)(mat,type);
5671:     }
5672:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5673:   } else if (mat->ops->assemblyend) {
5674:     (*mat->ops->assemblyend)(mat,type);
5675:   }

5677:   /* Flush assembly is not a true assembly */
5678:   if (type != MAT_FLUSH_ASSEMBLY) {
5679:     mat->num_ass++;
5680:     mat->assembled        = PETSC_TRUE;
5681:     mat->ass_nonzerostate = mat->nonzerostate;
5682:   }

5684:   mat->insertmode = NOT_SET_VALUES;
5685:   MatAssemblyEnd_InUse--;
5686:   PetscObjectStateIncrease((PetscObject)mat);
5687:   if (!mat->symmetric_eternal) {
5688:     mat->symmetric_set              = PETSC_FALSE;
5689:     mat->hermitian_set              = PETSC_FALSE;
5690:     mat->structurally_symmetric_set = PETSC_FALSE;
5691:   }
5692:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5693:     MatViewFromOptions(mat,NULL,"-mat_view");

5695:     if (mat->checksymmetryonassembly) {
5696:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5697:       if (flg) {
5698:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5699:       } else {
5700:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5701:       }
5702:     }
5703:     if (mat->nullsp && mat->checknullspaceonassembly) {
5704:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5705:     }
5706:   }
5707:   inassm--;
5708:   return(0);
5709: }

5711: /*@
5712:    MatSetOption - Sets a parameter option for a matrix. Some options
5713:    may be specific to certain storage formats.  Some options
5714:    determine how values will be inserted (or added). Sorted,
5715:    row-oriented input will generally assemble the fastest. The default
5716:    is row-oriented.

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

5720:    Input Parameters:
5721: +  mat - the matrix
5722: .  option - the option, one of those listed below (and possibly others),
5723: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5725:   Options Describing Matrix Structure:
5726: +    MAT_SPD - symmetric positive definite
5727: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5728: .    MAT_HERMITIAN - transpose is the complex conjugation
5729: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5730: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5731:                             you set to be kept with all future use of the matrix
5732:                             including after MatAssemblyBegin/End() which could
5733:                             potentially change the symmetry structure, i.e. you
5734:                             KNOW the matrix will ALWAYS have the property you set.
5735:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5736:                             the relevant flags must be set independently.

5738:    Options For Use with MatSetValues():
5739:    Insert a logically dense subblock, which can be
5740: .    MAT_ROW_ORIENTED - row-oriented (default)

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

5746:    When (re)assembling a matrix, we can restrict the input for
5747:    efficiency/debugging purposes.  These options include:
5748: +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5749: .    MAT_FORCE_DIAGONAL_ENTRIES - forces diagonal entries to be allocated
5750: .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5751: .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5752: .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5753: .    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5754:         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5755:         performance for very large process counts.
5756: -    MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5757:         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5758:         functions, instead sending only neighbor messages.

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

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

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

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

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

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

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

5794:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5795:    searches during matrix assembly. When this flag is set, the hash table
5796:    is created during the first Matrix Assembly. This hash table is
5797:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5798:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5799:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5800:    supported by MATMPIBAIJ format only.

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

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

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

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

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

5816:    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5817:                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5818:                      with finite difference schemes with non-periodic boundary conditions.

5820:    Level: intermediate

5822: .seealso:  MatOption, Mat

5824: @*/
5825: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5826: {

5831:   if (op > 0) {
5834:   }

5836:   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);

5838:   switch (op) {
5839:   case MAT_FORCE_DIAGONAL_ENTRIES:
5840:     mat->force_diagonals = flg;
5841:     return(0);
5842:   case MAT_NO_OFF_PROC_ENTRIES:
5843:     mat->nooffprocentries = flg;
5844:     return(0);
5845:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5846:     mat->assembly_subset = flg;
5847:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5848: #if !defined(PETSC_HAVE_MPIUNI)
5849:       MatStashScatterDestroy_BTS(&mat->stash);
5850: #endif
5851:       mat->stash.first_assembly_done = PETSC_FALSE;
5852:     }
5853:     return(0);
5854:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5855:     mat->nooffproczerorows = flg;
5856:     return(0);
5857:   case MAT_SPD:
5858:     mat->spd_set = PETSC_TRUE;
5859:     mat->spd     = flg;
5860:     if (flg) {
5861:       mat->symmetric                  = PETSC_TRUE;
5862:       mat->structurally_symmetric     = PETSC_TRUE;
5863:       mat->symmetric_set              = PETSC_TRUE;
5864:       mat->structurally_symmetric_set = PETSC_TRUE;
5865:     }
5866:     break;
5867:   case MAT_SYMMETRIC:
5868:     mat->symmetric = flg;
5869:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5870:     mat->symmetric_set              = PETSC_TRUE;
5871:     mat->structurally_symmetric_set = flg;
5872: #if !defined(PETSC_USE_COMPLEX)
5873:     mat->hermitian     = flg;
5874:     mat->hermitian_set = PETSC_TRUE;
5875: #endif
5876:     break;
5877:   case MAT_HERMITIAN:
5878:     mat->hermitian = flg;
5879:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5880:     mat->hermitian_set              = PETSC_TRUE;
5881:     mat->structurally_symmetric_set = flg;
5882: #if !defined(PETSC_USE_COMPLEX)
5883:     mat->symmetric     = flg;
5884:     mat->symmetric_set = PETSC_TRUE;
5885: #endif
5886:     break;
5887:   case MAT_STRUCTURALLY_SYMMETRIC:
5888:     mat->structurally_symmetric     = flg;
5889:     mat->structurally_symmetric_set = PETSC_TRUE;
5890:     break;
5891:   case MAT_SYMMETRY_ETERNAL:
5892:     mat->symmetric_eternal = flg;
5893:     break;
5894:   case MAT_STRUCTURE_ONLY:
5895:     mat->structure_only = flg;
5896:     break;
5897:   case MAT_SORTED_FULL:
5898:     mat->sortedfull = flg;
5899:     break;
5900:   default:
5901:     break;
5902:   }
5903:   if (mat->ops->setoption) {
5904:     (*mat->ops->setoption)(mat,op,flg);
5905:   }
5906:   return(0);
5907: }

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

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

5914:    Input Parameters:
5915: +  mat - the matrix
5916: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5924:    Level: intermediate

5926: .seealso:  MatOption, MatSetOption()

5928: @*/
5929: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5930: {

5935:   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);
5936:   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()");

5938:   switch (op) {
5939:   case MAT_NO_OFF_PROC_ENTRIES:
5940:     *flg = mat->nooffprocentries;
5941:     break;
5942:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5943:     *flg = mat->nooffproczerorows;
5944:     break;
5945:   case MAT_SYMMETRIC:
5946:     *flg = mat->symmetric;
5947:     break;
5948:   case MAT_HERMITIAN:
5949:     *flg = mat->hermitian;
5950:     break;
5951:   case MAT_STRUCTURALLY_SYMMETRIC:
5952:     *flg = mat->structurally_symmetric;
5953:     break;
5954:   case MAT_SYMMETRY_ETERNAL:
5955:     *flg = mat->symmetric_eternal;
5956:     break;
5957:   case MAT_SPD:
5958:     *flg = mat->spd;
5959:     break;
5960:   default:
5961:     break;
5962:   }
5963:   return(0);
5964: }

5966: /*@
5967:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5968:    this routine retains the old nonzero structure.

5970:    Logically Collective on Mat

5972:    Input Parameters:
5973: .  mat - the matrix

5975:    Level: intermediate

5977:    Notes:
5978:     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.
5979:    See the Performance chapter of the users manual for information on preallocating matrices.

5981: .seealso: MatZeroRows()
5982: @*/
5983: PetscErrorCode MatZeroEntries(Mat mat)
5984: {

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

5995:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5996:   (*mat->ops->zeroentries)(mat);
5997:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5998:   PetscObjectStateIncrease((PetscObject)mat);
5999:   return(0);
6000: }

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

6006:    Collective on Mat

6008:    Input Parameters:
6009: +  mat - the matrix
6010: .  numRows - the number of rows to remove
6011: .  rows - the global row indices
6012: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6013: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6014: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

6033:    Level: intermediate

6035: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6036:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6037: @*/
6038: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6039: {

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

6051:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
6052:   MatViewFromOptions(mat,NULL,"-mat_view");
6053:   PetscObjectStateIncrease((PetscObject)mat);
6054:   return(0);
6055: }

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

6061:    Collective on Mat

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

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

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

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

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

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

6087:    Level: intermediate

6089: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6090:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
6091: @*/
6092: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6093: {
6095:   PetscInt       numRows;
6096:   const PetscInt *rows;

6103:   ISGetLocalSize(is,&numRows);
6104:   ISGetIndices(is,&rows);
6105:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
6106:   ISRestoreIndices(is,&rows);
6107:   return(0);
6108: }

6110: /*@
6111:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
6112:    of a set of rows of a matrix.

6114:    Collective on Mat

6116:    Input Parameters:
6117: +  mat - the matrix
6118: .  numRows - the number of rows to remove
6119: .  rows - the global row indices
6120: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6121: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6122: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

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

6148:    Level: intermediate

6150: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6151:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6152: @*/
6153: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6154: {

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

6166:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
6167:   MatViewFromOptions(mat,NULL,"-mat_view");
6168:   PetscObjectStateIncrease((PetscObject)mat);
6169:   return(0);
6170: }

6172: /*@
6173:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6174:    of a set of rows of a matrix.

6176:    Collective on Mat

6178:    Input Parameters:
6179: +  mat - the matrix
6180: .  is - index set of rows to remove (if NULL then no row is removed)
6181: .  diag - value put in all diagonals of eliminated rows
6182: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6183: -  b - optional vector of right hand side, that will be adjusted by provided solution

6185:    Notes:
6186:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6187:    but does not release memory.  For the dense and block diagonal
6188:    formats this does not alter the nonzero structure.

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

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

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

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

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

6209:    Level: intermediate

6211: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6212:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6213: @*/
6214: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6215: {
6216:   PetscInt       numRows = 0;
6217:   const PetscInt *rows = NULL;

6223:   if (is) {
6225:     ISGetLocalSize(is,&numRows);
6226:     ISGetIndices(is,&rows);
6227:   }
6228:   MatZeroRows(mat,numRows,rows,diag,x,b);
6229:   if (is) {
6230:     ISRestoreIndices(is,&rows);
6231:   }
6232:   return(0);
6233: }

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

6239:    Collective on Mat

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

6249:    Notes:
6250:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6251:    but does not release memory.  For the dense and block diagonal
6252:    formats this does not alter the nonzero structure.

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

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

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

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

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

6272:    In Fortran idxm and idxn should be declared as
6273: $     MatStencil idxm(4,m)
6274:    and the values inserted using
6275: $    idxm(MatStencil_i,1) = i
6276: $    idxm(MatStencil_j,1) = j
6277: $    idxm(MatStencil_k,1) = k
6278: $    idxm(MatStencil_c,1) = c
6279:    etc

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

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

6289:    Level: intermediate

6291: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6292:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6293: @*/
6294: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6295: {
6296:   PetscInt       dim     = mat->stencil.dim;
6297:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6298:   PetscInt       *dims   = mat->stencil.dims+1;
6299:   PetscInt       *starts = mat->stencil.starts;
6300:   PetscInt       *dxm    = (PetscInt*) rows;
6301:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6309:   PetscMalloc1(numRows, &jdxm);
6310:   for (i = 0; i < numRows; ++i) {
6311:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6312:     for (j = 0; j < 3-sdim; ++j) dxm++;
6313:     /* Local index in X dir */
6314:     tmp = *dxm++ - starts[0];
6315:     /* Loop over remaining dimensions */
6316:     for (j = 0; j < dim-1; ++j) {
6317:       /* If nonlocal, set index to be negative */
6318:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6319:       /* Update local index */
6320:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6321:     }
6322:     /* Skip component slot if necessary */
6323:     if (mat->stencil.noc) dxm++;
6324:     /* Local row number */
6325:     if (tmp >= 0) {
6326:       jdxm[numNewRows++] = tmp;
6327:     }
6328:   }
6329:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6330:   PetscFree(jdxm);
6331:   return(0);
6332: }

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

6338:    Collective on Mat

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

6348:    Notes:
6349:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6350:    but does not release memory.  For the dense and block diagonal
6351:    formats this does not alter the nonzero structure.

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

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:    For the parallel case, all processes that share the matrix (i.e.,
6362:    those in the communicator used for matrix creation) MUST call this
6363:    routine, regardless of whether any rows being zeroed are owned by
6364:    them.

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

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

6371:    In Fortran idxm and idxn should be declared as
6372: $     MatStencil idxm(4,m)
6373:    and the values inserted using
6374: $    idxm(MatStencil_i,1) = i
6375: $    idxm(MatStencil_j,1) = j
6376: $    idxm(MatStencil_k,1) = k
6377: $    idxm(MatStencil_c,1) = c
6378:    etc

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

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

6388:    Level: intermediate

6390: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6391:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6392: @*/
6393: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6394: {
6395:   PetscInt       dim     = mat->stencil.dim;
6396:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6397:   PetscInt       *dims   = mat->stencil.dims+1;
6398:   PetscInt       *starts = mat->stencil.starts;
6399:   PetscInt       *dxm    = (PetscInt*) rows;
6400:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6408:   PetscMalloc1(numRows, &jdxm);
6409:   for (i = 0; i < numRows; ++i) {
6410:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6411:     for (j = 0; j < 3-sdim; ++j) dxm++;
6412:     /* Local index in X dir */
6413:     tmp = *dxm++ - starts[0];
6414:     /* Loop over remaining dimensions */
6415:     for (j = 0; j < dim-1; ++j) {
6416:       /* If nonlocal, set index to be negative */
6417:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6418:       /* Update local index */
6419:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6420:     }
6421:     /* Skip component slot if necessary */
6422:     if (mat->stencil.noc) dxm++;
6423:     /* Local row number */
6424:     if (tmp >= 0) {
6425:       jdxm[numNewRows++] = tmp;
6426:     }
6427:   }
6428:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6429:   PetscFree(jdxm);
6430:   return(0);
6431: }

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

6437:    Collective on Mat

6439:    Input Parameters:
6440: +  mat - the matrix
6441: .  numRows - the number of rows to remove
6442: .  rows - the local row indices
6443: .  diag - value put in all diagonals of eliminated rows
6444: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6445: -  b - optional vector of right hand side, that will be adjusted by provided solution

6447:    Notes:
6448:    Before calling MatZeroRowsLocal(), the user must first set the
6449:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6451:    For the AIJ matrix formats this removes the old nonzero structure,
6452:    but does not release memory.  For the dense and block diagonal
6453:    formats this does not alter the nonzero structure.

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

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

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

6466:    Level: intermediate

6468: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6469:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6470: @*/
6471: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6472: {

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

6483:   if (mat->ops->zerorowslocal) {
6484:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6485:   } else {
6486:     IS             is, newis;
6487:     const PetscInt *newRows;

6489:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6490:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6491:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6492:     ISGetIndices(newis,&newRows);
6493:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6494:     ISRestoreIndices(newis,&newRows);
6495:     ISDestroy(&newis);
6496:     ISDestroy(&is);
6497:   }
6498:   PetscObjectStateIncrease((PetscObject)mat);
6499:   return(0);
6500: }

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

6506:    Collective on Mat

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

6515:    Notes:
6516:    Before calling MatZeroRowsLocalIS(), the user must first set the
6517:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6519:    For the AIJ matrix formats this removes the old nonzero structure,
6520:    but does not release memory.  For the dense and block diagonal
6521:    formats this does not alter the nonzero structure.

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

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

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

6534:    Level: intermediate

6536: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6537:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6538: @*/
6539: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6540: {
6542:   PetscInt       numRows;
6543:   const PetscInt *rows;

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

6553:   ISGetLocalSize(is,&numRows);
6554:   ISGetIndices(is,&rows);
6555:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6556:   ISRestoreIndices(is,&rows);
6557:   return(0);
6558: }

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

6564:    Collective on Mat

6566:    Input Parameters:
6567: +  mat - the matrix
6568: .  numRows - the number of rows to remove
6569: .  rows - the global row indices
6570: .  diag - value put in all diagonals of eliminated rows
6571: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6572: -  b - optional vector of right hand side, that will be adjusted by provided solution

6574:    Notes:
6575:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6576:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6582:    Level: intermediate

6584: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6585:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6586: @*/
6587: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6588: {
6590:   IS             is, newis;
6591:   const PetscInt *newRows;

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

6601:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6602:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6603:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6604:   ISGetIndices(newis,&newRows);
6605:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6606:   ISRestoreIndices(newis,&newRows);
6607:   ISDestroy(&newis);
6608:   ISDestroy(&is);
6609:   PetscObjectStateIncrease((PetscObject)mat);
6610:   return(0);
6611: }

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

6617:    Collective on Mat

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

6626:    Notes:
6627:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6628:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6634:    Level: intermediate

6636: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6637:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6638: @*/
6639: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6640: {
6642:   PetscInt       numRows;
6643:   const PetscInt *rows;

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

6653:   ISGetLocalSize(is,&numRows);
6654:   ISGetIndices(is,&rows);
6655:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6656:   ISRestoreIndices(is,&rows);
6657:   return(0);
6658: }

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

6663:    Not Collective

6665:    Input Parameter:
6666: .  mat - the matrix

6668:    Output Parameters:
6669: +  m - the number of global rows
6670: -  n - the number of global columns

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

6674:    Level: beginner

6676: .seealso: MatGetLocalSize()
6677: @*/
6678: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6679: {
6682:   if (m) *m = mat->rmap->N;
6683:   if (n) *n = mat->cmap->N;
6684:   return(0);
6685: }

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

6691:    Not Collective

6693:    Input Parameter:
6694: .  mat - the matrix

6696:    Output Parameters:
6697: +  m - the number of local rows
6698: -  n - the number of local columns

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

6702:    Level: beginner

6704: .seealso: MatGetSize()
6705: @*/
6706: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6707: {
6712:   if (m) *m = mat->rmap->n;
6713:   if (n) *n = mat->cmap->n;
6714:   return(0);
6715: }

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

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

6723:    Input Parameter:
6724: .  mat - the matrix

6726:    Output Parameters:
6727: +  m - the global index of the first local column
6728: -  n - one more than the global index of the last local column

6730:    Notes:
6731:     both output parameters can be NULL on input.

6733:    Level: developer

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

6737: @*/
6738: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6739: {
6745:   MatCheckPreallocated(mat,1);
6746:   if (m) *m = mat->cmap->rstart;
6747:   if (n) *n = mat->cmap->rend;
6748:   return(0);
6749: }

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

6757:    Not Collective

6759:    Input Parameter:
6760: .  mat - the matrix

6762:    Output Parameters:
6763: +  m - the global index of the first local row
6764: -  n - one more than the global index of the last local row

6766:    Note: Both output parameters can be NULL on input.
6767: $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6768: $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6769: $  and then MPI_Scan() to calculate prefix sums of the local sizes.

6771:    Level: beginner

6773: .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()

6775: @*/
6776: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6777: {
6783:   MatCheckPreallocated(mat,1);
6784:   if (m) *m = mat->rmap->rstart;
6785:   if (n) *n = mat->rmap->rend;
6786:   return(0);
6787: }

6789: /*@C
6790:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6791:    each process

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

6795:    Input Parameters:
6796: .  mat - the matrix

6798:    Output Parameters:
6799: .  ranges - start of each processors portion plus one more than the total length at the end

6801:    Level: beginner

6803: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()

6805: @*/
6806: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6807: {

6813:   MatCheckPreallocated(mat,1);
6814:   PetscLayoutGetRanges(mat->rmap,ranges);
6815:   return(0);
6816: }

6818: /*@C
6819:    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6820:    this processor. (The columns of the "diagonal blocks" for each process)

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

6824:    Input Parameters:
6825: .  mat - the matrix

6827:    Output Parameters:
6828: .  ranges - start of each processors portion plus one more then the total length at the end

6830:    Level: beginner

6832: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()

6834: @*/
6835: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6836: {

6842:   MatCheckPreallocated(mat,1);
6843:   PetscLayoutGetRanges(mat->cmap,ranges);
6844:   return(0);
6845: }

6847: /*@C
6848:    MatGetOwnershipIS - Get row and column ownership as index sets

6850:    Not Collective

6852:    Input Parameter:
6853: .  A - matrix of type Elemental or ScaLAPACK

6855:    Output Parameters:
6856: +  rows - rows in which this process owns elements
6857: -  cols - columns in which this process owns elements

6859:    Level: intermediate

6861: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6862: @*/
6863: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6864: {
6865:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6868:   MatCheckPreallocated(A,1);
6869:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6870:   if (f) {
6871:     (*f)(A,rows,cols);
6872:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6873:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6874:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6875:   }
6876:   return(0);
6877: }

6879: /*@C
6880:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6881:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6882:    to complete the factorization.

6884:    Collective on Mat

6886:    Input Parameters:
6887: +  mat - the matrix
6888: .  row - row permutation
6889: .  column - column permutation
6890: -  info - structure containing
6891: $      levels - number of levels of fill.
6892: $      expected fill - as ratio of original fill.
6893: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6894:                 missing diagonal entries)

6896:    Output Parameters:
6897: .  fact - new matrix that has been symbolically factored

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

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

6906:    Level: developer

6908: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6909:           MatGetOrdering(), MatFactorInfo

6911:     Note: this uses the definition of level of fill as in Y. Saad, 2003

6913:     Developer Note: fortran interface is not autogenerated as the f90
6914:     interface definition cannot be generated correctly [due to MatFactorInfo]

6916:    References:
6917:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6918: @*/
6919: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6920: {

6930:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6931:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6932:   if (!fact->ops->ilufactorsymbolic) {
6933:     MatSolverType stype;
6934:     MatFactorGetSolverType(fact,&stype);
6935:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver type %s",((PetscObject)mat)->type_name,stype);
6936:   }
6937:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6938:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6939:   MatCheckPreallocated(mat,2);

6941:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);}
6942:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6943:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);}
6944:   return(0);
6945: }

6947: /*@C
6948:    MatICCFactorSymbolic - Performs symbolic incomplete
6949:    Cholesky factorization for a symmetric matrix.  Use
6950:    MatCholeskyFactorNumeric() to complete the factorization.

6952:    Collective on Mat

6954:    Input Parameters:
6955: +  mat - the matrix
6956: .  perm - row and column permutation
6957: -  info - structure containing
6958: $      levels - number of levels of fill.
6959: $      expected fill - as ratio of original fill.

6961:    Output Parameter:
6962: .  fact - the factored matrix

6964:    Notes:
6965:    Most users should employ the KSP interface for linear solvers
6966:    instead of working directly with matrix algebra routines such as this.
6967:    See, e.g., KSPCreate().

6969:    Level: developer

6971: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6973:     Note: this uses the definition of level of fill as in Y. Saad, 2003

6975:     Developer Note: fortran interface is not autogenerated as the f90
6976:     interface definition cannot be generated correctly [due to MatFactorInfo]

6978:    References:
6979:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6980: @*/
6981: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6982: {

6991:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6992:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6993:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6994:   if (!(fact)->ops->iccfactorsymbolic) {
6995:     MatSolverType stype;
6996:     MatFactorGetSolverType(fact,&stype);
6997:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver type %s",((PetscObject)mat)->type_name,stype);
6998:   }
6999:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7000:   MatCheckPreallocated(mat,2);

7002:   if (!fact->trivialsymbolic) {PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);}
7003:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
7004:   if (!fact->trivialsymbolic) {PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);}
7005:   return(0);
7006: }

7008: /*@C
7009:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7010:    points to an array of valid matrices, they may be reused to store the new
7011:    submatrices.

7013:    Collective on Mat

7015:    Input Parameters:
7016: +  mat - the matrix
7017: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
7018: .  irow, icol - index sets of rows and columns to extract
7019: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7021:    Output Parameter:
7022: .  submat - the array of submatrices

7024:    Notes:
7025:    MatCreateSubMatrices() can extract ONLY sequential submatrices
7026:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
7027:    to extract a parallel submatrix.

7029:    Some matrix types place restrictions on the row and column
7030:    indices, such as that they be sorted or that they be equal to each other.

7032:    The index sets may not have duplicate entries.

7034:    When extracting submatrices from a parallel matrix, each processor can
7035:    form a different submatrix by setting the rows and columns of its
7036:    individual index sets according to the local submatrix desired.

7038:    When finished using the submatrices, the user should destroy
7039:    them with MatDestroySubMatrices().

7041:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
7042:    original matrix has not changed from that last call to MatCreateSubMatrices().

7044:    This routine creates the matrices in submat; you should NOT create them before
7045:    calling it. It also allocates the array of matrix pointers submat.

7047:    For BAIJ matrices the index sets must respect the block structure, that is if they
7048:    request one row/column in a block, they must request all rows/columns that are in
7049:    that block. For example, if the block size is 2 you cannot request just row 0 and
7050:    column 0.

7052:    Fortran Note:
7053:    The Fortran interface is slightly different from that given below; it
7054:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

7056:    Level: advanced

7058: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
7059: @*/
7060: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
7061: {
7063:   PetscInt       i;
7064:   PetscBool      eq;

7069:   if (n) {
7074:   }
7076:   if (n && scall == MAT_REUSE_MATRIX) {
7079:   }
7080:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7081:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7082:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7083:   MatCheckPreallocated(mat,1);

7085:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
7086:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
7087:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
7088:   for (i=0; i<n; i++) {
7089:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
7090:     ISEqualUnsorted(irow[i],icol[i],&eq);
7091:     if (eq) {
7092:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
7093:     }
7094:   }
7095:   return(0);
7096: }

7098: /*@C
7099:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

7101:    Collective on Mat

7103:    Input Parameters:
7104: +  mat - the matrix
7105: .  n   - the number of submatrixes to be extracted
7106: .  irow, icol - index sets of rows and columns to extract
7107: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7109:    Output Parameter:
7110: .  submat - the array of submatrices

7112:    Level: advanced

7114: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
7115: @*/
7116: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
7117: {
7119:   PetscInt       i;
7120:   PetscBool      eq;

7125:   if (n) {
7130:   }
7132:   if (n && scall == MAT_REUSE_MATRIX) {
7135:   }
7136:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7137:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7138:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7139:   MatCheckPreallocated(mat,1);

7141:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
7142:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
7143:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
7144:   for (i=0; i<n; i++) {
7145:     ISEqualUnsorted(irow[i],icol[i],&eq);
7146:     if (eq) {
7147:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
7148:     }
7149:   }
7150:   return(0);
7151: }

7153: /*@C
7154:    MatDestroyMatrices - Destroys an array of matrices.

7156:    Collective on Mat

7158:    Input Parameters:
7159: +  n - the number of local matrices
7160: -  mat - the matrices (note that this is a pointer to the array of matrices)

7162:    Level: advanced

7164:     Notes:
7165:     Frees not only the matrices, but also the array that contains the matrices
7166:            In Fortran will not free the array.

7168: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
7169: @*/
7170: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
7171: {
7173:   PetscInt       i;

7176:   if (!*mat) return(0);
7177:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

7180:   for (i=0; i<n; i++) {
7181:     MatDestroy(&(*mat)[i]);
7182:   }

7184:   /* memory is allocated even if n = 0 */
7185:   PetscFree(*mat);
7186:   return(0);
7187: }

7189: /*@C
7190:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

7192:    Collective on Mat

7194:    Input Parameters:
7195: +  n - the number of local matrices
7196: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
7197:                        sequence of MatCreateSubMatrices())

7199:    Level: advanced

7201:     Notes:
7202:     Frees not only the matrices, but also the array that contains the matrices
7203:            In Fortran will not free the array.

7205: .seealso: MatCreateSubMatrices()
7206: @*/
7207: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
7208: {
7210:   Mat            mat0;

7213:   if (!*mat) return(0);
7214:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7215:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

7218:   mat0 = (*mat)[0];
7219:   if (mat0 && mat0->ops->destroysubmatrices) {
7220:     (mat0->ops->destroysubmatrices)(n,mat);
7221:   } else {
7222:     MatDestroyMatrices(n,mat);
7223:   }
7224:   return(0);
7225: }

7227: /*@C
7228:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

7230:    Collective on Mat

7232:    Input Parameters:
7233: .  mat - the matrix

7235:    Output Parameter:
7236: .  matstruct - the sequential matrix with the nonzero structure of mat

7238:   Level: intermediate

7240: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7241: @*/
7242: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7243: {


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

7254:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7255:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7256:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
7257:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7258:   return(0);
7259: }

7261: /*@C
7262:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

7264:    Collective on Mat

7266:    Input Parameters:
7267: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
7268:                        sequence of MatGetSequentialNonzeroStructure())

7270:    Level: advanced

7272:     Notes:
7273:     Frees not only the matrices, but also the array that contains the matrices

7275: .seealso: MatGetSeqNonzeroStructure()
7276: @*/
7277: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7278: {

7283:   MatDestroy(mat);
7284:   return(0);
7285: }

7287: /*@
7288:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7289:    replaces the index sets by larger ones that represent submatrices with
7290:    additional overlap.

7292:    Collective on Mat

7294:    Input Parameters:
7295: +  mat - the matrix
7296: .  n   - the number of index sets
7297: .  is  - the array of index sets (these index sets will changed during the call)
7298: -  ov  - the additional overlap requested

7300:    Options Database:
7301: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7303:    Level: developer

7305: .seealso: MatCreateSubMatrices()
7306: @*/
7307: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7308: {

7314:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7315:   if (n) {
7318:   }
7319:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7320:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7321:   MatCheckPreallocated(mat,1);

7323:   if (!ov) return(0);
7324:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7325:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7326:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7327:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7328:   return(0);
7329: }

7331: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7333: /*@
7334:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7335:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7336:    additional overlap.

7338:    Collective on Mat

7340:    Input Parameters:
7341: +  mat - the matrix
7342: .  n   - the number of index sets
7343: .  is  - the array of index sets (these index sets will changed during the call)
7344: -  ov  - the additional overlap requested

7346:    Options Database:
7347: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7349:    Level: developer

7351: .seealso: MatCreateSubMatrices()
7352: @*/
7353: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7354: {
7355:   PetscInt       i;

7361:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7362:   if (n) {
7365:   }
7366:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7367:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7368:   MatCheckPreallocated(mat,1);
7369:   if (!ov) return(0);
7370:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7371:   for (i=0; i<n; i++) {
7372:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7373:   }
7374:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7375:   return(0);
7376: }

7378: /*@
7379:    MatGetBlockSize - Returns the matrix block size.

7381:    Not Collective

7383:    Input Parameter:
7384: .  mat - the matrix

7386:    Output Parameter:
7387: .  bs - block size

7389:    Notes:
7390:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7392:    If the block size has not been set yet this routine returns 1.

7394:    Level: intermediate

7396: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7397: @*/
7398: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7399: {
7403:   *bs = PetscAbs(mat->rmap->bs);
7404:   return(0);
7405: }

7407: /*@
7408:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7410:    Not Collective

7412:    Input Parameter:
7413: .  mat - the matrix

7415:    Output Parameters:
7416: +  rbs - row block size
7417: -  cbs - column block size

7419:    Notes:
7420:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7421:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7423:    If a block size has not been set yet this routine returns 1.

7425:    Level: intermediate

7427: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7428: @*/
7429: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7430: {
7435:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7436:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7437:   return(0);
7438: }

7440: /*@
7441:    MatSetBlockSize - Sets the matrix block size.

7443:    Logically Collective on Mat

7445:    Input Parameters:
7446: +  mat - the matrix
7447: -  bs - block size

7449:    Notes:
7450:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7451:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7453:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7454:     is compatible with the matrix local sizes.

7456:    Level: intermediate

7458: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7459: @*/
7460: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7461: {

7467:   MatSetBlockSizes(mat,bs,bs);
7468:   return(0);
7469: }

7471: /*@
7472:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7474:    Logically Collective on Mat

7476:    Input Parameters:
7477: +  mat - the matrix
7478: .  nblocks - the number of blocks on this process
7479: -  bsizes - the block sizes

7481:    Notes:
7482:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7484:    Level: intermediate

7486: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7487: @*/
7488: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7489: {
7491:   PetscInt       i,ncnt = 0, nlocal;

7495:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7496:   MatGetLocalSize(mat,&nlocal,NULL);
7497:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7498:   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);
7499:   PetscFree(mat->bsizes);
7500:   mat->nblocks = nblocks;
7501:   PetscMalloc1(nblocks,&mat->bsizes);
7502:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7503:   return(0);
7504: }

7506: /*@C
7507:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7509:    Logically Collective on Mat

7511:    Input Parameter:
7512: .  mat - the matrix

7514:    Output Parameters:
7515: +  nblocks - the number of blocks on this process
7516: -  bsizes - the block sizes

7518:    Notes: Currently not supported from Fortran

7520:    Level: intermediate

7522: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7523: @*/
7524: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7525: {
7528:   *nblocks = mat->nblocks;
7529:   *bsizes  = mat->bsizes;
7530:   return(0);
7531: }

7533: /*@
7534:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7536:    Logically Collective on Mat

7538:    Input Parameters:
7539: +  mat - the matrix
7540: .  rbs - row block size
7541: -  cbs - column block size

7543:    Notes:
7544:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7545:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7546:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7548:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7549:     are compatible with the matrix local sizes.

7551:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7553:    Level: intermediate

7555: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7556: @*/
7557: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7558: {

7565:   if (mat->ops->setblocksizes) {
7566:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7567:   }
7568:   if (mat->rmap->refcnt) {
7569:     ISLocalToGlobalMapping l2g = NULL;
7570:     PetscLayout            nmap = NULL;

7572:     PetscLayoutDuplicate(mat->rmap,&nmap);
7573:     if (mat->rmap->mapping) {
7574:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7575:     }
7576:     PetscLayoutDestroy(&mat->rmap);
7577:     mat->rmap = nmap;
7578:     mat->rmap->mapping = l2g;
7579:   }
7580:   if (mat->cmap->refcnt) {
7581:     ISLocalToGlobalMapping l2g = NULL;
7582:     PetscLayout            nmap = NULL;

7584:     PetscLayoutDuplicate(mat->cmap,&nmap);
7585:     if (mat->cmap->mapping) {
7586:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7587:     }
7588:     PetscLayoutDestroy(&mat->cmap);
7589:     mat->cmap = nmap;
7590:     mat->cmap->mapping = l2g;
7591:   }
7592:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7593:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7594:   return(0);
7595: }

7597: /*@
7598:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7600:    Logically Collective on Mat

7602:    Input Parameters:
7603: +  mat - the matrix
7604: .  fromRow - matrix from which to copy row block size
7605: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7607:    Level: developer

7609: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7610: @*/
7611: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7612: {

7619:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7620:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7621:   return(0);
7622: }

7624: /*@
7625:    MatResidual - Default routine to calculate the residual.

7627:    Collective on Mat

7629:    Input Parameters:
7630: +  mat - the matrix
7631: .  b   - the right-hand-side
7632: -  x   - the approximate solution

7634:    Output Parameter:
7635: .  r - location to store the residual

7637:    Level: developer

7639: .seealso: PCMGSetResidual()
7640: @*/
7641: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7642: {

7651:   MatCheckPreallocated(mat,1);
7652:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7653:   if (!mat->ops->residual) {
7654:     MatMult(mat,x,r);
7655:     VecAYPX(r,-1.0,b);
7656:   } else {
7657:     (*mat->ops->residual)(mat,b,x,r);
7658:   }
7659:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7660:   return(0);
7661: }

7663: /*@C
7664:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7666:    Collective on Mat

7668:     Input Parameters:
7669: +   mat - the matrix
7670: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7671: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7672: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7673:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7674:                  always used.

7676:     Output Parameters:
7677: +   n - number of rows in the (possibly compressed) matrix
7678: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7679: .   ja - the column indices
7680: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7681:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7683:     Level: developer

7685:     Notes:
7686:     You CANNOT change any of the ia[] or ja[] values.

7688:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7690:     Fortran Notes:
7691:     In Fortran use
7692: $
7693: $      PetscInt ia(1), ja(1)
7694: $      PetscOffset iia, jja
7695: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7696: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7698:      or
7699: $
7700: $    PetscInt, pointer :: ia(:),ja(:)
7701: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7702: $    ! Access the ith and jth entries via ia(i) and ja(j)

7704: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7705: @*/
7706: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7707: {

7717:   MatCheckPreallocated(mat,1);
7718:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7719:   else {
7720:     *done = PETSC_TRUE;
7721:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7722:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7723:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7724:   }
7725:   return(0);
7726: }

7728: /*@C
7729:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7731:     Collective on Mat

7733:     Input Parameters:
7734: +   mat - the matrix
7735: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7736: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7737:                 symmetrized
7738: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7739:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7740:                  always used.
7741: .   n - number of columns in the (possibly compressed) matrix
7742: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7743: -   ja - the row indices

7745:     Output Parameters:
7746: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7748:     Level: developer

7750: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7751: @*/
7752: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7753: {

7763:   MatCheckPreallocated(mat,1);
7764:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7765:   else {
7766:     *done = PETSC_TRUE;
7767:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7768:   }
7769:   return(0);
7770: }

7772: /*@C
7773:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7774:     MatGetRowIJ().

7776:     Collective on Mat

7778:     Input Parameters:
7779: +   mat - the matrix
7780: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7781: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7782:                 symmetrized
7783: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7784:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7785:                  always used.
7786: .   n - size of (possibly compressed) matrix
7787: .   ia - the row pointers
7788: -   ja - the column indices

7790:     Output Parameters:
7791: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7793:     Note:
7794:     This routine zeros out n, ia, and ja. This is to prevent accidental
7795:     us of the array after it has been restored. If you pass NULL, it will
7796:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7798:     Level: developer

7800: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7801: @*/
7802: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7803: {

7812:   MatCheckPreallocated(mat,1);

7814:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7815:   else {
7816:     *done = PETSC_TRUE;
7817:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7818:     if (n)  *n = 0;
7819:     if (ia) *ia = NULL;
7820:     if (ja) *ja = NULL;
7821:   }
7822:   return(0);
7823: }

7825: /*@C
7826:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7827:     MatGetColumnIJ().

7829:     Collective on Mat

7831:     Input Parameters:
7832: +   mat - the matrix
7833: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7834: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7835:                 symmetrized
7836: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7837:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7838:                  always used.

7840:     Output Parameters:
7841: +   n - size of (possibly compressed) matrix
7842: .   ia - the column pointers
7843: .   ja - the row indices
7844: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7846:     Level: developer

7848: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7849: @*/
7850: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7851: {

7860:   MatCheckPreallocated(mat,1);

7862:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7863:   else {
7864:     *done = PETSC_TRUE;
7865:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7866:     if (n)  *n = 0;
7867:     if (ia) *ia = NULL;
7868:     if (ja) *ja = NULL;
7869:   }
7870:   return(0);
7871: }

7873: /*@C
7874:     MatColoringPatch -Used inside matrix coloring routines that
7875:     use MatGetRowIJ() and/or MatGetColumnIJ().

7877:     Collective on Mat

7879:     Input Parameters:
7880: +   mat - the matrix
7881: .   ncolors - max color value
7882: .   n   - number of entries in colorarray
7883: -   colorarray - array indicating color for each column

7885:     Output Parameters:
7886: .   iscoloring - coloring generated using colorarray information

7888:     Level: developer

7890: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7892: @*/
7893: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7894: {

7902:   MatCheckPreallocated(mat,1);

7904:   if (!mat->ops->coloringpatch) {
7905:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7906:   } else {
7907:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7908:   }
7909:   return(0);
7910: }

7912: /*@
7913:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7915:    Logically Collective on Mat

7917:    Input Parameter:
7918: .  mat - the factored matrix to be reset

7920:    Notes:
7921:    This routine should be used only with factored matrices formed by in-place
7922:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7923:    format).  This option can save memory, for example, when solving nonlinear
7924:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7925:    ILU(0) preconditioner.

7927:    Note that one can specify in-place ILU(0) factorization by calling
7928: .vb
7929:      PCType(pc,PCILU);
7930:      PCFactorSeUseInPlace(pc);
7931: .ve
7932:    or by using the options -pc_type ilu -pc_factor_in_place

7934:    In-place factorization ILU(0) can also be used as a local
7935:    solver for the blocks within the block Jacobi or additive Schwarz
7936:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7937:    for details on setting local solver options.

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

7943:    Level: developer

7945: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7947: @*/
7948: PetscErrorCode MatSetUnfactored(Mat mat)
7949: {

7955:   MatCheckPreallocated(mat,1);
7956:   mat->factortype = MAT_FACTOR_NONE;
7957:   if (!mat->ops->setunfactored) return(0);
7958:   (*mat->ops->setunfactored)(mat);
7959:   return(0);
7960: }

7962: /*MC
7963:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7965:     Synopsis:
7966:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7968:     Not collective

7970:     Input Parameter:
7971: .   x - matrix

7973:     Output Parameters:
7974: +   xx_v - the Fortran90 pointer to the array
7975: -   ierr - error code

7977:     Example of Usage:
7978: .vb
7979:       PetscScalar, pointer xx_v(:,:)
7980:       ....
7981:       call MatDenseGetArrayF90(x,xx_v,ierr)
7982:       a = xx_v(3)
7983:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7984: .ve

7986:     Level: advanced

7988: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7990: M*/

7992: /*MC
7993:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7994:     accessed with MatDenseGetArrayF90().

7996:     Synopsis:
7997:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7999:     Not collective

8001:     Input Parameters:
8002: +   x - matrix
8003: -   xx_v - the Fortran90 pointer to the array

8005:     Output Parameter:
8006: .   ierr - error code

8008:     Example of Usage:
8009: .vb
8010:        PetscScalar, pointer xx_v(:,:)
8011:        ....
8012:        call MatDenseGetArrayF90(x,xx_v,ierr)
8013:        a = xx_v(3)
8014:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
8015: .ve

8017:     Level: advanced

8019: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

8021: M*/

8023: /*MC
8024:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

8026:     Synopsis:
8027:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

8029:     Not collective

8031:     Input Parameter:
8032: .   x - matrix

8034:     Output Parameters:
8035: +   xx_v - the Fortran90 pointer to the array
8036: -   ierr - error code

8038:     Example of Usage:
8039: .vb
8040:       PetscScalar, pointer xx_v(:)
8041:       ....
8042:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8043:       a = xx_v(3)
8044:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8045: .ve

8047:     Level: advanced

8049: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

8051: M*/

8053: /*MC
8054:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
8055:     accessed with MatSeqAIJGetArrayF90().

8057:     Synopsis:
8058:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

8060:     Not collective

8062:     Input Parameters:
8063: +   x - matrix
8064: -   xx_v - the Fortran90 pointer to the array

8066:     Output Parameter:
8067: .   ierr - error code

8069:     Example of Usage:
8070: .vb
8071:        PetscScalar, pointer xx_v(:)
8072:        ....
8073:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8074:        a = xx_v(3)
8075:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8076: .ve

8078:     Level: advanced

8080: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

8082: M*/

8084: /*@
8085:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8086:                       as the original matrix.

8088:     Collective on Mat

8090:     Input Parameters:
8091: +   mat - the original matrix
8092: .   isrow - parallel IS containing the rows this processor should obtain
8093: .   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.
8094: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

8096:     Output Parameter:
8097: .   newmat - the new submatrix, of the same type as the old

8099:     Level: advanced

8101:     Notes:
8102:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

8104:     Some matrix types place restrictions on the row and column indices, such
8105:     as that they be sorted or that they be equal to each other.

8107:     The index sets may not have duplicate entries.

8109:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
8110:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
8111:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
8112:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
8113:    you are finished using it.

8115:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8116:     the input matrix.

8118:     If iscol is NULL then all columns are obtained (not supported in Fortran).

8120:    Example usage:
8121:    Consider the following 8x8 matrix with 34 non-zero values, that is
8122:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8123:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8124:    as follows:

8126: .vb
8127:             1  2  0  |  0  3  0  |  0  4
8128:     Proc0   0  5  6  |  7  0  0  |  8  0
8129:             9  0 10  | 11  0  0  | 12  0
8130:     -------------------------------------
8131:            13  0 14  | 15 16 17  |  0  0
8132:     Proc1   0 18  0  | 19 20 21  |  0  0
8133:             0  0  0  | 22 23  0  | 24  0
8134:     -------------------------------------
8135:     Proc2  25 26 27  |  0  0 28  | 29  0
8136:            30  0  0  | 31 32 33  |  0 34
8137: .ve

8139:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

8141: .vb
8142:             2  0  |  0  3  0  |  0
8143:     Proc0   5  6  |  7  0  0  |  8
8144:     -------------------------------
8145:     Proc1  18  0  | 19 20 21  |  0
8146:     -------------------------------
8147:     Proc2  26 27  |  0  0 28  | 29
8148:             0  0  | 31 32 33  |  0
8149: .ve

8151: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
8152: @*/
8153: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
8154: {
8156:   PetscMPIInt    size;
8157:   Mat            *local;
8158:   IS             iscoltmp;
8159:   PetscBool      flg;

8168:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8169:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

8171:   MatCheckPreallocated(mat,1);
8172:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

8174:   if (!iscol || isrow == iscol) {
8175:     PetscBool   stride;
8176:     PetscMPIInt grabentirematrix = 0,grab;
8177:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
8178:     if (stride) {
8179:       PetscInt first,step,n,rstart,rend;
8180:       ISStrideGetInfo(isrow,&first,&step);
8181:       if (step == 1) {
8182:         MatGetOwnershipRange(mat,&rstart,&rend);
8183:         if (rstart == first) {
8184:           ISGetLocalSize(isrow,&n);
8185:           if (n == rend-rstart) {
8186:             grabentirematrix = 1;
8187:           }
8188:         }
8189:       }
8190:     }
8191:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
8192:     if (grab) {
8193:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
8194:       if (cll == MAT_INITIAL_MATRIX) {
8195:         *newmat = mat;
8196:         PetscObjectReference((PetscObject)mat);
8197:       }
8198:       return(0);
8199:     }
8200:   }

8202:   if (!iscol) {
8203:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
8204:   } else {
8205:     iscoltmp = iscol;
8206:   }

8208:   /* if original matrix is on just one processor then use submatrix generated */
8209:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8210:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
8211:     goto setproperties;
8212:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8213:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
8214:     *newmat = *local;
8215:     PetscFree(local);
8216:     goto setproperties;
8217:   } else if (!mat->ops->createsubmatrix) {
8218:     /* Create a new matrix type that implements the operation using the full matrix */
8219:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8220:     switch (cll) {
8221:     case MAT_INITIAL_MATRIX:
8222:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
8223:       break;
8224:     case MAT_REUSE_MATRIX:
8225:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
8226:       break;
8227:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8228:     }
8229:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8230:     goto setproperties;
8231:   }

8233:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8234:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8235:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
8236:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

8238: setproperties:
8239:   ISEqualUnsorted(isrow,iscoltmp,&flg);
8240:   if (flg) {
8241:     MatPropagateSymmetryOptions(mat,*newmat);
8242:   }
8243:   if (!iscol) {ISDestroy(&iscoltmp);}
8244:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
8245:   return(0);
8246: }

8248: /*@
8249:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8251:    Not Collective

8253:    Input Parameters:
8254: +  A - the matrix we wish to propagate options from
8255: -  B - the matrix we wish to propagate options to

8257:    Level: beginner

8259:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

8261: .seealso: MatSetOption()
8262: @*/
8263: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8264: {

8270:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
8271:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
8272:   }
8273:   if (A->structurally_symmetric_set) {
8274:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
8275:   }
8276:   if (A->hermitian_set) {
8277:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
8278:   }
8279:   if (A->spd_set) {
8280:     MatSetOption(B,MAT_SPD,A->spd);
8281:   }
8282:   if (A->symmetric_set) {
8283:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
8284:   }
8285:   return(0);
8286: }

8288: /*@
8289:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8290:    used during the assembly process to store values that belong to
8291:    other processors.

8293:    Not Collective

8295:    Input Parameters:
8296: +  mat   - the matrix
8297: .  size  - the initial size of the stash.
8298: -  bsize - the initial size of the block-stash(if used).

8300:    Options Database Keys:
8301: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8302: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

8304:    Level: intermediate

8306:    Notes:
8307:      The block-stash is used for values set with MatSetValuesBlocked() while
8308:      the stash is used for values set with MatSetValues()

8310:      Run with the option -info and look for output of the form
8311:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8312:      to determine the appropriate value, MM, to use for size and
8313:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8314:      to determine the value, BMM to use for bsize

8316: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

8318: @*/
8319: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8320: {

8326:   MatStashSetInitialSize_Private(&mat->stash,size);
8327:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8328:   return(0);
8329: }

8331: /*@
8332:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8333:      the matrix

8335:    Neighbor-wise Collective on Mat

8337:    Input Parameters:
8338: +  mat   - the matrix
8339: .  x,y - the vectors
8340: -  w - where the result is stored

8342:    Level: intermediate

8344:    Notes:
8345:     w may be the same vector as y.

8347:     This allows one to use either the restriction or interpolation (its transpose)
8348:     matrix to do the interpolation

8350: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8352: @*/
8353: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8354: {
8356:   PetscInt       M,N,Ny;

8363:   MatGetSize(A,&M,&N);
8364:   VecGetSize(y,&Ny);
8365:   if (M == Ny) {
8366:     MatMultAdd(A,x,y,w);
8367:   } else {
8368:     MatMultTransposeAdd(A,x,y,w);
8369:   }
8370:   return(0);
8371: }

8373: /*@
8374:    MatInterpolate - y = A*x or A'*x depending on the shape of
8375:      the matrix

8377:    Neighbor-wise Collective on Mat

8379:    Input Parameters:
8380: +  mat   - the matrix
8381: -  x,y - the vectors

8383:    Level: intermediate

8385:    Notes:
8386:     This allows one to use either the restriction or interpolation (its transpose)
8387:     matrix to do the interpolation

8389: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8391: @*/
8392: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8393: {
8395:   PetscInt       M,N,Ny;

8401:   MatGetSize(A,&M,&N);
8402:   VecGetSize(y,&Ny);
8403:   if (M == Ny) {
8404:     MatMult(A,x,y);
8405:   } else {
8406:     MatMultTranspose(A,x,y);
8407:   }
8408:   return(0);
8409: }

8411: /*@
8412:    MatRestrict - y = A*x or A'*x

8414:    Neighbor-wise Collective on Mat

8416:    Input Parameters:
8417: +  mat   - the matrix
8418: -  x,y - the vectors

8420:    Level: intermediate

8422:    Notes:
8423:     This allows one to use either the restriction or interpolation (its transpose)
8424:     matrix to do the restriction

8426: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8428: @*/
8429: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8430: {
8432:   PetscInt       M,N,Ny;

8438:   MatGetSize(A,&M,&N);
8439:   VecGetSize(y,&Ny);
8440:   if (M == Ny) {
8441:     MatMult(A,x,y);
8442:   } else {
8443:     MatMultTranspose(A,x,y);
8444:   }
8445:   return(0);
8446: }

8448: /*@
8449:    MatMatInterpolateAdd - Y = W + A*X or W + A'*X

8451:    Neighbor-wise Collective on Mat

8453:    Input Parameters:
8454: +  mat   - the matrix
8455: -  w, x - the input dense matrices

8457:    Output Parameters:
8458: .  y - the output dense matrix

8460:    Level: intermediate

8462:    Notes:
8463:     This allows one to use either the restriction or interpolation (its transpose)
8464:     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
8465:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

8467: .seealso: MatInterpolateAdd(), MatMatInterpolate(), MatMatRestrict()

8469: @*/
8470: PetscErrorCode MatMatInterpolateAdd(Mat A,Mat x,Mat w,Mat *y)
8471: {
8473:   PetscInt       M,N,Mx,Nx,Mo,My = 0,Ny = 0;
8474:   PetscBool      trans = PETSC_TRUE;
8475:   MatReuse       reuse = MAT_INITIAL_MATRIX;

8483:   MatGetSize(A,&M,&N);
8484:   MatGetSize(x,&Mx,&Nx);
8485:   if (N == Mx) trans = PETSC_FALSE;
8486:   else if (M != Mx) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Size mismatch: A %Dx%D, X %Dx%D",M,N,Mx,Nx);
8487:   Mo = trans ? N : M;
8488:   if (*y) {
8489:     MatGetSize(*y,&My,&Ny);
8490:     if (Mo == My && Nx == Ny) { reuse = MAT_REUSE_MATRIX; }
8491:     else {
8492:       if (w && *y == w) SETERRQ6(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Cannot reuse y and w, size mismatch: A %Dx%D, X %Dx%D, Y %Dx%D",M,N,Mx,Nx,My,Ny);
8493:       MatDestroy(y);
8494:     }
8495:   }

8497:   if (w && *y == w) { /* this is to minimize changes in PCMG */
8498:     PetscBool flg;

8500:     PetscObjectQuery((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject*)&w);
8501:     if (w) {
8502:       PetscInt My,Ny,Mw,Nw;

8504:       PetscObjectTypeCompare((PetscObject)*y,((PetscObject)w)->type_name,&flg);
8505:       MatGetSize(*y,&My,&Ny);
8506:       MatGetSize(w,&Mw,&Nw);
8507:       if (!flg || My != Mw || Ny != Nw) w = NULL;
8508:     }
8509:     if (!w) {
8510:       MatDuplicate(*y,MAT_COPY_VALUES,&w);
8511:       PetscObjectCompose((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject)w);
8512:       PetscLogObjectParent((PetscObject)*y,(PetscObject)w);
8513:       PetscObjectDereference((PetscObject)w);
8514:     } else {
8515:       MatCopy(*y,w,UNKNOWN_NONZERO_PATTERN);
8516:     }
8517:   }
8518:   if (!trans) {
8519:     MatMatMult(A,x,reuse,PETSC_DEFAULT,y);
8520:   } else {
8521:     MatTransposeMatMult(A,x,reuse,PETSC_DEFAULT,y);
8522:   }
8523:   if (w) {
8524:     MatAXPY(*y,1.0,w,UNKNOWN_NONZERO_PATTERN);
8525:   }
8526:   return(0);
8527: }

8529: /*@
8530:    MatMatInterpolate - Y = A*X or A'*X

8532:    Neighbor-wise Collective on Mat

8534:    Input Parameters:
8535: +  mat   - the matrix
8536: -  x - the input dense matrix

8538:    Output Parameters:
8539: .  y - the output dense matrix

8541:    Level: intermediate

8543:    Notes:
8544:     This allows one to use either the restriction or interpolation (its transpose)
8545:     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
8546:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

8548: .seealso: MatInterpolate(), MatRestrict(), MatMatRestrict()

8550: @*/
8551: PetscErrorCode MatMatInterpolate(Mat A,Mat x,Mat *y)
8552: {

8556:   MatMatInterpolateAdd(A,x,NULL,y);
8557:   return(0);
8558: }

8560: /*@
8561:    MatMatRestrict - Y = A*X or A'*X

8563:    Neighbor-wise Collective on Mat

8565:    Input Parameters:
8566: +  mat   - the matrix
8567: -  x - the input dense matrix

8569:    Output Parameters:
8570: .  y - the output dense matrix

8572:    Level: intermediate

8574:    Notes:
8575:     This allows one to use either the restriction or interpolation (its transpose)
8576:     matrix to do the restriction. y matrix can be reused if already created with the proper sizes,
8577:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

8579: .seealso: MatRestrict(), MatInterpolate(), MatMatInterpolate()
8580: @*/
8581: PetscErrorCode MatMatRestrict(Mat A,Mat x,Mat *y)
8582: {

8586:   MatMatInterpolateAdd(A,x,NULL,y);
8587:   return(0);
8588: }

8590: /*@
8591:    MatGetNullSpace - retrieves the null space of a matrix.

8593:    Logically Collective on Mat

8595:    Input Parameters:
8596: +  mat - the matrix
8597: -  nullsp - the null space object

8599:    Level: developer

8601: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8602: @*/
8603: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8604: {
8608:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8609:   return(0);
8610: }

8612: /*@
8613:    MatSetNullSpace - attaches a null space to a matrix.

8615:    Logically Collective on Mat

8617:    Input Parameters:
8618: +  mat - the matrix
8619: -  nullsp - the null space object

8621:    Level: advanced

8623:    Notes:
8624:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8626:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8627:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8629:       You can remove the null space by calling this routine with an nullsp of NULL

8631:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8632:    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).
8633:    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
8634:    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
8635:    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).

8637:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8639:     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
8640:     routine also automatically calls MatSetTransposeNullSpace().

8642: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8643: @*/
8644: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8645: {

8651:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8652:   MatNullSpaceDestroy(&mat->nullsp);
8653:   mat->nullsp = nullsp;
8654:   if (mat->symmetric_set && mat->symmetric) {
8655:     MatSetTransposeNullSpace(mat,nullsp);
8656:   }
8657:   return(0);
8658: }

8660: /*@
8661:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8663:    Logically Collective on Mat

8665:    Input Parameters:
8666: +  mat - the matrix
8667: -  nullsp - the null space object

8669:    Level: developer

8671: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8672: @*/
8673: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8674: {
8679:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8680:   return(0);
8681: }

8683: /*@
8684:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8686:    Logically Collective on Mat

8688:    Input Parameters:
8689: +  mat - the matrix
8690: -  nullsp - the null space object

8692:    Level: advanced

8694:    Notes:
8695:       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.
8696:       You must also call MatSetNullSpace()

8698:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8699:    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).
8700:    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
8701:    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
8702:    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).

8704:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8706: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8707: @*/
8708: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8709: {

8715:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8716:   MatNullSpaceDestroy(&mat->transnullsp);
8717:   mat->transnullsp = nullsp;
8718:   return(0);
8719: }

8721: /*@
8722:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8723:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8725:    Logically Collective on Mat

8727:    Input Parameters:
8728: +  mat - the matrix
8729: -  nullsp - the null space object

8731:    Level: advanced

8733:    Notes:
8734:       Overwrites any previous near null space that may have been attached

8736:       You can remove the null space by calling this routine with an nullsp of NULL

8738: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8739: @*/
8740: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8741: {

8748:   MatCheckPreallocated(mat,1);
8749:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8750:   MatNullSpaceDestroy(&mat->nearnullsp);
8751:   mat->nearnullsp = nullsp;
8752:   return(0);
8753: }

8755: /*@
8756:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8758:    Not Collective

8760:    Input Parameter:
8761: .  mat - the matrix

8763:    Output Parameter:
8764: .  nullsp - the null space object, NULL if not set

8766:    Level: developer

8768: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8769: @*/
8770: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8771: {
8776:   MatCheckPreallocated(mat,1);
8777:   *nullsp = mat->nearnullsp;
8778:   return(0);
8779: }

8781: /*@C
8782:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8784:    Collective on Mat

8786:    Input Parameters:
8787: +  mat - the matrix
8788: .  row - row/column permutation
8789: .  fill - expected fill factor >= 1.0
8790: -  level - level of fill, for ICC(k)

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

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

8800:    Level: developer

8802: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

8804:     Developer Note: fortran interface is not autogenerated as the f90
8805:     interface definition cannot be generated correctly [due to MatFactorInfo]

8807: @*/
8808: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8809: {

8817:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8818:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8819:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8820:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8821:   MatCheckPreallocated(mat,1);
8822:   (*mat->ops->iccfactor)(mat,row,info);
8823:   PetscObjectStateIncrease((PetscObject)mat);
8824:   return(0);
8825: }

8827: /*@
8828:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8829:          ghosted ones.

8831:    Not Collective

8833:    Input Parameters:
8834: +  mat - the matrix
8835: -  diag = the diagonal values, including ghost ones

8837:    Level: developer

8839:    Notes:
8840:     Works only for MPIAIJ and MPIBAIJ matrices

8842: .seealso: MatDiagonalScale()
8843: @*/
8844: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8845: {
8847:   PetscMPIInt    size;


8854:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8855:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8856:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8857:   if (size == 1) {
8858:     PetscInt n,m;
8859:     VecGetSize(diag,&n);
8860:     MatGetSize(mat,NULL,&m);
8861:     if (m == n) {
8862:       MatDiagonalScale(mat,NULL,diag);
8863:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8864:   } else {
8865:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8866:   }
8867:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8868:   PetscObjectStateIncrease((PetscObject)mat);
8869:   return(0);
8870: }

8872: /*@
8873:    MatGetInertia - Gets the inertia from a factored matrix

8875:    Collective on Mat

8877:    Input Parameter:
8878: .  mat - the matrix

8880:    Output Parameters:
8881: +   nneg - number of negative eigenvalues
8882: .   nzero - number of zero eigenvalues
8883: -   npos - number of positive eigenvalues

8885:    Level: advanced

8887:    Notes:
8888:     Matrix must have been factored by MatCholeskyFactor()

8890: @*/
8891: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8892: {

8898:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8899:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8900:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8901:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8902:   return(0);
8903: }

8905: /* ----------------------------------------------------------------*/
8906: /*@C
8907:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8909:    Neighbor-wise Collective on Mats

8911:    Input Parameters:
8912: +  mat - the factored matrix
8913: -  b - the right-hand-side vectors

8915:    Output Parameter:
8916: .  x - the result vectors

8918:    Notes:
8919:    The vectors b and x cannot be the same.  I.e., one cannot
8920:    call MatSolves(A,x,x).

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

8927:    Level: developer

8929: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8930: @*/
8931: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8932: {

8938:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8939:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8940:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8942:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8943:   MatCheckPreallocated(mat,1);
8944:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8945:   (*mat->ops->solves)(mat,b,x);
8946:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8947:   return(0);
8948: }

8950: /*@
8951:    MatIsSymmetric - Test whether a matrix is symmetric

8953:    Collective on Mat

8955:    Input Parameters:
8956: +  A - the matrix to test
8957: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8959:    Output Parameters:
8960: .  flg - the result

8962:    Notes:
8963:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8965:    Level: intermediate

8967: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8968: @*/
8969: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8970: {


8977:   if (!A->symmetric_set) {
8978:     if (!A->ops->issymmetric) {
8979:       MatType mattype;
8980:       MatGetType(A,&mattype);
8981:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8982:     }
8983:     (*A->ops->issymmetric)(A,tol,flg);
8984:     if (!tol) {
8985:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8986:     }
8987:   } else if (A->symmetric) {
8988:     *flg = PETSC_TRUE;
8989:   } else if (!tol) {
8990:     *flg = PETSC_FALSE;
8991:   } else {
8992:     if (!A->ops->issymmetric) {
8993:       MatType mattype;
8994:       MatGetType(A,&mattype);
8995:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8996:     }
8997:     (*A->ops->issymmetric)(A,tol,flg);
8998:   }
8999:   return(0);
9000: }

9002: /*@
9003:    MatIsHermitian - Test whether a matrix is Hermitian

9005:    Collective on Mat

9007:    Input Parameters:
9008: +  A - the matrix to test
9009: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9011:    Output Parameters:
9012: .  flg - the result

9014:    Level: intermediate

9016: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
9017:           MatIsSymmetricKnown(), MatIsSymmetric()
9018: @*/
9019: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
9020: {


9027:   if (!A->hermitian_set) {
9028:     if (!A->ops->ishermitian) {
9029:       MatType mattype;
9030:       MatGetType(A,&mattype);
9031:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
9032:     }
9033:     (*A->ops->ishermitian)(A,tol,flg);
9034:     if (!tol) {
9035:       MatSetOption(A,MAT_HERMITIAN,*flg);
9036:     }
9037:   } else if (A->hermitian) {
9038:     *flg = PETSC_TRUE;
9039:   } else if (!tol) {
9040:     *flg = PETSC_FALSE;
9041:   } else {
9042:     if (!A->ops->ishermitian) {
9043:       MatType mattype;
9044:       MatGetType(A,&mattype);
9045:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
9046:     }
9047:     (*A->ops->ishermitian)(A,tol,flg);
9048:   }
9049:   return(0);
9050: }

9052: /*@
9053:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

9055:    Not Collective

9057:    Input Parameter:
9058: .  A - the matrix to check

9060:    Output Parameters:
9061: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
9062: -  flg - the result

9064:    Level: advanced

9066:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
9067:          if you want it explicitly checked

9069: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
9070: @*/
9071: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
9072: {
9077:   if (A->symmetric_set) {
9078:     *set = PETSC_TRUE;
9079:     *flg = A->symmetric;
9080:   } else {
9081:     *set = PETSC_FALSE;
9082:   }
9083:   return(0);
9084: }

9086: /*@
9087:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

9089:    Not Collective

9091:    Input Parameter:
9092: .  A - the matrix to check

9094:    Output Parameters:
9095: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
9096: -  flg - the result

9098:    Level: advanced

9100:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
9101:          if you want it explicitly checked

9103: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
9104: @*/
9105: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
9106: {
9111:   if (A->hermitian_set) {
9112:     *set = PETSC_TRUE;
9113:     *flg = A->hermitian;
9114:   } else {
9115:     *set = PETSC_FALSE;
9116:   }
9117:   return(0);
9118: }

9120: /*@
9121:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9123:    Collective on Mat

9125:    Input Parameter:
9126: .  A - the matrix to test

9128:    Output Parameters:
9129: .  flg - the result

9131:    Level: intermediate

9133: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
9134: @*/
9135: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
9136: {

9142:   if (!A->structurally_symmetric_set) {
9143:     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);
9144:     (*A->ops->isstructurallysymmetric)(A,flg);
9145:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
9146:   } else *flg = A->structurally_symmetric;
9147:   return(0);
9148: }

9150: /*@
9151:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9152:        to be communicated to other processors during the MatAssemblyBegin/End() process

9154:     Not collective

9156:    Input Parameter:
9157: .   vec - the vector

9159:    Output Parameters:
9160: +   nstash   - the size of the stash
9161: .   reallocs - the number of additional mallocs incurred.
9162: .   bnstash   - the size of the block stash
9163: -   breallocs - the number of additional mallocs incurred.in the block stash

9165:    Level: advanced

9167: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

9169: @*/
9170: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
9171: {

9175:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
9176:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
9177:   return(0);
9178: }

9180: /*@C
9181:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9182:      parallel layout

9184:    Collective on Mat

9186:    Input Parameter:
9187: .  mat - the matrix

9189:    Output Parameters:
9190: +   right - (optional) vector that the matrix can be multiplied against
9191: -   left - (optional) vector that the matrix vector product can be stored in

9193:    Notes:
9194:     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().

9196:   Notes:
9197:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

9199:   Level: advanced

9201: .seealso: MatCreate(), VecDestroy()
9202: @*/
9203: PetscErrorCode