Actual source code: matrix.c

petsc-master 2015-02-28
Report Typos and Errors
  2: /*
  3:    This is where the abstract matrix operations are defined
  4: */

  6: #include <petsc-private/matimpl.h>        /*I "petscmat.h" I*/
  7: #include <petsc-private/vecimpl.h>
  8: #include <petsc-private/isimpl.h>

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

 16: PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
 17: PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve;
 18: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
 19: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
 20: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
 21: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_GetSubMatrices, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
 22: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
 23: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_GetSubMatrix;
 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_Transpose_SeqAIJ, 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_CUSPCopyToGPU, MAT_CUSPARSECopyToGPU, MAT_SetValuesBatch, MAT_SetValuesBatchI, MAT_SetValuesBatchII, MAT_SetValuesBatchIII, MAT_SetValuesBatchIV;
 36: PetscLogEvent MAT_ViennaCLCopyToGPU;
 37: PetscLogEvent MAT_Merge,MAT_Residual;
 38: PetscLogEvent Mat_Coloring_Apply,Mat_Coloring_Comm,Mat_Coloring_Local,Mat_Coloring_ISCreate,Mat_Coloring_SetUp,Mat_Coloring_Weights;

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

 44: /*@
 45:    MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated it randomly selects appropriate locations

 47:    Logically Collective on Vec

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

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

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

 64:    Level: intermediate

 66:    Concepts: vector^setting to random
 67:    Concepts: random^vector

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


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

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

 93:   x->assembled = PETSC_TRUE;
 94:   PetscRandomDestroy(&randObj);
 95:   return(0);
 96: }


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

104:   Input Parameter:
105: .    A  - the matrix

107:   Output Parameter:
108: .    keptrows - the rows that are not completely zero

110:   Level: intermediate

112:  @*/
113: PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
114: {

119:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
120:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
121:   if (!mat->ops->findnonzerorows) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not coded for this matrix type");
122:   (*mat->ops->findnonzerorows)(mat,keptrows);
123:   return(0);
124: }

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

131:    Not Collective

133:    Input Parameters:
134: .   A - the matrix

136:    Output Parameters:
137: .   a - the diagonal part (which is a SEQUENTIAL matrix)

139:    Notes: see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.

141:    Level: advanced

143: @*/
144: PetscErrorCode  MatGetDiagonalBlock(Mat A,Mat *a)
145: {
146:   PetscErrorCode ierr,(*f)(Mat,Mat*);
147:   PetscMPIInt    size;

153:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
154:   MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
155:   PetscObjectQueryFunction((PetscObject)A,"MatGetDiagonalBlock_C",&f);
156:   if (f) {
157:     (*f)(A,a);
158:     return(0);
159:   } else if (size == 1) {
160:     *a = A;
161:   } else {
162:     MatType mattype;
163:     MatGetType(A,&mattype);
164:     SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix type %s does not support getting diagonal block",mattype);
165:   }
166:   return(0);
167: }

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

174:    Collective on Mat

176:    Input Parameters:
177: .  mat - the matrix

179:    Output Parameter:
180: .   trace - the sum of the diagonal entries

182:    Level: advanced

184: @*/
185: PetscErrorCode  MatGetTrace(Mat mat,PetscScalar *trace)
186: {
188:   Vec            diag;

191:   MatCreateVecs(mat,&diag,NULL);
192:   MatGetDiagonal(mat,diag);
193:   VecSum(diag,trace);
194:   VecDestroy(&diag);
195:   return(0);
196: }

200: /*@
201:    MatRealPart - Zeros out the imaginary part of the matrix

203:    Logically Collective on Mat

205:    Input Parameters:
206: .  mat - the matrix

208:    Level: advanced


211: .seealso: MatImaginaryPart()
212: @*/
213: PetscErrorCode  MatRealPart(Mat mat)
214: {

220:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
221:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
222:   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
223:   MatCheckPreallocated(mat,1);
224:   (*mat->ops->realpart)(mat);
225: #if defined(PETSC_HAVE_CUSP)
226:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
227:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
228:   }
229: #endif
230: #if defined(PETSC_HAVE_VIENNACL)
231:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
232:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
233:   }
234: #endif
235:   return(0);
236: }

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

243:    Collective on Mat

245:    Input Parameter:
246: .  mat - the matrix

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

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

254:    Level: advanced

256: @*/
257: PetscErrorCode  MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
258: {

264:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
265:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
266:   if (!mat->ops->getghosts) {
267:     if (nghosts) *nghosts = 0;
268:     if (ghosts) *ghosts = 0;
269:   } else {
270:     (*mat->ops->getghosts)(mat,nghosts,ghosts);
271:   }
272:   return(0);
273: }


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

281:    Logically Collective on Mat

283:    Input Parameters:
284: .  mat - the matrix

286:    Level: advanced


289: .seealso: MatRealPart()
290: @*/
291: PetscErrorCode  MatImaginaryPart(Mat mat)
292: {

298:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
299:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
300:   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
301:   MatCheckPreallocated(mat,1);
302:   (*mat->ops->imaginarypart)(mat);
303: #if defined(PETSC_HAVE_CUSP)
304:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
305:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
306:   }
307: #endif
308: #if defined(PETSC_HAVE_VIENNACL)
309:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
310:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
311:   }
312: #endif
313:   return(0);
314: }

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

321:    Collective on Mat

323:    Input Parameter:
324: .  mat - the matrix

326:    Output Parameters:
327: +  missing - is any diagonal missing
328: -  dd - first diagonal entry that is missing (optional)

330:    Level: advanced


333: .seealso: MatRealPart()
334: @*/
335: PetscErrorCode  MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
336: {

342:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
343:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
344:   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
345:   (*mat->ops->missingdiagonal)(mat,missing,dd);
346:   return(0);
347: }

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

356:    Not Collective

358:    Input Parameters:
359: +  mat - the matrix
360: -  row - the row to get

362:    Output Parameters:
363: +  ncols -  if not NULL, the number of nonzeros in the row
364: .  cols - if not NULL, the column numbers
365: -  vals - if not NULL, the values

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

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

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

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

382:    You can only have one call to MatGetRow() outstanding for a particular
383:    matrix at a time, per processor. MatGetRow() can only obtain rows
384:    associated with the given processor, it cannot get rows from the
385:    other processors; for that we suggest using MatGetSubMatrices(), then
386:    MatGetRow() on the submatrix. The row indix passed to MatGetRows()
387:    is in the global number of rows.

389:    Fortran Notes:
390:    The calling sequence from Fortran is
391: .vb
392:    MatGetRow(matrix,row,ncols,cols,values,ierr)
393:          Mat     matrix (input)
394:          integer row    (input)
395:          integer ncols  (output)
396:          integer cols(maxcols) (output)
397:          double precision (or double complex) values(maxcols) output
398: .ve
399:    where maxcols >= maximum nonzeros in any row of the matrix.


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

406:    Level: advanced

408:    Concepts: matrices^row access

410: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatGetSubMatrices(), MatGetDiagonal()
411: @*/
412: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
413: {
415:   PetscInt       incols;

420:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
421:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
422:   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
423:   MatCheckPreallocated(mat,1);
424:   PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
425:   (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
426:   if (ncols) *ncols = incols;
427:   PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
428:   return(0);
429: }

433: /*@
434:    MatConjugate - replaces the matrix values with their complex conjugates

436:    Logically Collective on Mat

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

441:    Level: advanced

443: .seealso:  VecConjugate()
444: @*/
445: PetscErrorCode  MatConjugate(Mat mat)
446: {
447: #if defined(PETSC_USE_COMPLEX)

452:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
453:   if (!mat->ops->conjugate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not provided for this matrix format, send email to petsc-maint@mcs.anl.gov");
454:   (*mat->ops->conjugate)(mat);
455: #if defined(PETSC_HAVE_CUSP)
456:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
457:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
458:   }
459: #endif
460: #if defined(PETSC_HAVE_VIENNACL)
461:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
462:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
463:   }
464: #endif
465:   return(0);
466: #else
467:   return 0;
468: #endif
469: }

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

476:    Not Collective

478:    Input Parameters:
479: +  mat - the matrix
480: .  row - the row to get
481: .  ncols, cols - the number of nonzeros and their columns
482: -  vals - if nonzero the column values

484:    Notes:
485:    This routine should be called after you have finished examining the entries.

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

491:    Fortran Notes:
492:    The calling sequence from Fortran is
493: .vb
494:    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
495:       Mat     matrix (input)
496:       integer row    (input)
497:       integer ncols  (output)
498:       integer cols(maxcols) (output)
499:       double precision (or double complex) values(maxcols) output
500: .ve
501:    Where maxcols >= maximum nonzeros in any row of the matrix.

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

506:    Level: advanced

508: .seealso:  MatGetRow()
509: @*/
510: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
511: {

517:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
518:   if (!mat->ops->restorerow) return(0);
519:   (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
520:   if (ncols) *ncols = 0;
521:   if (cols)  *cols = NULL;
522:   if (vals)  *vals = NULL;
523:   return(0);
524: }

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

532:    Not Collective

534:    Input Parameters:
535: +  mat - the matrix

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

540:    Level: advanced

542:    Concepts: matrices^row access

544: .seealso: MatRestoreRowRowUpperTriangular()
545: @*/
546: PetscErrorCode  MatGetRowUpperTriangular(Mat mat)
547: {

553:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
554:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
555:   if (!mat->ops->getrowuppertriangular) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
556:   MatCheckPreallocated(mat,1);
557:   (*mat->ops->getrowuppertriangular)(mat);
558:   return(0);
559: }

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

566:    Not Collective

568:    Input Parameters:
569: +  mat - the matrix

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


575:    Level: advanced

577: .seealso:  MatGetRowUpperTriangular()
578: @*/
579: PetscErrorCode  MatRestoreRowUpperTriangular(Mat mat)
580: {

585:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
586:   if (!mat->ops->restorerowuppertriangular) return(0);
587:   (*mat->ops->restorerowuppertriangular)(mat);
588:   return(0);
589: }

593: /*@C
594:    MatSetOptionsPrefix - Sets the prefix used for searching for all
595:    Mat options in the database.

597:    Logically Collective on Mat

599:    Input Parameter:
600: +  A - the Mat context
601: -  prefix - the prefix to prepend to all option names

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

607:    Level: advanced

609: .keywords: Mat, set, options, prefix, database

611: .seealso: MatSetFromOptions()
612: @*/
613: PetscErrorCode  MatSetOptionsPrefix(Mat A,const char prefix[])
614: {

619:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
620:   return(0);
621: }

625: /*@C
626:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
627:    Mat options in the database.

629:    Logically Collective on Mat

631:    Input Parameters:
632: +  A - the Mat context
633: -  prefix - the prefix to prepend to all option names

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

639:    Level: advanced

641: .keywords: Mat, append, options, prefix, database

643: .seealso: MatGetOptionsPrefix()
644: @*/
645: PetscErrorCode  MatAppendOptionsPrefix(Mat A,const char prefix[])
646: {

651:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
652:   return(0);
653: }

657: /*@C
658:    MatGetOptionsPrefix - Sets the prefix used for searching for all
659:    Mat options in the database.

661:    Not Collective

663:    Input Parameter:
664: .  A - the Mat context

666:    Output Parameter:
667: .  prefix - pointer to the prefix string used

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

672:    Level: advanced

674: .keywords: Mat, get, options, prefix, database

676: .seealso: MatAppendOptionsPrefix()
677: @*/
678: PetscErrorCode  MatGetOptionsPrefix(Mat A,const char *prefix[])
679: {

684:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
685:   return(0);
686: }

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

693:    Collective on Mat

695:    Input Parameters:
696: .  A - the Mat context

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

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

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

705:    Level: beginner

707: .keywords: Mat, setup

709: .seealso: MatCreate(), MatDestroy()
710: @*/
711: PetscErrorCode  MatSetUp(Mat A)
712: {
713:   PetscMPIInt    size;

718:   if (!((PetscObject)A)->type_name) {
719:     MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
720:     if (size == 1) {
721:       MatSetType(A, MATSEQAIJ);
722:     } else {
723:       MatSetType(A, MATMPIAIJ);
724:     }
725:   }
726:   if (!A->preallocated && A->ops->setup) {
727:     PetscInfo(A,"Warning not preallocating matrix storage\n");
728:     (*A->ops->setup)(A);
729:   }
730:   A->preallocated = PETSC_TRUE;
731:   return(0);
732: }

734: #if defined(PETSC_HAVE_SAWS)
735: #include <petscviewersaws.h>
736: #endif
739: /*@C
740:    MatView - Visualizes a matrix object.

742:    Collective on Mat

744:    Input Parameters:
745: +  mat - the matrix
746: -  viewer - visualization context

748:   Notes:
749:   The available visualization contexts include
750: +    PETSC_VIEWER_STDOUT_SELF - standard output (default)
751: .    PETSC_VIEWER_STDOUT_WORLD - synchronized standard
752:         output where only the first processor opens
753:         the file.  All other processors send their
754:         data to the first processor to print.
755: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

757:    The user can open alternative visualization contexts with
758: +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
759: .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
760:          specified file; corresponding input uses MatLoad()
761: .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
762:          an X window display
763: -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
764:          Currently only the sequential dense and AIJ
765:          matrix types support the Socket viewer.

767:    The user can call PetscViewerSetFormat() to specify the output
768:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
769:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
770: +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
771: .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
772: .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
773: .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
774:          format common among all matrix types
775: .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
776:          format (which is in many cases the same as the default)
777: .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
778:          size and structure (not the matrix entries)
779: .    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
780:          the matrix structure

782:    Options Database Keys:
783: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
784: .  -mat_view ::ascii_info_detail - Prints more detailed info
785: .  -mat_view - Prints matrix in ASCII format
786: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
787: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
788: .  -display <name> - Sets display name (default is host)
789: .  -draw_pause <sec> - Sets number of seconds to pause after display
790: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 11 Using MATLAB with PETSc for details)
791: .  -viewer_socket_machine <machine> -
792: .  -viewer_socket_port <port> -
793: .  -mat_view binary - save matrix to file in binary format
794: -  -viewer_binary_filename <name> -
795:    Level: beginner

797:    Notes: see the manual page for MatLoad() for the exact format of the binary file when the binary
798:       viewer is used.

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

803:       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure.
804:       And then use the following mouse functions:
805:           left mouse: zoom in
806:           middle mouse: zoom out
807:           right mouse: continue with the simulation

809:    Concepts: matrices^viewing
810:    Concepts: matrices^plotting
811:    Concepts: matrices^printing

813: .seealso: PetscViewerSetFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
814:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
815: @*/
816: PetscErrorCode  MatView(Mat mat,PetscViewer viewer)
817: {
818:   PetscErrorCode    ierr;
819:   PetscInt          rows,cols,rbs,cbs;
820:   PetscBool         iascii;
821:   PetscViewerFormat format;
822: #if defined(PETSC_HAVE_SAWS)
823:   PetscBool         issaws;
824: #endif

829:   if (!viewer) {
830:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
831:   }
834:   MatCheckPreallocated(mat,1);

836:   PetscLogEventBegin(MAT_View,mat,viewer,0,0);
837:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
838:   PetscViewerGetFormat(viewer,&format);
839:   if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
840:     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
841:   }

843: #if defined(PETSC_HAVE_SAWS)
844:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
845: #endif
846:   if (iascii) {
847:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
848:     PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
849:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
850:       PetscViewerASCIIPushTab(viewer);
851:       MatGetSize(mat,&rows,&cols);
852:       MatGetBlockSizes(mat,&rbs,&cbs);
853:       if (rbs != 1 || cbs != 1) {
854:         if (rbs != cbs) {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs = %D\n",rows,cols,rbs,cbs);}
855:         else            {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);}
856:       } else {
857:         PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);
858:       }
859:       if (mat->factortype) {
860:         const MatSolverPackage solver;
861:         MatFactorGetSolverPackage(mat,&solver);
862:         PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);
863:       }
864:       if (mat->ops->getinfo) {
865:         MatInfo info;
866:         MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
867:         PetscViewerASCIIPrintf(viewer,"total: nonzeros=%g, allocated nonzeros=%g\n",info.nz_used,info.nz_allocated);
868:         PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls =%D\n",(PetscInt)info.mallocs);
869:       }
870:       if (mat->nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached null space\n");}
871:       if (mat->nearnullsp) {PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");}
872:     }
873: #if defined(PETSC_HAVE_SAWS)
874:   } else if (issaws) {
875:     PetscMPIInt rank;

877:     PetscObjectName((PetscObject)mat);
878:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
879:     if (!((PetscObject)mat)->amsmem && !rank) {
880:       PetscObjectViewSAWs((PetscObject)mat,viewer);
881:     }
882: #endif
883:   }
884:   if (mat->ops->view) {
885:     PetscViewerASCIIPushTab(viewer);
886:     (*mat->ops->view)(mat,viewer);
887:     PetscViewerASCIIPopTab(viewer);
888:   }
889:   if (iascii) {
890:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
891:     PetscViewerGetFormat(viewer,&format);
892:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
893:       PetscViewerASCIIPopTab(viewer);
894:     }
895:   }
896:   PetscLogEventEnd(MAT_View,mat,viewer,0,0);
897:   return(0);
898: }

900: #if defined(PETSC_USE_DEBUG)
901: #include <../src/sys/totalview/tv_data_display.h>
902: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
903: {
904:   TV_add_row("Local rows", "int", &mat->rmap->n);
905:   TV_add_row("Local columns", "int", &mat->cmap->n);
906:   TV_add_row("Global rows", "int", &mat->rmap->N);
907:   TV_add_row("Global columns", "int", &mat->cmap->N);
908:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
909:   return TV_format_OK;
910: }
911: #endif

915: /*@C
916:    MatLoad - Loads a matrix that has been stored in binary format
917:    with MatView().  The matrix format is determined from the options database.
918:    Generates a parallel MPI matrix if the communicator has more than one
919:    processor.  The default matrix type is AIJ.

921:    Collective on PetscViewer

923:    Input Parameters:
924: +  newmat - the newly loaded matrix, this needs to have been created with MatCreate()
925:             or some related function before a call to MatLoad()
926: -  viewer - binary file viewer, created with PetscViewerBinaryOpen()

928:    Options Database Keys:
929:    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
930:    block size
931: .    -matload_block_size <bs>

933:    Level: beginner

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

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

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

948:    In parallel, each processor can load a subset of rows (or the
949:    entire matrix).  This routine is especially useful when a large
950:    matrix is stored on disk and only part of it is desired on each
951:    processor.  For example, a parallel solver may access only some of
952:    the rows from each processor.  The algorithm used here reads
953:    relatively small blocks of data rather than reading the entire
954:    matrix and then subsetting it.

956:    Notes for advanced users:
957:    Most users should not need to know the details of the binary storage
958:    format, since MatLoad() and MatView() completely hide these details.
959:    But for anyone who's interested, the standard binary matrix storage
960:    format is

962: $    int    MAT_FILE_CLASSID
963: $    int    number of rows
964: $    int    number of columns
965: $    int    total number of nonzeros
966: $    int    *number nonzeros in each row
967: $    int    *column indices of all nonzeros (starting index is zero)
968: $    PetscScalar *values of all nonzeros

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

976: .keywords: matrix, load, binary, input

978: .seealso: PetscViewerBinaryOpen(), MatView(), VecLoad()

980:  @*/
981: PetscErrorCode  MatLoad(Mat newmat,PetscViewer viewer)
982: {
984:   PetscBool      isbinary,flg;

989:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
990:   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");

992:   if (!((PetscObject)newmat)->type_name) {
993:     MatSetType(newmat,MATAIJ);
994:   }

996:   if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
997:   PetscLogEventBegin(MAT_Load,viewer,0,0,0);
998:   (*newmat->ops->load)(newmat,viewer);
999:   PetscLogEventEnd(MAT_Load,viewer,0,0,0);

1001:   flg  = PETSC_FALSE;
1002:   PetscOptionsGetBool(((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);
1003:   if (flg) {
1004:     MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);
1005:     MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1006:   }
1007:   flg  = PETSC_FALSE;
1008:   PetscOptionsGetBool(((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);
1009:   if (flg) {
1010:     MatSetOption(newmat,MAT_SPD,PETSC_TRUE);
1011:   }
1012:   return(0);
1013: }

1017: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1018: {
1020:   Mat_Redundant  *redund = *redundant;
1021:   PetscInt       i;

1024:   if (redund){
1025:     if (redund->matseq) { /* via MatGetSubMatrices()  */
1026:       ISDestroy(&redund->isrow);
1027:       ISDestroy(&redund->iscol);
1028:       MatDestroy(&redund->matseq[0]);
1029:       PetscFree(redund->matseq);
1030:     } else {
1031:       PetscFree2(redund->send_rank,redund->recv_rank);
1032:       PetscFree(redund->sbuf_j);
1033:       PetscFree(redund->sbuf_a);
1034:       for (i=0; i<redund->nrecvs; i++) {
1035:         PetscFree(redund->rbuf_j[i]);
1036:         PetscFree(redund->rbuf_a[i]);
1037:       }
1038:       PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1039:     }

1041:     if (redund->subcomm) {
1042:       PetscCommDestroy(&redund->subcomm);
1043:     }
1044:     PetscFree(redund);
1045:   }
1046:   return(0);
1047: }

1051: /*@
1052:    MatDestroy - Frees space taken by a matrix.

1054:    Collective on Mat

1056:    Input Parameter:
1057: .  A - the matrix

1059:    Level: beginner

1061: @*/
1062: PetscErrorCode  MatDestroy(Mat *A)
1063: {

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

1071:   /* if memory was published with SAWs then destroy it */
1072:   PetscObjectSAWsViewOff((PetscObject)*A);
1073:   if ((*A)->ops->destroy) {
1074:     (*(*A)->ops->destroy)(*A);
1075:   }
1076:   MatDestroy_Redundant(&(*A)->redundant);
1077:   MatNullSpaceDestroy(&(*A)->nullsp);
1078:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1079:   PetscLayoutDestroy(&(*A)->rmap);
1080:   PetscLayoutDestroy(&(*A)->cmap);
1081:   PetscHeaderDestroy(A);
1082:   return(0);
1083: }

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

1092:    Not Collective

1094:    Input Parameters:
1095: +  mat - the matrix
1096: .  v - a logically two-dimensional array of values
1097: .  m, idxm - the number of rows and their global indices
1098: .  n, idxn - the number of columns and their global indices
1099: -  addv - either ADD_VALUES or INSERT_VALUES, where
1100:    ADD_VALUES adds values to any existing entries, and
1101:    INSERT_VALUES replaces existing entries with new values

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

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

1109:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1110:    options cannot be mixed without intervening calls to the assembly
1111:    routines.

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

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

1121:    Efficiency Alert:
1122:    The routine MatSetValuesBlocked() may offer much better efficiency
1123:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1125:    Level: beginner

1127:    Concepts: matrices^putting entries in

1129: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1130:           InsertMode, INSERT_VALUES, ADD_VALUES
1131: @*/
1132: PetscErrorCode  MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1133: {
1135: #if defined(PETSC_USE_DEBUG)
1136:   PetscInt       i,j;
1137: #endif

1142:   if (!m || !n) return(0); /* no values to insert */
1146:   MatCheckPreallocated(mat,1);
1147:   if (mat->insertmode == NOT_SET_VALUES) {
1148:     mat->insertmode = addv;
1149:   }
1150: #if defined(PETSC_USE_DEBUG)
1151:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1152:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1153:   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

1155:   for (i=0; i<m; i++) {
1156:     for (j=0; j<n; j++) {
1157:       if (PetscIsInfOrNanScalar(v[i*n+j]))
1158: #if defined(PETSC_USE_COMPLEX)
1159:         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]);
1160: #else
1161:       SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1162: #endif
1163:     }
1164:   }
1165: #endif

1167:   if (mat->assembled) {
1168:     mat->was_assembled = PETSC_TRUE;
1169:     mat->assembled     = PETSC_FALSE;
1170:   }
1171:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1172:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1173:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1174: #if defined(PETSC_HAVE_CUSP)
1175:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1176:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1177:   }
1178: #endif
1179: #if defined(PETSC_HAVE_VIENNACL)
1180:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1181:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1182:   }
1183: #endif
1184:   return(0);
1185: }


1190: /*@
1191:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1192:         values into a matrix

1194:    Not Collective

1196:    Input Parameters:
1197: +  mat - the matrix
1198: .  row - the (block) row to set
1199: -  v - a logically two-dimensional array of values

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

1204:    All the nonzeros in the row must be provided

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

1208:    The row must belong to this process

1210:    Level: intermediate

1212:    Concepts: matrices^putting entries in

1214: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1215:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1216: @*/
1217: PetscErrorCode  MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1218: {
1220:   PetscInt       globalrow;

1226:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1227:   MatSetValuesRow(mat,globalrow,v);
1228: #if defined(PETSC_HAVE_CUSP)
1229:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1230:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1231:   }
1232: #endif
1233: #if defined(PETSC_HAVE_VIENNACL)
1234:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1235:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1236:   }
1237: #endif
1238:   return(0);
1239: }

1243: /*@
1244:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1245:         values into a matrix

1247:    Not Collective

1249:    Input Parameters:
1250: +  mat - the matrix
1251: .  row - the (block) row to set
1252: -  v - a logically two-dimensional array of values

1254:    Notes:
1255:    The values, v, are column-oriented for the block version.

1257:    All the nonzeros in the row must be provided

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

1261:    The row must belong to this process

1263:    Level: advanced

1265:    Concepts: matrices^putting entries in

1267: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1268:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1269: @*/
1270: PetscErrorCode  MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1271: {

1277:   MatCheckPreallocated(mat,1);
1279: #if defined(PETSC_USE_DEBUG)
1280:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1281:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1282: #endif
1283:   mat->insertmode = INSERT_VALUES;

1285:   if (mat->assembled) {
1286:     mat->was_assembled = PETSC_TRUE;
1287:     mat->assembled     = PETSC_FALSE;
1288:   }
1289:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1290:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1291:   (*mat->ops->setvaluesrow)(mat,row,v);
1292:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1293: #if defined(PETSC_HAVE_CUSP)
1294:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1295:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1296:   }
1297: #endif
1298: #if defined(PETSC_HAVE_VIENNACL)
1299:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1300:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1301:   }
1302: #endif
1303:   return(0);
1304: }

1308: /*@
1309:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1310:      Using structured grid indexing

1312:    Not Collective

1314:    Input Parameters:
1315: +  mat - the matrix
1316: .  m - number of rows being entered
1317: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1318: .  n - number of columns being entered
1319: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1320: .  v - a logically two-dimensional array of values
1321: -  addv - either ADD_VALUES or INSERT_VALUES, where
1322:    ADD_VALUES adds values to any existing entries, and
1323:    INSERT_VALUES replaces existing entries with new values

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

1328:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1329:    options cannot be mixed without intervening calls to the assembly
1330:    routines.

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

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

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

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

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

1348:    In Fortran idxm and idxn should be declared as
1349: $     MatStencil idxm(4,m),idxn(4,n)
1350:    and the values inserted using
1351: $    idxm(MatStencil_i,1) = i
1352: $    idxm(MatStencil_j,1) = j
1353: $    idxm(MatStencil_k,1) = k
1354: $    idxm(MatStencil_c,1) = c
1355:    etc

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

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

1365:    Inspired by the structured grid interface to the HYPRE package
1366:    (http://www.llnl.gov/CASC/hypre)

1368:    Efficiency Alert:
1369:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1370:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1372:    Level: beginner

1374:    Concepts: matrices^putting entries in

1376: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1377:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1378: @*/
1379: PetscErrorCode  MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1380: {
1382:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1383:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1384:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1394:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1395:     jdxm = buf; jdxn = buf+m;
1396:   } else {
1397:     PetscMalloc2(m,&bufm,n,&bufn);
1398:     jdxm = bufm; jdxn = bufn;
1399:   }
1400:   for (i=0; i<m; i++) {
1401:     for (j=0; j<3-sdim; j++) dxm++;
1402:     tmp = *dxm++ - starts[0];
1403:     for (j=0; j<dim-1; j++) {
1404:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1405:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1406:     }
1407:     if (mat->stencil.noc) dxm++;
1408:     jdxm[i] = tmp;
1409:   }
1410:   for (i=0; i<n; i++) {
1411:     for (j=0; j<3-sdim; j++) dxn++;
1412:     tmp = *dxn++ - starts[0];
1413:     for (j=0; j<dim-1; j++) {
1414:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1415:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1416:     }
1417:     if (mat->stencil.noc) dxn++;
1418:     jdxn[i] = tmp;
1419:   }
1420:   MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1421:   PetscFree2(bufm,bufn);
1422:   return(0);
1423: }

1427: /*@
1428:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1429:      Using structured grid indexing

1431:    Not Collective

1433:    Input Parameters:
1434: +  mat - the matrix
1435: .  m - number of rows being entered
1436: .  idxm - grid coordinates for matrix rows being entered
1437: .  n - number of columns being entered
1438: .  idxn - grid coordinates for matrix columns being entered
1439: .  v - a logically two-dimensional array of values
1440: -  addv - either ADD_VALUES or INSERT_VALUES, where
1441:    ADD_VALUES adds values to any existing entries, and
1442:    INSERT_VALUES replaces existing entries with new values

1444:    Notes:
1445:    By default the values, v, are row-oriented and unsorted.
1446:    See MatSetOption() for other options.

1448:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1449:    options cannot be mixed without intervening calls to the assembly
1450:    routines.

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

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

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

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

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

1468:    In Fortran idxm and idxn should be declared as
1469: $     MatStencil idxm(4,m),idxn(4,n)
1470:    and the values inserted using
1471: $    idxm(MatStencil_i,1) = i
1472: $    idxm(MatStencil_j,1) = j
1473: $    idxm(MatStencil_k,1) = k
1474:    etc

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

1481:    Inspired by the structured grid interface to the HYPRE package
1482:    (http://www.llnl.gov/CASC/hypre)

1484:    Level: beginner

1486:    Concepts: matrices^putting entries in

1488: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1489:           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1490:           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1491: @*/
1492: PetscErrorCode  MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1493: {
1495:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1496:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1497:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1507:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1508:     jdxm = buf; jdxn = buf+m;
1509:   } else {
1510:     PetscMalloc2(m,&bufm,n,&bufn);
1511:     jdxm = bufm; jdxn = bufn;
1512:   }
1513:   for (i=0; i<m; i++) {
1514:     for (j=0; j<3-sdim; j++) dxm++;
1515:     tmp = *dxm++ - starts[0];
1516:     for (j=0; j<sdim-1; j++) {
1517:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1518:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1519:     }
1520:     dxm++;
1521:     jdxm[i] = tmp;
1522:   }
1523:   for (i=0; i<n; i++) {
1524:     for (j=0; j<3-sdim; j++) dxn++;
1525:     tmp = *dxn++ - starts[0];
1526:     for (j=0; j<sdim-1; j++) {
1527:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1528:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1529:     }
1530:     dxn++;
1531:     jdxn[i] = tmp;
1532:   }
1533:   MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1534:   PetscFree2(bufm,bufn);
1535: #if defined(PETSC_HAVE_CUSP)
1536:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1537:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1538:   }
1539: #endif
1540: #if defined(PETSC_HAVE_VIENNACL)
1541:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1542:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1543:   }
1544: #endif
1545:   return(0);
1546: }

1550: /*@
1551:    MatSetStencil - Sets the grid information for setting values into a matrix via
1552:         MatSetValuesStencil()

1554:    Not Collective

1556:    Input Parameters:
1557: +  mat - the matrix
1558: .  dim - dimension of the grid 1, 2, or 3
1559: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1560: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1561: -  dof - number of degrees of freedom per node


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

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

1570:    Level: beginner

1572:    Concepts: matrices^putting entries in

1574: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1575:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1576: @*/
1577: PetscErrorCode  MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1578: {
1579:   PetscInt i;


1586:   mat->stencil.dim = dim + (dof > 1);
1587:   for (i=0; i<dim; i++) {
1588:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1589:     mat->stencil.starts[i] = starts[dim-i-1];
1590:   }
1591:   mat->stencil.dims[dim]   = dof;
1592:   mat->stencil.starts[dim] = 0;
1593:   mat->stencil.noc         = (PetscBool)(dof == 1);
1594:   return(0);
1595: }

1599: /*@
1600:    MatSetValuesBlocked - Inserts or adds a block of values into a matrix.

1602:    Not Collective

1604:    Input Parameters:
1605: +  mat - the matrix
1606: .  v - a logically two-dimensional array of values
1607: .  m, idxm - the number of block rows and their global block indices
1608: .  n, idxn - the number of block columns and their global block indices
1609: -  addv - either ADD_VALUES or INSERT_VALUES, where
1610:    ADD_VALUES adds values to any existing entries, and
1611:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

1629:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1630:    options cannot be mixed without intervening calls to the assembly
1631:    routines.

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

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

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

1647:    Example:
1648: $   Suppose m=n=2 and block size(bs) = 2 The array is
1649: $
1650: $   1  2  | 3  4
1651: $   5  6  | 7  8
1652: $   - - - | - - -
1653: $   9  10 | 11 12
1654: $   13 14 | 15 16
1655: $
1656: $   v[] should be passed in like
1657: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1658: $
1659: $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1660: $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]

1662:    Level: intermediate

1664:    Concepts: matrices^putting entries in blocked

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

1675:   if (!m || !n) return(0); /* no values to insert */
1679:   MatCheckPreallocated(mat,1);
1680:   if (mat->insertmode == NOT_SET_VALUES) {
1681:     mat->insertmode = addv;
1682:   }
1683: #if defined(PETSC_USE_DEBUG)
1684:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1685:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1686:   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1687: #endif

1689:   if (mat->assembled) {
1690:     mat->was_assembled = PETSC_TRUE;
1691:     mat->assembled     = PETSC_FALSE;
1692:   }
1693:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1694:   if (mat->ops->setvaluesblocked) {
1695:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1696:   } else {
1697:     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1698:     PetscInt i,j,bs,cbs;
1699:     MatGetBlockSizes(mat,&bs,&cbs);
1700:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1701:       iidxm = buf; iidxn = buf + m*bs;
1702:     } else {
1703:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1704:       iidxm = bufr; iidxn = bufc;
1705:     }
1706:     for (i=0; i<m; i++) {
1707:       for (j=0; j<bs; j++) {
1708:         iidxm[i*bs+j] = bs*idxm[i] + j;
1709:       }
1710:     }
1711:     for (i=0; i<n; i++) {
1712:       for (j=0; j<cbs; j++) {
1713:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1714:       }
1715:     }
1716:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1717:     PetscFree2(bufr,bufc);
1718:   }
1719:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1720: #if defined(PETSC_HAVE_CUSP)
1721:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1722:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1723:   }
1724: #endif
1725: #if defined(PETSC_HAVE_VIENNACL)
1726:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1727:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1728:   }
1729: #endif
1730:   return(0);
1731: }

1735: /*@
1736:    MatGetValues - Gets a block of values from a matrix.

1738:    Not Collective; currently only returns a local block

1740:    Input Parameters:
1741: +  mat - the matrix
1742: .  v - a logically two-dimensional array for storing the values
1743: .  m, idxm - the number of rows and their global indices
1744: -  n, idxn - the number of columns and their global indices

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

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

1754:    MatGetValues() requires that the matrix has been assembled
1755:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1756:    MatSetValues() and MatGetValues() CANNOT be made in succession
1757:    without intermediate matrix assembly.

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

1762:    Level: advanced

1764:    Concepts: matrices^accessing values

1766: .seealso: MatGetRow(), MatGetSubMatrices(), MatSetValues()
1767: @*/
1768: PetscErrorCode  MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1769: {

1775:   if (!m || !n) return(0);
1779:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1780:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1781:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1782:   MatCheckPreallocated(mat,1);

1784:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1785:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1786:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1787:   return(0);
1788: }

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

1796:   Not Collective

1798:   Input Parameters:
1799: + mat - the matrix
1800: . nb - the number of blocks
1801: . bs - the number of rows (and columns) in each block
1802: . rows - a concatenation of the rows for each block
1803: - v - a concatenation of logically two-dimensional arrays of values

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

1808:   Level: advanced

1810:   Concepts: matrices^putting entries in

1812: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1813:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1814: @*/
1815: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1816: {

1824: #if defined(PETSC_USE_DEBUG)
1825:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1826: #endif

1828:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
1829:   if (mat->ops->setvaluesbatch) {
1830:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
1831:   } else {
1832:     PetscInt b;
1833:     for (b = 0; b < nb; ++b) {
1834:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
1835:     }
1836:   }
1837:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
1838:   return(0);
1839: }

1843: /*@
1844:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1845:    the routine MatSetValuesLocal() to allow users to insert matrix entries
1846:    using a local (per-processor) numbering.

1848:    Not Collective

1850:    Input Parameters:
1851: +  x - the matrix
1852: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
1853: - cmapping - column mapping

1855:    Level: intermediate

1857:    Concepts: matrices^local to global mapping
1858:    Concepts: local to global mapping^for matrices

1860: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
1861: @*/
1862: PetscErrorCode  MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
1863: {


1872:   if (x->ops->setlocaltoglobalmapping) {
1873:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
1874:   } else {
1875:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
1876:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
1877:   }
1878:   return(0);
1879: }


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

1887:    Not Collective

1889:    Input Parameters:
1890: .  A - the matrix

1892:    Output Parameters:
1893: + rmapping - row mapping
1894: - cmapping - column mapping

1896:    Level: advanced

1898:    Concepts: matrices^local to global mapping
1899:    Concepts: local to global mapping^for matrices

1901: .seealso:  MatSetValuesLocal()
1902: @*/
1903: PetscErrorCode  MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
1904: {
1910:   if (rmapping) *rmapping = A->rmap->mapping;
1911:   if (cmapping) *cmapping = A->cmap->mapping;
1912:   return(0);
1913: }

1917: /*@
1918:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

1920:    Not Collective

1922:    Input Parameters:
1923: .  A - the matrix

1925:    Output Parameters:
1926: + rmap - row layout
1927: - cmap - column layout

1929:    Level: advanced

1931: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
1932: @*/
1933: PetscErrorCode  MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
1934: {
1940:   if (rmap) *rmap = A->rmap;
1941:   if (cmap) *cmap = A->cmap;
1942:   return(0);
1943: }

1947: /*@
1948:    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
1949:    using a local ordering of the nodes.

1951:    Not Collective

1953:    Input Parameters:
1954: +  x - the matrix
1955: .  nrow, irow - number of rows and their local indices
1956: .  ncol, icol - number of columns and their local indices
1957: .  y -  a logically two-dimensional array of values
1958: -  addv - either INSERT_VALUES or ADD_VALUES, where
1959:    ADD_VALUES adds values to any existing entries, and
1960:    INSERT_VALUES replaces existing entries with new values

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

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

1968:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
1969:    options cannot be mixed without intervening calls to the assembly
1970:    routines.

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

1975:    Level: intermediate

1977:    Concepts: matrices^putting entries in with local numbering

1979: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1980:            MatSetValueLocal()
1981: @*/
1982: PetscErrorCode  MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
1983: {

1989:   MatCheckPreallocated(mat,1);
1990:   if (!nrow || !ncol) return(0); /* no values to insert */
1994:   if (mat->insertmode == NOT_SET_VALUES) {
1995:     mat->insertmode = addv;
1996:   }
1997: #if defined(PETSC_USE_DEBUG)
1998:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1999:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2000:   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2001: #endif

2003:   if (mat->assembled) {
2004:     mat->was_assembled = PETSC_TRUE;
2005:     mat->assembled     = PETSC_FALSE;
2006:   }
2007:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2008:   if (mat->ops->setvalueslocal) {
2009:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2010:   } else {
2011:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2012:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2013:       irowm = buf; icolm = buf+nrow;
2014:     } else {
2015:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2016:       irowm = bufr; icolm = bufc;
2017:     }
2018:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2019:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2020:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2021:     PetscFree2(bufr,bufc);
2022:   }
2023:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2024: #if defined(PETSC_HAVE_CUSP)
2025:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
2026:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
2027:   }
2028: #endif
2029: #if defined(PETSC_HAVE_VIENNACL)
2030:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
2031:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
2032:   }
2033: #endif
2034:   return(0);
2035: }

2039: /*@
2040:    MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2041:    using a local ordering of the nodes a block at a time.

2043:    Not Collective

2045:    Input Parameters:
2046: +  x - the matrix
2047: .  nrow, irow - number of rows and their local indices
2048: .  ncol, icol - number of columns and their local indices
2049: .  y -  a logically two-dimensional array of values
2050: -  addv - either INSERT_VALUES or ADD_VALUES, where
2051:    ADD_VALUES adds values to any existing entries, and
2052:    INSERT_VALUES replaces existing entries with new values

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

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

2061:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2062:    options cannot be mixed without intervening calls to the assembly
2063:    routines.

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

2068:    Level: intermediate

2070:    Concepts: matrices^putting blocked values in with local numbering

2072: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2073:            MatSetValuesLocal(),  MatSetValuesBlocked()
2074: @*/
2075: PetscErrorCode  MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2076: {

2082:   MatCheckPreallocated(mat,1);
2083:   if (!nrow || !ncol) return(0); /* no values to insert */
2087:   if (mat->insertmode == NOT_SET_VALUES) {
2088:     mat->insertmode = addv;
2089:   }
2090: #if defined(PETSC_USE_DEBUG)
2091:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2092:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2093:   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);
2094: #endif

2096:   if (mat->assembled) {
2097:     mat->was_assembled = PETSC_TRUE;
2098:     mat->assembled     = PETSC_FALSE;
2099:   }
2100:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2101:   if (mat->ops->setvaluesblockedlocal) {
2102:     (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2103:   } else {
2104:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2105:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2106:       irowm = buf; icolm = buf + nrow;
2107:     } else {
2108:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2109:       irowm = bufr; icolm = bufc;
2110:     }
2111:     ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2112:     ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2113:     MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2114:     PetscFree2(bufr,bufc);
2115:   }
2116:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2117: #if defined(PETSC_HAVE_CUSP)
2118:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
2119:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
2120:   }
2121: #endif
2122: #if defined(PETSC_HAVE_VIENNACL)
2123:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
2124:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
2125:   }
2126: #endif
2127:   return(0);
2128: }

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

2135:    Collective on Mat and Vec

2137:    Input Parameters:
2138: +  mat - the matrix
2139: -  x   - the vector to be multiplied

2141:    Output Parameters:
2142: .  y - the result

2144:    Notes:
2145:    The vectors x and y cannot be the same.  I.e., one cannot
2146:    call MatMult(A,y,y).

2148:    Level: developer

2150:    Concepts: matrix-vector product

2152: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2153: @*/
2154: PetscErrorCode  MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2155: {


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

2169:   if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2170:   (*mat->ops->multdiagonalblock)(mat,x,y);
2171:   PetscObjectStateIncrease((PetscObject)y);
2172:   return(0);
2173: }

2175: /* --------------------------------------------------------*/
2178: /*@
2179:    MatMult - Computes the matrix-vector product, y = Ax.

2181:    Neighbor-wise Collective on Mat and Vec

2183:    Input Parameters:
2184: +  mat - the matrix
2185: -  x   - the vector to be multiplied

2187:    Output Parameters:
2188: .  y - the result

2190:    Notes:
2191:    The vectors x and y cannot be the same.  I.e., one cannot
2192:    call MatMult(A,y,y).

2194:    Level: beginner

2196:    Concepts: matrix-vector product

2198: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2199: @*/
2200: PetscErrorCode  MatMult(Mat mat,Vec x,Vec y)
2201: {

2209:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2210:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2211:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2212: #if !defined(PETSC_HAVE_CONSTRAINTS)
2213:   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);
2214:   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);
2215:   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);
2216: #endif
2217:   VecLocked(y,3);
2218:   VecValidValues(x,2,PETSC_TRUE);
2219:   MatCheckPreallocated(mat,1);

2221:   VecLockPush(x);
2222:   if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2223:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2224:   (*mat->ops->mult)(mat,x,y);
2225:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2226:   VecValidValues(y,3,PETSC_FALSE);
2227:   VecLockPop(x);
2228:   return(0);
2229: }

2233: /*@
2234:    MatMultTranspose - Computes matrix transpose times a vector.

2236:    Neighbor-wise Collective on Mat and Vec

2238:    Input Parameters:
2239: +  mat - the matrix
2240: -  x   - the vector to be multilplied

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

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

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

2252:    Level: beginner

2254:    Concepts: matrix vector product^transpose

2256: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2257: @*/
2258: PetscErrorCode  MatMultTranspose(Mat mat,Vec x,Vec y)
2259: {


2268:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2269:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2270:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2271: #if !defined(PETSC_HAVE_CONSTRAINTS)
2272:   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2273:   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2274: #endif
2275:   VecValidValues(x,2,PETSC_TRUE);
2276:   MatCheckPreallocated(mat,1);

2278:   if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply tranpose defined");
2279:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2280:   VecLockPush(x);
2281:   (*mat->ops->multtranspose)(mat,x,y);
2282:   VecLockPop(x);
2283:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2284:   PetscObjectStateIncrease((PetscObject)y);
2285:   VecValidValues(y,3,PETSC_FALSE);
2286:   return(0);
2287: }

2291: /*@
2292:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2294:    Neighbor-wise Collective on Mat and Vec

2296:    Input Parameters:
2297: +  mat - the matrix
2298: -  x   - the vector to be multilplied

2300:    Output Parameters:
2301: .  y - the result

2303:    Notes:
2304:    The vectors x and y cannot be the same.  I.e., one cannot
2305:    call MatMultHermitianTranspose(A,y,y).

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

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

2311:    Level: beginner

2313:    Concepts: matrix vector product^transpose

2315: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2316: @*/
2317: PetscErrorCode  MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2318: {
2320:   Vec            w;


2328:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2329:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2330:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2331: #if !defined(PETSC_HAVE_CONSTRAINTS)
2332:   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2333:   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2334: #endif
2335:   MatCheckPreallocated(mat,1);

2337:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2338:   if (mat->ops->multhermitiantranspose) {
2339:     VecLockPush(x);
2340:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2341:     VecLockPop(x);
2342:   } else {
2343:     VecDuplicate(x,&w);
2344:     VecCopy(x,w);
2345:     VecConjugate(w);
2346:     MatMultTranspose(mat,w,y);
2347:     VecDestroy(&w);
2348:     VecConjugate(y);
2349:   }
2350:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2351:   PetscObjectStateIncrease((PetscObject)y);
2352:   return(0);
2353: }

2357: /*@
2358:     MatMultAdd -  Computes v3 = v2 + A * v1.

2360:     Neighbor-wise Collective on Mat and Vec

2362:     Input Parameters:
2363: +   mat - the matrix
2364: -   v1, v2 - the vectors

2366:     Output Parameters:
2367: .   v3 - the result

2369:     Notes:
2370:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2371:     call MatMultAdd(A,v1,v2,v1).

2373:     Level: beginner

2375:     Concepts: matrix vector product^addition

2377: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2378: @*/
2379: PetscErrorCode  MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2380: {


2390:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2391:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2392:   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);
2393:   /* 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);
2394:      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); */
2395:   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);
2396:   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);
2397:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2398:   MatCheckPreallocated(mat,1);

2400:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2401:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2402:   VecLockPush(v1);
2403:   (*mat->ops->multadd)(mat,v1,v2,v3);
2404:   VecLockPop(v1);
2405:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2406:   PetscObjectStateIncrease((PetscObject)v3);
2407:   return(0);
2408: }

2412: /*@
2413:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2415:    Neighbor-wise Collective on Mat and Vec

2417:    Input Parameters:
2418: +  mat - the matrix
2419: -  v1, v2 - the vectors

2421:    Output Parameters:
2422: .  v3 - the result

2424:    Notes:
2425:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2426:    call MatMultTransposeAdd(A,v1,v2,v1).

2428:    Level: beginner

2430:    Concepts: matrix vector product^transpose and addition

2432: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2433: @*/
2434: PetscErrorCode  MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2435: {


2445:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2446:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2447:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2448:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2449:   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);
2450:   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);
2451:   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);
2452:   MatCheckPreallocated(mat,1);

2454:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2455:   VecLockPush(v1);
2456:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2457:   VecLockPop(v1);
2458:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2459:   PetscObjectStateIncrease((PetscObject)v3);
2460:   return(0);
2461: }

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

2468:    Neighbor-wise Collective on Mat and Vec

2470:    Input Parameters:
2471: +  mat - the matrix
2472: -  v1, v2 - the vectors

2474:    Output Parameters:
2475: .  v3 - the result

2477:    Notes:
2478:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2479:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2481:    Level: beginner

2483:    Concepts: matrix vector product^transpose and addition

2485: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2486: @*/
2487: PetscErrorCode  MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2488: {


2498:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2499:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2500:   if (!mat->ops->multhermitiantransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2501:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2502:   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);
2503:   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);
2504:   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);
2505:   MatCheckPreallocated(mat,1);

2507:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2508:   VecLockPush(v1);
2509:   (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2510:   VecLockPop(v1);
2511:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2512:   PetscObjectStateIncrease((PetscObject)v3);
2513:   return(0);
2514: }

2518: /*@
2519:    MatMultConstrained - The inner multiplication routine for a
2520:    constrained matrix P^T A P.

2522:    Neighbor-wise Collective on Mat and Vec

2524:    Input Parameters:
2525: +  mat - the matrix
2526: -  x   - the vector to be multilplied

2528:    Output Parameters:
2529: .  y - the result

2531:    Notes:
2532:    The vectors x and y cannot be the same.  I.e., one cannot
2533:    call MatMult(A,y,y).

2535:    Level: beginner

2537: .keywords: matrix, multiply, matrix-vector product, constraint
2538: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2539: @*/
2540: PetscErrorCode  MatMultConstrained(Mat mat,Vec x,Vec y)
2541: {

2548:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2549:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2550:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2551:   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);
2552:   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);
2553:   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);

2555:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2556:   VecLockPush(x);
2557:   (*mat->ops->multconstrained)(mat,x,y);
2558:   VecLockPop(x);
2559:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2560:   PetscObjectStateIncrease((PetscObject)y);
2561:   return(0);
2562: }

2566: /*@
2567:    MatMultTransposeConstrained - The inner multiplication routine for a
2568:    constrained matrix P^T A^T P.

2570:    Neighbor-wise Collective on Mat and Vec

2572:    Input Parameters:
2573: +  mat - the matrix
2574: -  x   - the vector to be multilplied

2576:    Output Parameters:
2577: .  y - the result

2579:    Notes:
2580:    The vectors x and y cannot be the same.  I.e., one cannot
2581:    call MatMult(A,y,y).

2583:    Level: beginner

2585: .keywords: matrix, multiply, matrix-vector product, constraint
2586: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2587: @*/
2588: PetscErrorCode  MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2589: {

2596:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2597:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2598:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2599:   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);
2600:   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);

2602:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2603:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2604:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2605:   PetscObjectStateIncrease((PetscObject)y);
2606:   return(0);
2607: }

2611: /*@C
2612:    MatGetFactorType - gets the type of factorization it is

2614:    Note Collective
2615:    as the flag

2617:    Input Parameters:
2618: .  mat - the matrix

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

2623:     Level: intermediate

2625: .seealso:    MatFactorType, MatGetFactor()
2626: @*/
2627: PetscErrorCode  MatGetFactorType(Mat mat,MatFactorType *t)
2628: {
2632:   *t = mat->factortype;
2633:   return(0);
2634: }

2636: /* ------------------------------------------------------------*/
2639: /*@C
2640:    MatGetInfo - Returns information about matrix storage (number of
2641:    nonzeros, memory, etc.).

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

2645:    Input Parameters:
2646: .  mat - the matrix

2648:    Output Parameters:
2649: +  flag - flag indicating the type of parameters to be returned
2650:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2651:    MAT_GLOBAL_SUM - sum over all processors)
2652: -  info - matrix information context

2654:    Notes:
2655:    The MatInfo context contains a variety of matrix data, including
2656:    number of nonzeros allocated and used, number of mallocs during
2657:    matrix assembly, etc.  Additional information for factored matrices
2658:    is provided (such as the fill ratio, number of mallocs during
2659:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2660:    when using the runtime options
2661: $       -info -mat_view ::ascii_info

2663:    Example for C/C++ Users:
2664:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2665:    data within the MatInfo context.  For example,
2666: .vb
2667:       MatInfo info;
2668:       Mat     A;
2669:       double  mal, nz_a, nz_u;

2671:       MatGetInfo(A,MAT_LOCAL,&info);
2672:       mal  = info.mallocs;
2673:       nz_a = info.nz_allocated;
2674: .ve

2676:    Example for Fortran Users:
2677:    Fortran users should declare info as a double precision
2678:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2679:    of interest.  See the file ${PETSC_DIR}/include/petsc-finclude/petscmat.h
2680:    a complete list of parameter names.
2681: .vb
2682:       double  precision info(MAT_INFO_SIZE)
2683:       double  precision mal, nz_a
2684:       Mat     A
2685:       integer ierr

2687:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2688:       mal = info(MAT_INFO_MALLOCS)
2689:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2690: .ve

2692:     Level: intermediate

2694:     Concepts: matrices^getting information on

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

2699: .seealso: MatStashGetInfo()

2701: @*/
2702: PetscErrorCode  MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2703: {

2710:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2711:   MatCheckPreallocated(mat,1);
2712:   (*mat->ops->getinfo)(mat,flag,info);
2713:   return(0);
2714: }

2716: /* ----------------------------------------------------------*/

2720: /*@C
2721:    MatLUFactor - Performs in-place LU factorization of matrix.

2723:    Collective on Mat

2725:    Input Parameters:
2726: +  mat - the matrix
2727: .  row - row permutation
2728: .  col - column permutation
2729: -  info - options for factorization, includes
2730: $          fill - expected fill as ratio of original fill.
2731: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2732: $                   Run with the option -info to determine an optimal value to use

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

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

2742:    Level: developer

2744:    Concepts: matrices^LU factorization

2746: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2747:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2752: @*/
2753: PetscErrorCode  MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2754: {
2756:   MatFactorInfo  tinfo;

2764:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2765:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2766:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2767:   MatCheckPreallocated(mat,1);
2768:   if (!info) {
2769:     MatFactorInfoInitialize(&tinfo);
2770:     info = &tinfo;
2771:   }

2773:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2774:   (*mat->ops->lufactor)(mat,row,col,info);
2775:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2776:   PetscObjectStateIncrease((PetscObject)mat);
2777:   return(0);
2778: }

2782: /*@C
2783:    MatILUFactor - Performs in-place ILU factorization of matrix.

2785:    Collective on Mat

2787:    Input Parameters:
2788: +  mat - the matrix
2789: .  row - row permutation
2790: .  col - column permutation
2791: -  info - structure containing
2792: $      levels - number of levels of fill.
2793: $      expected fill - as ratio of original fill.
2794: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2795:                 missing diagonal entries)

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

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

2805:    Level: developer

2807:    Concepts: matrices^ILU factorization

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

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

2814: @*/
2815: PetscErrorCode  MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2816: {

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

2831:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
2832:   (*mat->ops->ilufactor)(mat,row,col,info);
2833:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
2834:   PetscObjectStateIncrease((PetscObject)mat);
2835:   return(0);
2836: }

2840: /*@C
2841:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2842:    Call this routine before calling MatLUFactorNumeric().

2844:    Collective on Mat

2846:    Input Parameters:
2847: +  fact - the factor matrix obtained with MatGetFactor()
2848: .  mat - the matrix
2849: .  row, col - row and column permutations
2850: -  info - options for factorization, includes
2851: $          fill - expected fill as ratio of original fill.
2852: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2853: $                   Run with the option -info to determine an optimal value to use


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

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

2862:    Level: developer

2864:    Concepts: matrices^LU symbolic factorization

2866: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

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

2871: @*/
2872: PetscErrorCode  MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
2873: {

2883:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2884:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2885:   if (!(fact)->ops->lufactorsymbolic) {
2886:     const MatSolverPackage spackage;
2887:     MatFactorGetSolverPackage(fact,&spackage);
2888:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
2889:   }
2890:   MatCheckPreallocated(mat,2);

2892:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
2893:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
2894:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
2895:   PetscObjectStateIncrease((PetscObject)fact);
2896:   return(0);
2897: }

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

2905:    Collective on Mat

2907:    Input Parameters:
2908: +  fact - the factor matrix obtained with MatGetFactor()
2909: .  mat - the matrix
2910: -  info - options for factorization

2912:    Notes:
2913:    See MatLUFactor() for in-place factorization.  See
2914:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

2920:    Level: developer

2922:    Concepts: matrices^LU numeric factorization

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

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

2929: @*/
2930: PetscErrorCode  MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
2931: {

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

2942:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
2943:   MatCheckPreallocated(mat,2);
2944:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
2945:   (fact->ops->lufactornumeric)(fact,mat,info);
2946:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
2947:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
2948:   PetscObjectStateIncrease((PetscObject)fact);
2949:   return(0);
2950: }

2954: /*@C
2955:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
2956:    symmetric matrix.

2958:    Collective on Mat

2960:    Input Parameters:
2961: +  mat - the matrix
2962: .  perm - row and column permutations
2963: -  f - expected fill as ratio of original fill

2965:    Notes:
2966:    See MatLUFactor() for the nonsymmetric case.  See also
2967:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

2973:    Level: developer

2975:    Concepts: matrices^Cholesky factorization

2977: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
2978:           MatGetOrdering()

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

2983: @*/
2984: PetscErrorCode  MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
2985: {

2993:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
2994:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2995:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2996:   if (!mat->ops->choleskyfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2997:   MatCheckPreallocated(mat,1);

2999:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3000:   (*mat->ops->choleskyfactor)(mat,perm,info);
3001:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3002:   PetscObjectStateIncrease((PetscObject)mat);
3003:   return(0);
3004: }

3008: /*@C
3009:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3010:    of a symmetric matrix.

3012:    Collective on Mat

3014:    Input Parameters:
3015: +  fact - the factor matrix obtained with MatGetFactor()
3016: .  mat - the matrix
3017: .  perm - row and column permutations
3018: -  info - options for factorization, includes
3019: $          fill - expected fill as ratio of original fill.
3020: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3021: $                   Run with the option -info to determine an optimal value to use

3023:    Notes:
3024:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3025:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3031:    Level: developer

3033:    Concepts: matrices^Cholesky symbolic factorization

3035: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3036:           MatGetOrdering()

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

3041: @*/
3042: PetscErrorCode  MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3043: {

3052:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3053:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3054:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3055:   if (!(fact)->ops->choleskyfactorsymbolic) {
3056:     const MatSolverPackage spackage;
3057:     MatFactorGetSolverPackage(fact,&spackage);
3058:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3059:   }
3060:   MatCheckPreallocated(mat,2);

3062:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3063:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3064:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3065:   PetscObjectStateIncrease((PetscObject)fact);
3066:   return(0);
3067: }

3071: /*@C
3072:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3073:    of a symmetric matrix. Call this routine after first calling
3074:    MatCholeskyFactorSymbolic().

3076:    Collective on Mat

3078:    Input Parameters:
3079: +  fact - the factor matrix obtained with MatGetFactor()
3080: .  mat - the initial matrix
3081: .  info - options for factorization
3082: -  fact - the symbolic factor of mat


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

3090:    Level: developer

3092:    Concepts: matrices^Cholesky numeric factorization

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

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

3099: @*/
3100: PetscErrorCode  MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3101: {

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

3114:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3115:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3116:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3117:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3118:   PetscObjectStateIncrease((PetscObject)fact);
3119:   return(0);
3120: }

3122: /* ----------------------------------------------------------------*/
3125: /*@
3126:    MatSolve - Solves A x = b, given a factored matrix.

3128:    Neighbor-wise Collective on Mat and Vec

3130:    Input Parameters:
3131: +  mat - the factored matrix
3132: -  b - the right-hand-side vector

3134:    Output Parameter:
3135: .  x - the result vector

3137:    Notes:
3138:    The vectors b and x cannot be the same.  I.e., one cannot
3139:    call MatSolve(A,x,x).

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

3146:    Level: developer

3148:    Concepts: matrices^triangular solves

3150: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3151: @*/
3152: PetscErrorCode  MatSolve(Mat mat,Vec b,Vec x)
3153: {

3163:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3164:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3165:   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);
3166:   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);
3167:   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);
3168:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3169:   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3170:   MatCheckPreallocated(mat,1);

3172:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3173:   (*mat->ops->solve)(mat,b,x);
3174:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3175:   PetscObjectStateIncrease((PetscObject)x);
3176:   return(0);
3177: }

3181: PetscErrorCode  MatMatSolve_Basic(Mat A,Mat B,Mat X)
3182: {
3184:   Vec            b,x;
3185:   PetscInt       m,N,i;
3186:   PetscScalar    *bb,*xx;
3187:   PetscBool      flg;

3190:   PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3191:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
3192:   PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3193:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");

3195:   MatDenseGetArray(B,&bb);
3196:   MatDenseGetArray(X,&xx);
3197:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3198:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3199:   MatCreateVecs(A,&x,&b);
3200:   for (i=0; i<N; i++) {
3201:     VecPlaceArray(b,bb + i*m);
3202:     VecPlaceArray(x,xx + i*m);
3203:     MatSolve(A,b,x);
3204:     VecResetArray(x);
3205:     VecResetArray(b);
3206:   }
3207:   VecDestroy(&b);
3208:   VecDestroy(&x);
3209:   MatDenseRestoreArray(B,&bb);
3210:   MatDenseRestoreArray(X,&xx);
3211:   return(0);
3212: }

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

3219:    Neighbor-wise Collective on Mat

3221:    Input Parameters:
3222: +  mat - the factored matrix
3223: -  B - the right-hand-side matrix  (dense matrix)

3225:    Output Parameter:
3226: .  X - the result matrix (dense matrix)

3228:    Notes:
3229:    The matrices b and x cannot be the same.  I.e., one cannot
3230:    call MatMatSolve(A,x,x).

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

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

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

3243:    Level: developer

3245:    Concepts: matrices^triangular solves

3247: .seealso: MatMatSolveAdd(), MatMatSolveTranspose(), MatMatSolveTransposeAdd(), MatLUFactor(), MatCholeskyFactor()
3248: @*/
3249: PetscErrorCode  MatMatSolve(Mat A,Mat B,Mat X)
3250: {

3260:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3261:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3262:   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);
3263:   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);
3264:   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);
3265:   if (!A->rmap->N && !A->cmap->N) return(0);
3266:   MatCheckPreallocated(A,1);

3268:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3269:   if (!A->ops->matsolve) {
3270:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3271:     MatMatSolve_Basic(A,B,X);
3272:   } else {
3273:     (*A->ops->matsolve)(A,B,X);
3274:   }
3275:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3276:   PetscObjectStateIncrease((PetscObject)X);
3277:   return(0);
3278: }


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

3287:    Neighbor-wise Collective on Mat and Vec

3289:    Input Parameters:
3290: +  mat - the factored matrix
3291: -  b - the right-hand-side vector

3293:    Output Parameter:
3294: .  x - the result vector

3296:    Notes:
3297:    MatSolve() should be used for most applications, as it performs
3298:    a forward solve followed by a backward solve.

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

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

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

3313:    Level: developer

3315:    Concepts: matrices^forward solves

3317: .seealso: MatSolve(), MatBackwardSolve()
3318: @*/
3319: PetscErrorCode  MatForwardSolve(Mat mat,Vec b,Vec x)
3320: {

3330:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3331:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3332:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3333:   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);
3334:   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);
3335:   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);
3336:   MatCheckPreallocated(mat,1);
3337:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3338:   (*mat->ops->forwardsolve)(mat,b,x);
3339:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3340:   PetscObjectStateIncrease((PetscObject)x);
3341:   return(0);
3342: }

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

3350:    Neighbor-wise Collective on Mat and Vec

3352:    Input Parameters:
3353: +  mat - the factored matrix
3354: -  b - the right-hand-side vector

3356:    Output Parameter:
3357: .  x - the result vector

3359:    Notes:
3360:    MatSolve() should be used for most applications, as it performs
3361:    a forward solve followed by a backward solve.

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

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

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

3376:    Level: developer

3378:    Concepts: matrices^backward solves

3380: .seealso: MatSolve(), MatForwardSolve()
3381: @*/
3382: PetscErrorCode  MatBackwardSolve(Mat mat,Vec b,Vec x)
3383: {

3393:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3394:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3395:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3396:   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);
3397:   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);
3398:   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);
3399:   MatCheckPreallocated(mat,1);

3401:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3402:   (*mat->ops->backwardsolve)(mat,b,x);
3403:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3404:   PetscObjectStateIncrease((PetscObject)x);
3405:   return(0);
3406: }

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

3413:    Neighbor-wise Collective on Mat and Vec

3415:    Input Parameters:
3416: +  mat - the factored matrix
3417: .  b - the right-hand-side vector
3418: -  y - the vector to be added to

3420:    Output Parameter:
3421: .  x - the result vector

3423:    Notes:
3424:    The vectors b and x cannot be the same.  I.e., one cannot
3425:    call MatSolveAdd(A,x,y,x).

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

3431:    Level: developer

3433:    Concepts: matrices^triangular solves

3435: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3436: @*/
3437: PetscErrorCode  MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3438: {
3439:   PetscScalar    one = 1.0;
3440:   Vec            tmp;

3452:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3453:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3454:   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);
3455:   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);
3456:   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);
3457:   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);
3458:   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);
3459:   MatCheckPreallocated(mat,1);

3461:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3462:   if (mat->ops->solveadd) {
3463:     (*mat->ops->solveadd)(mat,b,y,x);
3464:   } else {
3465:     /* do the solve then the add manually */
3466:     if (x != y) {
3467:       MatSolve(mat,b,x);
3468:       VecAXPY(x,one,y);
3469:     } else {
3470:       VecDuplicate(x,&tmp);
3471:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3472:       VecCopy(x,tmp);
3473:       MatSolve(mat,b,x);
3474:       VecAXPY(x,one,tmp);
3475:       VecDestroy(&tmp);
3476:     }
3477:   }
3478:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3479:   PetscObjectStateIncrease((PetscObject)x);
3480:   return(0);
3481: }

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

3488:    Neighbor-wise Collective on Mat and Vec

3490:    Input Parameters:
3491: +  mat - the factored matrix
3492: -  b - the right-hand-side vector

3494:    Output Parameter:
3495: .  x - the result vector

3497:    Notes:
3498:    The vectors b and x cannot be the same.  I.e., one cannot
3499:    call MatSolveTranspose(A,x,x).

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

3505:    Level: developer

3507:    Concepts: matrices^triangular solves

3509: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3510: @*/
3511: PetscErrorCode  MatSolveTranspose(Mat mat,Vec b,Vec x)
3512: {

3522:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3523:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3524:   if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3525:   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);
3526:   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);
3527:   MatCheckPreallocated(mat,1);
3528:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3529:   (*mat->ops->solvetranspose)(mat,b,x);
3530:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3531:   PetscObjectStateIncrease((PetscObject)x);
3532:   return(0);
3533: }

3537: /*@
3538:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3539:                       factored matrix.

3541:    Neighbor-wise Collective on Mat and Vec

3543:    Input Parameters:
3544: +  mat - the factored matrix
3545: .  b - the right-hand-side vector
3546: -  y - the vector to be added to

3548:    Output Parameter:
3549: .  x - the result vector

3551:    Notes:
3552:    The vectors b and x cannot be the same.  I.e., one cannot
3553:    call MatSolveTransposeAdd(A,x,y,x).

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

3559:    Level: developer

3561:    Concepts: matrices^triangular solves

3563: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3564: @*/
3565: PetscErrorCode  MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3566: {
3567:   PetscScalar    one = 1.0;
3569:   Vec            tmp;

3580:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3581:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3582:   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);
3583:   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);
3584:   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);
3585:   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);
3586:   MatCheckPreallocated(mat,1);

3588:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3589:   if (mat->ops->solvetransposeadd) {
3590:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
3591:   } else {
3592:     /* do the solve then the add manually */
3593:     if (x != y) {
3594:       MatSolveTranspose(mat,b,x);
3595:       VecAXPY(x,one,y);
3596:     } else {
3597:       VecDuplicate(x,&tmp);
3598:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3599:       VecCopy(x,tmp);
3600:       MatSolveTranspose(mat,b,x);
3601:       VecAXPY(x,one,tmp);
3602:       VecDestroy(&tmp);
3603:     }
3604:   }
3605:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3606:   PetscObjectStateIncrease((PetscObject)x);
3607:   return(0);
3608: }
3609: /* ----------------------------------------------------------------*/

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

3616:    Neighbor-wise Collective on Mat and Vec

3618:    Input Parameters:
3619: +  mat - the matrix
3620: .  b - the right hand side
3621: .  omega - the relaxation factor
3622: .  flag - flag indicating the type of SOR (see below)
3623: .  shift -  diagonal shift
3624: .  its - the number of iterations
3625: -  lits - the number of local iterations

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

3630:    SOR Flags:
3631: .     SOR_FORWARD_SWEEP - forward SOR
3632: .     SOR_BACKWARD_SWEEP - backward SOR
3633: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3634: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3635: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3636: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3637: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3638:          upper/lower triangular part of matrix to
3639:          vector (with omega)
3640: .     SOR_ZERO_INITIAL_GUESS - zero initial guess

3642:    Notes:
3643:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3644:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3645:    on each processor.

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

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

3652:    Notes for Advanced Users:
3653:    The flags are implemented as bitwise inclusive or operations.
3654:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3655:    to specify a zero initial guess for SSOR.

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

3661:    Vectors x and b CANNOT be the same

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

3665:    Level: developer

3667:    Concepts: matrices^relaxation
3668:    Concepts: matrices^SOR
3669:    Concepts: matrices^Gauss-Seidel

3671: @*/
3672: PetscErrorCode  MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3673: {

3683:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3684:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3685:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3686:   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);
3687:   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);
3688:   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);
3689:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3690:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3691:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

3693:   MatCheckPreallocated(mat,1);
3694:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3695:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3696:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3697:   PetscObjectStateIncrease((PetscObject)x);
3698:   return(0);
3699: }

3703: /*
3704:       Default matrix copy routine.
3705: */
3706: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3707: {
3708:   PetscErrorCode    ierr;
3709:   PetscInt          i,rstart = 0,rend = 0,nz;
3710:   const PetscInt    *cwork;
3711:   const PetscScalar *vwork;

3714:   if (B->assembled) {
3715:     MatZeroEntries(B);
3716:   }
3717:   MatGetOwnershipRange(A,&rstart,&rend);
3718:   for (i=rstart; i<rend; i++) {
3719:     MatGetRow(A,i,&nz,&cwork,&vwork);
3720:     MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3721:     MatRestoreRow(A,i,&nz,&cwork,&vwork);
3722:   }
3723:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3724:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3725:   PetscObjectStateIncrease((PetscObject)B);
3726:   return(0);
3727: }

3731: /*@
3732:    MatCopy - Copys a matrix to another matrix.

3734:    Collective on Mat

3736:    Input Parameters:
3737: +  A - the matrix
3738: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

3740:    Output Parameter:
3741: .  B - where the copy is put

3743:    Notes:
3744:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3745:    same nonzero pattern or the routine will crash.

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

3751:    Level: intermediate

3753:    Concepts: matrices^copying

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

3757: @*/
3758: PetscErrorCode  MatCopy(Mat A,Mat B,MatStructure str)
3759: {
3761:   PetscInt       i;

3769:   MatCheckPreallocated(B,2);
3770:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3771:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3772:   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);
3773:   MatCheckPreallocated(A,1);

3775:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
3776:   if (A->ops->copy) {
3777:     (*A->ops->copy)(A,B,str);
3778:   } else { /* generic conversion */
3779:     MatCopy_Basic(A,B,str);
3780:   }

3782:   B->stencil.dim = A->stencil.dim;
3783:   B->stencil.noc = A->stencil.noc;
3784:   for (i=0; i<=A->stencil.dim; i++) {
3785:     B->stencil.dims[i]   = A->stencil.dims[i];
3786:     B->stencil.starts[i] = A->stencil.starts[i];
3787:   }

3789:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
3790:   PetscObjectStateIncrease((PetscObject)B);
3791:   return(0);
3792: }

3796: /*@C
3797:    MatConvert - Converts a matrix to another matrix, either of the same
3798:    or different type.

3800:    Collective on Mat

3802:    Input Parameters:
3803: +  mat - the matrix
3804: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
3805:    same type as the original matrix.
3806: -  reuse - denotes if the destination matrix is to be created or reused.  Currently
3807:    MAT_REUSE_MATRIX is only supported for inplace conversion, otherwise use
3808:    MAT_INITIAL_MATRIX.

3810:    Output Parameter:
3811: .  M - pointer to place new matrix

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

3818:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
3819:    the MPI communicator of the generated matrix is always the same as the communicator
3820:    of the input matrix.

3822:    Level: intermediate

3824:    Concepts: matrices^converting between storage formats

3826: .seealso: MatCopy(), MatDuplicate()
3827: @*/
3828: PetscErrorCode  MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
3829: {
3831:   PetscBool      sametype,issame,flg;
3832:   char           convname[256],mtype[256];
3833:   Mat            B;

3839:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3840:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3841:   MatCheckPreallocated(mat,1);
3842:   MatSetOption(mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);

3844:   PetscOptionsGetString(((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
3845:   if (flg) {
3846:     newtype = mtype;
3847:   }
3848:   PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
3849:   PetscStrcmp(newtype,"same",&issame);
3850:   if ((reuse == MAT_REUSE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_REUSE_MATRIX only supported for in-place conversion currently");

3852:   if ((reuse == MAT_REUSE_MATRIX) && (issame || sametype)) return(0);

3854:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
3855:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
3856:   } else {
3857:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
3858:     const char     *prefix[3] = {"seq","mpi",""};
3859:     PetscInt       i;
3860:     /*
3861:        Order of precedence:
3862:        1) See if a specialized converter is known to the current matrix.
3863:        2) See if a specialized converter is known to the desired matrix class.
3864:        3) See if a good general converter is registered for the desired class
3865:           (as of 6/27/03 only MATMPIADJ falls into this category).
3866:        4) See if a good general converter is known for the current matrix.
3867:        5) Use a really basic converter.
3868:     */

3870:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
3871:     for (i=0; i<3; i++) {
3872:       PetscStrcpy(convname,"MatConvert_");
3873:       PetscStrcat(convname,((PetscObject)mat)->type_name);
3874:       PetscStrcat(convname,"_");
3875:       PetscStrcat(convname,prefix[i]);
3876:       PetscStrcat(convname,issame ? ((PetscObject)mat)->type_name : newtype);
3877:       PetscStrcat(convname,"_C");
3878:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
3879:       if (conv) goto foundconv;
3880:     }

3882:     /* 2)  See if a specialized converter is known to the desired matrix class. */
3883:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
3884:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
3885:     MatSetType(B,newtype);
3886:     for (i=0; i<3; i++) {
3887:       PetscStrcpy(convname,"MatConvert_");
3888:       PetscStrcat(convname,((PetscObject)mat)->type_name);
3889:       PetscStrcat(convname,"_");
3890:       PetscStrcat(convname,prefix[i]);
3891:       PetscStrcat(convname,newtype);
3892:       PetscStrcat(convname,"_C");
3893:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
3894:       if (conv) {
3895:         MatDestroy(&B);
3896:         goto foundconv;
3897:       }
3898:     }

3900:     /* 3) See if a good general converter is registered for the desired class */
3901:     conv = B->ops->convertfrom;
3902:     MatDestroy(&B);
3903:     if (conv) goto foundconv;

3905:     /* 4) See if a good general converter is known for the current matrix */
3906:     if (mat->ops->convert) {
3907:       conv = mat->ops->convert;
3908:     }
3909:     if (conv) goto foundconv;

3911:     /* 5) Use a really basic converter. */
3912:     conv = MatConvert_Basic;

3914: foundconv:
3915:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
3916:     (*conv)(mat,newtype,reuse,M);
3917:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
3918:   }
3919:   PetscObjectStateIncrease((PetscObject)*M);

3921:   /* Copy Mat options */
3922:   if (mat->symmetric) {MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);}
3923:   if (mat->hermitian) {MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);}
3924:   return(0);
3925: }

3929: /*@C
3930:    MatFactorGetSolverPackage - Returns name of the package providing the factorization routines

3932:    Not Collective

3934:    Input Parameter:
3935: .  mat - the matrix, must be a factored matrix

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

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

3944:    Level: intermediate

3946: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
3947: @*/
3948: PetscErrorCode  MatFactorGetSolverPackage(Mat mat, const MatSolverPackage *type)
3949: {
3950:   PetscErrorCode ierr, (*conv)(Mat,const MatSolverPackage*);

3955:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
3956:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverPackage_C",&conv);
3957:   if (!conv) {
3958:     *type = MATSOLVERPETSC;
3959:   } else {
3960:     (*conv)(mat,type);
3961:   }
3962:   return(0);
3963: }

3965: typedef struct _MatSolverPackageForSpecifcType* MatSolverPackageForSpecifcType;
3966: struct _MatSolverPackageForSpecifcType {
3967:   MatType                        mtype;
3968:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
3969:   MatSolverPackageForSpecifcType next;
3970: };

3972: typedef struct _MatSolverPackageHolder* MatSolverPackageHolder;
3973: struct _MatSolverPackageHolder {
3974:   char                           *name;
3975:   MatSolverPackageForSpecifcType handlers;
3976:   MatSolverPackageHolder         next;
3977: };

3979: static MatSolverPackageHolder MatSolverPackageHolders = NULL;

3983: /*@C
3984:    MatSolvePackageRegister - Registers a MatSolverPackage that works for a particular matrix type

3986:    Input Parameters:
3987: +    package - name of the package, for example petsc or superlu
3988: .    mtype - the matrix type that works with this package
3989: .    ftype - the type of factorization supported by the package
3990: -    getfactor - routine that will create the factored matrix ready to be used

3992:     Level: intermediate

3994: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
3995: @*/
3996: PetscErrorCode  MatSolverPackageRegister(const MatSolverPackage package,const MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
3997: {
3998:   PetscErrorCode                 ierr;
3999:   MatSolverPackageHolder         next = MatSolverPackageHolders,prev;
4000:   PetscBool                      flg;
4001:   MatSolverPackageForSpecifcType inext,iprev = NULL;

4004:   if (!MatSolverPackageHolders) {
4005:     PetscNew(&MatSolverPackageHolders);
4006:     PetscStrallocpy(package,&MatSolverPackageHolders->name);
4007:     PetscNew(&MatSolverPackageHolders->handlers);
4008:     PetscStrallocpy(mtype,(char **)&MatSolverPackageHolders->handlers->mtype);
4009:     MatSolverPackageHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4010:     return(0);
4011:   }
4012:   while (next) {
4013:     PetscStrcasecmp(package,next->name,&flg);
4014:     if (flg) {
4015:       inext = next->handlers;
4016:       while (inext) {
4017:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4018:         if (flg) {
4019:           inext->getfactor[(int)ftype-1] = getfactor;
4020:           return(0);
4021:         }
4022:         iprev = inext;
4023:         inext = inext->next;
4024:       }
4025:       PetscNew(&iprev->next);
4026:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4027:       iprev->next->getfactor[(int)ftype-1] = getfactor;
4028:       return(0);
4029:     }
4030:     prev = next;
4031:     next = next->next;
4032:   }
4033:   PetscNew(&prev->next);
4034:   PetscStrallocpy(package,&prev->next->name);
4035:   PetscNew(&prev->next->handlers);
4036:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4037:   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4038:   return(0);
4039: }

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

4046:    Input Parameters:
4047: +    package - name of the package, for example petsc or superlu
4048: .    ftype - the type of factorization supported by the package
4049: -    mtype - the matrix type that works with this package

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

4056:     Level: intermediate

4058: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4059: @*/
4060: PetscErrorCode  MatSolverPackageGet(const MatSolverPackage package,const MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4061: {
4062:   PetscErrorCode                 ierr;
4063:   MatSolverPackageHolder         next = MatSolverPackageHolders;
4064:   PetscBool                      flg;
4065:   MatSolverPackageForSpecifcType inext;

4068:   if (foundpackage) *foundpackage = PETSC_FALSE;
4069:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4070:   if (getfactor)    *getfactor    = NULL;
4071:   while (next) {
4072:     PetscStrcasecmp(package,next->name,&flg);
4073:     if (flg) {
4074:       if (foundpackage) *foundpackage = PETSC_TRUE;
4075:       inext = next->handlers;
4076:       while (inext) {
4077:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4078:         if (flg) {
4079:           if (foundmtype) *foundmtype = PETSC_TRUE;
4080:           if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4081:           return(0);
4082:         }
4083:         inext = inext->next;
4084:       }
4085:     }
4086:     next = next->next;
4087:   }
4088:   return(0);
4089: }

4093: PetscErrorCode  MatSolverPackageDestroy(void)
4094: {
4095:   PetscErrorCode                 ierr;
4096:   MatSolverPackageHolder         next = MatSolverPackageHolders,prev;
4097:   MatSolverPackageForSpecifcType inext,iprev;

4100:   while (next) {
4101:     PetscFree(next->name);
4102:     inext = next->handlers;
4103:     while (inext) {
4104:       PetscFree(inext->mtype);
4105:       iprev = inext;
4106:       inext = inext->next;
4107:       PetscFree(iprev);
4108:     }
4109:     prev = next;
4110:     next = next->next;
4111:     PetscFree(prev);
4112:   }
4113:   MatSolverPackageHolders = NULL;
4114:   return(0);
4115: }

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

4122:    Collective on Mat

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

4129:    Output Parameters:
4130: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4132:    Notes:
4133:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4134:      such as pastix, superlu, mumps etc.

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

4138:    Level: intermediate

4140: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4141: @*/
4142: PetscErrorCode  MatGetFactor(Mat mat, const MatSolverPackage type,MatFactorType ftype,Mat *f)
4143: {
4144:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4145:   PetscBool      foundpackage,foundmtype;


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

4154:   MatSolverPackageGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4155:   if (!foundpackage) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4156:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverPackage %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4157:   if (!conv) SETERRQ3(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverPackage %s does not support factorization type %s for  matrix type %s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name);

4159:   (*conv)(mat,ftype,f);
4160:   return(0);
4161: }

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

4168:    Not Collective

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

4175:    Output Parameter:
4176: .    flg - PETSC_TRUE if the factorization is available

4178:    Notes:
4179:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4180:      such as pastix, superlu, mumps etc.

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

4184:    Level: intermediate

4186: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4187: @*/
4188: PetscErrorCode  MatGetFactorAvailable(Mat mat, const MatSolverPackage type,MatFactorType ftype,PetscBool  *flg)
4189: {
4190:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4199:   *flg = PETSC_FALSE;
4200:   MatSolverPackageGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4201:   if (gconv) {
4202:     *flg = PETSC_TRUE;
4203:   }
4204:   return(0);
4205: }

4209: /*@
4210:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4212:    Collective on Mat

4214:    Input Parameters:
4215: +  mat - the matrix
4216: -  op - either MAT_DO_NOT_COPY_VALUES or MAT_COPY_VALUES, cause it to copy the numerical values in the matrix
4217:         MAT_SHARE_NONZERO_PATTERN to share the nonzero patterns with the previous matrix and not copy them.

4219:    Output Parameter:
4220: .  M - pointer to place new matrix

4222:    Level: intermediate

4224:    Concepts: matrices^duplicating

4226:     Notes: You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.

4228: .seealso: MatCopy(), MatConvert()
4229: @*/
4230: PetscErrorCode  MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4231: {
4233:   Mat            B;
4234:   PetscInt       i;

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

4244:   *M = 0;
4245:   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4246:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4247:   (*mat->ops->duplicate)(mat,op,M);
4248:   B    = *M;

4250:   B->stencil.dim = mat->stencil.dim;
4251:   B->stencil.noc = mat->stencil.noc;
4252:   for (i=0; i<=mat->stencil.dim; i++) {
4253:     B->stencil.dims[i]   = mat->stencil.dims[i];
4254:     B->stencil.starts[i] = mat->stencil.starts[i];
4255:   }

4257:   B->nooffproczerorows = mat->nooffproczerorows;
4258:   B->nooffprocentries  = mat->nooffprocentries;

4260:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4261:   PetscObjectStateIncrease((PetscObject)B);
4262:   return(0);
4263: }

4267: /*@
4268:    MatGetDiagonal - Gets the diagonal of a matrix.

4270:    Logically Collective on Mat and Vec

4272:    Input Parameters:
4273: +  mat - the matrix
4274: -  v - the vector for storing the diagonal

4276:    Output Parameter:
4277: .  v - the diagonal of the matrix

4279:    Level: intermediate

4281:    Note:
4282:    Currently only correct in parallel for square matrices.

4284:    Concepts: matrices^accessing diagonals

4286: .seealso: MatGetRow(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs()
4287: @*/
4288: PetscErrorCode  MatGetDiagonal(Mat mat,Vec v)
4289: {

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

4300:   (*mat->ops->getdiagonal)(mat,v);
4301:   PetscObjectStateIncrease((PetscObject)v);
4302:   return(0);
4303: }

4307: /*@C
4308:    MatGetRowMin - Gets the minimum value (of the real part) of each
4309:         row of the matrix

4311:    Logically Collective on Mat and Vec

4313:    Input Parameters:
4314: .  mat - the matrix

4316:    Output Parameter:
4317: +  v - the vector for storing the maximums
4318: -  idx - the indices of the column found for each row (optional)

4320:    Level: intermediate

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

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

4327:    Concepts: matrices^getting row maximums

4329: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(),
4330:           MatGetRowMax()
4331: @*/
4332: PetscErrorCode  MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4333: {

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

4344:   (*mat->ops->getrowmin)(mat,v,idx);
4345:   PetscObjectStateIncrease((PetscObject)v);
4346:   return(0);
4347: }

4351: /*@C
4352:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4353:         row of the matrix

4355:    Logically Collective on Mat and Vec

4357:    Input Parameters:
4358: .  mat - the matrix

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

4364:    Level: intermediate

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

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

4371:    Concepts: matrices^getting row maximums

4373: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4374: @*/
4375: PetscErrorCode  MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4376: {

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

4388:   (*mat->ops->getrowminabs)(mat,v,idx);
4389:   PetscObjectStateIncrease((PetscObject)v);
4390:   return(0);
4391: }

4395: /*@C
4396:    MatGetRowMax - Gets the maximum value (of the real part) of each
4397:         row of the matrix

4399:    Logically Collective on Mat and Vec

4401:    Input Parameters:
4402: .  mat - the matrix

4404:    Output Parameter:
4405: +  v - the vector for storing the maximums
4406: -  idx - the indices of the column found for each row (optional)

4408:    Level: intermediate

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

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

4415:    Concepts: matrices^getting row maximums

4417: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4418: @*/
4419: PetscErrorCode  MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4420: {

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

4431:   (*mat->ops->getrowmax)(mat,v,idx);
4432:   PetscObjectStateIncrease((PetscObject)v);
4433:   return(0);
4434: }

4438: /*@C
4439:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4440:         row of the matrix

4442:    Logically Collective on Mat and Vec

4444:    Input Parameters:
4445: .  mat - the matrix

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

4451:    Level: intermediate

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

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

4458:    Concepts: matrices^getting row maximums

4460: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
4461: @*/
4462: PetscErrorCode  MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4463: {

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

4475:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4476:   PetscObjectStateIncrease((PetscObject)v);
4477:   return(0);
4478: }

4482: /*@
4483:    MatGetRowSum - Gets the sum of each row of the matrix

4485:    Logically Collective on Mat and Vec

4487:    Input Parameters:
4488: .  mat - the matrix

4490:    Output Parameter:
4491: .  v - the vector for storing the sum of rows

4493:    Level: intermediate

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

4497:    Concepts: matrices^getting row sums

4499: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
4500: @*/
4501: PetscErrorCode  MatGetRowSum(Mat mat, Vec v)
4502: {
4503:   PetscInt       start = 0, end = 0, row;
4504:   PetscScalar    *array;

4511:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4512:   MatCheckPreallocated(mat,1);
4513:   MatGetOwnershipRange(mat, &start, &end);
4514:   VecGetArray(v, &array);
4515:   for (row = start; row < end; ++row) {
4516:     PetscInt          ncols, col;
4517:     const PetscInt    *cols;
4518:     const PetscScalar *vals;

4520:     array[row - start] = 0.0;

4522:     MatGetRow(mat, row, &ncols, &cols, &vals);
4523:     for (col = 0; col < ncols; col++) {
4524:       array[row - start] += vals[col];
4525:     }
4526:     MatRestoreRow(mat, row, &ncols, &cols, &vals);
4527:   }
4528:   VecRestoreArray(v, &array);
4529:   PetscObjectStateIncrease((PetscObject) v);
4530:   return(0);
4531: }

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

4538:    Collective on Mat

4540:    Input Parameter:
4541: +  mat - the matrix to transpose
4542: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4544:    Output Parameters:
4545: .  B - the transpose

4547:    Notes:
4548:      If you  pass in &mat for B the transpose will be done in place, for example MatTranspose(mat,MAT_REUSE_MATRIX,&mat);

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

4552:    Level: intermediate

4554:    Concepts: matrices^transposing

4556: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4557: @*/
4558: PetscErrorCode  MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4559: {

4565:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4566:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4567:   if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4568:   MatCheckPreallocated(mat,1);

4570:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4571:   (*mat->ops->transpose)(mat,reuse,B);
4572:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4573:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4574:   return(0);
4575: }

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

4583:    Collective on Mat

4585:    Input Parameter:
4586: +  A - the matrix to test
4587: -  B - the matrix to test against, this can equal the first parameter

4589:    Output Parameters:
4590: .  flg - the result

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

4597:    Level: intermediate

4599:    Concepts: matrices^transposing, matrix^symmetry

4601: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4602: @*/
4603: PetscErrorCode  MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4604: {
4605:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4611:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4612:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4613:   *flg = PETSC_FALSE;
4614:   if (f && g) {
4615:     if (f == g) {
4616:       (*f)(A,B,tol,flg);
4617:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4618:   } else {
4619:     MatType mattype;
4620:     if (!f) {
4621:       MatGetType(A,&mattype);
4622:     } else {
4623:       MatGetType(B,&mattype);
4624:     }
4625:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4626:   }
4627:   return(0);
4628: }

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

4635:    Collective on Mat

4637:    Input Parameter:
4638: +  mat - the matrix to transpose and complex conjugate
4639: -  reuse - store the transpose matrix in the provided B

4641:    Output Parameters:
4642: .  B - the Hermitian

4644:    Notes:
4645:      If you  pass in &mat for B the Hermitian will be done in place

4647:    Level: intermediate

4649:    Concepts: matrices^transposing, complex conjugatex

4651: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4652: @*/
4653: PetscErrorCode  MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4654: {

4658:   MatTranspose(mat,reuse,B);
4659: #if defined(PETSC_USE_COMPLEX)
4660:   MatConjugate(*B);
4661: #endif
4662:   return(0);
4663: }

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

4670:    Collective on Mat

4672:    Input Parameter:
4673: +  A - the matrix to test
4674: -  B - the matrix to test against, this can equal the first parameter

4676:    Output Parameters:
4677: .  flg - the result

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

4684:    Level: intermediate

4686:    Concepts: matrices^transposing, matrix^symmetry

4688: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4689: @*/
4690: PetscErrorCode  MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4691: {
4692:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4698:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4699:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
4700:   if (f && g) {
4701:     if (f==g) {
4702:       (*f)(A,B,tol,flg);
4703:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4704:   }
4705:   return(0);
4706: }

4710: /*@
4711:    MatPermute - Creates a new matrix with rows and columns permuted from the
4712:    original.

4714:    Collective on Mat

4716:    Input Parameters:
4717: +  mat - the matrix to permute
4718: .  row - row permutation, each processor supplies only the permutation for its rows
4719: -  col - column permutation, each processor supplies only the permutation for its columns

4721:    Output Parameters:
4722: .  B - the permuted matrix

4724:    Level: advanced

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

4730:    Concepts: matrices^permuting

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

4734: @*/
4735: PetscErrorCode  MatPermute(Mat mat,IS row,IS col,Mat *B)
4736: {

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

4750:   (*mat->ops->permute)(mat,row,col,B);
4751:   PetscObjectStateIncrease((PetscObject)*B);
4752:   return(0);
4753: }

4757: /*@
4758:    MatEqual - Compares two matrices.

4760:    Collective on Mat

4762:    Input Parameters:
4763: +  A - the first matrix
4764: -  B - the second matrix

4766:    Output Parameter:
4767: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

4769:    Level: intermediate

4771:    Concepts: matrices^equality between
4772: @*/
4773: PetscErrorCode  MatEqual(Mat A,Mat B,PetscBool  *flg)
4774: {

4784:   MatCheckPreallocated(B,2);
4785:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4786:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4787:   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);
4788:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
4789:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
4790:   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);
4791:   MatCheckPreallocated(A,1);

4793:   (*A->ops->equal)(A,B,flg);
4794:   return(0);
4795: }

4799: /*@
4800:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
4801:    matrices that are stored as vectors.  Either of the two scaling
4802:    matrices can be NULL.

4804:    Collective on Mat

4806:    Input Parameters:
4807: +  mat - the matrix to be scaled
4808: .  l - the left scaling vector (or NULL)
4809: -  r - the right scaling vector (or NULL)

4811:    Notes:
4812:    MatDiagonalScale() computes A = LAR, where
4813:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
4814:    The L scales the rows of the matrix, the R scales the columns of the matrix.

4816:    Level: intermediate

4818:    Concepts: matrices^diagonal scaling
4819:    Concepts: diagonal scaling of matrices

4821: .seealso: MatScale()
4822: @*/
4823: PetscErrorCode  MatDiagonalScale(Mat mat,Vec l,Vec r)
4824: {

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

4837:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
4838:   (*mat->ops->diagonalscale)(mat,l,r);
4839:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
4840:   PetscObjectStateIncrease((PetscObject)mat);
4841: #if defined(PETSC_HAVE_CUSP)
4842:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
4843:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
4844:   }
4845: #endif
4846: #if defined(PETSC_HAVE_VIENNACL)
4847:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
4848:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
4849:   }
4850: #endif
4851:   return(0);
4852: }

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

4859:     Logically Collective on Mat

4861:     Input Parameters:
4862: +   mat - the matrix to be scaled
4863: -   a  - the scaling value

4865:     Output Parameter:
4866: .   mat - the scaled matrix

4868:     Level: intermediate

4870:     Concepts: matrices^scaling all entries

4872: .seealso: MatDiagonalScale()
4873: @*/
4874: PetscErrorCode  MatScale(Mat mat,PetscScalar a)
4875: {

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

4887:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
4888:   if (a != (PetscScalar)1.0) {
4889:     (*mat->ops->scale)(mat,a);
4890:     PetscObjectStateIncrease((PetscObject)mat);
4891:   }
4892:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
4893: #if defined(PETSC_HAVE_CUSP)
4894:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
4895:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
4896:   }
4897: #endif
4898: #if defined(PETSC_HAVE_VIENNACL)
4899:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
4900:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
4901:   }
4902: #endif
4903:   return(0);
4904: }

4908: /*@
4909:    MatNorm - Calculates various norms of a matrix.

4911:    Collective on Mat

4913:    Input Parameters:
4914: +  mat - the matrix
4915: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

4917:    Output Parameters:
4918: .  nrm - the resulting norm

4920:    Level: intermediate

4922:    Concepts: matrices^norm
4923:    Concepts: norm^of matrix
4924: @*/
4925: PetscErrorCode  MatNorm(Mat mat,NormType type,PetscReal *nrm)
4926: {


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

4939:   (*mat->ops->norm)(mat,type,nrm);
4940:   return(0);
4941: }

4943: /*
4944:      This variable is used to prevent counting of MatAssemblyBegin() that
4945:    are called from within a MatAssemblyEnd().
4946: */
4947: static PetscInt MatAssemblyEnd_InUse = 0;
4950: /*@
4951:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
4952:    be called after completing all calls to MatSetValues().

4954:    Collective on Mat

4956:    Input Parameters:
4957: +  mat - the matrix
4958: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

4960:    Notes:
4961:    MatSetValues() generally caches the values.  The matrix is ready to
4962:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
4963:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
4964:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
4965:    using the matrix.

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

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

4975:    Level: beginner

4977:    Concepts: matrices^assembling

4979: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
4980: @*/
4981: PetscErrorCode  MatAssemblyBegin(Mat mat,MatAssemblyType type)
4982: {

4988:   MatCheckPreallocated(mat,1);
4989:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
4990:   if (mat->assembled) {
4991:     mat->was_assembled = PETSC_TRUE;
4992:     mat->assembled     = PETSC_FALSE;
4993:   }
4994:   if (!MatAssemblyEnd_InUse) {
4995:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
4996:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
4997:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
4998:   } else if (mat->ops->assemblybegin) {
4999:     (*mat->ops->assemblybegin)(mat,type);
5000:   }
5001:   return(0);
5002: }

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

5010:    Not Collective

5012:    Input Parameter:
5013: .  mat - the matrix

5015:    Output Parameter:
5016: .  assembled - PETSC_TRUE or PETSC_FALSE

5018:    Level: advanced

5020:    Concepts: matrices^assembled?

5022: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5023: @*/
5024: PetscErrorCode  MatAssembled(Mat mat,PetscBool  *assembled)
5025: {
5030:   *assembled = mat->assembled;
5031:   return(0);
5032: }

5036: /*@
5037:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5038:    be called after MatAssemblyBegin().

5040:    Collective on Mat

5042:    Input Parameters:
5043: +  mat - the matrix
5044: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5046:    Options Database Keys:
5047: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5048: .  -mat_view ::ascii_info_detail - Prints more detailed info
5049: .  -mat_view - Prints matrix in ASCII format
5050: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5051: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5052: .  -display <name> - Sets display name (default is host)
5053: .  -draw_pause <sec> - Sets number of seconds to pause after display
5054: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 11 Using MATLAB with PETSc )
5055: .  -viewer_socket_machine <machine>
5056: .  -viewer_socket_port <port>
5057: .  -mat_view binary - save matrix to file in binary format
5058: -  -viewer_binary_filename <name>

5060:    Notes:
5061:    MatSetValues() generally caches the values.  The matrix is ready to
5062:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5063:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5064:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5065:    using the matrix.

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

5071:    Level: beginner

5073: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5074: @*/
5075: PetscErrorCode  MatAssemblyEnd(Mat mat,MatAssemblyType type)
5076: {
5077:   PetscErrorCode  ierr;
5078:   static PetscInt inassm = 0;
5079:   PetscBool       flg    = PETSC_FALSE;


5085:   inassm++;
5086:   MatAssemblyEnd_InUse++;
5087:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5088:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5089:     if (mat->ops->assemblyend) {
5090:       (*mat->ops->assemblyend)(mat,type);
5091:     }
5092:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5093:   } else if (mat->ops->assemblyend) {
5094:     (*mat->ops->assemblyend)(mat,type);
5095:   }

5097:   /* Flush assembly is not a true assembly */
5098:   if (type != MAT_FLUSH_ASSEMBLY) {
5099:     mat->assembled = PETSC_TRUE; mat->num_ass++;
5100:   }
5101:   mat->insertmode = NOT_SET_VALUES;
5102:   MatAssemblyEnd_InUse--;
5103:   PetscObjectStateIncrease((PetscObject)mat);
5104:   if (!mat->symmetric_eternal) {
5105:     mat->symmetric_set              = PETSC_FALSE;
5106:     mat->hermitian_set              = PETSC_FALSE;
5107:     mat->structurally_symmetric_set = PETSC_FALSE;
5108:   }
5109: #if defined(PETSC_HAVE_CUSP)
5110:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5111:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5112:   }
5113: #endif
5114: #if defined(PETSC_HAVE_VIENNACL)
5115:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5116:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5117:   }
5118: #endif
5119:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5120:     MatViewFromOptions(mat,NULL,"-mat_view");

5122:     if (mat->checksymmetryonassembly) {
5123:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5124:       if (flg) {
5125:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5126:       } else {
5127:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5128:       }
5129:     }
5130:     if (mat->nullsp && mat->checknullspaceonassembly) {
5131:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5132:     }
5133:   }
5134:   inassm--;
5135:   return(0);
5136: }

5140: /*@
5141:    MatSetOption - Sets a parameter option for a matrix. Some options
5142:    may be specific to certain storage formats.  Some options
5143:    determine how values will be inserted (or added). Sorted,
5144:    row-oriented input will generally assemble the fastest. The default
5145:    is row-oriented.

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

5149:    Input Parameters:
5150: +  mat - the matrix
5151: .  option - the option, one of those listed below (and possibly others),
5152: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5154:   Options Describing Matrix Structure:
5155: +    MAT_SPD - symmetric positive definite
5156: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5157: .    MAT_HERMITIAN - transpose is the complex conjugation
5158: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5159: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5160:                             you set to be kept with all future use of the matrix
5161:                             including after MatAssemblyBegin/End() which could
5162:                             potentially change the symmetry structure, i.e. you
5163:                             KNOW the matrix will ALWAYS have the property you set.


5166:    Options For Use with MatSetValues():
5167:    Insert a logically dense subblock, which can be
5168: .    MAT_ROW_ORIENTED - row-oriented (default)

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

5174:    When (re)assembling a matrix, we can restrict the input for
5175:    efficiency/debugging purposes.  These options include:
5176: +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5177: .    MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5178: .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5179: .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5180: .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5181: +    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5182:         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5183:         performance for very large process counts.

5185:    Notes:
5186:    Some options are relevant only for particular matrix types and
5187:    are thus ignored by others.  Other options are not supported by
5188:    certain matrix types and will generate an error message if set.

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

5194:    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5195:    that would generate a new entry in the nonzero structure is instead
5196:    ignored.  Thus, if memory has not alredy been allocated for this particular
5197:    data, then the insertion is ignored. For dense matrices, in which
5198:    the entire array is allocated, no entries are ever ignored.
5199:    Set after the first MatAssemblyEnd()

5201:    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5202:    that would generate a new entry in the nonzero structure instead produces
5203:    an error. (Currently supported for AIJ and BAIJ formats only.)

5205:    MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5206:    that would generate a new entry that has not been preallocated will
5207:    instead produce an error. (Currently supported for AIJ and BAIJ formats
5208:    only.) This is a useful flag when debugging matrix memory preallocation.

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

5216:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5217:    searches during matrix assembly. When this flag is set, the hash table
5218:    is created during the first Matrix Assembly. This hash table is
5219:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5220:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5221:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5222:    supported by MATMPIBAIJ format only.

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

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

5230:    MAT_USE_INODES - indicates using inode version of the code - works with AIJ and
5231:    ROWBS matrix types

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

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

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

5241:    Level: intermediate

5243:    Concepts: matrices^setting options

5245: .seealso:  MatOption, Mat

5247: @*/
5248: PetscErrorCode  MatSetOption(Mat mat,MatOption op,PetscBool flg)
5249: {

5255:   if (op > 0) {
5258:   }

5260:   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);
5261:   if (!((PetscObject)mat)->type_name) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_TYPENOTSET,"Cannot set options until type and size have been set, see MatSetType() and MatSetSizes()");

5263:   switch (op) {
5264:   case MAT_NO_OFF_PROC_ENTRIES:
5265:     mat->nooffprocentries = flg;
5266:     return(0);
5267:     break;
5268:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5269:     mat->nooffproczerorows = flg;
5270:     return(0);
5271:     break;
5272:   case MAT_SPD:
5273:     mat->spd_set = PETSC_TRUE;
5274:     mat->spd     = flg;
5275:     if (flg) {
5276:       mat->symmetric                  = PETSC_TRUE;
5277:       mat->structurally_symmetric     = PETSC_TRUE;
5278:       mat->symmetric_set              = PETSC_TRUE;
5279:       mat->structurally_symmetric_set = PETSC_TRUE;
5280:     }
5281:     break;
5282:   case MAT_SYMMETRIC:
5283:     mat->symmetric = flg;
5284:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5285:     mat->symmetric_set              = PETSC_TRUE;
5286:     mat->structurally_symmetric_set = flg;
5287:     break;
5288:   case MAT_HERMITIAN:
5289:     mat->hermitian = flg;
5290:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5291:     mat->hermitian_set              = PETSC_TRUE;
5292:     mat->structurally_symmetric_set = flg;
5293:     break;
5294:   case MAT_STRUCTURALLY_SYMMETRIC:
5295:     mat->structurally_symmetric     = flg;
5296:     mat->structurally_symmetric_set = PETSC_TRUE;
5297:     break;
5298:   case MAT_SYMMETRY_ETERNAL:
5299:     mat->symmetric_eternal = flg;
5300:     break;
5301:   default:
5302:     break;
5303:   }
5304:   if (mat->ops->setoption) {
5305:     (*mat->ops->setoption)(mat,op,flg);
5306:   }
5307:   return(0);
5308: }

5312: /*@
5313:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5314:    this routine retains the old nonzero structure.

5316:    Logically Collective on Mat

5318:    Input Parameters:
5319: .  mat - the matrix

5321:    Level: intermediate

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

5326:    Concepts: matrices^zeroing

5328: .seealso: MatZeroRows()
5329: @*/
5330: PetscErrorCode  MatZeroEntries(Mat mat)
5331: {

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

5342:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5343:   (*mat->ops->zeroentries)(mat);
5344:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5345:   PetscObjectStateIncrease((PetscObject)mat);
5346: #if defined(PETSC_HAVE_CUSP)
5347:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5348:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5349:   }
5350: #endif
5351: #if defined(PETSC_HAVE_VIENNACL)
5352:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5353:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5354:   }
5355: #endif
5356:   return(0);
5357: }

5361: /*@C
5362:    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5363:    of a set of rows and columns of a matrix.

5365:    Collective on Mat

5367:    Input Parameters:
5368: +  mat - the matrix
5369: .  numRows - the number of rows to remove
5370: .  rows - the global row indices
5371: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5372: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5373: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5392:    Level: intermediate

5394:    Concepts: matrices^zeroing rows

5396: .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(), MatZeroRowsColumnsIS()
5397: @*/
5398: PetscErrorCode  MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5399: {

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

5411:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5412:   MatViewFromOptions(mat,NULL,"-mat_view");
5413:   PetscObjectStateIncrease((PetscObject)mat);
5414: #if defined(PETSC_HAVE_CUSP)
5415:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5416:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5417:   }
5418: #endif
5419: #if defined(PETSC_HAVE_VIENNACL)
5420:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5421:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5422:   }
5423: #endif
5424:   return(0);
5425: }

5429: /*@C
5430:    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5431:    of a set of rows and columns of a matrix.

5433:    Collective on Mat

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

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

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

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

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

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

5459:    Level: intermediate

5461:    Concepts: matrices^zeroing rows

5463: .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(), MatZeroRowsColumns()
5464: @*/
5465: PetscErrorCode  MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5466: {
5468:   PetscInt       numRows;
5469:   const PetscInt *rows;

5476:   ISGetLocalSize(is,&numRows);
5477:   ISGetIndices(is,&rows);
5478:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5479:   ISRestoreIndices(is,&rows);
5480:   return(0);
5481: }

5485: /*@C
5486:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5487:    of a set of rows of a matrix.

5489:    Collective on Mat

5491:    Input Parameters:
5492: +  mat - the matrix
5493: .  numRows - the number of rows to remove
5494: .  rows - the global row indices
5495: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5496: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5497: -  b - optional vector of right hand side, that will be adjusted by provided solution

5499:    Notes:
5500:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5501:    but does not release memory.  For the dense and block diagonal
5502:    formats this does not alter the nonzero structure.

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

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

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

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

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

5523:    Level: intermediate

5525:    Concepts: matrices^zeroing rows

5527: .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5528: @*/
5529: PetscErrorCode  MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5530: {

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

5542:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5543:   MatViewFromOptions(mat,NULL,"-mat_view");
5544:   PetscObjectStateIncrease((PetscObject)mat);
5545: #if defined(PETSC_HAVE_CUSP)
5546:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5547:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5548:   }
5549: #endif
5550: #if defined(PETSC_HAVE_VIENNACL)
5551:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5552:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5553:   }
5554: #endif
5555:   return(0);
5556: }

5560: /*@C
5561:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5562:    of a set of rows of a matrix.

5564:    Collective on Mat

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

5573:    Notes:
5574:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5575:    but does not release memory.  For the dense and block diagonal
5576:    formats this does not alter the nonzero structure.

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

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

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

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

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

5597:    Level: intermediate

5599:    Concepts: matrices^zeroing rows

5601: .seealso: MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5602: @*/
5603: PetscErrorCode  MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5604: {
5605:   PetscInt       numRows;
5606:   const PetscInt *rows;

5613:   ISGetLocalSize(is,&numRows);
5614:   ISGetIndices(is,&rows);
5615:   MatZeroRows(mat,numRows,rows,diag,x,b);
5616:   ISRestoreIndices(is,&rows);
5617:   return(0);
5618: }

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

5626:    Collective on Mat

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

5636:    Notes:
5637:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5638:    but does not release memory.  For the dense and block diagonal
5639:    formats this does not alter the nonzero structure.

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

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

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

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

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

5659:    In Fortran idxm and idxn should be declared as
5660: $     MatStencil idxm(4,m)
5661:    and the values inserted using
5662: $    idxm(MatStencil_i,1) = i
5663: $    idxm(MatStencil_j,1) = j
5664: $    idxm(MatStencil_k,1) = k
5665: $    idxm(MatStencil_c,1) = c
5666:    etc

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

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

5676:    Level: intermediate

5678:    Concepts: matrices^zeroing rows

5680: .seealso: MatZeroRows(), MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5681: @*/
5682: PetscErrorCode  MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5683: {
5684:   PetscInt       dim     = mat->stencil.dim;
5685:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5686:   PetscInt       *dims   = mat->stencil.dims+1;
5687:   PetscInt       *starts = mat->stencil.starts;
5688:   PetscInt       *dxm    = (PetscInt*) rows;
5689:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5697:   PetscMalloc1(numRows, &jdxm);
5698:   for (i = 0; i < numRows; ++i) {
5699:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5700:     for (j = 0; j < 3-sdim; ++j) dxm++;
5701:     /* Local index in X dir */
5702:     tmp = *dxm++ - starts[0];
5703:     /* Loop over remaining dimensions */
5704:     for (j = 0; j < dim-1; ++j) {
5705:       /* If nonlocal, set index to be negative */
5706:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5707:       /* Update local index */
5708:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5709:     }
5710:     /* Skip component slot if necessary */
5711:     if (mat->stencil.noc) dxm++;
5712:     /* Local row number */
5713:     if (tmp >= 0) {
5714:       jdxm[numNewRows++] = tmp;
5715:     }
5716:   }
5717:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5718:   PetscFree(jdxm);
5719:   return(0);
5720: }

5724: /*@C
5725:    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
5726:    of a set of rows and columns of a matrix.

5728:    Collective on Mat

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

5738:    Notes:
5739:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5740:    but does not release memory.  For the dense and block diagonal
5741:    formats this does not alter the nonzero structure.

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

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

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

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

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

5761:    In Fortran idxm and idxn should be declared as
5762: $     MatStencil idxm(4,m)
5763:    and the values inserted using
5764: $    idxm(MatStencil_i,1) = i
5765: $    idxm(MatStencil_j,1) = j
5766: $    idxm(MatStencil_k,1) = k
5767: $    idxm(MatStencil_c,1) = c
5768:    etc

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

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

5778:    Level: intermediate

5780:    Concepts: matrices^zeroing rows

5782: .seealso: MatZeroRows(), MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5783: @*/
5784: PetscErrorCode  MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5785: {
5786:   PetscInt       dim     = mat->stencil.dim;
5787:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5788:   PetscInt       *dims   = mat->stencil.dims+1;
5789:   PetscInt       *starts = mat->stencil.starts;
5790:   PetscInt       *dxm    = (PetscInt*) rows;
5791:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5799:   PetscMalloc1(numRows, &jdxm);
5800:   for (i = 0; i < numRows; ++i) {
5801:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5802:     for (j = 0; j < 3-sdim; ++j) dxm++;
5803:     /* Local index in X dir */
5804:     tmp = *dxm++ - starts[0];
5805:     /* Loop over remaining dimensions */
5806:     for (j = 0; j < dim-1; ++j) {
5807:       /* If nonlocal, set index to be negative */
5808:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5809:       /* Update local index */
5810:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5811:     }
5812:     /* Skip component slot if necessary */
5813:     if (mat->stencil.noc) dxm++;
5814:     /* Local row number */
5815:     if (tmp >= 0) {
5816:       jdxm[numNewRows++] = tmp;
5817:     }
5818:   }
5819:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
5820:   PetscFree(jdxm);
5821:   return(0);
5822: }

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

5830:    Collective on Mat

5832:    Input Parameters:
5833: +  mat - the matrix
5834: .  numRows - the number of rows to remove
5835: .  rows - the global row indices
5836: .  diag - value put in all diagonals of eliminated rows
5837: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5838: -  b - optional vector of right hand side, that will be adjusted by provided solution

5840:    Notes:
5841:    Before calling MatZeroRowsLocal(), the user must first set the
5842:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

5844:    For the AIJ matrix formats this removes the old nonzero structure,
5845:    but does not release memory.  For the dense and block diagonal
5846:    formats this does not alter the nonzero structure.

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

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

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

5859:    Level: intermediate

5861:    Concepts: matrices^zeroing

5863: .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5864: @*/
5865: PetscErrorCode  MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5866: {

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

5877:   if (mat->ops->zerorowslocal) {
5878:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
5879:   } else {
5880:     IS             is, newis;
5881:     const PetscInt *newRows;

5883:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
5884:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
5885:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
5886:     ISGetIndices(newis,&newRows);
5887:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
5888:     ISRestoreIndices(newis,&newRows);
5889:     ISDestroy(&newis);
5890:     ISDestroy(&is);
5891:   }
5892:   PetscObjectStateIncrease((PetscObject)mat);
5893: #if defined(PETSC_HAVE_CUSP)
5894:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5895:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5896:   }
5897: #endif
5898: #if defined(PETSC_HAVE_VIENNACL)
5899:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5900:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5901:   }
5902: #endif
5903:   return(0);
5904: }

5908: /*@C
5909:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
5910:    of a set of rows of a matrix; using local numbering of rows.

5912:    Collective on Mat

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

5921:    Notes:
5922:    Before calling MatZeroRowsLocalIS(), the user must first set the
5923:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

5925:    For the AIJ matrix formats this removes the old nonzero structure,
5926:    but does not release memory.  For the dense and block diagonal
5927:    formats this does not alter the nonzero structure.

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

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

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

5940:    Level: intermediate

5942:    Concepts: matrices^zeroing

5944: .seealso: MatZeroRows(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5945: @*/
5946: PetscErrorCode  MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5947: {
5949:   PetscInt       numRows;
5950:   const PetscInt *rows;

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

5960:   ISGetLocalSize(is,&numRows);
5961:   ISGetIndices(is,&rows);
5962:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
5963:   ISRestoreIndices(is,&rows);
5964:   return(0);
5965: }

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

5973:    Collective on Mat

5975:    Input Parameters:
5976: +  mat - the matrix
5977: .  numRows - the number of rows to remove
5978: .  rows - the global row indices
5979: .  diag - value put in all diagonals of eliminated rows
5980: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5981: -  b - optional vector of right hand side, that will be adjusted by provided solution

5983:    Notes:
5984:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
5985:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

5991:    Level: intermediate

5993:    Concepts: matrices^zeroing

5995: .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5996: @*/
5997: PetscErrorCode  MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5998: {
6000:   IS             is, newis;
6001:   const PetscInt *newRows;

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

6011:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6012:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6013:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6014:   ISGetIndices(newis,&newRows);
6015:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6016:   ISRestoreIndices(newis,&newRows);
6017:   ISDestroy(&newis);
6018:   ISDestroy(&is);
6019:   PetscObjectStateIncrease((PetscObject)mat);
6020: #if defined(PETSC_HAVE_CUSP)
6021:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
6022:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
6023:   }
6024: #endif
6025: #if defined(PETSC_HAVE_VIENNACL)
6026:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
6027:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
6028:   }
6029: #endif
6030:   return(0);
6031: }

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

6039:    Collective on Mat

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

6048:    Notes:
6049:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6050:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6056:    Level: intermediate

6058:    Concepts: matrices^zeroing

6060: .seealso: MatZeroRows(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
6061: @*/
6062: PetscErrorCode  MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6063: {
6065:   PetscInt       numRows;
6066:   const PetscInt *rows;

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

6076:   ISGetLocalSize(is,&numRows);
6077:   ISGetIndices(is,&rows);
6078:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6079:   ISRestoreIndices(is,&rows);
6080:   return(0);
6081: }

6085: /*@
6086:    MatGetSize - Returns the numbers of rows and columns in a matrix.

6088:    Not Collective

6090:    Input Parameter:
6091: .  mat - the matrix

6093:    Output Parameters:
6094: +  m - the number of global rows
6095: -  n - the number of global columns

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

6099:    Level: beginner

6101:    Concepts: matrices^size

6103: .seealso: MatGetLocalSize()
6104: @*/
6105: PetscErrorCode  MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6106: {
6109:   if (m) *m = mat->rmap->N;
6110:   if (n) *n = mat->cmap->N;
6111:   return(0);
6112: }

6116: /*@
6117:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6118:    stored locally.  This information may be implementation dependent, so
6119:    use with care.

6121:    Not Collective

6123:    Input Parameters:
6124: .  mat - the matrix

6126:    Output Parameters:
6127: +  m - the number of local rows
6128: -  n - the number of local columns

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

6132:    Level: beginner

6134:    Concepts: matrices^local size

6136: .seealso: MatGetSize()
6137: @*/
6138: PetscErrorCode  MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6139: {
6144:   if (m) *m = mat->rmap->n;
6145:   if (n) *n = mat->cmap->n;
6146:   return(0);
6147: }

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

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

6157:    Input Parameters:
6158: .  mat - the matrix

6160:    Output Parameters:
6161: +  m - the global index of the first local column
6162: -  n - one more than the global index of the last local column

6164:    Notes: both output parameters can be NULL on input.

6166:    Level: developer

6168:    Concepts: matrices^column ownership

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

6172: @*/
6173: PetscErrorCode  MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6174: {
6180:   MatCheckPreallocated(mat,1);
6181:   if (m) *m = mat->cmap->rstart;
6182:   if (n) *n = mat->cmap->rend;
6183:   return(0);
6184: }

6188: /*@
6189:    MatGetOwnershipRange - Returns the range of matrix rows owned by
6190:    this processor, assuming that the matrix is laid out with the first
6191:    n1 rows on the first processor, the next n2 rows on the second, etc.
6192:    For certain parallel layouts this range may not be well defined.

6194:    Not Collective

6196:    Input Parameters:
6197: .  mat - the matrix

6199:    Output Parameters:
6200: +  m - the global index of the first local row
6201: -  n - one more than the global index of the last local row

6203:    Note: Both output parameters can be NULL on input.
6204: $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6205: $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6206: $  and then MPI_Scan() to calculate prefix sums of the local sizes.

6208:    Level: beginner

6210:    Concepts: matrices^row ownership

6212: .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()

6214: @*/
6215: PetscErrorCode  MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6216: {
6222:   MatCheckPreallocated(mat,1);
6223:   if (m) *m = mat->rmap->rstart;
6224:   if (n) *n = mat->rmap->rend;
6225:   return(0);
6226: }

6230: /*@C
6231:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6232:    each process

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

6236:    Input Parameters:
6237: .  mat - the matrix

6239:    Output Parameters:
6240: .  ranges - start of each processors portion plus one more then the total length at the end

6242:    Level: beginner

6244:    Concepts: matrices^row ownership

6246: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()

6248: @*/
6249: PetscErrorCode  MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6250: {

6256:   MatCheckPreallocated(mat,1);
6257:   PetscLayoutGetRanges(mat->rmap,ranges);
6258:   return(0);
6259: }

6263: /*@C
6264:    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6265:    this processor. (The columns of the "diagonal blocks" for each process)

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

6269:    Input Parameters:
6270: .  mat - the matrix

6272:    Output Parameters:
6273: .  ranges - start of each processors portion plus one more then the total length at the end

6275:    Level: beginner

6277:    Concepts: matrices^column ownership

6279: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()

6281: @*/
6282: PetscErrorCode  MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6283: {

6289:   MatCheckPreallocated(mat,1);
6290:   PetscLayoutGetRanges(mat->cmap,ranges);
6291:   return(0);
6292: }

6296: /*@C
6297:    MatGetOwnershipIS - Get row and column ownership as index sets

6299:    Not Collective

6301:    Input Arguments:
6302: .  A - matrix of type Elemental

6304:    Output Arguments:
6305: +  rows - rows in which this process owns elements
6306: .  cols - columns in which this process owns elements

6308:    Level: intermediate

6310: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL, MatSetValues()
6311: @*/
6312: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6313: {
6314:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6317:   MatCheckPreallocated(A,1);
6318:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6319:   if (f) {
6320:     (*f)(A,rows,cols);
6321:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6322:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6323:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6324:   }
6325:   return(0);
6326: }

6330: /*@C
6331:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6332:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6333:    to complete the factorization.

6335:    Collective on Mat

6337:    Input Parameters:
6338: +  mat - the matrix
6339: .  row - row permutation
6340: .  column - column permutation
6341: -  info - structure containing
6342: $      levels - number of levels of fill.
6343: $      expected fill - as ratio of original fill.
6344: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6345:                 missing diagonal entries)

6347:    Output Parameters:
6348: .  fact - new matrix that has been symbolically factored

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

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

6356:    Level: developer

6358:   Concepts: matrices^symbolic LU factorization
6359:   Concepts: matrices^factorization
6360:   Concepts: LU^symbolic factorization

6362: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6363:           MatGetOrdering(), MatFactorInfo

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

6368: @*/
6369: PetscErrorCode  MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6370: {

6380:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6381:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6382:   if (!(fact)->ops->ilufactorsymbolic) {
6383:     const MatSolverPackage spackage;
6384:     MatFactorGetSolverPackage(fact,&spackage);
6385:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6386:   }
6387:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6388:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6389:   MatCheckPreallocated(mat,2);

6391:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6392:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6393:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6394:   return(0);
6395: }

6399: /*@C
6400:    MatICCFactorSymbolic - Performs symbolic incomplete
6401:    Cholesky factorization for a symmetric matrix.  Use
6402:    MatCholeskyFactorNumeric() to complete the factorization.

6404:    Collective on Mat

6406:    Input Parameters:
6407: +  mat - the matrix
6408: .  perm - row and column permutation
6409: -  info - structure containing
6410: $      levels - number of levels of fill.
6411: $      expected fill - as ratio of original fill.

6413:    Output Parameter:
6414: .  fact - the factored matrix

6416:    Notes:
6417:    Most users should employ the KSP interface for linear solvers
6418:    instead of working directly with matrix algebra routines such as this.
6419:    See, e.g., KSPCreate().

6421:    Level: developer

6423:   Concepts: matrices^symbolic incomplete Cholesky factorization
6424:   Concepts: matrices^factorization
6425:   Concepts: Cholsky^symbolic factorization

6427: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

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

6432: @*/
6433: PetscErrorCode  MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6434: {

6443:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6444:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6445:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6446:   if (!(fact)->ops->iccfactorsymbolic) {
6447:     const MatSolverPackage spackage;
6448:     MatFactorGetSolverPackage(fact,&spackage);
6449:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6450:   }
6451:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6452:   MatCheckPreallocated(mat,2);

6454:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6455:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6456:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6457:   return(0);
6458: }

6462: /*@C
6463:    MatGetSubMatrices - Extracts several submatrices from a matrix. If submat
6464:    points to an array of valid matrices, they may be reused to store the new
6465:    submatrices.

6467:    Collective on Mat

6469:    Input Parameters:
6470: +  mat - the matrix
6471: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6472: .  irow, icol - index sets of rows and columns to extract (must be sorted)
6473: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6475:    Output Parameter:
6476: .  submat - the array of submatrices

6478:    Notes:
6479:    MatGetSubMatrices() can extract ONLY sequential submatrices
6480:    (from both sequential and parallel matrices). Use MatGetSubMatrix()
6481:    to extract a parallel submatrix.

6483:    Currently both row and column indices must be sorted to guarantee
6484:    correctness with all matrix types.

6486:    When extracting submatrices from a parallel matrix, each processor can
6487:    form a different submatrix by setting the rows and columns of its
6488:    individual index sets according to the local submatrix desired.

6490:    When finished using the submatrices, the user should destroy
6491:    them with MatDestroyMatrices().

6493:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6494:    original matrix has not changed from that last call to MatGetSubMatrices().

6496:    This routine creates the matrices in submat; you should NOT create them before
6497:    calling it. It also allocates the array of matrix pointers submat.

6499:    For BAIJ matrices the index sets must respect the block structure, that is if they
6500:    request one row/column in a block, they must request all rows/columns that are in
6501:    that block. For example, if the block size is 2 you cannot request just row 0 and
6502:    column 0.

6504:    Fortran Note:
6505:    The Fortran interface is slightly different from that given below; it
6506:    requires one to pass in  as submat a Mat (integer) array of size at least m.

6508:    Level: advanced

6510:    Concepts: matrices^accessing submatrices
6511:    Concepts: submatrices

6513: .seealso: MatDestroyMatrices(), MatGetSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6514: @*/
6515: PetscErrorCode  MatGetSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6516: {
6518:   PetscInt       i;
6519:   PetscBool      eq;

6524:   if (n) {
6529:   }
6531:   if (n && scall == MAT_REUSE_MATRIX) {
6534:   }
6535:   if (!mat->ops->getsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6536:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6537:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6538:   MatCheckPreallocated(mat,1);

6540:   PetscLogEventBegin(MAT_GetSubMatrices,mat,0,0,0);
6541:   (*mat->ops->getsubmatrices)(mat,n,irow,icol,scall,submat);
6542:   PetscLogEventEnd(MAT_GetSubMatrices,mat,0,0,0);
6543:   for (i=0; i<n; i++) {
6544:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6545:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6546:       ISEqual(irow[i],icol[i],&eq);
6547:       if (eq) {
6548:         if (mat->symmetric) {
6549:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6550:         } else if (mat->hermitian) {
6551:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6552:         } else if (mat->structurally_symmetric) {
6553:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6554:         }
6555:       }
6556:     }
6557:   }
6558:   return(0);
6559: }

6563: PetscErrorCode  MatGetSubMatricesParallel(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6564: {
6566:   PetscInt       i;
6567:   PetscBool      eq;

6572:   if (n) {
6577:   }
6579:   if (n && scall == MAT_REUSE_MATRIX) {
6582:   }
6583:   if (!mat->ops->getsubmatricesparallel) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6584:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6585:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6586:   MatCheckPreallocated(mat,1);

6588:   PetscLogEventBegin(MAT_GetSubMatrices,mat,0,0,0);
6589:   (*mat->ops->getsubmatricesparallel)(mat,n,irow,icol,scall,submat);
6590:   PetscLogEventEnd(MAT_GetSubMatrices,mat,0,0,0);
6591:   for (i=0; i<n; i++) {
6592:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6593:       ISEqual(irow[i],icol[i],&eq);
6594:       if (eq) {
6595:         if (mat->symmetric) {
6596:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6597:         } else if (mat->hermitian) {
6598:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6599:         } else if (mat->structurally_symmetric) {
6600:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6601:         }
6602:       }
6603:     }
6604:   }
6605:   return(0);
6606: }

6610: /*@C
6611:    MatDestroyMatrices - Destroys a set of matrices obtained with MatGetSubMatrices().

6613:    Collective on Mat

6615:    Input Parameters:
6616: +  n - the number of local matrices
6617: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6618:                        sequence of MatGetSubMatrices())

6620:    Level: advanced

6622:     Notes: Frees not only the matrices, but also the array that contains the matrices
6623:            In Fortran will not free the array.

6625: .seealso: MatGetSubMatrices()
6626: @*/
6627: PetscErrorCode  MatDestroyMatrices(PetscInt n,Mat *mat[])
6628: {
6630:   PetscInt       i;

6633:   if (!*mat) return(0);
6634:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6636:   for (i=0; i<n; i++) {
6637:     MatDestroy(&(*mat)[i]);
6638:   }
6639:   /* memory is allocated even if n = 0 */
6640:   PetscFree(*mat);
6641:   *mat = NULL;
6642:   return(0);
6643: }

6647: /*@C
6648:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6650:    Collective on Mat

6652:    Input Parameters:
6653: .  mat - the matrix

6655:    Output Parameter:
6656: .  matstruct - the sequential matrix with the nonzero structure of mat

6658:   Level: intermediate

6660: .seealso: MatDestroySeqNonzeroStructure(), MatGetSubMatrices(), MatDestroyMatrices()
6661: @*/
6662: PetscErrorCode  MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6663: {


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

6674:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6675:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6676:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6677:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6678:   return(0);
6679: }

6683: /*@C
6684:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6686:    Collective on Mat

6688:    Input Parameters:
6689: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6690:                        sequence of MatGetSequentialNonzeroStructure())

6692:    Level: advanced

6694:     Notes: Frees not only the matrices, but also the array that contains the matrices

6696: .seealso: MatGetSeqNonzeroStructure()
6697: @*/
6698: PetscErrorCode  MatDestroySeqNonzeroStructure(Mat *mat)
6699: {

6704:   MatDestroy(mat);
6705:   return(0);
6706: }

6710: /*@
6711:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6712:    replaces the index sets by larger ones that represent submatrices with
6713:    additional overlap.

6715:    Collective on Mat

6717:    Input Parameters:
6718: +  mat - the matrix
6719: .  n   - the number of index sets
6720: .  is  - the array of index sets (these index sets will changed during the call)
6721: -  ov  - the additional overlap requested

6723:    Level: developer

6725:    Concepts: overlap
6726:    Concepts: ASM^computing overlap

6728: .seealso: MatGetSubMatrices()
6729: @*/
6730: PetscErrorCode  MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6731: {

6737:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6738:   if (n) {
6741:   }
6742:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6743:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6744:   MatCheckPreallocated(mat,1);

6746:   if (!ov) return(0);
6747:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6748:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6749:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
6750:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6751:   return(0);
6752: }

6756: /*@
6757:    MatGetBlockSize - Returns the matrix block size.

6759:    Not Collective

6761:    Input Parameter:
6762: .  mat - the matrix

6764:    Output Parameter:
6765: .  bs - block size

6767:    Notes:
6768:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

6770:    If the block size has not been set yet this routine returns 1.

6772:    Level: intermediate

6774:    Concepts: matrices^block size

6776: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
6777: @*/
6778: PetscErrorCode  MatGetBlockSize(Mat mat,PetscInt *bs)
6779: {
6783:   *bs = PetscAbs(mat->rmap->bs);
6784:   return(0);
6785: }

6789: /*@
6790:    MatGetBlockSizes - Returns the matrix block row and column sizes.

6792:    Not Collective

6794:    Input Parameter:
6795: .  mat - the matrix

6797:    Output Parameter:
6798: .  rbs - row block size
6799: .  cbs - coumn block size

6801:    Notes:
6802:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6803:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

6805:    If a block size has not been set yet this routine returns 1.

6807:    Level: intermediate

6809:    Concepts: matrices^block size

6811: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
6812: @*/
6813: PetscErrorCode  MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
6814: {
6819:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
6820:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
6821:   return(0);
6822: }

6826: /*@
6827:    MatSetBlockSize - Sets the matrix block size.

6829:    Logically Collective on Mat

6831:    Input Parameters:
6832: +  mat - the matrix
6833: -  bs - block size

6835:    Notes:
6836:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

6838:      This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later

6840:    Level: intermediate

6842:    Concepts: matrices^block size

6844: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
6845: @*/
6846: PetscErrorCode  MatSetBlockSize(Mat mat,PetscInt bs)
6847: {

6853:   PetscLayoutSetBlockSize(mat->rmap,bs);
6854:   PetscLayoutSetBlockSize(mat->cmap,bs);
6855:   return(0);
6856: }

6860: /*@
6861:    MatSetBlockSizes - Sets the matrix block row and column sizes.

6863:    Logically Collective on Mat

6865:    Input Parameters:
6866: +  mat - the matrix
6867: -  rbs - row block size
6868: -  cbs - column block size

6870:    Notes:
6871:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6872:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

6874:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later

6876:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

6878:    Level: intermediate

6880:    Concepts: matrices^block size

6882: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
6883: @*/
6884: PetscErrorCode  MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
6885: {

6892:   PetscLayoutSetBlockSize(mat->rmap,rbs);
6893:   PetscLayoutSetBlockSize(mat->cmap,cbs);
6894:   return(0);
6895: }

6899: /*@
6900:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

6902:    Logically Collective on Mat

6904:    Input Parameters:
6905: +  mat - the matrix
6906: .  fromRow - matrix from which to copy row block size
6907: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

6909:    Level: developer

6911:    Concepts: matrices^block size

6913: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
6914: @*/
6915: PetscErrorCode  MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
6916: {

6923:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
6924:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
6925:   return(0);
6926: }

6930: /*@
6931:    MatResidual - Default routine to calculate the residual.

6933:    Collective on Mat and Vec

6935:    Input Parameters:
6936: +  mat - the matrix
6937: .  b   - the right-hand-side
6938: -  x   - the approximate solution

6940:    Output Parameter:
6941: .  r - location to store the residual

6943:    Level: developer

6945: .keywords: MG, default, multigrid, residual

6947: .seealso: PCMGSetResidual()
6948: @*/
6949: PetscErrorCode  MatResidual(Mat mat,Vec b,Vec x,Vec r)
6950: {

6959:   MatCheckPreallocated(mat,1);
6960:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
6961:   if (!mat->ops->residual) {
6962:     MatMult(mat,x,r);
6963:     VecAYPX(r,-1.0,b);
6964:   } else {
6965:     (*mat->ops->residual)(mat,b,x,r);
6966:   }
6967:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
6968:   return(0);
6969: }

6973: /*@C
6974:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

6976:    Collective on Mat

6978:     Input Parameters:
6979: +   mat - the matrix
6980: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
6981: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
6982: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
6983:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
6984:                  always used.

6986:     Output Parameters:
6987: +   n - number of rows in the (possibly compressed) matrix
6988: .   ia - the row pointers [of length n+1]
6989: .   ja - the column indices
6990: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
6991:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

6993:     Level: developer

6995:     Notes: You CANNOT change any of the ia[] or ja[] values.

6997:            Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values

6999:     Fortran Node

7001:            In Fortran use
7002: $           PetscInt ia(1), ja(1)
7003: $           PetscOffset iia, jja
7004: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7005: $
7006: $          or
7007: $
7008: $           PetscScalar, pointer :: xx_v(:)
7009: $    call  MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)


7012:        Acess the ith and jth entries via ia(iia + i) and ja(jja + j)

7014: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7015: @*/
7016: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7017: {

7027:   MatCheckPreallocated(mat,1);
7028:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7029:   else {
7030:     *done = PETSC_TRUE;
7031:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7032:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7033:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7034:   }
7035:   return(0);
7036: }

7040: /*@C
7041:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7043:     Collective on Mat

7045:     Input Parameters:
7046: +   mat - the matrix
7047: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7048: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7049:                 symmetrized
7050: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7051:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7052:                  always used.
7053: .   n - number of columns in the (possibly compressed) matrix
7054: .   ia - the column pointers
7055: -   ja - the row indices

7057:     Output Parameters:
7058: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7060:     Note:
7061:     This routine zeros out n, ia, and ja. This is to prevent accidental
7062:     us of the array after it has been restored. If you pass NULL, it will
7063:     not zero the pointers.  Use of ia or ja after MatRestoreColumnIJ() is invalid.

7065:     Level: developer

7067: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7068: @*/
7069: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7070: {

7080:   MatCheckPreallocated(mat,1);
7081:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7082:   else {
7083:     *done = PETSC_TRUE;
7084:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7085:   }
7086:   return(0);
7087: }

7091: /*@C
7092:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7093:     MatGetRowIJ().

7095:     Collective on Mat

7097:     Input Parameters:
7098: +   mat - the matrix
7099: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7100: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7101:                 symmetrized
7102: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7103:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7104:                  always used.
7105: .   n - size of (possibly compressed) matrix
7106: .   ia - the row pointers
7107: -   ja - the column indices

7109:     Output Parameters:
7110: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7112:     Note:
7113:     This routine zeros out n, ia, and ja. This is to prevent accidental
7114:     us of the array after it has been restored. If you pass NULL, it will
7115:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7117:     Level: developer

7119: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7120: @*/
7121: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7122: {

7131:   MatCheckPreallocated(mat,1);

7133:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7134:   else {
7135:     *done = PETSC_TRUE;
7136:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7137:     if (n)  *n = 0;
7138:     if (ia) *ia = NULL;
7139:     if (ja) *ja = NULL;
7140:   }
7141:   return(0);
7142: }

7146: /*@C
7147:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7148:     MatGetColumnIJ().

7150:     Collective on Mat

7152:     Input Parameters:
7153: +   mat - the matrix
7154: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7155: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7156:                 symmetrized
7157: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7158:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7159:                  always used.

7161:     Output Parameters:
7162: +   n - size of (possibly compressed) matrix
7163: .   ia - the column pointers
7164: .   ja - the row indices
7165: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7167:     Level: developer

7169: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7170: @*/
7171: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7172: {

7181:   MatCheckPreallocated(mat,1);

7183:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7184:   else {
7185:     *done = PETSC_TRUE;
7186:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7187:     if (n)  *n = 0;
7188:     if (ia) *ia = NULL;
7189:     if (ja) *ja = NULL;
7190:   }
7191:   return(0);
7192: }

7196: /*@C
7197:     MatColoringPatch -Used inside matrix coloring routines that
7198:     use MatGetRowIJ() and/or MatGetColumnIJ().

7200:     Collective on Mat

7202:     Input Parameters:
7203: +   mat - the matrix
7204: .   ncolors - max color value
7205: .   n   - number of entries in colorarray
7206: -   colorarray - array indicating color for each column

7208:     Output Parameters:
7209: .   iscoloring - coloring generated using colorarray information

7211:     Level: developer

7213: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7215: @*/
7216: PetscErrorCode  MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7217: {

7225:   MatCheckPreallocated(mat,1);

7227:   if (!mat->ops->coloringpatch) {
7228:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7229:   } else {
7230:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7231:   }
7232:   return(0);
7233: }


7238: /*@
7239:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7241:    Logically Collective on Mat

7243:    Input Parameter:
7244: .  mat - the factored matrix to be reset

7246:    Notes:
7247:    This routine should be used only with factored matrices formed by in-place
7248:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7249:    format).  This option can save memory, for example, when solving nonlinear
7250:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7251:    ILU(0) preconditioner.

7253:    Note that one can specify in-place ILU(0) factorization by calling
7254: .vb
7255:      PCType(pc,PCILU);
7256:      PCFactorSeUseInPlace(pc);
7257: .ve
7258:    or by using the options -pc_type ilu -pc_factor_in_place

7260:    In-place factorization ILU(0) can also be used as a local
7261:    solver for the blocks within the block Jacobi or additive Schwarz
7262:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7263:    for details on setting local solver options.

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

7269:    Level: developer

7271: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7273:    Concepts: matrices^unfactored

7275: @*/
7276: PetscErrorCode  MatSetUnfactored(Mat mat)
7277: {

7283:   MatCheckPreallocated(mat,1);
7284:   mat->factortype = MAT_FACTOR_NONE;
7285:   if (!mat->ops->setunfactored) return(0);
7286:   (*mat->ops->setunfactored)(mat);
7287:   return(0);
7288: }

7290: /*MC
7291:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7293:     Synopsis:
7294:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7296:     Not collective

7298:     Input Parameter:
7299: .   x - matrix

7301:     Output Parameters:
7302: +   xx_v - the Fortran90 pointer to the array
7303: -   ierr - error code

7305:     Example of Usage:
7306: .vb
7307:       PetscScalar, pointer xx_v(:,:)
7308:       ....
7309:       call MatDenseGetArrayF90(x,xx_v,ierr)
7310:       a = xx_v(3)
7311:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7312: .ve

7314:     Level: advanced

7316: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7318:     Concepts: matrices^accessing array

7320: M*/

7322: /*MC
7323:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7324:     accessed with MatDenseGetArrayF90().

7326:     Synopsis:
7327:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7329:     Not collective

7331:     Input Parameters:
7332: +   x - matrix
7333: -   xx_v - the Fortran90 pointer to the array

7335:     Output Parameter:
7336: .   ierr - error code

7338:     Example of Usage:
7339: .vb
7340:        PetscScalar, pointer xx_v(:)
7341:        ....
7342:        call MatDenseGetArrayF90(x,xx_v,ierr)
7343:        a = xx_v(3)
7344:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7345: .ve

7347:     Level: advanced

7349: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7351: M*/


7354: /*MC
7355:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7357:     Synopsis:
7358:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7360:     Not collective

7362:     Input Parameter:
7363: .   x - matrix

7365:     Output Parameters:
7366: +   xx_v - the Fortran90 pointer to the array
7367: -   ierr - error code

7369:     Example of Usage:
7370: .vb
7371:       PetscScalar, pointer xx_v(:,:)
7372:       ....
7373:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7374:       a = xx_v(3)
7375:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7376: .ve

7378:     Level: advanced

7380: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7382:     Concepts: matrices^accessing array

7384: M*/

7386: /*MC
7387:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7388:     accessed with MatSeqAIJGetArrayF90().

7390:     Synopsis:
7391:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7393:     Not collective

7395:     Input Parameters:
7396: +   x - matrix
7397: -   xx_v - the Fortran90 pointer to the array

7399:     Output Parameter:
7400: .   ierr - error code

7402:     Example of Usage:
7403: .vb
7404:        PetscScalar, pointer xx_v(:)
7405:        ....
7406:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7407:        a = xx_v(3)
7408:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7409: .ve

7411:     Level: advanced

7413: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7415: M*/


7420: /*@
7421:     MatGetSubMatrix - Gets a single submatrix on the same number of processors
7422:                       as the original matrix.

7424:     Collective on Mat

7426:     Input Parameters:
7427: +   mat - the original matrix
7428: .   isrow - parallel IS containing the rows this processor should obtain
7429: .   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.
7430: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7432:     Output Parameter:
7433: .   newmat - the new submatrix, of the same type as the old

7435:     Level: advanced

7437:     Notes:
7438:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7440:     The rows in isrow will be sorted into the same order as the original matrix on each process.

7442:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7443:    the MatGetSubMatrix() routine will create the newmat for you. Any additional calls
7444:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7445:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7446:    you are finished using it.

7448:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7449:     the input matrix.

7451:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7453:    Example usage:
7454:    Consider the following 8x8 matrix with 34 non-zero values, that is
7455:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7456:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7457:    as follows:

7459: .vb
7460:             1  2  0  |  0  3  0  |  0  4
7461:     Proc0   0  5  6  |  7  0  0  |  8  0
7462:             9  0 10  | 11  0  0  | 12  0
7463:     -------------------------------------
7464:            13  0 14  | 15 16 17  |  0  0
7465:     Proc1   0 18  0  | 19 20 21  |  0  0
7466:             0  0  0  | 22 23  0  | 24  0
7467:     -------------------------------------
7468:     Proc2  25 26 27  |  0  0 28  | 29  0
7469:            30  0  0  | 31 32 33  |  0 34
7470: .ve

7472:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7474: .vb
7475:             2  0  |  0  3  0  |  0
7476:     Proc0   5  6  |  7  0  0  |  8
7477:     -------------------------------
7478:     Proc1  18  0  | 19 20 21  |  0
7479:     -------------------------------
7480:     Proc2  26 27  |  0  0 28  | 29
7481:             0  0  | 31 32 33  |  0
7482: .ve


7485:     Concepts: matrices^submatrices

7487: .seealso: MatGetSubMatrices()
7488: @*/
7489: PetscErrorCode  MatGetSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7490: {
7492:   PetscMPIInt    size;
7493:   Mat            *local;
7494:   IS             iscoltmp;

7503:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7504:   MatCheckPreallocated(mat,1);
7505:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7507:   if (!iscol || isrow == iscol) {
7508:     PetscBool stride;
7509:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7510:     if (stride) {
7511:       PetscInt first,step,n,rstart,rend;
7512:       ISStrideGetInfo(isrow,&first,&step);
7513:       if (step == 1) {
7514:         MatGetOwnershipRange(mat,&rstart,&rend);
7515:         if (rstart == first) {
7516:           ISGetLocalSize(isrow,&n);
7517:           if (n == rend-rstart) {
7518:             /* special case grabbing all rows; NEED to do a global reduction to make sure all processes are doing this */
7519:             if (cll == MAT_INITIAL_MATRIX) {
7520:               *newmat = mat;
7521:               PetscObjectReference((PetscObject)mat);
7522:             }
7523:             return(0);
7524:           }
7525:         }
7526:       }
7527:     }
7528:   }

7530:   if (!iscol) {
7531:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7532:   } else {
7533:     iscoltmp = iscol;
7534:   }

7536:   /* if original matrix is on just one processor then use submatrix generated */
7537:   if (mat->ops->getsubmatrices && !mat->ops->getsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7538:     MatGetSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7539:     if (!iscol) {ISDestroy(&iscoltmp);}
7540:     return(0);
7541:   } else if (mat->ops->getsubmatrices && !mat->ops->getsubmatrix && size == 1) {
7542:     MatGetSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7543:     *newmat = *local;
7544:     PetscFree(local);
7545:     if (!iscol) {ISDestroy(&iscoltmp);}
7546:     return(0);
7547:   } else if (!mat->ops->getsubmatrix) {
7548:     /* Create a new matrix type that implements the operation using the full matrix */
7549:     PetscLogEventBegin(MAT_GetSubMatrix,mat,0,0,0);
7550:     switch (cll) {
7551:     case MAT_INITIAL_MATRIX:
7552:       MatCreateSubMatrix(mat,isrow,iscoltmp,newmat);
7553:       break;
7554:     case MAT_REUSE_MATRIX:
7555:       MatSubMatrixUpdate(*newmat,mat,isrow,iscoltmp);
7556:       break;
7557:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7558:     }
7559:     PetscLogEventEnd(MAT_GetSubMatrix,mat,0,0,0);
7560:     if (!iscol) {ISDestroy(&iscoltmp);}
7561:     return(0);
7562:   }

7564:   if (!mat->ops->getsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7565:   PetscLogEventBegin(MAT_GetSubMatrix,mat,0,0,0);
7566:   (*mat->ops->getsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7567:   PetscLogEventEnd(MAT_GetSubMatrix,mat,0,0,0);
7568:   if (!iscol) {ISDestroy(&iscoltmp);}
7569:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7570:   return(0);
7571: }

7575: /*@
7576:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7577:    used during the assembly process to store values that belong to
7578:    other processors.

7580:    Not Collective

7582:    Input Parameters:
7583: +  mat   - the matrix
7584: .  size  - the initial size of the stash.
7585: -  bsize - the initial size of the block-stash(if used).

7587:    Options Database Keys:
7588: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7589: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7591:    Level: intermediate

7593:    Notes:
7594:      The block-stash is used for values set with MatSetValuesBlocked() while
7595:      the stash is used for values set with MatSetValues()

7597:      Run with the option -info and look for output of the form
7598:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7599:      to determine the appropriate value, MM, to use for size and
7600:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7601:      to determine the value, BMM to use for bsize

7603:    Concepts: stash^setting matrix size
7604:    Concepts: matrices^stash

7606: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

7608: @*/
7609: PetscErrorCode  MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7610: {

7616:   MatStashSetInitialSize_Private(&mat->stash,size);
7617:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
7618:   return(0);
7619: }

7623: /*@
7624:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7625:      the matrix

7627:    Neighbor-wise Collective on Mat

7629:    Input Parameters:
7630: +  mat   - the matrix
7631: .  x,y - the vectors
7632: -  w - where the result is stored

7634:    Level: intermediate

7636:    Notes:
7637:     w may be the same vector as y.

7639:     This allows one to use either the restriction or interpolation (its transpose)
7640:     matrix to do the interpolation

7642:     Concepts: interpolation

7644: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

7646: @*/
7647: PetscErrorCode  MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
7648: {
7650:   PetscInt       M,N,Ny;

7658:   MatCheckPreallocated(A,1);
7659:   MatGetSize(A,&M,&N);
7660:   VecGetSize(y,&Ny);
7661:   if (M == Ny) {
7662:     MatMultAdd(A,x,y,w);
7663:   } else {
7664:     MatMultTransposeAdd(A,x,y,w);
7665:   }
7666:   return(0);
7667: }

7671: /*@
7672:    MatInterpolate - y = A*x or A'*x depending on the shape of
7673:      the matrix

7675:    Neighbor-wise Collective on Mat

7677:    Input Parameters:
7678: +  mat   - the matrix
7679: -  x,y - the vectors

7681:    Level: intermediate

7683:    Notes:
7684:     This allows one to use either the restriction or interpolation (its transpose)
7685:     matrix to do the interpolation

7687:    Concepts: matrices^interpolation

7689: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

7691: @*/
7692: PetscErrorCode  MatInterpolate(Mat A,Vec x,Vec y)
7693: {
7695:   PetscInt       M,N,Ny;

7702:   MatCheckPreallocated(A,1);
7703:   MatGetSize(A,&M,&N);
7704:   VecGetSize(y,&Ny);
7705:   if (M == Ny) {
7706:     MatMult(A,x,y);
7707:   } else {
7708:     MatMultTranspose(A,x,y);
7709:   }
7710:   return(0);
7711: }

7715: /*@
7716:    MatRestrict - y = A*x or A'*x

7718:    Neighbor-wise Collective on Mat

7720:    Input Parameters:
7721: +  mat   - the matrix
7722: -  x,y - the vectors

7724:    Level: intermediate

7726:    Notes:
7727:     This allows one to use either the restriction or interpolation (its transpose)
7728:     matrix to do the restriction

7730:    Concepts: matrices^restriction

7732: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

7734: @*/
7735: PetscErrorCode  MatRestrict(Mat A,Vec x,Vec y)
7736: {
7738:   PetscInt       M,N,Ny;

7745:   MatCheckPreallocated(A,1);

7747:   MatGetSize(A,&M,&N);
7748:   VecGetSize(y,&Ny);
7749:   if (M == Ny) {
7750:     MatMult(A,x,y);
7751:   } else {
7752:     MatMultTranspose(A,x,y);
7753:   }
7754:   return(0);
7755: }

7759: /*@
7760:    MatGetNullSpace - retrieves the null space to a matrix.

7762:    Logically Collective on Mat and MatNullSpace

7764:    Input Parameters:
7765: +  mat - the matrix
7766: -  nullsp - the null space object

7768:    Level: developer

7770:    Notes:
7771:       This null space is used by solvers. Overwrites any previous null space that may have been attached

7773:    Concepts: null space^attaching to matrix

7775: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace()
7776: @*/
7777: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
7778: {
7783:   *nullsp = mat->nullsp;
7784:   return(0);
7785: }

7789: /*@
7790:    MatSetNullSpace - attaches a null space to a matrix.
7791:         This null space will be removed from the resulting vector whenever
7792:         MatMult() is called

7794:    Logically Collective on Mat and MatNullSpace

7796:    Input Parameters:
7797: +  mat - the matrix
7798: -  nullsp - the null space object

7800:    Level: advanced

7802:    Notes:
7803:       This null space is used by solvers. Overwrites any previous null space that may have been attached

7805:    Concepts: null space^attaching to matrix

7807: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace()
7808: @*/
7809: PetscErrorCode  MatSetNullSpace(Mat mat,MatNullSpace nullsp)
7810: {

7817:   MatCheckPreallocated(mat,1);
7818:   PetscObjectReference((PetscObject)nullsp);
7819:   MatNullSpaceDestroy(&mat->nullsp);

7821:   mat->nullsp = nullsp;
7822:   return(0);
7823: }

7827: /*@
7828:    MatSetNearNullSpace - attaches a null space to a matrix.
7829:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

7831:    Logically Collective on Mat and MatNullSpace

7833:    Input Parameters:
7834: +  mat - the matrix
7835: -  nullsp - the null space object

7837:    Level: advanced

7839:    Notes:
7840:       Overwrites any previous near null space that may have been attached

7842:    Concepts: null space^attaching to matrix

7844: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace()
7845: @*/
7846: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
7847: {

7854:   MatCheckPreallocated(mat,1);
7855:   PetscObjectReference((PetscObject)nullsp);
7856:   MatNullSpaceDestroy(&mat->nearnullsp);

7858:   mat->nearnullsp = nullsp;
7859:   return(0);
7860: }

7864: /*@
7865:    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()

7867:    Not Collective

7869:    Input Parameters:
7870: .  mat - the matrix

7872:    Output Parameters:
7873: .  nullsp - the null space object, NULL if not set

7875:    Level: developer

7877:    Concepts: null space^attaching to matrix

7879: .seealso: MatSetNearNullSpace(), MatGetNullSpace()
7880: @*/
7881: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
7882: {
7887:   MatCheckPreallocated(mat,1);
7888:   *nullsp = mat->nearnullsp;
7889:   return(0);
7890: }

7894: /*@C
7895:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

7897:    Collective on Mat

7899:    Input Parameters:
7900: +  mat - the matrix
7901: .  row - row/column permutation
7902: .  fill - expected fill factor >= 1.0
7903: -  level - level of fill, for ICC(k)

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

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

7913:    Level: developer

7915:    Concepts: matrices^incomplete Cholesky factorization
7916:    Concepts: Cholesky factorization

7918: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

7923: @*/
7924: PetscErrorCode  MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
7925: {

7933:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
7934:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7935:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7936:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7937:   MatCheckPreallocated(mat,1);
7938:   (*mat->ops->iccfactor)(mat,row,info);
7939:   PetscObjectStateIncrease((PetscObject)mat);
7940:   return(0);
7941: }

7945: /*@
7946:    MatSetValuesAdifor - Sets values computed with automatic differentiation into a matrix.

7948:    Not Collective

7950:    Input Parameters:
7951: +  mat - the matrix
7952: .  nl - leading dimension of v
7953: -  v - the values compute with ADIFOR

7955:    Level: developer

7957:    Notes:
7958:      Must call MatSetColoring() before using this routine. Also this matrix must already
7959:      have its nonzero pattern determined.

7961: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
7962:           MatSetValues(), MatSetColoring()
7963: @*/
7964: PetscErrorCode  MatSetValuesAdifor(Mat mat,PetscInt nl,void *v)
7965: {


7973:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
7974:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
7975:   if (!mat->ops->setvaluesadifor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7976:   (*mat->ops->setvaluesadifor)(mat,nl,v);
7977:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
7978:   PetscObjectStateIncrease((PetscObject)mat);
7979:   return(0);
7980: }

7984: /*@
7985:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
7986:          ghosted ones.

7988:    Not Collective

7990:    Input Parameters:
7991: +  mat - the matrix
7992: -  diag = the diagonal values, including ghost ones

7994:    Level: developer

7996:    Notes: Works only for MPIAIJ and MPIBAIJ matrices

7998: .seealso: MatDiagonalScale()
7999: @*/
8000: PetscErrorCode  MatDiagonalScaleLocal(Mat mat,Vec diag)
8001: {
8003:   PetscMPIInt    size;


8010:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8011:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8012:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8013:   if (size == 1) {
8014:     PetscInt n,m;
8015:     VecGetSize(diag,&n);
8016:     MatGetSize(mat,0,&m);
8017:     if (m == n) {
8018:       MatDiagonalScale(mat,0,diag);
8019:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8020:   } else {
8021:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8022:   }
8023:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8024:   PetscObjectStateIncrease((PetscObject)mat);
8025:   return(0);
8026: }

8030: /*@
8031:    MatGetInertia - Gets the inertia from a factored matrix

8033:    Collective on Mat

8035:    Input Parameter:
8036: .  mat - the matrix

8038:    Output Parameters:
8039: +   nneg - number of negative eigenvalues
8040: .   nzero - number of zero eigenvalues
8041: -   npos - number of positive eigenvalues

8043:    Level: advanced

8045:    Notes: Matrix must have been factored by MatCholeskyFactor()


8048: @*/
8049: PetscErrorCode  MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8050: {

8056:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8057:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8058:   if (!mat->ops->getinertia) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8059:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8060:   return(0);
8061: }

8063: /* ----------------------------------------------------------------*/
8066: /*@C
8067:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8069:    Neighbor-wise Collective on Mat and Vecs

8071:    Input Parameters:
8072: +  mat - the factored matrix
8073: -  b - the right-hand-side vectors

8075:    Output Parameter:
8076: .  x - the result vectors

8078:    Notes:
8079:    The vectors b and x cannot be the same.  I.e., one cannot
8080:    call MatSolves(A,x,x).

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

8087:    Level: developer

8089:    Concepts: matrices^triangular solves

8091: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8092: @*/
8093: PetscErrorCode  MatSolves(Mat mat,Vecs b,Vecs x)
8094: {

8100:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8101:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8102:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8104:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8105:   MatCheckPreallocated(mat,1);
8106:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8107:   (*mat->ops->solves)(mat,b,x);
8108:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8109:   return(0);
8110: }

8114: /*@
8115:    MatIsSymmetric - Test whether a matrix is symmetric

8117:    Collective on Mat

8119:    Input Parameter:
8120: +  A - the matrix to test
8121: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8123:    Output Parameters:
8124: .  flg - the result

8126:    Notes: For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8128:    Level: intermediate

8130:    Concepts: matrix^symmetry

8132: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8133: @*/
8134: PetscErrorCode  MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8135: {


8142:   if (!A->symmetric_set) {
8143:     if (!A->ops->issymmetric) {
8144:       MatType mattype;
8145:       MatGetType(A,&mattype);
8146:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8147:     }
8148:     (*A->ops->issymmetric)(A,tol,flg);
8149:     if (!tol) {
8150:       A->symmetric_set = PETSC_TRUE;
8151:       A->symmetric     = *flg;
8152:       if (A->symmetric) {
8153:         A->structurally_symmetric_set = PETSC_TRUE;
8154:         A->structurally_symmetric     = PETSC_TRUE;
8155:       }
8156:     }
8157:   } else if (A->symmetric) {
8158:     *flg = PETSC_TRUE;
8159:   } else if (!tol) {
8160:     *flg = PETSC_FALSE;
8161:   } else {
8162:     if (!A->ops->issymmetric) {
8163:       MatType mattype;
8164:       MatGetType(A,&mattype);
8165:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8166:     }
8167:     (*A->ops->issymmetric)(A,tol,flg);
8168:   }
8169:   return(0);
8170: }

8174: /*@
8175:    MatIsHermitian - Test whether a matrix is Hermitian

8177:    Collective on Mat

8179:    Input Parameter:
8180: +  A - the matrix to test
8181: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8183:    Output Parameters:
8184: .  flg - the result

8186:    Level: intermediate

8188:    Concepts: matrix^symmetry

8190: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8191:           MatIsSymmetricKnown(), MatIsSymmetric()
8192: @*/
8193: PetscErrorCode  MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8194: {


8201:   if (!A->hermitian_set) {
8202:     if (!A->ops->ishermitian) {
8203:       MatType mattype;
8204:       MatGetType(A,&mattype);
8205:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8206:     }
8207:     (*A->ops->ishermitian)(A,tol,flg);
8208:     if (!tol) {
8209:       A->hermitian_set = PETSC_TRUE;
8210:       A->hermitian     = *flg;
8211:       if (A->hermitian) {
8212:         A->structurally_symmetric_set = PETSC_TRUE;
8213:         A->structurally_symmetric     = PETSC_TRUE;
8214:       }
8215:     }
8216:   } else if (A->hermitian) {
8217:     *flg = PETSC_TRUE;
8218:   } else if (!tol) {
8219:     *flg = PETSC_FALSE;
8220:   } else {
8221:     if (!A->ops->ishermitian) {
8222:       MatType mattype;
8223:       MatGetType(A,&mattype);
8224:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8225:     }
8226:     (*A->ops->ishermitian)(A,tol,flg);
8227:   }
8228:   return(0);
8229: }

8233: /*@
8234:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8236:    Not Collective

8238:    Input Parameter:
8239: .  A - the matrix to check

8241:    Output Parameters:
8242: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8243: -  flg - the result

8245:    Level: advanced

8247:    Concepts: matrix^symmetry

8249:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8250:          if you want it explicitly checked

8252: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8253: @*/
8254: PetscErrorCode  MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8255: {
8260:   if (A->symmetric_set) {
8261:     *set = PETSC_TRUE;
8262:     *flg = A->symmetric;
8263:   } else {
8264:     *set = PETSC_FALSE;
8265:   }
8266:   return(0);
8267: }

8271: /*@
8272:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8274:    Not Collective

8276:    Input Parameter:
8277: .  A - the matrix to check

8279:    Output Parameters:
8280: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8281: -  flg - the result

8283:    Level: advanced

8285:    Concepts: matrix^symmetry

8287:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8288:          if you want it explicitly checked

8290: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8291: @*/
8292: PetscErrorCode  MatIsHermitianKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8293: {
8298:   if (A->hermitian_set) {
8299:     *set = PETSC_TRUE;
8300:     *flg = A->hermitian;
8301:   } else {
8302:     *set = PETSC_FALSE;
8303:   }
8304:   return(0);
8305: }

8309: /*@
8310:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8312:    Collective on Mat

8314:    Input Parameter:
8315: .  A - the matrix to test

8317:    Output Parameters:
8318: .  flg - the result

8320:    Level: intermediate

8322:    Concepts: matrix^symmetry

8324: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8325: @*/
8326: PetscErrorCode  MatIsStructurallySymmetric(Mat A,PetscBool  *flg)
8327: {

8333:   if (!A->structurally_symmetric_set) {
8334:     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8335:     (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);

8337:     A->structurally_symmetric_set = PETSC_TRUE;
8338:   }
8339:   *flg = A->structurally_symmetric;
8340:   return(0);
8341: }

8345: extern PetscErrorCode MatStashGetInfo_Private(MatStash*,PetscInt*,PetscInt*);
8346: /*@
8347:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8348:        to be communicated to other processors during the MatAssemblyBegin/End() process

8350:     Not collective

8352:    Input Parameter:
8353: .   vec - the vector

8355:    Output Parameters:
8356: +   nstash   - the size of the stash
8357: .   reallocs - the number of additional mallocs incurred.
8358: .   bnstash   - the size of the block stash
8359: -   breallocs - the number of additional mallocs incurred.in the block stash

8361:    Level: advanced

8363: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8365: @*/
8366: PetscErrorCode  MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8367: {

8371:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8372:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8373:   return(0);
8374: }

8378: /*@C
8379:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8380:      parallel layout

8382:    Collective on Mat

8384:    Input Parameter:
8385: .  mat - the matrix

8387:    Output Parameter:
8388: +   right - (optional) vector that the matrix can be multiplied against
8389: -   left - (optional) vector that the matrix vector product can be stored in

8391:    Notes:
8392:     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().

8394:   Notes: These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8396:   Level: advanced

8398: .seealso: MatCreate(), VecDestroy()
8399: @*/
8400: PetscErrorCode  MatCreateVecs(Mat mat,Vec *right,Vec *left)
8401: {

8407:   MatCheckPreallocated(mat,1);
8408:   if (mat->ops->getvecs) {
8409:     (*mat->ops->getvecs)(mat,right,left);
8410:   } else {
8411:     PetscMPIInt size;
8412:     PetscInt    rbs,cbs;
8413:     MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size);
8414:     MatGetBlockSizes(mat,&rbs,&cbs);
8415:     if (right) {
8416:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8417:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8418:       VecSetBlockSize(*right,cbs);
8419:       VecSetType(*right,VECSTANDARD);
8420:       PetscLayoutReference(mat->cmap,&(*right)->map);
8421:     }
8422:     if (left) {
8423:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8424:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8425:       VecSetBlockSize(*left,rbs);
8426:       VecSetType(*left,VECSTANDARD);
8427:       PetscLayoutReference(mat->rmap,&(*left)->map);
8428:     }
8429:   }
8430:   return(0);
8431: }

8435: /*@C
8436:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8437:      with default values.

8439:    Not Collective

8441:    Input Parameters:
8442: .    info - the MatFactorInfo data structure


8445:    Notes: The solvers are generally used through the KSP and PC objects, for example
8446:           PCLU, PCILU, PCCHOLESKY, PCICC

8448:    Level: developer

8450: .seealso: MatFactorInfo

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

8455: @*/

8457: PetscErrorCode  MatFactorInfoInitialize(MatFactorInfo *info)
8458: {

8462:   PetscMemzero(info,sizeof(MatFactorInfo));
8463:   return(0);
8464: }

8468: /*@
8469:    MatPtAP - Creates the matrix product C = P^T * A * P

8471:    Neighbor-wise Collective on Mat

8473:    Input Parameters:
8474: +  A - the matrix
8475: .  P - the projection matrix
8476: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8477: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P))

8479:    Output Parameters:
8480: .  C - the product matrix

8482:    Notes:
8483:    C will be created and must be destroyed by the user with MatDestroy().

8485:    This routine is currently only implemented for pairs of AIJ matrices and classes
8486:    which inherit from AIJ.

8488:    Level: intermediate

8490: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
8491: @*/
8492: PetscErrorCode  MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
8493: {
8495:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
8496:   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
8497:   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
8498:   PetscBool      viatranspose=PETSC_FALSE,viamatmatmatmult=PETSC_FALSE;

8501:   PetscOptionsGetBool(((PetscObject)A)->prefix,"-matptap_viatranspose",&viatranspose,NULL);
8502:   PetscOptionsGetBool(((PetscObject)A)->prefix,"-matptap_viamatmatmatmult",&viamatmatmatmult,NULL);

8506:   MatCheckPreallocated(A,1);
8507:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8508:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8511:   MatCheckPreallocated(P,2);
8512:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8513:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8515:   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
8516:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

8518:   if (scall == MAT_REUSE_MATRIX) {
8521:     if (viatranspose || viamatmatmatmult) {
8522:       Mat Pt;
8523:       MatTranspose(P,MAT_INITIAL_MATRIX,&Pt);
8524:       if (viamatmatmatmult) {
8525:         MatMatMatMult(Pt,A,P,scall,fill,C);
8526:       } else {
8527:         Mat AP;
8528:         MatMatMult(A,P,MAT_INITIAL_MATRIX,fill,&AP);
8529:         MatMatMult(Pt,AP,scall,fill,C);
8530:         MatDestroy(&AP);
8531:       }
8532:       MatDestroy(&Pt);
8533:     } else {
8534:       PetscLogEventBegin(MAT_PtAP,A,P,0,0);
8535:       PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
8536:       (*(*C)->ops->ptapnumeric)(A,P,*C);
8537:       PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
8538:       PetscLogEventEnd(MAT_PtAP,A,P,0,0);
8539:     }
8540:     return(0);
8541:   }

8543:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
8544:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

8546:   fA = A->ops->ptap;
8547:   fP = P->ops->ptap;
8548:   if (fP == fA) {
8549:     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatPtAP not supported for A of type %s",((PetscObject)A)->type_name);
8550:     ptap = fA;
8551:   } else {
8552:     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
8553:     char ptapname[256];
8554:     PetscStrcpy(ptapname,"MatPtAP_");
8555:     PetscStrcat(ptapname,((PetscObject)A)->type_name);
8556:     PetscStrcat(ptapname,"_");
8557:     PetscStrcat(ptapname,((PetscObject)P)->type_name);
8558:     PetscStrcat(ptapname,"_C"); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
8559:     PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
8560:     if (!ptap) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatPtAP requires A, %s, to be compatible with P, %s",((PetscObject)A)->type_name,((PetscObject)P)->type_name);
8561:   }

8563:   if (viatranspose || viamatmatmatmult) {
8564:     Mat Pt;
8565:     MatTranspose(P,MAT_INITIAL_MATRIX,&Pt);
8566:     if (viamatmatmatmult) {
8567:       MatMatMatMult(Pt,A,P,scall,fill,C);
8568:       PetscInfo(*C,"MatPtAP via MatMatMatMult\n");
8569:     } else {
8570:       Mat AP;
8571:       MatMatMult(A,P,MAT_INITIAL_MATRIX,fill,&AP);
8572:       MatMatMult(Pt,AP,scall,fill,C);
8573:       MatDestroy(&AP);
8574:       PetscInfo(*C,"MatPtAP via MatTranspose and MatMatMult\n");
8575:     }
8576:     MatDestroy(&Pt);
8577:   } else {
8578:     PetscLogEventBegin(MAT_PtAP,A,P,0,0);
8579:     (*ptap)(A,P,scall,fill,C);
8580:     PetscLogEventEnd(MAT_PtAP,A,P,0,0);
8581:   }
8582:   return(0);
8583: }

8587: /*@
8588:    MatPtAPNumeric - Computes the matrix product C = P^T * A * P

8590:    Neighbor-wise Collective on Mat

8592:    Input Parameters:
8593: +  A - the matrix
8594: -  P - the projection matrix

8596:    Output Parameters:
8597: .  C - the product matrix

8599:    Notes:
8600:    C must have been created by calling MatPtAPSymbolic and must be destroyed by
8601:    the user using MatDeatroy().

8603:    This routine is currently only implemented for pairs of AIJ matrices and classes
8604:    which inherit from AIJ.  C will be of type MATAIJ.

8606:    Level: intermediate

8608: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
8609: @*/
8610: PetscErrorCode  MatPtAPNumeric(Mat A,Mat P,Mat C)
8611: {

8617:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8618:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8621:   MatCheckPreallocated(P,2);
8622:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8623:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8626:   MatCheckPreallocated(C,3);
8627:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8628:   if (P->cmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->rmap->N);
8629:   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
8630:   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8631:   if (P->cmap->N!=C->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->cmap->N);
8632:   MatCheckPreallocated(A,1);

8634:   PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
8635:   (*C->ops->ptapnumeric)(A,P,C);
8636:   PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
8637:   return(0);
8638: }

8642: /*@
8643:    MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P

8645:    Neighbor-wise Collective on Mat

8647:    Input Parameters:
8648: +  A - the matrix
8649: -  P - the projection matrix

8651:    Output Parameters:
8652: .  C - the (i,j) structure of the product matrix

8654:    Notes:
8655:    C will be created and must be destroyed by the user with MatDestroy().

8657:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
8658:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
8659:    this (i,j) structure by calling MatPtAPNumeric().

8661:    Level: intermediate

8663: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
8664: @*/
8665: PetscErrorCode  MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
8666: {

8672:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8673:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8674:   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8677:   MatCheckPreallocated(P,2);
8678:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8679:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8682:   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
8683:   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8684:   MatCheckPreallocated(A,1);
8685:   PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);
8686:   (*A->ops->ptapsymbolic)(A,P,fill,C);
8687:   PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);

8689:   /* MatSetBlockSize(*C,A->rmap->bs); NO! this is not always true -ma */
8690:   return(0);
8691: }

8695: /*@
8696:    MatRARt - Creates the matrix product C = R * A * R^T

8698:    Neighbor-wise Collective on Mat

8700:    Input Parameters:
8701: +  A - the matrix
8702: .  R - the projection matrix
8703: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8704: -  fill - expected fill as ratio of nnz(C)/nnz(A)

8706:    Output Parameters:
8707: .  C - the product matrix

8709:    Notes:
8710:    C will be created and must be destroyed by the user with MatDestroy().

8712:    This routine is currently only implemented for pairs of AIJ matrices and classes
8713:    which inherit from AIJ.

8715:    Level: intermediate

8717: .seealso: MatRARtSymbolic(), MatRARtNumeric(), MatMatMult(), MatPtAP()
8718: @*/
8719: PetscErrorCode  MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
8720: {

8726:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8727:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8730:   MatCheckPreallocated(R,2);
8731:   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8732:   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8734:   if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)R),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
8735:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8736:   MatCheckPreallocated(A,1);

8738:   if (!A->ops->rart) {
8739:     MatType mattype;
8740:     MatGetType(A,&mattype);
8741:     SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type <%s> does not support RARt",mattype);
8742:   }
8743:   PetscLogEventBegin(MAT_RARt,A,R,0,0);
8744:   (*A->ops->rart)(A,R,scall,fill,C);
8745:   PetscLogEventEnd(MAT_RARt,A,R,0,0);
8746:   return(0);
8747: }

8751: /*@
8752:    MatRARtNumeric - Computes the matrix product C = R * A * R^T

8754:    Neighbor-wise Collective on Mat

8756:    Input Parameters:
8757: +  A - the matrix
8758: -  R - the projection matrix

8760:    Output Parameters:
8761: .  C - the product matrix

8763:    Notes:
8764:    C must have been created by calling MatRARtSymbolic and must be destroyed by
8765:    the user using MatDeatroy().

8767:    This routine is currently only implemented for pairs of AIJ matrices and classes
8768:    which inherit from AIJ.  C will be of type MATAIJ.

8770:    Level: intermediate

8772: .seealso: MatRARt(), MatRARtSymbolic(), MatMatMultNumeric()
8773: @*/
8774: PetscErrorCode  MatRARtNumeric(Mat A,Mat R,Mat C)
8775: {

8781:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8782:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8785:   MatCheckPreallocated(R,2);
8786:   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8787:   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8790:   MatCheckPreallocated(C,3);
8791:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8792:   if (R->rmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->rmap->N,C->rmap->N);
8793:   if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
8794:   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8795:   if (R->rmap->N!=C->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->rmap->N,C->cmap->N);
8796:   MatCheckPreallocated(A,1);

8798:   PetscLogEventBegin(MAT_RARtNumeric,A,R,0,0);
8799:   (*A->ops->rartnumeric)(A,R,C);
8800:   PetscLogEventEnd(MAT_RARtNumeric,A,R,0,0);
8801:   return(0);
8802: }

8806: /*@
8807:    MatRARtSymbolic - Creates the (i,j) structure of the matrix product C = R * A * R^T

8809:    Neighbor-wise Collective on Mat

8811:    Input Parameters:
8812: +  A - the matrix
8813: -  R - the projection matrix

8815:    Output Parameters:
8816: .  C - the (i,j) structure of the product matrix

8818:    Notes:
8819:    C will be created and must be destroyed by the user with MatDestroy().

8821:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
8822:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
8823:    this (i,j) structure by calling MatRARtNumeric().

8825:    Level: intermediate

8827: .seealso: MatRARt(), MatRARtNumeric(), MatMatMultSymbolic()
8828: @*/
8829: PetscErrorCode  MatRARtSymbolic(Mat A,Mat R,PetscReal fill,Mat *C)
8830: {

8836:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8837:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8838:   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8841:   MatCheckPreallocated(R,2);
8842:   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8843:   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8846:   if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
8847:   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8848:   MatCheckPreallocated(A,1);
8849:   PetscLogEventBegin(MAT_RARtSymbolic,A,R,0,0);
8850:   (*A->ops->rartsymbolic)(A,R,fill,C);
8851:   PetscLogEventEnd(MAT_RARtSymbolic,A,R,0,0);

8853:   MatSetBlockSizes(*C,PetscAbs(R->rmap->bs),PetscAbs(R->rmap->bs));
8854:   return(0);
8855: }

8859: /*@
8860:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

8862:    Neighbor-wise Collective on Mat

8864:    Input Parameters:
8865: +  A - the left matrix
8866: .  B - the right matrix
8867: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8868: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
8869:           if the result is a dense matrix this is irrelevent

8871:    Output Parameters:
8872: .  C - the product matrix

8874:    Notes:
8875:    Unless scall is MAT_REUSE_MATRIX C will be created.

8877:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

8879:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
8880:    actually needed.

8882:    If you have many matrices with the same non-zero structure to multiply, you
8883:    should either
8884: $   1) use MAT_REUSE_MATRIX in all calls but the first or
8885: $   2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed

8887:    Level: intermediate

8889: .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatTransposeMatMult(),  MatMatTransposeMult(), MatPtAP()
8890: @*/
8891: PetscErrorCode  MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
8892: {
8894:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
8895:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
8896:   PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;

8901:   MatCheckPreallocated(A,1);
8902:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8903:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8906:   MatCheckPreallocated(B,2);
8907:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8908:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8910:   if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
8911:   if (scall == MAT_REUSE_MATRIX) {
8914:     PetscLogEventBegin(MAT_MatMult,A,B,0,0);
8915:     PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
8916:     (*(*C)->ops->matmultnumeric)(A,B,*C);
8917:     PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
8918:     PetscLogEventEnd(MAT_MatMult,A,B,0,0);
8919:     return(0);
8920:   }
8921:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
8922:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

8924:   fA = A->ops->matmult;
8925:   fB = B->ops->matmult;
8926:   if (fB == fA) {
8927:     if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",((PetscObject)B)->type_name);
8928:     mult = fB;
8929:   } else {
8930:     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
8931:     char multname[256];
8932:     PetscStrcpy(multname,"MatMatMult_");
8933:     PetscStrcat(multname,((PetscObject)A)->type_name);
8934:     PetscStrcat(multname,"_");
8935:     PetscStrcat(multname,((PetscObject)B)->type_name);
8936:     PetscStrcat(multname,"_C"); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
8937:     PetscObjectQueryFunction((PetscObject)B,multname,&mult);
8938:     if (!mult) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
8939:   }
8940:   PetscLogEventBegin(MAT_MatMult,A,B,0,0);
8941:   (*mult)(A,B,scall,fill,C);
8942:   PetscLogEventEnd(MAT_MatMult,A,B,0,0);
8943:   return(0);
8944: }

8948: /*@
8949:    MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
8950:    of the matrix-matrix product C=A*B.  Call this routine before calling MatMatMultNumeric().

8952:    Neighbor-wise Collective on Mat

8954:    Input Parameters:
8955: +  A - the left matrix
8956: .  B - the right matrix
8957: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate,
8958:       if C is a dense matrix this is irrelevent

8960:    Output Parameters:
8961: .  C - the product matrix

8963:    Notes:
8964:    Unless scall is MAT_REUSE_MATRIX C will be created.

8966:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
8967:    actually needed.

8969:    This routine is currently implemented for
8970:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type AIJ
8971:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
8972:     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.

8974:    Level: intermediate

8976:    Developers Note: There are ways to estimate the number of nonzeros in the resulting product, see for example, http://arxiv.org/abs/1006.4173
8977:      We should incorporate them into PETSc.

8979: .seealso: MatMatMult(), MatMatMultNumeric()
8980: @*/
8981: PetscErrorCode  MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
8982: {
8984:   PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat*);
8985:   PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat*);
8986:   PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat*)=NULL;

8991:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8992:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8996:   MatCheckPreallocated(B,2);
8997:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8998:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9001:   if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
9002:   if (fill == PETSC_DEFAULT) fill = 2.0;
9003:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9004:   MatCheckPreallocated(A,1);

9006:   Asymbolic = A->ops->matmultsymbolic;
9007:   Bsymbolic = B->ops->matmultsymbolic;
9008:   if (Asymbolic == Bsymbolic) {
9009:     if (!Bsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
9010:     symbolic = Bsymbolic;
9011:   } else { /* dispatch based on the type of A and B */
9012:     char symbolicname[256];
9013:     PetscStrcpy(symbolicname,"MatMatMultSymbolic_");
9014:     PetscStrcat(symbolicname,((PetscObject)A)->type_name);
9015:     PetscStrcat(symbolicname,"_");
9016:     PetscStrcat(symbolicname,((PetscObject)B)->type_name);
9017:     PetscStrcat(symbolicname,"_C");
9018:     PetscObjectQueryFunction((PetscObject)B,symbolicname,&symbolic);
9019:     if (!symbolic) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMultSymbolic requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9020:   }
9021:   PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
9022:   (*symbolic)(A,B,fill,C);
9023:   PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
9024:   return(0);
9025: }

9029: /*@
9030:    MatMatMultNumeric - Performs the numeric matrix-matrix product.
9031:    Call this routine after first calling MatMatMultSymbolic().

9033:    Neighbor-wise Collective on Mat

9035:    Input Parameters:
9036: +  A - the left matrix
9037: -  B - the right matrix

9039:    Output Parameters:
9040: .  C - the product matrix, which was created by from MatMatMultSymbolic() or a call to MatMatMult().

9042:    Notes:
9043:    C must have been created with MatMatMultSymbolic().

9045:    This routine is currently implemented for
9046:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
9047:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9048:     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.

9050:    Level: intermediate

9052: .seealso: MatMatMult(), MatMatMultSymbolic()
9053: @*/
9054: PetscErrorCode  MatMatMultNumeric(Mat A,Mat B,Mat C)
9055: {

9059:   MatMatMult(A,B,MAT_REUSE_MATRIX,0.0,&C);
9060:   return(0);
9061: }

9065: /*@
9066:    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.

9068:    Neighbor-wise Collective on Mat

9070:    Input Parameters:
9071: +  A - the left matrix
9072: .  B - the right matrix
9073: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9074: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9076:    Output Parameters:
9077: .  C - the product matrix

9079:    Notes:
9080:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9082:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

9084:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9085:    actually needed.

9087:    This routine is currently only implemented for pairs of SeqAIJ matrices.  C will be of type MATSEQAIJ.

9089:    Level: intermediate

9091: .seealso: MatMatTransposeMultSymbolic(), MatMatTransposeMultNumeric(), MatMatMult(), MatTransposeMatMult() MatPtAP()
9092: @*/
9093: PetscErrorCode  MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9094: {
9096:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9097:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);

9102:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9103:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9106:   MatCheckPreallocated(B,2);
9107:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9108:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9110:   if (B->cmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, AN %D != BN %D",A->cmap->N,B->cmap->N);
9111:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9112:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9113:   MatCheckPreallocated(A,1);

9115:   fA = A->ops->mattransposemult;
9116:   if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for A of type %s",((PetscObject)A)->type_name);
9117:   fB = B->ops->mattransposemult;
9118:   if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for B of type %s",((PetscObject)B)->type_name);
9119:   if (fB!=fA) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatTransposeMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);

9121:   PetscLogEventBegin(MAT_MatTransposeMult,A,B,0,0);
9122:   if (scall == MAT_INITIAL_MATRIX) {
9123:     PetscLogEventBegin(MAT_MatTransposeMultSymbolic,A,B,0,0);
9124:     (*A->ops->mattransposemultsymbolic)(A,B,fill,C);
9125:     PetscLogEventEnd(MAT_MatTransposeMultSymbolic,A,B,0,0);
9126:   }
9127:   PetscLogEventBegin(MAT_MatTransposeMultNumeric,A,B,0,0);
9128:   (*A->ops->mattransposemultnumeric)(A,B,*C);
9129:   PetscLogEventEnd(MAT_MatTransposeMultNumeric,A,B,0,0);
9130:   PetscLogEventEnd(MAT_MatTransposeMult,A,B,0,0);
9131:   return(0);
9132: }

9136: /*@
9137:    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.

9139:    Neighbor-wise Collective on Mat

9141:    Input Parameters:
9142: +  A - the left matrix
9143: .  B - the right matrix
9144: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9145: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9147:    Output Parameters:
9148: .  C - the product matrix

9150:    Notes:
9151:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9153:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

9155:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9156:    actually needed.

9158:    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9159:    which inherit from SeqAIJ.  C will be of same type as the input matrices.

9161:    Level: intermediate

9163: .seealso: MatTransposeMatMultSymbolic(), MatTransposeMatMultNumeric(), MatMatMult(), MatMatTransposeMult(), MatPtAP()
9164: @*/
9165: PetscErrorCode  MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9166: {
9168:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9169:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9170:   PetscErrorCode (*transposematmult)(Mat,Mat,MatReuse,PetscReal,Mat*) = NULL;

9175:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9176:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9179:   MatCheckPreallocated(B,2);
9180:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9181:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9183:   if (B->rmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->rmap->N);
9184:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9185:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9186:   MatCheckPreallocated(A,1);

9188:   fA = A->ops->transposematmult;
9189:   fB = B->ops->transposematmult;
9190:   if (fB==fA) {
9191:     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatTransposeMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9192:     transposematmult = fA;
9193:   } else {
9194:     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9195:     char multname[256];
9196:     PetscStrcpy(multname,"MatTransposeMatMult_");
9197:     PetscStrcat(multname,((PetscObject)A)->type_name);
9198:     PetscStrcat(multname,"_");
9199:     PetscStrcat(multname,((PetscObject)B)->type_name);
9200:     PetscStrcat(multname,"_C"); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9201:     PetscObjectQueryFunction((PetscObject)B,multname,&transposematmult);
9202:     if (!transposematmult) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatTransposeMatMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9203:   }
9204:   PetscLogEventBegin(MAT_TransposeMatMult,A,B,0,0);
9205:   (*transposematmult)(A,B,scall,fill,C);
9206:   PetscLogEventEnd(MAT_TransposeMatMult,A,B,0,0);
9207:   return(0);
9208: }

9212: /*@
9213:    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.

9215:    Neighbor-wise Collective on Mat

9217:    Input Parameters:
9218: +  A - the left matrix
9219: .  B - the middle matrix
9220: .  C - the right matrix
9221: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9222: -  fill - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use PETSC_DEFAULT if you do not have a good estimate
9223:           if the result is a dense matrix this is irrelevent

9225:    Output Parameters:
9226: .  D - the product matrix

9228:    Notes:
9229:    Unless scall is MAT_REUSE_MATRIX D will be created.

9231:    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call

9233:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9234:    actually needed.

9236:    If you have many matrices with the same non-zero structure to multiply, you
9237:    should either
9238: $   1) use MAT_REUSE_MATRIX in all calls but the first or
9239: $   2) call MatMatMatMultSymbolic() once and then MatMatMatMultNumeric() for each product needed

9241:    Level: intermediate

9243: .seealso: MatMatMult, MatPtAP()
9244: @*/
9245: PetscErrorCode  MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9246: {
9248:   PetscErrorCode (*fA)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9249:   PetscErrorCode (*fB)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9250:   PetscErrorCode (*fC)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9251:   PetscErrorCode (*mult)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;

9256:   MatCheckPreallocated(A,1);
9257:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9258:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9261:   MatCheckPreallocated(B,2);
9262:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9263:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9266:   MatCheckPreallocated(C,3);
9267:   if (!C->assembled) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9268:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9269:   if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
9270:   if (C->rmap->N!=B->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",C->rmap->N,B->cmap->N);
9271:   if (scall == MAT_REUSE_MATRIX) {
9274:     PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
9275:     (*(*D)->ops->matmatmult)(A,B,C,scall,fill,D);
9276:     PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
9277:     return(0);
9278:   }
9279:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9280:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9282:   fA = A->ops->matmatmult;
9283:   fB = B->ops->matmatmult;
9284:   fC = C->ops->matmatmult;
9285:   if (fA == fB && fA == fC) {
9286:     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9287:     mult = fA;
9288:   } else {
9289:     /* dispatch based on the type of A, B and C from their PetscObject's PetscFunctionLists. */
9290:     char multname[256];
9291:     PetscStrcpy(multname,"MatMatMatMult_");
9292:     PetscStrcat(multname,((PetscObject)A)->type_name);
9293:     PetscStrcat(multname,"_");
9294:     PetscStrcat(multname,((PetscObject)B)->type_name);
9295:     PetscStrcat(multname,"_");
9296:     PetscStrcat(multname,((PetscObject)C)->type_name);
9297:     PetscStrcat(multname,"_C");
9298:     PetscObjectQueryFunction((PetscObject)B,multname,&mult);
9299:     if (!mult) SETERRQ3(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMatMult requires A, %s, to be compatible with B, %s, C, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name,((PetscObject)C)->type_name);
9300:   }
9301:   PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
9302:   (*mult)(A,B,C,scall,fill,D);
9303:   PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
9304:   return(0);
9305: }

9309: /*@C
9310:    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

9312:    Collective on Mat

9314:    Input Parameters:
9315: +  mat - the matrix
9316: .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9317: .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9318: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9320:    Output Parameter:
9321: .  matredundant - redundant matrix

9323:    Notes:
9324:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9325:    original matrix has not changed from that last call to MatCreateRedundantMatrix().

9327:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9328:    calling it.

9330:    Level: advanced

9332:    Concepts: subcommunicator
9333:    Concepts: duplicate matrix

9335: .seealso: MatDestroy()
9336: @*/
9337: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9338: {
9340:   MPI_Comm       comm;
9341:   PetscMPIInt    size;
9342:   PetscInt       mloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9343:   Mat_Redundant  *redund=NULL;
9344:   PetscSubcomm   psubcomm=NULL;
9345:   MPI_Comm       subcomm_in=subcomm;
9346:   Mat            *matseq;
9347:   IS             isrow,iscol;
9348:   PetscBool      newsubcomm=PETSC_FALSE;
9349: 
9351:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
9352:   if (size == 1 || nsubcomm == 1) {
9353:     if (reuse == MAT_INITIAL_MATRIX) {
9354:       MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
9355:     } else {
9356:       MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
9357:     }
9358:     return(0);
9359:   }

9362:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9365:   }
9366:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9367:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9368:   MatCheckPreallocated(mat,1);

9370:   PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
9371:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9372:     /* create psubcomm, then get subcomm */
9373:     PetscObjectGetComm((PetscObject)mat,&comm);
9374:     MPI_Comm_size(comm,&size);
9375:     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);

9377:     PetscSubcommCreate(comm,&psubcomm);
9378:     PetscSubcommSetNumber(psubcomm,nsubcomm);
9379:     PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
9380:     PetscSubcommSetFromOptions(psubcomm);
9381:     PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
9382:     newsubcomm = PETSC_TRUE;
9383:     PetscSubcommDestroy(&psubcomm);
9384:   }

9386:   /* get isrow, iscol and a local sequential matrix matseq[0] */
9387:   if (reuse == MAT_INITIAL_MATRIX) {
9388:     mloc_sub = PETSC_DECIDE;
9389:     if (bs < 1) {
9390:       PetscSplitOwnership(subcomm,&mloc_sub,&M);
9391:     } else {
9392:       PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
9393:     }
9394:     MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
9395:     rstart = rend - mloc_sub;
9396:     ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
9397:     ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
9398:   } else { /* reuse == MAT_REUSE_MATRIX */
9399:     /* retrieve subcomm */
9400:     PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
9401:     redund = (*matredundant)->redundant;
9402:     isrow  = redund->isrow;
9403:     iscol  = redund->iscol;
9404:     matseq = redund->matseq;
9405:   }
9406:   MatGetSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);
9407: 
9408:   /* get matredundant over subcomm */
9409:   if (reuse == MAT_INITIAL_MATRIX) {
9410:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],mloc_sub,reuse,matredundant);

9412:     /* create a supporting struct and attach it to C for reuse */
9413:     PetscNewLog(*matredundant,&redund);
9414:     (*matredundant)->redundant = redund;
9415:     redund->isrow              = isrow;
9416:     redund->iscol              = iscol;
9417:     redund->matseq             = matseq;
9418:     if (newsubcomm) {
9419:       redund->subcomm          = subcomm;
9420:     } else {
9421:       redund->subcomm          = MPI_COMM_NULL;
9422:     }
9423:   } else {
9424:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
9425:   }
9426:   PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
9427:   return(0);
9428: }

9432: /*@C
9433:    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
9434:    a given 'mat' object. Each submatrix can span multiple procs.

9436:    Collective on Mat

9438:    Input Parameters:
9439: +  mat - the matrix
9440: .  subcomm - the subcommunicator obtained by com_split(comm)
9441: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9443:    Output Parameter:
9444: .  subMat - 'parallel submatrices each spans a given subcomm

9446:   Notes:
9447:   The submatrix partition across processors is dictated by 'subComm' a
9448:   communicator obtained by com_split(comm). The comm_split
9449:   is not restriced to be grouped with consecutive original ranks.

9451:   Due the comm_split() usage, the parallel layout of the submatrices
9452:   map directly to the layout of the original matrix [wrt the local
9453:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
9454:   into the 'DiagonalMat' of the subMat, hence it is used directly from
9455:   the subMat. However the offDiagMat looses some columns - and this is
9456:   reconstructed with MatSetValues()

9458:   Level: advanced

9460:   Concepts: subcommunicator
9461:   Concepts: submatrices

9463: .seealso: MatGetSubMatrices()
9464: @*/
9465: PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
9466: {
9468:   PetscMPIInt    commsize,subCommSize;

9471:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
9472:   MPI_Comm_size(subComm,&subCommSize);
9473:   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);

9475:   PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
9476:   (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
9477:   PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
9478:   return(0);
9479: }

9483: /*@
9484:    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

9486:    Not Collective

9488:    Input Arguments:
9489:    mat - matrix to extract local submatrix from
9490:    isrow - local row indices for submatrix
9491:    iscol - local column indices for submatrix

9493:    Output Arguments:
9494:    submat - the submatrix

9496:    Level: intermediate

9498:    Notes:
9499:    The submat should be returned with MatRestoreLocalSubMatrix().

9501:    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
9502:    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.

9504:    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
9505:    MatSetValuesBlockedLocal() will also be implemented.

9507: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef()
9508: @*/
9509: PetscErrorCode  MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9510: {


9520:   if (mat->ops->getlocalsubmatrix) {
9521:     (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
9522:   } else {
9523:     MatCreateLocalRef(mat,isrow,iscol,submat);
9524:   }
9525:   return(0);
9526: }

9530: /*@
9531:    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering

9533:    Not Collective

9535:    Input Arguments:
9536:    mat - matrix to extract local submatrix from
9537:    isrow - local row indices for submatrix
9538:    iscol - local column indices for submatrix
9539:    submat - the submatrix

9541:    Level: intermediate

9543: .seealso: MatGetLocalSubMatrix()
9544: @*/
9545: PetscErrorCode  MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9546: {

9555:   if (*submat) {
9557:   }

9559:   if (mat->ops->restorelocalsubmatrix) {
9560:     (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
9561:   } else {
9562:     MatDestroy(submat);
9563:   }
9564:   *submat = NULL;
9565:   return(0);
9566: }

9568: /* --------------------------------------------------------*/
9571: /*@
9572:    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no entry in the matrix

9574:    Collective on Mat

9576:    Input Parameter:
9577: .  mat - the matrix

9579:    Output Parameter:
9580: .  is - if any rows have zero diagonals this contains the list of them

9582:    Level: developer

9584:    Concepts: matrix-vector product

9586: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9587: @*/
9588: PetscErrorCode  MatFindZeroDiagonals(Mat mat,IS *is)
9589: {

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

9598:   if (!mat->ops->findzerodiagonals) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find zero diagonals defined");
9599:   (*mat->ops->findzerodiagonals)(mat,is);
9600:   return(0);
9601: }

9605: /*@
9606:    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

9608:    Collective on Mat

9610:    Input Parameter:
9611: .  mat - the matrix

9613:    Output Parameter:
9614: .  is - contains the list of rows with off block diagonal entries

9616:    Level: developer

9618:    Concepts: matrix-vector product

9620: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9621: @*/
9622: PetscErrorCode  MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
9623: {

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

9632:   if (!mat->ops->findoffblockdiagonalentries) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find off block diagonal entries defined");
9633:   (*mat->ops->findoffblockdiagonalentries)(mat,is);
9634:   return(0);
9635: }

9639: /*@C
9640:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

9642:   Collective on Mat

9644:   Input Parameters:
9645: . mat - the matrix

9647:   Output Parameters:
9648: . values - the block inverses in column major order (FORTRAN-like)

9650:    Note:
9651:    This routine is not available from Fortran.

9653:   Level: advanced
9654: @*/
9655: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
9656: {

9661:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9662:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9663:   if (!mat->ops->invertblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
9664:   (*mat->ops->invertblockdiagonal)(mat,values);
9665:   return(0);
9666: }

9670: /*@C
9671:     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
9672:     via MatTransposeColoringCreate().

9674:     Collective on MatTransposeColoring

9676:     Input Parameter:
9677: .   c - coloring context

9679:     Level: intermediate

9681: .seealso: MatTransposeColoringCreate()
9682: @*/
9683: PetscErrorCode  MatTransposeColoringDestroy(MatTransposeColoring *c)
9684: {
9685:   PetscErrorCode       ierr;
9686:   MatTransposeColoring matcolor=*c;

9689:   if (!matcolor) return(0);
9690:   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; return(0);}

9692:   PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
9693:   PetscFree(matcolor->rows);
9694:   PetscFree(matcolor->den2sp);
9695:   PetscFree(matcolor->colorforcol);
9696:   PetscFree(matcolor->columns);
9697:   if (matcolor->brows>0) {
9698:     PetscFree(matcolor->lstart);
9699:   }
9700:   PetscHeaderDestroy(c);
9701:   return(0);
9702: }

9706: /*@C
9707:     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
9708:     a MatTransposeColoring context has been created, computes a dense B^T by Apply
9709:     MatTransposeColoring to sparse B.

9711:     Collective on MatTransposeColoring

9713:     Input Parameters:
9714: +   B - sparse matrix B
9715: .   Btdense - symbolic dense matrix B^T
9716: -   coloring - coloring context created with MatTransposeColoringCreate()

9718:     Output Parameter:
9719: .   Btdense - dense matrix B^T

9721:     Options Database Keys:
9722: +    -mat_transpose_coloring_view - Activates basic viewing or coloring
9723: .    -mat_transpose_coloring_view_draw - Activates drawing of coloring
9724: -    -mat_transpose_coloring_view_info - Activates viewing of coloring info

9726:     Level: intermediate

9728: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy()

9730: .keywords: coloring
9731: @*/
9732: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
9733: {


9741:   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
9742:   (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
9743:   return(0);
9744: }

9748: /*@C
9749:     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
9750:     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
9751:     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
9752:     Csp from Cden.

9754:     Collective on MatTransposeColoring

9756:     Input Parameters:
9757: +   coloring - coloring context created with MatTransposeColoringCreate()
9758: -   Cden - matrix product of a sparse matrix and a dense matrix Btdense

9760:     Output Parameter:
9761: .   Csp - sparse matrix

9763:     Options Database Keys:
9764: +    -mat_multtranspose_coloring_view - Activates basic viewing or coloring
9765: .    -mat_multtranspose_coloring_view_draw - Activates drawing of coloring
9766: -    -mat_multtranspose_coloring_view_info - Activates viewing of coloring info

9768:     Level: intermediate

9770: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()

9772: .keywords: coloring
9773: @*/
9774: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
9775: {


9783:   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
9784:   (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
9785:   return(0);
9786: }

9790: /*@C
9791:    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.

9793:    Collective on Mat

9795:    Input Parameters:
9796: +  mat - the matrix product C
9797: -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()

9799:     Output Parameter:
9800: .   color - the new coloring context

9802:     Level: intermediate

9804: .seealso: MatTransposeColoringDestroy(), MatTransposeColoringSetFromOptions(), MatTransColoringApplySpToDen(),
9805:            MatTransColoringApplyDenToSp(), MatTransposeColoringView(),
9806: @*/
9807: PetscErrorCode  MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
9808: {
9809:   MatTransposeColoring c;
9810:   MPI_Comm             comm;
9811:   PetscErrorCode       ierr;

9814:   PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
9815:   PetscObjectGetComm((PetscObject)mat,&comm);
9816:   PetscHeaderCreate(c,_p_MatTransposeColoring,int,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,0);

9818:   c->ctype = iscoloring->ctype;
9819:   if (mat->ops->transposecoloringcreate) {
9820:     (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
9821:   } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for this matrix type");

9823:   *color = c;
9824:   PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
9825:   return(0);
9826: }

9830: /*@
9831:       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the 
9832:         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the 
9833:         same, otherwise it will be larger

9835:      Not Collective

9837:   Input Parameter:
9838: .    A  - the matrix

9840:   Output Parameter:
9841: .    state - the current state

9843:   Notes: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between 
9844:          different matrices

9846:   Level: intermediate

9848: @*/
9849: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
9850: {
9853:   *state = mat->nonzerostate;
9854:   return(0);
9855: }

9859: /*@
9860:       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
9861:                  matrices from each processor

9863:     Collective on MPI_Comm

9865:    Input Parameters:
9866: +    comm - the communicators the parallel matrix will live on
9867: .    seqmat - the input sequential matrices
9868: .    n - number of local columns (or PETSC_DECIDE)
9869: -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9871:    Output Parameter:
9872: .    mpimat - the parallel matrix generated

9874:     Level: advanced

9876:    Notes: The number of columns of the matrix in EACH processor MUST be the same.

9878: @*/
9879: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
9880: {
9882:   PetscMPIInt    size;

9885:   MPI_Comm_size(comm,&size);
9886:   if (size == 1) {
9887:     if (reuse == MAT_INITIAL_MATRIX) {
9888:       MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);
9889:     } else {
9890:       MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);
9891:     }
9892:     return(0);
9893:   }

9895:   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
9896:   PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
9897:   (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
9898:   PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
9899:   return(0);
9900: }