Actual source code: matrix.c

petsc-master 2015-01-24
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;
 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 10 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         isams;
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,&isams);
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 (isams) {
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:   VecValidValues(x,2,PETSC_TRUE);
2218:   MatCheckPreallocated(mat,1);

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

2230: /*@
2231:    MatMultTranspose - Computes matrix transpose times a vector.

2233:    Neighbor-wise Collective on Mat and Vec

2235:    Input Parameters:
2236: +  mat - the matrix
2237: -  x   - the vector to be multilplied

2239:    Output Parameters:
2240: .  y - the result

2242:    Notes:
2243:    The vectors x and y cannot be the same.  I.e., one cannot
2244:    call MatMultTranspose(A,y,y).

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

2249:    Level: beginner

2251:    Concepts: matrix vector product^transpose

2253: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2254: @*/
2255: PetscErrorCode  MatMultTranspose(Mat mat,Vec x,Vec y)
2256: {


2265:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2266:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2267:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2268: #if !defined(PETSC_HAVE_CONSTRAINTS)
2269:   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);
2270:   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);
2271: #endif
2272:   VecValidValues(x,2,PETSC_TRUE);
2273:   MatCheckPreallocated(mat,1);

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

2286: /*@
2287:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2289:    Neighbor-wise Collective on Mat and Vec

2291:    Input Parameters:
2292: +  mat - the matrix
2293: -  x   - the vector to be multilplied

2295:    Output Parameters:
2296: .  y - the result

2298:    Notes:
2299:    The vectors x and y cannot be the same.  I.e., one cannot
2300:    call MatMultHermitianTranspose(A,y,y).

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

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

2306:    Level: beginner

2308:    Concepts: matrix vector product^transpose

2310: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2311: @*/
2312: PetscErrorCode  MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2313: {
2315:   Vec            w;


2323:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2324:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2325:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2326: #if !defined(PETSC_HAVE_CONSTRAINTS)
2327:   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);
2328:   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);
2329: #endif
2330:   MatCheckPreallocated(mat,1);

2332:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2333:   if (mat->ops->multhermitiantranspose) {
2334:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2335:   } else {
2336:     VecDuplicate(x,&w);
2337:     VecCopy(x,w);
2338:     VecConjugate(w);
2339:     MatMultTranspose(mat,w,y);
2340:     VecDestroy(&w);
2341:     VecConjugate(y);
2342:   }
2343:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2344:   PetscObjectStateIncrease((PetscObject)y);
2345:   return(0);
2346: }

2350: /*@
2351:     MatMultAdd -  Computes v3 = v2 + A * v1.

2353:     Neighbor-wise Collective on Mat and Vec

2355:     Input Parameters:
2356: +   mat - the matrix
2357: -   v1, v2 - the vectors

2359:     Output Parameters:
2360: .   v3 - the result

2362:     Notes:
2363:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2364:     call MatMultAdd(A,v1,v2,v1).

2366:     Level: beginner

2368:     Concepts: matrix vector product^addition

2370: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2371: @*/
2372: PetscErrorCode  MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2373: {


2383:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2384:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2385:   if (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);
2386:   /* 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);
2387:      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); */
2388:   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);
2389:   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);
2390:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2391:   MatCheckPreallocated(mat,1);

2393:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2394:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2395:   (*mat->ops->multadd)(mat,v1,v2,v3);
2396:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2397:   PetscObjectStateIncrease((PetscObject)v3);
2398:   return(0);
2399: }

2403: /*@
2404:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2406:    Neighbor-wise Collective on Mat and Vec

2408:    Input Parameters:
2409: +  mat - the matrix
2410: -  v1, v2 - the vectors

2412:    Output Parameters:
2413: .  v3 - the result

2415:    Notes:
2416:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2417:    call MatMultTransposeAdd(A,v1,v2,v1).

2419:    Level: beginner

2421:    Concepts: matrix vector product^transpose and addition

2423: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2424: @*/
2425: PetscErrorCode  MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2426: {


2436:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2437:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2438:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2439:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2440:   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);
2441:   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);
2442:   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);
2443:   MatCheckPreallocated(mat,1);

2445:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2446:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2447:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2448:   PetscObjectStateIncrease((PetscObject)v3);
2449:   return(0);
2450: }

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

2457:    Neighbor-wise Collective on Mat and Vec

2459:    Input Parameters:
2460: +  mat - the matrix
2461: -  v1, v2 - the vectors

2463:    Output Parameters:
2464: .  v3 - the result

2466:    Notes:
2467:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2468:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2470:    Level: beginner

2472:    Concepts: matrix vector product^transpose and addition

2474: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2475: @*/
2476: PetscErrorCode  MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2477: {


2487:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2488:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2489:   if (!mat->ops->multhermitiantransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2490:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2491:   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);
2492:   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);
2493:   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);
2494:   MatCheckPreallocated(mat,1);

2496:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2497:   (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2498:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2499:   PetscObjectStateIncrease((PetscObject)v3);
2500:   return(0);
2501: }

2505: /*@
2506:    MatMultConstrained - The inner multiplication routine for a
2507:    constrained matrix P^T A P.

2509:    Neighbor-wise Collective on Mat and Vec

2511:    Input Parameters:
2512: +  mat - the matrix
2513: -  x   - the vector to be multilplied

2515:    Output Parameters:
2516: .  y - the result

2518:    Notes:
2519:    The vectors x and y cannot be the same.  I.e., one cannot
2520:    call MatMult(A,y,y).

2522:    Level: beginner

2524: .keywords: matrix, multiply, matrix-vector product, constraint
2525: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2526: @*/
2527: PetscErrorCode  MatMultConstrained(Mat mat,Vec x,Vec y)
2528: {

2535:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2536:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2537:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2538:   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);
2539:   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);
2540:   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);

2542:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2543:   (*mat->ops->multconstrained)(mat,x,y);
2544:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2545:   PetscObjectStateIncrease((PetscObject)y);
2546:   return(0);
2547: }

2551: /*@
2552:    MatMultTransposeConstrained - The inner multiplication routine for a
2553:    constrained matrix P^T A^T P.

2555:    Neighbor-wise Collective on Mat and Vec

2557:    Input Parameters:
2558: +  mat - the matrix
2559: -  x   - the vector to be multilplied

2561:    Output Parameters:
2562: .  y - the result

2564:    Notes:
2565:    The vectors x and y cannot be the same.  I.e., one cannot
2566:    call MatMult(A,y,y).

2568:    Level: beginner

2570: .keywords: matrix, multiply, matrix-vector product, constraint
2571: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2572: @*/
2573: PetscErrorCode  MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2574: {

2581:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2582:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2583:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2584:   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);
2585:   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);

2587:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2588:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2589:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2590:   PetscObjectStateIncrease((PetscObject)y);
2591:   return(0);
2592: }

2596: /*@C
2597:    MatGetFactorType - gets the type of factorization it is

2599:    Note Collective
2600:    as the flag

2602:    Input Parameters:
2603: .  mat - the matrix

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

2608:     Level: intermediate

2610: .seealso:    MatFactorType, MatGetFactor()
2611: @*/
2612: PetscErrorCode  MatGetFactorType(Mat mat,MatFactorType *t)
2613: {
2617:   *t = mat->factortype;
2618:   return(0);
2619: }

2621: /* ------------------------------------------------------------*/
2624: /*@C
2625:    MatGetInfo - Returns information about matrix storage (number of
2626:    nonzeros, memory, etc.).

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

2630:    Input Parameters:
2631: .  mat - the matrix

2633:    Output Parameters:
2634: +  flag - flag indicating the type of parameters to be returned
2635:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2636:    MAT_GLOBAL_SUM - sum over all processors)
2637: -  info - matrix information context

2639:    Notes:
2640:    The MatInfo context contains a variety of matrix data, including
2641:    number of nonzeros allocated and used, number of mallocs during
2642:    matrix assembly, etc.  Additional information for factored matrices
2643:    is provided (such as the fill ratio, number of mallocs during
2644:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2645:    when using the runtime options
2646: $       -info -mat_view ::ascii_info

2648:    Example for C/C++ Users:
2649:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2650:    data within the MatInfo context.  For example,
2651: .vb
2652:       MatInfo info;
2653:       Mat     A;
2654:       double  mal, nz_a, nz_u;

2656:       MatGetInfo(A,MAT_LOCAL,&info);
2657:       mal  = info.mallocs;
2658:       nz_a = info.nz_allocated;
2659: .ve

2661:    Example for Fortran Users:
2662:    Fortran users should declare info as a double precision
2663:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2664:    of interest.  See the file ${PETSC_DIR}/include/petsc-finclude/petscmat.h
2665:    a complete list of parameter names.
2666: .vb
2667:       double  precision info(MAT_INFO_SIZE)
2668:       double  precision mal, nz_a
2669:       Mat     A
2670:       integer ierr

2672:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2673:       mal = info(MAT_INFO_MALLOCS)
2674:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2675: .ve

2677:     Level: intermediate

2679:     Concepts: matrices^getting information on

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

2684: .seealso: MatStashGetInfo()

2686: @*/
2687: PetscErrorCode  MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2688: {

2695:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2696:   MatCheckPreallocated(mat,1);
2697:   (*mat->ops->getinfo)(mat,flag,info);
2698:   return(0);
2699: }

2701: /* ----------------------------------------------------------*/

2705: /*@C
2706:    MatLUFactor - Performs in-place LU factorization of matrix.

2708:    Collective on Mat

2710:    Input Parameters:
2711: +  mat - the matrix
2712: .  row - row permutation
2713: .  col - column permutation
2714: -  info - options for factorization, includes
2715: $          fill - expected fill as ratio of original fill.
2716: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2717: $                   Run with the option -info to determine an optimal value to use

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

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

2727:    Level: developer

2729:    Concepts: matrices^LU factorization

2731: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2732:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2737: @*/
2738: PetscErrorCode  MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2739: {
2741:   MatFactorInfo  tinfo;

2749:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2750:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2751:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2752:   MatCheckPreallocated(mat,1);
2753:   if (!info) {
2754:     MatFactorInfoInitialize(&tinfo);
2755:     info = &tinfo;
2756:   }

2758:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2759:   (*mat->ops->lufactor)(mat,row,col,info);
2760:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2761:   PetscObjectStateIncrease((PetscObject)mat);
2762:   return(0);
2763: }

2767: /*@C
2768:    MatILUFactor - Performs in-place ILU factorization of matrix.

2770:    Collective on Mat

2772:    Input Parameters:
2773: +  mat - the matrix
2774: .  row - row permutation
2775: .  col - column permutation
2776: -  info - structure containing
2777: $      levels - number of levels of fill.
2778: $      expected fill - as ratio of original fill.
2779: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2780:                 missing diagonal entries)

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

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

2790:    Level: developer

2792:    Concepts: matrices^ILU factorization

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

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

2799: @*/
2800: PetscErrorCode  MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2801: {

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

2816:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
2817:   (*mat->ops->ilufactor)(mat,row,col,info);
2818:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
2819:   PetscObjectStateIncrease((PetscObject)mat);
2820:   return(0);
2821: }

2825: /*@C
2826:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2827:    Call this routine before calling MatLUFactorNumeric().

2829:    Collective on Mat

2831:    Input Parameters:
2832: +  fact - the factor matrix obtained with MatGetFactor()
2833: .  mat - the matrix
2834: .  row, col - row and column permutations
2835: -  info - options for factorization, includes
2836: $          fill - expected fill as ratio of original fill.
2837: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2838: $                   Run with the option -info to determine an optimal value to use


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

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

2847:    Level: developer

2849:    Concepts: matrices^LU symbolic factorization

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

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

2856: @*/
2857: PetscErrorCode  MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
2858: {

2868:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2869:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2870:   if (!(fact)->ops->lufactorsymbolic) {
2871:     const MatSolverPackage spackage;
2872:     MatFactorGetSolverPackage(fact,&spackage);
2873:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
2874:   }
2875:   MatCheckPreallocated(mat,2);

2877:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
2878:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
2879:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
2880:   PetscObjectStateIncrease((PetscObject)fact);
2881:   return(0);
2882: }

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

2890:    Collective on Mat

2892:    Input Parameters:
2893: +  fact - the factor matrix obtained with MatGetFactor()
2894: .  mat - the matrix
2895: -  info - options for factorization

2897:    Notes:
2898:    See MatLUFactor() for in-place factorization.  See
2899:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

2905:    Level: developer

2907:    Concepts: matrices^LU numeric factorization

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

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

2914: @*/
2915: PetscErrorCode  MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
2916: {

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

2927:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
2928:   MatCheckPreallocated(mat,2);
2929:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
2930:   (fact->ops->lufactornumeric)(fact,mat,info);
2931:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
2932:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
2933:   PetscObjectStateIncrease((PetscObject)fact);
2934:   return(0);
2935: }

2939: /*@C
2940:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
2941:    symmetric matrix.

2943:    Collective on Mat

2945:    Input Parameters:
2946: +  mat - the matrix
2947: .  perm - row and column permutations
2948: -  f - expected fill as ratio of original fill

2950:    Notes:
2951:    See MatLUFactor() for the nonsymmetric case.  See also
2952:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

2958:    Level: developer

2960:    Concepts: matrices^Cholesky factorization

2962: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
2963:           MatGetOrdering()

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

2968: @*/
2969: PetscErrorCode  MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
2970: {

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

2984:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
2985:   (*mat->ops->choleskyfactor)(mat,perm,info);
2986:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
2987:   PetscObjectStateIncrease((PetscObject)mat);
2988:   return(0);
2989: }

2993: /*@C
2994:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
2995:    of a symmetric matrix.

2997:    Collective on Mat

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

3008:    Notes:
3009:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3010:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3016:    Level: developer

3018:    Concepts: matrices^Cholesky symbolic factorization

3020: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3021:           MatGetOrdering()

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

3026: @*/
3027: PetscErrorCode  MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3028: {

3037:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3038:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3039:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3040:   if (!(fact)->ops->choleskyfactorsymbolic) {
3041:     const MatSolverPackage spackage;
3042:     MatFactorGetSolverPackage(fact,&spackage);
3043:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3044:   }
3045:   MatCheckPreallocated(mat,2);

3047:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3048:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3049:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3050:   PetscObjectStateIncrease((PetscObject)fact);
3051:   return(0);
3052: }

3056: /*@C
3057:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3058:    of a symmetric matrix. Call this routine after first calling
3059:    MatCholeskyFactorSymbolic().

3061:    Collective on Mat

3063:    Input Parameters:
3064: +  fact - the factor matrix obtained with MatGetFactor()
3065: .  mat - the initial matrix
3066: .  info - options for factorization
3067: -  fact - the symbolic factor of mat


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

3075:    Level: developer

3077:    Concepts: matrices^Cholesky numeric factorization

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

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

3084: @*/
3085: PetscErrorCode  MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3086: {

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

3099:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3100:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3101:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3102:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3103:   PetscObjectStateIncrease((PetscObject)fact);
3104:   return(0);
3105: }

3107: /* ----------------------------------------------------------------*/
3110: /*@
3111:    MatSolve - Solves A x = b, given a factored matrix.

3113:    Neighbor-wise Collective on Mat and Vec

3115:    Input Parameters:
3116: +  mat - the factored matrix
3117: -  b - the right-hand-side vector

3119:    Output Parameter:
3120: .  x - the result vector

3122:    Notes:
3123:    The vectors b and x cannot be the same.  I.e., one cannot
3124:    call MatSolve(A,x,x).

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

3131:    Level: developer

3133:    Concepts: matrices^triangular solves

3135: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3136: @*/
3137: PetscErrorCode  MatSolve(Mat mat,Vec b,Vec x)
3138: {

3148:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3149:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3150:   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);
3151:   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);
3152:   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);
3153:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3154:   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3155:   MatCheckPreallocated(mat,1);

3157:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3158:   (*mat->ops->solve)(mat,b,x);
3159:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3160:   PetscObjectStateIncrease((PetscObject)x);
3161:   return(0);
3162: }

3166: PetscErrorCode  MatMatSolve_Basic(Mat A,Mat B,Mat X)
3167: {
3169:   Vec            b,x;
3170:   PetscInt       m,N,i;
3171:   PetscScalar    *bb,*xx;
3172:   PetscBool      flg;

3175:   PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3176:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
3177:   PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3178:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");

3180:   MatDenseGetArray(B,&bb);
3181:   MatDenseGetArray(X,&xx);
3182:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3183:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3184:   MatCreateVecs(A,&x,&b);
3185:   for (i=0; i<N; i++) {
3186:     VecPlaceArray(b,bb + i*m);
3187:     VecPlaceArray(x,xx + i*m);
3188:     MatSolve(A,b,x);
3189:     VecResetArray(x);
3190:     VecResetArray(b);
3191:   }
3192:   VecDestroy(&b);
3193:   VecDestroy(&x);
3194:   MatDenseRestoreArray(B,&bb);
3195:   MatDenseRestoreArray(X,&xx);
3196:   return(0);
3197: }

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

3204:    Neighbor-wise Collective on Mat

3206:    Input Parameters:
3207: +  mat - the factored matrix
3208: -  B - the right-hand-side matrix  (dense matrix)

3210:    Output Parameter:
3211: .  X - the result matrix (dense matrix)

3213:    Notes:
3214:    The matrices b and x cannot be the same.  I.e., one cannot
3215:    call MatMatSolve(A,x,x).

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

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

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

3228:    Level: developer

3230:    Concepts: matrices^triangular solves

3232: .seealso: MatMatSolveAdd(), MatMatSolveTranspose(), MatMatSolveTransposeAdd(), MatLUFactor(), MatCholeskyFactor()
3233: @*/
3234: PetscErrorCode  MatMatSolve(Mat A,Mat B,Mat X)
3235: {

3245:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3246:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3247:   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);
3248:   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);
3249:   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);
3250:   if (!A->rmap->N && !A->cmap->N) return(0);
3251:   MatCheckPreallocated(A,1);

3253:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3254:   if (!A->ops->matsolve) {
3255:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3256:     MatMatSolve_Basic(A,B,X);
3257:   } else {
3258:     (*A->ops->matsolve)(A,B,X);
3259:   }
3260:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3261:   PetscObjectStateIncrease((PetscObject)X);
3262:   return(0);
3263: }


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

3272:    Neighbor-wise Collective on Mat and Vec

3274:    Input Parameters:
3275: +  mat - the factored matrix
3276: -  b - the right-hand-side vector

3278:    Output Parameter:
3279: .  x - the result vector

3281:    Notes:
3282:    MatSolve() should be used for most applications, as it performs
3283:    a forward solve followed by a backward solve.

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

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

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

3298:    Level: developer

3300:    Concepts: matrices^forward solves

3302: .seealso: MatSolve(), MatBackwardSolve()
3303: @*/
3304: PetscErrorCode  MatForwardSolve(Mat mat,Vec b,Vec x)
3305: {

3315:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3316:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3317:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3318:   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);
3319:   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);
3320:   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);
3321:   MatCheckPreallocated(mat,1);
3322:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3323:   (*mat->ops->forwardsolve)(mat,b,x);
3324:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3325:   PetscObjectStateIncrease((PetscObject)x);
3326:   return(0);
3327: }

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

3335:    Neighbor-wise Collective on Mat and Vec

3337:    Input Parameters:
3338: +  mat - the factored matrix
3339: -  b - the right-hand-side vector

3341:    Output Parameter:
3342: .  x - the result vector

3344:    Notes:
3345:    MatSolve() should be used for most applications, as it performs
3346:    a forward solve followed by a backward solve.

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

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

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

3361:    Level: developer

3363:    Concepts: matrices^backward solves

3365: .seealso: MatSolve(), MatForwardSolve()
3366: @*/
3367: PetscErrorCode  MatBackwardSolve(Mat mat,Vec b,Vec x)
3368: {

3378:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3379:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3380:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3381:   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);
3382:   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);
3383:   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);
3384:   MatCheckPreallocated(mat,1);

3386:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3387:   (*mat->ops->backwardsolve)(mat,b,x);
3388:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3389:   PetscObjectStateIncrease((PetscObject)x);
3390:   return(0);
3391: }

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

3398:    Neighbor-wise Collective on Mat and Vec

3400:    Input Parameters:
3401: +  mat - the factored matrix
3402: .  b - the right-hand-side vector
3403: -  y - the vector to be added to

3405:    Output Parameter:
3406: .  x - the result vector

3408:    Notes:
3409:    The vectors b and x cannot be the same.  I.e., one cannot
3410:    call MatSolveAdd(A,x,y,x).

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

3416:    Level: developer

3418:    Concepts: matrices^triangular solves

3420: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3421: @*/
3422: PetscErrorCode  MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3423: {
3424:   PetscScalar    one = 1.0;
3425:   Vec            tmp;

3437:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3438:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3439:   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);
3440:   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);
3441:   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);
3442:   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);
3443:   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);
3444:   MatCheckPreallocated(mat,1);

3446:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3447:   if (mat->ops->solveadd) {
3448:     (*mat->ops->solveadd)(mat,b,y,x);
3449:   } else {
3450:     /* do the solve then the add manually */
3451:     if (x != y) {
3452:       MatSolve(mat,b,x);
3453:       VecAXPY(x,one,y);
3454:     } else {
3455:       VecDuplicate(x,&tmp);
3456:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3457:       VecCopy(x,tmp);
3458:       MatSolve(mat,b,x);
3459:       VecAXPY(x,one,tmp);
3460:       VecDestroy(&tmp);
3461:     }
3462:   }
3463:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3464:   PetscObjectStateIncrease((PetscObject)x);
3465:   return(0);
3466: }

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

3473:    Neighbor-wise Collective on Mat and Vec

3475:    Input Parameters:
3476: +  mat - the factored matrix
3477: -  b - the right-hand-side vector

3479:    Output Parameter:
3480: .  x - the result vector

3482:    Notes:
3483:    The vectors b and x cannot be the same.  I.e., one cannot
3484:    call MatSolveTranspose(A,x,x).

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

3490:    Level: developer

3492:    Concepts: matrices^triangular solves

3494: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3495: @*/
3496: PetscErrorCode  MatSolveTranspose(Mat mat,Vec b,Vec x)
3497: {

3507:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3508:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3509:   if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3510:   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);
3511:   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);
3512:   MatCheckPreallocated(mat,1);
3513:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3514:   (*mat->ops->solvetranspose)(mat,b,x);
3515:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3516:   PetscObjectStateIncrease((PetscObject)x);
3517:   return(0);
3518: }

3522: /*@
3523:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3524:                       factored matrix.

3526:    Neighbor-wise Collective on Mat and Vec

3528:    Input Parameters:
3529: +  mat - the factored matrix
3530: .  b - the right-hand-side vector
3531: -  y - the vector to be added to

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

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

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

3544:    Level: developer

3546:    Concepts: matrices^triangular solves

3548: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3549: @*/
3550: PetscErrorCode  MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3551: {
3552:   PetscScalar    one = 1.0;
3554:   Vec            tmp;

3565:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3566:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3567:   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);
3568:   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);
3569:   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);
3570:   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);
3571:   MatCheckPreallocated(mat,1);

3573:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3574:   if (mat->ops->solvetransposeadd) {
3575:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
3576:   } else {
3577:     /* do the solve then the add manually */
3578:     if (x != y) {
3579:       MatSolveTranspose(mat,b,x);
3580:       VecAXPY(x,one,y);
3581:     } else {
3582:       VecDuplicate(x,&tmp);
3583:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3584:       VecCopy(x,tmp);
3585:       MatSolveTranspose(mat,b,x);
3586:       VecAXPY(x,one,tmp);
3587:       VecDestroy(&tmp);
3588:     }
3589:   }
3590:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3591:   PetscObjectStateIncrease((PetscObject)x);
3592:   return(0);
3593: }
3594: /* ----------------------------------------------------------------*/

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

3601:    Neighbor-wise Collective on Mat and Vec

3603:    Input Parameters:
3604: +  mat - the matrix
3605: .  b - the right hand side
3606: .  omega - the relaxation factor
3607: .  flag - flag indicating the type of SOR (see below)
3608: .  shift -  diagonal shift
3609: .  its - the number of iterations
3610: -  lits - the number of local iterations

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

3615:    SOR Flags:
3616: .     SOR_FORWARD_SWEEP - forward SOR
3617: .     SOR_BACKWARD_SWEEP - backward SOR
3618: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3619: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3620: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3621: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3622: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3623:          upper/lower triangular part of matrix to
3624:          vector (with omega)
3625: .     SOR_ZERO_INITIAL_GUESS - zero initial guess

3627:    Notes:
3628:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3629:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3630:    on each processor.

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

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

3637:    Notes for Advanced Users:
3638:    The flags are implemented as bitwise inclusive or operations.
3639:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3640:    to specify a zero initial guess for SSOR.

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

3646:    Vectors x and b CANNOT be the same

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

3650:    Level: developer

3652:    Concepts: matrices^relaxation
3653:    Concepts: matrices^SOR
3654:    Concepts: matrices^Gauss-Seidel

3656: @*/
3657: PetscErrorCode  MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3658: {

3668:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3669:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3670:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3671:   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);
3672:   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);
3673:   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);
3674:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3675:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3676:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

3678:   MatCheckPreallocated(mat,1);
3679:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3680:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3681:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3682:   PetscObjectStateIncrease((PetscObject)x);
3683:   return(0);
3684: }

3688: /*
3689:       Default matrix copy routine.
3690: */
3691: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3692: {
3693:   PetscErrorCode    ierr;
3694:   PetscInt          i,rstart = 0,rend = 0,nz;
3695:   const PetscInt    *cwork;
3696:   const PetscScalar *vwork;

3699:   if (B->assembled) {
3700:     MatZeroEntries(B);
3701:   }
3702:   MatGetOwnershipRange(A,&rstart,&rend);
3703:   for (i=rstart; i<rend; i++) {
3704:     MatGetRow(A,i,&nz,&cwork,&vwork);
3705:     MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3706:     MatRestoreRow(A,i,&nz,&cwork,&vwork);
3707:   }
3708:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3709:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3710:   PetscObjectStateIncrease((PetscObject)B);
3711:   return(0);
3712: }

3716: /*@
3717:    MatCopy - Copys a matrix to another matrix.

3719:    Collective on Mat

3721:    Input Parameters:
3722: +  A - the matrix
3723: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

3725:    Output Parameter:
3726: .  B - where the copy is put

3728:    Notes:
3729:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3730:    same nonzero pattern or the routine will crash.

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

3736:    Level: intermediate

3738:    Concepts: matrices^copying

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

3742: @*/
3743: PetscErrorCode  MatCopy(Mat A,Mat B,MatStructure str)
3744: {
3746:   PetscInt       i;

3754:   MatCheckPreallocated(B,2);
3755:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3756:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3757:   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);
3758:   MatCheckPreallocated(A,1);

3760:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
3761:   if (A->ops->copy) {
3762:     (*A->ops->copy)(A,B,str);
3763:   } else { /* generic conversion */
3764:     MatCopy_Basic(A,B,str);
3765:   }

3767:   B->stencil.dim = A->stencil.dim;
3768:   B->stencil.noc = A->stencil.noc;
3769:   for (i=0; i<=A->stencil.dim; i++) {
3770:     B->stencil.dims[i]   = A->stencil.dims[i];
3771:     B->stencil.starts[i] = A->stencil.starts[i];
3772:   }

3774:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
3775:   PetscObjectStateIncrease((PetscObject)B);
3776:   return(0);
3777: }

3781: /*@C
3782:    MatConvert - Converts a matrix to another matrix, either of the same
3783:    or different type.

3785:    Collective on Mat

3787:    Input Parameters:
3788: +  mat - the matrix
3789: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
3790:    same type as the original matrix.
3791: -  reuse - denotes if the destination matrix is to be created or reused.  Currently
3792:    MAT_REUSE_MATRIX is only supported for inplace conversion, otherwise use
3793:    MAT_INITIAL_MATRIX.

3795:    Output Parameter:
3796: .  M - pointer to place new matrix

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

3803:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
3804:    the MPI communicator of the generated matrix is always the same as the communicator
3805:    of the input matrix.

3807:    Level: intermediate

3809:    Concepts: matrices^converting between storage formats

3811: .seealso: MatCopy(), MatDuplicate()
3812: @*/
3813: PetscErrorCode  MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
3814: {
3816:   PetscBool      sametype,issame,flg;
3817:   char           convname[256],mtype[256];
3818:   Mat            B;

3824:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3825:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3826:   MatCheckPreallocated(mat,1);
3827:   MatSetOption(mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);

3829:   PetscOptionsGetString(((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
3830:   if (flg) {
3831:     newtype = mtype;
3832:   }
3833:   PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
3834:   PetscStrcmp(newtype,"same",&issame);
3835:   if ((reuse == MAT_REUSE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_REUSE_MATRIX only supported for in-place conversion currently");

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

3839:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
3840:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
3841:   } else {
3842:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
3843:     const char     *prefix[3] = {"seq","mpi",""};
3844:     PetscInt       i;
3845:     /*
3846:        Order of precedence:
3847:        1) See if a specialized converter is known to the current matrix.
3848:        2) See if a specialized converter is known to the desired matrix class.
3849:        3) See if a good general converter is registered for the desired class
3850:           (as of 6/27/03 only MATMPIADJ falls into this category).
3851:        4) See if a good general converter is known for the current matrix.
3852:        5) Use a really basic converter.
3853:     */

3855:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
3856:     for (i=0; i<3; i++) {
3857:       PetscStrcpy(convname,"MatConvert_");
3858:       PetscStrcat(convname,((PetscObject)mat)->type_name);
3859:       PetscStrcat(convname,"_");
3860:       PetscStrcat(convname,prefix[i]);
3861:       PetscStrcat(convname,issame ? ((PetscObject)mat)->type_name : newtype);
3862:       PetscStrcat(convname,"_C");
3863:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
3864:       if (conv) goto foundconv;
3865:     }

3867:     /* 2)  See if a specialized converter is known to the desired matrix class. */
3868:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
3869:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
3870:     MatSetType(B,newtype);
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,newtype);
3877:       PetscStrcat(convname,"_C");
3878:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
3879:       if (conv) {
3880:         MatDestroy(&B);
3881:         goto foundconv;
3882:       }
3883:     }

3885:     /* 3) See if a good general converter is registered for the desired class */
3886:     conv = B->ops->convertfrom;
3887:     MatDestroy(&B);
3888:     if (conv) goto foundconv;

3890:     /* 4) See if a good general converter is known for the current matrix */
3891:     if (mat->ops->convert) {
3892:       conv = mat->ops->convert;
3893:     }
3894:     if (conv) goto foundconv;

3896:     /* 5) Use a really basic converter. */
3897:     conv = MatConvert_Basic;

3899: foundconv:
3900:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
3901:     (*conv)(mat,newtype,reuse,M);
3902:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
3903:   }
3904:   PetscObjectStateIncrease((PetscObject)*M);

3906:   /* Copy Mat options */
3907:   if (mat->symmetric) {MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);}
3908:   if (mat->hermitian) {MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);}
3909:   return(0);
3910: }

3914: /*@C
3915:    MatFactorGetSolverPackage - Returns name of the package providing the factorization routines

3917:    Not Collective

3919:    Input Parameter:
3920: .  mat - the matrix, must be a factored matrix

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

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

3929:    Level: intermediate

3931: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
3932: @*/
3933: PetscErrorCode  MatFactorGetSolverPackage(Mat mat, const MatSolverPackage *type)
3934: {
3935:   PetscErrorCode ierr, (*conv)(Mat,const MatSolverPackage*);

3940:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
3941:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverPackage_C",&conv);
3942:   if (!conv) {
3943:     *type = MATSOLVERPETSC;
3944:   } else {
3945:     (*conv)(mat,type);
3946:   }
3947:   return(0);
3948: }

3950: typedef struct _MatSolverPackageForSpecifcType* MatSolverPackageForSpecifcType;
3951: struct _MatSolverPackageForSpecifcType {
3952:   MatType                        mtype;
3953:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
3954:   MatSolverPackageForSpecifcType next;
3955: };

3957: typedef struct _MatSolverPackageHolder* MatSolverPackageHolder;
3958: struct _MatSolverPackageHolder {
3959:   char                           *name;
3960:   MatSolverPackageForSpecifcType handlers;
3961:   MatSolverPackageHolder         next;
3962: };

3964: static MatSolverPackageHolder MatSolverPackageHolders = NULL;

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

3971:    Input Parameters:
3972: +    package - name of the package, for example petsc or superlu
3973: .    mtype - the matrix type that works with this package
3974: .    ftype - the type of factorization supported by the package
3975: -    getfactor - routine that will create the factored matrix ready to be used

3977:     Level: intermediate

3979: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
3980: @*/
3981: PetscErrorCode  MatSolverPackageRegister(const MatSolverPackage package,const MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
3982: {
3983:   PetscErrorCode                 ierr;
3984:   MatSolverPackageHolder         next = MatSolverPackageHolders,prev;
3985:   PetscBool                      flg;
3986:   MatSolverPackageForSpecifcType inext,iprev = NULL;

3989:   if (!MatSolverPackageHolders) {
3990:     PetscNew(&MatSolverPackageHolders);
3991:     PetscStrallocpy(package,&MatSolverPackageHolders->name);
3992:     PetscNew(&MatSolverPackageHolders->handlers);
3993:     PetscStrallocpy(mtype,(char **)&MatSolverPackageHolders->handlers->mtype);
3994:     MatSolverPackageHolders->handlers->getfactor[(int)ftype-1] = getfactor;
3995:     return(0);
3996:   }
3997:   while (next) {
3998:     PetscStrcasecmp(package,next->name,&flg);
3999:     if (flg) {
4000:       inext = next->handlers;
4001:       while (inext) {
4002:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4003:         if (flg) {
4004:           inext->getfactor[(int)ftype-1] = getfactor;
4005:           return(0);
4006:         }
4007:         iprev = inext;
4008:         inext = inext->next;
4009:       }
4010:       PetscNew(&iprev->next);
4011:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4012:       iprev->next->getfactor[(int)ftype-1] = getfactor;
4013:       return(0);
4014:     }
4015:     prev = next;
4016:     next = next->next;
4017:   }
4018:   PetscNew(&prev->next);
4019:   PetscStrallocpy(package,&prev->next->name);
4020:   PetscNew(&prev->next->handlers);
4021:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4022:   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4023:   return(0);
4024: }

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

4031:    Input Parameters:
4032: +    package - name of the package, for example petsc or superlu
4033: .    ftype - the type of factorization supported by the package
4034: -    mtype - the matrix type that works with this package

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

4041:     Level: intermediate

4043: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4044: @*/
4045: PetscErrorCode  MatSolverPackageGet(const MatSolverPackage package,const MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4046: {
4047:   PetscErrorCode                 ierr;
4048:   MatSolverPackageHolder         next = MatSolverPackageHolders;
4049:   PetscBool                      flg;
4050:   MatSolverPackageForSpecifcType inext;

4053:   if (foundpackage) *foundpackage = PETSC_FALSE;
4054:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4055:   if (getfactor)    *getfactor    = NULL;
4056:   while (next) {
4057:     PetscStrcasecmp(package,next->name,&flg);
4058:     if (flg) {
4059:       if (foundpackage) *foundpackage = PETSC_TRUE;
4060:       inext = next->handlers;
4061:       while (inext) {
4062:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4063:         if (flg) {
4064:           if (foundmtype) *foundmtype = PETSC_TRUE;
4065:           if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4066:           return(0);
4067:         }
4068:         inext = inext->next;
4069:       }
4070:     }
4071:     next = next->next;
4072:   }
4073:   return(0);
4074: }

4078: PetscErrorCode  MatSolverPackageDestroy(void)
4079: {
4080:   PetscErrorCode                 ierr;
4081:   MatSolverPackageHolder         next = MatSolverPackageHolders,prev;
4082:   MatSolverPackageForSpecifcType inext,iprev;

4085:   while (next) {
4086:     PetscFree(next->name);
4087:     inext = next->handlers;
4088:     while (inext) {
4089:       PetscFree(inext->mtype);
4090:       iprev = inext;
4091:       inext = inext->next;
4092:       PetscFree(iprev);
4093:     }
4094:     prev = next;
4095:     next = next->next;
4096:     PetscFree(prev);
4097:   }
4098:   MatSolverPackageHolders = NULL;
4099:   return(0);
4100: }

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

4107:    Collective on Mat

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

4114:    Output Parameters:
4115: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4117:    Notes:
4118:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4119:      such as pastix, superlu, mumps etc.

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

4123:    Level: intermediate

4125: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4126: @*/
4127: PetscErrorCode  MatGetFactor(Mat mat, const MatSolverPackage type,MatFactorType ftype,Mat *f)
4128: {
4129:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4130:   PetscBool      foundpackage,foundmtype;


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

4139:   MatSolverPackageGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4140:   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);
4141:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverPackage %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4142:   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);

4144:   (*conv)(mat,ftype,f);
4145:   return(0);
4146: }

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

4153:    Not Collective

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

4160:    Output Parameter:
4161: .    flg - PETSC_TRUE if the factorization is available

4163:    Notes:
4164:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4165:      such as pastix, superlu, mumps etc.

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

4169:    Level: intermediate

4171: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4172: @*/
4173: PetscErrorCode  MatGetFactorAvailable(Mat mat, const MatSolverPackage type,MatFactorType ftype,PetscBool  *flg)
4174: {
4175:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4184:   *flg = PETSC_FALSE;
4185:   MatSolverPackageGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4186:   if (gconv) {
4187:     *flg = PETSC_TRUE;
4188:   }
4189:   return(0);
4190: }

4194: /*@
4195:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4197:    Collective on Mat

4199:    Input Parameters:
4200: +  mat - the matrix
4201: -  op - either MAT_DO_NOT_COPY_VALUES or MAT_COPY_VALUES, cause it to copy the numerical values in the matrix
4202:         MAT_SHARE_NONZERO_PATTERN to share the nonzero patterns with the previous matrix and not copy them.

4204:    Output Parameter:
4205: .  M - pointer to place new matrix

4207:    Level: intermediate

4209:    Concepts: matrices^duplicating

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

4213: .seealso: MatCopy(), MatConvert()
4214: @*/
4215: PetscErrorCode  MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4216: {
4218:   Mat            B;
4219:   PetscInt       i;

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

4229:   *M = 0;
4230:   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4231:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4232:   (*mat->ops->duplicate)(mat,op,M);
4233:   B    = *M;

4235:   B->stencil.dim = mat->stencil.dim;
4236:   B->stencil.noc = mat->stencil.noc;
4237:   for (i=0; i<=mat->stencil.dim; i++) {
4238:     B->stencil.dims[i]   = mat->stencil.dims[i];
4239:     B->stencil.starts[i] = mat->stencil.starts[i];
4240:   }

4242:   B->nooffproczerorows = mat->nooffproczerorows;
4243:   B->nooffprocentries  = mat->nooffprocentries;

4245:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4246:   PetscObjectStateIncrease((PetscObject)B);
4247:   return(0);
4248: }

4252: /*@
4253:    MatGetDiagonal - Gets the diagonal of a matrix.

4255:    Logically Collective on Mat and Vec

4257:    Input Parameters:
4258: +  mat - the matrix
4259: -  v - the vector for storing the diagonal

4261:    Output Parameter:
4262: .  v - the diagonal of the matrix

4264:    Level: intermediate

4266:    Note:
4267:    Currently only correct in parallel for square matrices.

4269:    Concepts: matrices^accessing diagonals

4271: .seealso: MatGetRow(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs()
4272: @*/
4273: PetscErrorCode  MatGetDiagonal(Mat mat,Vec v)
4274: {

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

4285:   (*mat->ops->getdiagonal)(mat,v);
4286:   PetscObjectStateIncrease((PetscObject)v);
4287:   return(0);
4288: }

4292: /*@
4293:    MatGetRowMin - Gets the minimum value (of the real part) of each
4294:         row of the matrix

4296:    Logically Collective on Mat and Vec

4298:    Input Parameters:
4299: .  mat - the matrix

4301:    Output Parameter:
4302: +  v - the vector for storing the maximums
4303: -  idx - the indices of the column found for each row (optional)

4305:    Level: intermediate

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

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

4312:    Concepts: matrices^getting row maximums

4314: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(),
4315:           MatGetRowMax()
4316: @*/
4317: PetscErrorCode  MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4318: {

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

4329:   (*mat->ops->getrowmin)(mat,v,idx);
4330:   PetscObjectStateIncrease((PetscObject)v);
4331:   return(0);
4332: }

4336: /*@
4337:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4338:         row of the matrix

4340:    Logically Collective on Mat and Vec

4342:    Input Parameters:
4343: .  mat - the matrix

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

4349:    Level: intermediate

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

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

4356:    Concepts: matrices^getting row maximums

4358: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4359: @*/
4360: PetscErrorCode  MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4361: {

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

4373:   (*mat->ops->getrowminabs)(mat,v,idx);
4374:   PetscObjectStateIncrease((PetscObject)v);
4375:   return(0);
4376: }

4380: /*@
4381:    MatGetRowMax - Gets the maximum value (of the real part) of each
4382:         row of the matrix

4384:    Logically Collective on Mat and Vec

4386:    Input Parameters:
4387: .  mat - the matrix

4389:    Output Parameter:
4390: +  v - the vector for storing the maximums
4391: -  idx - the indices of the column found for each row (optional)

4393:    Level: intermediate

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

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

4400:    Concepts: matrices^getting row maximums

4402: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4403: @*/
4404: PetscErrorCode  MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4405: {

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

4416:   (*mat->ops->getrowmax)(mat,v,idx);
4417:   PetscObjectStateIncrease((PetscObject)v);
4418:   return(0);
4419: }

4423: /*@
4424:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4425:         row of the matrix

4427:    Logically Collective on Mat and Vec

4429:    Input Parameters:
4430: .  mat - the matrix

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

4436:    Level: intermediate

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

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

4443:    Concepts: matrices^getting row maximums

4445: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
4446: @*/
4447: PetscErrorCode  MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4448: {

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

4460:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4461:   PetscObjectStateIncrease((PetscObject)v);
4462:   return(0);
4463: }

4467: /*@
4468:    MatGetRowSum - Gets the sum of each row of the matrix

4470:    Logically Collective on Mat and Vec

4472:    Input Parameters:
4473: .  mat - the matrix

4475:    Output Parameter:
4476: .  v - the vector for storing the sum of rows

4478:    Level: intermediate

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

4482:    Concepts: matrices^getting row sums

4484: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
4485: @*/
4486: PetscErrorCode  MatGetRowSum(Mat mat, Vec v)
4487: {
4488:   PetscInt       start = 0, end = 0, row;
4489:   PetscScalar    *array;

4496:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4497:   MatCheckPreallocated(mat,1);
4498:   MatGetOwnershipRange(mat, &start, &end);
4499:   VecGetArray(v, &array);
4500:   for (row = start; row < end; ++row) {
4501:     PetscInt          ncols, col;
4502:     const PetscInt    *cols;
4503:     const PetscScalar *vals;

4505:     array[row - start] = 0.0;

4507:     MatGetRow(mat, row, &ncols, &cols, &vals);
4508:     for (col = 0; col < ncols; col++) {
4509:       array[row - start] += vals[col];
4510:     }
4511:     MatRestoreRow(mat, row, &ncols, &cols, &vals);
4512:   }
4513:   VecRestoreArray(v, &array);
4514:   PetscObjectStateIncrease((PetscObject) v);
4515:   return(0);
4516: }

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

4523:    Collective on Mat

4525:    Input Parameter:
4526: +  mat - the matrix to transpose
4527: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4529:    Output Parameters:
4530: .  B - the transpose

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

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

4537:    Level: intermediate

4539:    Concepts: matrices^transposing

4541: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4542: @*/
4543: PetscErrorCode  MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4544: {

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

4555:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4556:   (*mat->ops->transpose)(mat,reuse,B);
4557:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4558:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4559:   return(0);
4560: }

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

4568:    Collective on Mat

4570:    Input Parameter:
4571: +  A - the matrix to test
4572: -  B - the matrix to test against, this can equal the first parameter

4574:    Output Parameters:
4575: .  flg - the result

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

4582:    Level: intermediate

4584:    Concepts: matrices^transposing, matrix^symmetry

4586: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4587: @*/
4588: PetscErrorCode  MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4589: {
4590:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4596:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4597:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4598:   *flg = PETSC_FALSE;
4599:   if (f && g) {
4600:     if (f == g) {
4601:       (*f)(A,B,tol,flg);
4602:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4603:   } else {
4604:     MatType mattype;
4605:     if (!f) {
4606:       MatGetType(A,&mattype);
4607:     } else {
4608:       MatGetType(B,&mattype);
4609:     }
4610:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4611:   }
4612:   return(0);
4613: }

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

4620:    Collective on Mat

4622:    Input Parameter:
4623: +  mat - the matrix to transpose and complex conjugate
4624: -  reuse - store the transpose matrix in the provided B

4626:    Output Parameters:
4627: .  B - the Hermitian

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

4632:    Level: intermediate

4634:    Concepts: matrices^transposing, complex conjugatex

4636: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4637: @*/
4638: PetscErrorCode  MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4639: {

4643:   MatTranspose(mat,reuse,B);
4644: #if defined(PETSC_USE_COMPLEX)
4645:   MatConjugate(*B);
4646: #endif
4647:   return(0);
4648: }

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

4655:    Collective on Mat

4657:    Input Parameter:
4658: +  A - the matrix to test
4659: -  B - the matrix to test against, this can equal the first parameter

4661:    Output Parameters:
4662: .  flg - the result

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

4669:    Level: intermediate

4671:    Concepts: matrices^transposing, matrix^symmetry

4673: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4674: @*/
4675: PetscErrorCode  MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4676: {
4677:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4683:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4684:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
4685:   if (f && g) {
4686:     if (f==g) {
4687:       (*f)(A,B,tol,flg);
4688:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4689:   }
4690:   return(0);
4691: }

4695: /*@
4696:    MatPermute - Creates a new matrix with rows and columns permuted from the
4697:    original.

4699:    Collective on Mat

4701:    Input Parameters:
4702: +  mat - the matrix to permute
4703: .  row - row permutation, each processor supplies only the permutation for its rows
4704: -  col - column permutation, each processor supplies only the permutation for its columns

4706:    Output Parameters:
4707: .  B - the permuted matrix

4709:    Level: advanced

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

4715:    Concepts: matrices^permuting

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

4719: @*/
4720: PetscErrorCode  MatPermute(Mat mat,IS row,IS col,Mat *B)
4721: {

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

4735:   (*mat->ops->permute)(mat,row,col,B);
4736:   PetscObjectStateIncrease((PetscObject)*B);
4737:   return(0);
4738: }

4742: /*@
4743:    MatEqual - Compares two matrices.

4745:    Collective on Mat

4747:    Input Parameters:
4748: +  A - the first matrix
4749: -  B - the second matrix

4751:    Output Parameter:
4752: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

4754:    Level: intermediate

4756:    Concepts: matrices^equality between
4757: @*/
4758: PetscErrorCode  MatEqual(Mat A,Mat B,PetscBool  *flg)
4759: {

4769:   MatCheckPreallocated(B,2);
4770:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4771:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4772:   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);
4773:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
4774:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
4775:   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);
4776:   MatCheckPreallocated(A,1);

4778:   (*A->ops->equal)(A,B,flg);
4779:   return(0);
4780: }

4784: /*@
4785:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
4786:    matrices that are stored as vectors.  Either of the two scaling
4787:    matrices can be NULL.

4789:    Collective on Mat

4791:    Input Parameters:
4792: +  mat - the matrix to be scaled
4793: .  l - the left scaling vector (or NULL)
4794: -  r - the right scaling vector (or NULL)

4796:    Notes:
4797:    MatDiagonalScale() computes A = LAR, where
4798:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
4799:    The L scales the rows of the matrix, the R scales the columns of the matrix.

4801:    Level: intermediate

4803:    Concepts: matrices^diagonal scaling
4804:    Concepts: diagonal scaling of matrices

4806: .seealso: MatScale()
4807: @*/
4808: PetscErrorCode  MatDiagonalScale(Mat mat,Vec l,Vec r)
4809: {

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

4822:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
4823:   (*mat->ops->diagonalscale)(mat,l,r);
4824:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
4825:   PetscObjectStateIncrease((PetscObject)mat);
4826: #if defined(PETSC_HAVE_CUSP)
4827:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
4828:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
4829:   }
4830: #endif
4831: #if defined(PETSC_HAVE_VIENNACL)
4832:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
4833:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
4834:   }
4835: #endif
4836:   return(0);
4837: }

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

4844:     Logically Collective on Mat

4846:     Input Parameters:
4847: +   mat - the matrix to be scaled
4848: -   a  - the scaling value

4850:     Output Parameter:
4851: .   mat - the scaled matrix

4853:     Level: intermediate

4855:     Concepts: matrices^scaling all entries

4857: .seealso: MatDiagonalScale()
4858: @*/
4859: PetscErrorCode  MatScale(Mat mat,PetscScalar a)
4860: {

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

4872:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
4873:   if (a != (PetscScalar)1.0) {
4874:     (*mat->ops->scale)(mat,a);
4875:     PetscObjectStateIncrease((PetscObject)mat);
4876:   }
4877:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
4878: #if defined(PETSC_HAVE_CUSP)
4879:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
4880:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
4881:   }
4882: #endif
4883: #if defined(PETSC_HAVE_VIENNACL)
4884:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
4885:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
4886:   }
4887: #endif
4888:   return(0);
4889: }

4893: /*@
4894:    MatNorm - Calculates various norms of a matrix.

4896:    Collective on Mat

4898:    Input Parameters:
4899: +  mat - the matrix
4900: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

4902:    Output Parameters:
4903: .  nrm - the resulting norm

4905:    Level: intermediate

4907:    Concepts: matrices^norm
4908:    Concepts: norm^of matrix
4909: @*/
4910: PetscErrorCode  MatNorm(Mat mat,NormType type,PetscReal *nrm)
4911: {


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

4924:   (*mat->ops->norm)(mat,type,nrm);
4925:   return(0);
4926: }

4928: /*
4929:      This variable is used to prevent counting of MatAssemblyBegin() that
4930:    are called from within a MatAssemblyEnd().
4931: */
4932: static PetscInt MatAssemblyEnd_InUse = 0;
4935: /*@
4936:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
4937:    be called after completing all calls to MatSetValues().

4939:    Collective on Mat

4941:    Input Parameters:
4942: +  mat - the matrix
4943: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

4945:    Notes:
4946:    MatSetValues() generally caches the values.  The matrix is ready to
4947:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
4948:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
4949:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
4950:    using the matrix.

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

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

4960:    Level: beginner

4962:    Concepts: matrices^assembling

4964: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
4965: @*/
4966: PetscErrorCode  MatAssemblyBegin(Mat mat,MatAssemblyType type)
4967: {

4973:   MatCheckPreallocated(mat,1);
4974:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
4975:   if (mat->assembled) {
4976:     mat->was_assembled = PETSC_TRUE;
4977:     mat->assembled     = PETSC_FALSE;
4978:   }
4979:   if (!MatAssemblyEnd_InUse) {
4980:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
4981:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
4982:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
4983:   } else if (mat->ops->assemblybegin) {
4984:     (*mat->ops->assemblybegin)(mat,type);
4985:   }
4986:   return(0);
4987: }

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

4995:    Not Collective

4997:    Input Parameter:
4998: .  mat - the matrix

5000:    Output Parameter:
5001: .  assembled - PETSC_TRUE or PETSC_FALSE

5003:    Level: advanced

5005:    Concepts: matrices^assembled?

5007: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5008: @*/
5009: PetscErrorCode  MatAssembled(Mat mat,PetscBool  *assembled)
5010: {
5015:   *assembled = mat->assembled;
5016:   return(0);
5017: }

5021: /*@
5022:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5023:    be called after MatAssemblyBegin().

5025:    Collective on Mat

5027:    Input Parameters:
5028: +  mat - the matrix
5029: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5031:    Options Database Keys:
5032: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5033: .  -mat_view ::ascii_info_detail - Prints more detailed info
5034: .  -mat_view - Prints matrix in ASCII format
5035: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5036: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5037: .  -display <name> - Sets display name (default is host)
5038: .  -draw_pause <sec> - Sets number of seconds to pause after display
5039: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 10 Using MATLAB with PETSc )
5040: .  -viewer_socket_machine <machine>
5041: .  -viewer_socket_port <port>
5042: .  -mat_view binary - save matrix to file in binary format
5043: -  -viewer_binary_filename <name>

5045:    Notes:
5046:    MatSetValues() generally caches the values.  The matrix is ready to
5047:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5048:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5049:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5050:    using the matrix.

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

5056:    Level: beginner

5058: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5059: @*/
5060: PetscErrorCode  MatAssemblyEnd(Mat mat,MatAssemblyType type)
5061: {
5062:   PetscErrorCode  ierr;
5063:   static PetscInt inassm = 0;
5064:   PetscBool       flg    = PETSC_FALSE;


5070:   inassm++;
5071:   MatAssemblyEnd_InUse++;
5072:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5073:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5074:     if (mat->ops->assemblyend) {
5075:       (*mat->ops->assemblyend)(mat,type);
5076:     }
5077:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5078:   } else if (mat->ops->assemblyend) {
5079:     (*mat->ops->assemblyend)(mat,type);
5080:   }

5082:   /* Flush assembly is not a true assembly */
5083:   if (type != MAT_FLUSH_ASSEMBLY) {
5084:     mat->assembled = PETSC_TRUE; mat->num_ass++;
5085:   }
5086:   mat->insertmode = NOT_SET_VALUES;
5087:   MatAssemblyEnd_InUse--;
5088:   PetscObjectStateIncrease((PetscObject)mat);
5089:   if (!mat->symmetric_eternal) {
5090:     mat->symmetric_set              = PETSC_FALSE;
5091:     mat->hermitian_set              = PETSC_FALSE;
5092:     mat->structurally_symmetric_set = PETSC_FALSE;
5093:   }
5094: #if defined(PETSC_HAVE_CUSP)
5095:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5096:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5097:   }
5098: #endif
5099: #if defined(PETSC_HAVE_VIENNACL)
5100:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5101:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5102:   }
5103: #endif
5104:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5105:     MatViewFromOptions(mat,NULL,"-mat_view");

5107:     if (mat->checksymmetryonassembly) {
5108:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5109:       if (flg) {
5110:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5111:       } else {
5112:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5113:       }
5114:     }
5115:     if (mat->nullsp && mat->checknullspaceonassembly) {
5116:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5117:     }
5118:   }
5119:   inassm--;
5120:   return(0);
5121: }

5125: /*@
5126:    MatSetOption - Sets a parameter option for a matrix. Some options
5127:    may be specific to certain storage formats.  Some options
5128:    determine how values will be inserted (or added). Sorted,
5129:    row-oriented input will generally assemble the fastest. The default
5130:    is row-oriented.

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

5134:    Input Parameters:
5135: +  mat - the matrix
5136: .  option - the option, one of those listed below (and possibly others),
5137: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5139:   Options Describing Matrix Structure:
5140: +    MAT_SPD - symmetric positive definite
5141: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5142: .    MAT_HERMITIAN - transpose is the complex conjugation
5143: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5144: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5145:                             you set to be kept with all future use of the matrix
5146:                             including after MatAssemblyBegin/End() which could
5147:                             potentially change the symmetry structure, i.e. you
5148:                             KNOW the matrix will ALWAYS have the property you set.


5151:    Options For Use with MatSetValues():
5152:    Insert a logically dense subblock, which can be
5153: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

5170:    Notes:
5171:    Some options are relevant only for particular matrix types and
5172:    are thus ignored by others.  Other options are not supported by
5173:    certain matrix types and will generate an error message if set.

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

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

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

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

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

5201:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5202:    searches during matrix assembly. When this flag is set, the hash table
5203:    is created during the first Matrix Assembly. This hash table is
5204:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5205:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5206:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5207:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5226:    Level: intermediate

5228:    Concepts: matrices^setting options

5230: .seealso:  MatOption, Mat

5232: @*/
5233: PetscErrorCode  MatSetOption(Mat mat,MatOption op,PetscBool flg)
5234: {

5240:   if (op > 0) {
5243:   }

5245:   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);
5246:   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()");

5248:   switch (op) {
5249:   case MAT_NO_OFF_PROC_ENTRIES:
5250:     mat->nooffprocentries = flg;
5251:     return(0);
5252:     break;
5253:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5254:     mat->nooffproczerorows = flg;
5255:     return(0);
5256:     break;
5257:   case MAT_SPD:
5258:     mat->spd_set = PETSC_TRUE;
5259:     mat->spd     = flg;
5260:     if (flg) {
5261:       mat->symmetric                  = PETSC_TRUE;
5262:       mat->structurally_symmetric     = PETSC_TRUE;
5263:       mat->symmetric_set              = PETSC_TRUE;
5264:       mat->structurally_symmetric_set = PETSC_TRUE;
5265:     }
5266:     break;
5267:   case MAT_SYMMETRIC:
5268:     mat->symmetric = flg;
5269:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5270:     mat->symmetric_set              = PETSC_TRUE;
5271:     mat->structurally_symmetric_set = flg;
5272:     break;
5273:   case MAT_HERMITIAN:
5274:     mat->hermitian = flg;
5275:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5276:     mat->hermitian_set              = PETSC_TRUE;
5277:     mat->structurally_symmetric_set = flg;
5278:     break;
5279:   case MAT_STRUCTURALLY_SYMMETRIC:
5280:     mat->structurally_symmetric     = flg;
5281:     mat->structurally_symmetric_set = PETSC_TRUE;
5282:     break;
5283:   case MAT_SYMMETRY_ETERNAL:
5284:     mat->symmetric_eternal = flg;
5285:     break;
5286:   default:
5287:     break;
5288:   }
5289:   if (mat->ops->setoption) {
5290:     (*mat->ops->setoption)(mat,op,flg);
5291:   }
5292:   return(0);
5293: }

5297: /*@
5298:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5299:    this routine retains the old nonzero structure.

5301:    Logically Collective on Mat

5303:    Input Parameters:
5304: .  mat - the matrix

5306:    Level: intermediate

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

5311:    Concepts: matrices^zeroing

5313: .seealso: MatZeroRows()
5314: @*/
5315: PetscErrorCode  MatZeroEntries(Mat mat)
5316: {

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

5327:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5328:   (*mat->ops->zeroentries)(mat);
5329:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5330:   PetscObjectStateIncrease((PetscObject)mat);
5331: #if defined(PETSC_HAVE_CUSP)
5332:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5333:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5334:   }
5335: #endif
5336: #if defined(PETSC_HAVE_VIENNACL)
5337:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5338:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5339:   }
5340: #endif
5341:   return(0);
5342: }

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

5350:    Collective on Mat

5352:    Input Parameters:
5353: +  mat - the matrix
5354: .  numRows - the number of rows to remove
5355: .  rows - the global row indices
5356: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5357: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5358: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5377:    Level: intermediate

5379:    Concepts: matrices^zeroing rows

5381: .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(), MatZeroRowsColumnsIS()
5382: @*/
5383: PetscErrorCode  MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5384: {

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

5396:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5397:   MatViewFromOptions(mat,NULL,"-mat_view");
5398:   PetscObjectStateIncrease((PetscObject)mat);
5399: #if defined(PETSC_HAVE_CUSP)
5400:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5401:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5402:   }
5403: #endif
5404: #if defined(PETSC_HAVE_VIENNACL)
5405:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5406:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5407:   }
5408: #endif
5409:   return(0);
5410: }

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

5418:    Collective on Mat

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

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

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

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

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

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

5444:    Level: intermediate

5446:    Concepts: matrices^zeroing rows

5448: .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(), MatZeroRowsColumns()
5449: @*/
5450: PetscErrorCode  MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5451: {
5453:   PetscInt       numRows;
5454:   const PetscInt *rows;

5461:   ISGetLocalSize(is,&numRows);
5462:   ISGetIndices(is,&rows);
5463:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5464:   ISRestoreIndices(is,&rows);
5465:   return(0);
5466: }

5470: /*@C
5471:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5472:    of a set of rows of a matrix.

5474:    Collective on Mat

5476:    Input Parameters:
5477: +  mat - the matrix
5478: .  numRows - the number of rows to remove
5479: .  rows - the global row indices
5480: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5481: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5482: -  b - optional vector of right hand side, that will be adjusted by provided solution

5484:    Notes:
5485:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5486:    but does not release memory.  For the dense and block diagonal
5487:    formats this does not alter the nonzero structure.

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

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

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

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

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

5508:    Level: intermediate

5510:    Concepts: matrices^zeroing rows

5512: .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5513: @*/
5514: PetscErrorCode  MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5515: {

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

5527:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5528:   MatViewFromOptions(mat,NULL,"-mat_view");
5529:   PetscObjectStateIncrease((PetscObject)mat);
5530: #if defined(PETSC_HAVE_CUSP)
5531:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5532:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5533:   }
5534: #endif
5535: #if defined(PETSC_HAVE_VIENNACL)
5536:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5537:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5538:   }
5539: #endif
5540:   return(0);
5541: }

5545: /*@C
5546:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5547:    of a set of rows of a matrix.

5549:    Collective on Mat

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

5558:    Notes:
5559:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5560:    but does not release memory.  For the dense and block diagonal
5561:    formats this does not alter the nonzero structure.

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

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

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

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

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

5582:    Level: intermediate

5584:    Concepts: matrices^zeroing rows

5586: .seealso: MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5587: @*/
5588: PetscErrorCode  MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5589: {
5590:   PetscInt       numRows;
5591:   const PetscInt *rows;

5598:   ISGetLocalSize(is,&numRows);
5599:   ISGetIndices(is,&rows);
5600:   MatZeroRows(mat,numRows,rows,diag,x,b);
5601:   ISRestoreIndices(is,&rows);
5602:   return(0);
5603: }

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

5611:    Collective on Mat

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

5621:    Notes:
5622:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5623:    but does not release memory.  For the dense and block diagonal
5624:    formats this does not alter the nonzero structure.

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

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

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

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

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

5644:    In Fortran idxm and idxn should be declared as
5645: $     MatStencil idxm(4,m)
5646:    and the values inserted using
5647: $    idxm(MatStencil_i,1) = i
5648: $    idxm(MatStencil_j,1) = j
5649: $    idxm(MatStencil_k,1) = k
5650: $    idxm(MatStencil_c,1) = c
5651:    etc

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

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

5661:    Level: intermediate

5663:    Concepts: matrices^zeroing rows

5665: .seealso: MatZeroRows(), MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5666: @*/
5667: PetscErrorCode  MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5668: {
5669:   PetscInt       dim     = mat->stencil.dim;
5670:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5671:   PetscInt       *dims   = mat->stencil.dims+1;
5672:   PetscInt       *starts = mat->stencil.starts;
5673:   PetscInt       *dxm    = (PetscInt*) rows;
5674:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5682:   PetscMalloc1(numRows, &jdxm);
5683:   for (i = 0; i < numRows; ++i) {
5684:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5685:     for (j = 0; j < 3-sdim; ++j) dxm++;
5686:     /* Local index in X dir */
5687:     tmp = *dxm++ - starts[0];
5688:     /* Loop over remaining dimensions */
5689:     for (j = 0; j < dim-1; ++j) {
5690:       /* If nonlocal, set index to be negative */
5691:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5692:       /* Update local index */
5693:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5694:     }
5695:     /* Skip component slot if necessary */
5696:     if (mat->stencil.noc) dxm++;
5697:     /* Local row number */
5698:     if (tmp >= 0) {
5699:       jdxm[numNewRows++] = tmp;
5700:     }
5701:   }
5702:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5703:   PetscFree(jdxm);
5704:   return(0);
5705: }

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

5713:    Collective on Mat

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

5723:    Notes:
5724:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5725:    but does not release memory.  For the dense and block diagonal
5726:    formats this does not alter the nonzero structure.

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

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

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

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

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

5746:    In Fortran idxm and idxn should be declared as
5747: $     MatStencil idxm(4,m)
5748:    and the values inserted using
5749: $    idxm(MatStencil_i,1) = i
5750: $    idxm(MatStencil_j,1) = j
5751: $    idxm(MatStencil_k,1) = k
5752: $    idxm(MatStencil_c,1) = c
5753:    etc

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

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

5763:    Level: intermediate

5765:    Concepts: matrices^zeroing rows

5767: .seealso: MatZeroRows(), MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5768: @*/
5769: PetscErrorCode  MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5770: {
5771:   PetscInt       dim     = mat->stencil.dim;
5772:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5773:   PetscInt       *dims   = mat->stencil.dims+1;
5774:   PetscInt       *starts = mat->stencil.starts;
5775:   PetscInt       *dxm    = (PetscInt*) rows;
5776:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5784:   PetscMalloc1(numRows, &jdxm);
5785:   for (i = 0; i < numRows; ++i) {
5786:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5787:     for (j = 0; j < 3-sdim; ++j) dxm++;
5788:     /* Local index in X dir */
5789:     tmp = *dxm++ - starts[0];
5790:     /* Loop over remaining dimensions */
5791:     for (j = 0; j < dim-1; ++j) {
5792:       /* If nonlocal, set index to be negative */
5793:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5794:       /* Update local index */
5795:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5796:     }
5797:     /* Skip component slot if necessary */
5798:     if (mat->stencil.noc) dxm++;
5799:     /* Local row number */
5800:     if (tmp >= 0) {
5801:       jdxm[numNewRows++] = tmp;
5802:     }
5803:   }
5804:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
5805:   PetscFree(jdxm);
5806:   return(0);
5807: }

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

5815:    Collective on Mat

5817:    Input Parameters:
5818: +  mat - the matrix
5819: .  numRows - the number of rows to remove
5820: .  rows - the global row indices
5821: .  diag - value put in all diagonals of eliminated rows
5822: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5823: -  b - optional vector of right hand side, that will be adjusted by provided solution

5825:    Notes:
5826:    Before calling MatZeroRowsLocal(), the user must first set the
5827:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

5829:    For the AIJ matrix formats this removes the old nonzero structure,
5830:    but does not release memory.  For the dense and block diagonal
5831:    formats this does not alter the nonzero structure.

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

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

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

5844:    Level: intermediate

5846:    Concepts: matrices^zeroing

5848: .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5849: @*/
5850: PetscErrorCode  MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5851: {

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

5862:   if (mat->ops->zerorowslocal) {
5863:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
5864:   } else {
5865:     IS             is, newis;
5866:     const PetscInt *newRows;

5868:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
5869:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
5870:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
5871:     ISGetIndices(newis,&newRows);
5872:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
5873:     ISRestoreIndices(newis,&newRows);
5874:     ISDestroy(&newis);
5875:     ISDestroy(&is);
5876:   }
5877:   PetscObjectStateIncrease((PetscObject)mat);
5878: #if defined(PETSC_HAVE_CUSP)
5879:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5880:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5881:   }
5882: #endif
5883: #if defined(PETSC_HAVE_VIENNACL)
5884:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5885:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5886:   }
5887: #endif
5888:   return(0);
5889: }

5893: /*@C
5894:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
5895:    of a set of rows of a matrix; using local numbering of rows.

5897:    Collective on Mat

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

5906:    Notes:
5907:    Before calling MatZeroRowsLocalIS(), the user must first set the
5908:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

5910:    For the AIJ matrix formats this removes the old nonzero structure,
5911:    but does not release memory.  For the dense and block diagonal
5912:    formats this does not alter the nonzero structure.

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

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

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

5925:    Level: intermediate

5927:    Concepts: matrices^zeroing

5929: .seealso: MatZeroRows(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5930: @*/
5931: PetscErrorCode  MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5932: {
5934:   PetscInt       numRows;
5935:   const PetscInt *rows;

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

5945:   ISGetLocalSize(is,&numRows);
5946:   ISGetIndices(is,&rows);
5947:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
5948:   ISRestoreIndices(is,&rows);
5949:   return(0);
5950: }

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

5958:    Collective on Mat

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

5968:    Notes:
5969:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
5970:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

5976:    Level: intermediate

5978:    Concepts: matrices^zeroing

5980: .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5981: @*/
5982: PetscErrorCode  MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5983: {
5985:   IS             is, newis;
5986:   const PetscInt *newRows;

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

5996:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
5997:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
5998:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
5999:   ISGetIndices(newis,&newRows);
6000:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6001:   ISRestoreIndices(newis,&newRows);
6002:   ISDestroy(&newis);
6003:   ISDestroy(&is);
6004:   PetscObjectStateIncrease((PetscObject)mat);
6005: #if defined(PETSC_HAVE_CUSP)
6006:   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
6007:     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
6008:   }
6009: #endif
6010: #if defined(PETSC_HAVE_VIENNACL)
6011:   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
6012:     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
6013:   }
6014: #endif
6015:   return(0);
6016: }

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

6024:    Collective on Mat

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

6033:    Notes:
6034:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6035:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6041:    Level: intermediate

6043:    Concepts: matrices^zeroing

6045: .seealso: MatZeroRows(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
6046: @*/
6047: PetscErrorCode  MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6048: {
6050:   PetscInt       numRows;
6051:   const PetscInt *rows;

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

6061:   ISGetLocalSize(is,&numRows);
6062:   ISGetIndices(is,&rows);
6063:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6064:   ISRestoreIndices(is,&rows);
6065:   return(0);
6066: }

6070: /*@
6071:    MatGetSize - Returns the numbers of rows and columns in a matrix.

6073:    Not Collective

6075:    Input Parameter:
6076: .  mat - the matrix

6078:    Output Parameters:
6079: +  m - the number of global rows
6080: -  n - the number of global columns

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

6084:    Level: beginner

6086:    Concepts: matrices^size

6088: .seealso: MatGetLocalSize()
6089: @*/
6090: PetscErrorCode  MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6091: {
6094:   if (m) *m = mat->rmap->N;
6095:   if (n) *n = mat->cmap->N;
6096:   return(0);
6097: }

6101: /*@
6102:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6103:    stored locally.  This information may be implementation dependent, so
6104:    use with care.

6106:    Not Collective

6108:    Input Parameters:
6109: .  mat - the matrix

6111:    Output Parameters:
6112: +  m - the number of local rows
6113: -  n - the number of local columns

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

6117:    Level: beginner

6119:    Concepts: matrices^local size

6121: .seealso: MatGetSize()
6122: @*/
6123: PetscErrorCode  MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6124: {
6129:   if (m) *m = mat->rmap->n;
6130:   if (n) *n = mat->cmap->n;
6131:   return(0);
6132: }

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

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

6142:    Input Parameters:
6143: .  mat - the matrix

6145:    Output Parameters:
6146: +  m - the global index of the first local column
6147: -  n - one more than the global index of the last local column

6149:    Notes: both output parameters can be NULL on input.

6151:    Level: developer

6153:    Concepts: matrices^column ownership

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

6157: @*/
6158: PetscErrorCode  MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6159: {
6165:   MatCheckPreallocated(mat,1);
6166:   if (m) *m = mat->cmap->rstart;
6167:   if (n) *n = mat->cmap->rend;
6168:   return(0);
6169: }

6173: /*@
6174:    MatGetOwnershipRange - Returns the range of matrix rows owned by
6175:    this processor, assuming that the matrix is laid out with the first
6176:    n1 rows on the first processor, the next n2 rows on the second, etc.
6177:    For certain parallel layouts this range may not be well defined.

6179:    Not Collective

6181:    Input Parameters:
6182: .  mat - the matrix

6184:    Output Parameters:
6185: +  m - the global index of the first local row
6186: -  n - one more than the global index of the last local row

6188:    Note: Both output parameters can be NULL on input.
6189: $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6190: $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6191: $  and then MPI_Scan() to calculate prefix sums of the local sizes.

6193:    Level: beginner

6195:    Concepts: matrices^row ownership

6197: .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()

6199: @*/
6200: PetscErrorCode  MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6201: {
6207:   MatCheckPreallocated(mat,1);
6208:   if (m) *m = mat->rmap->rstart;
6209:   if (n) *n = mat->rmap->rend;
6210:   return(0);
6211: }

6215: /*@C
6216:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6217:    each process

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

6221:    Input Parameters:
6222: .  mat - the matrix

6224:    Output Parameters:
6225: .  ranges - start of each processors portion plus one more then the total length at the end

6227:    Level: beginner

6229:    Concepts: matrices^row ownership

6231: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()

6233: @*/
6234: PetscErrorCode  MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6235: {

6241:   MatCheckPreallocated(mat,1);
6242:   PetscLayoutGetRanges(mat->rmap,ranges);
6243:   return(0);
6244: }

6248: /*@C
6249:    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6250:    this processor. (The columns of the "diagonal blocks" for each process)

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

6254:    Input Parameters:
6255: .  mat - the matrix

6257:    Output Parameters:
6258: .  ranges - start of each processors portion plus one more then the total length at the end

6260:    Level: beginner

6262:    Concepts: matrices^column ownership

6264: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()

6266: @*/
6267: PetscErrorCode  MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6268: {

6274:   MatCheckPreallocated(mat,1);
6275:   PetscLayoutGetRanges(mat->cmap,ranges);
6276:   return(0);
6277: }

6281: /*@C
6282:    MatGetOwnershipIS - Get row and column ownership as index sets

6284:    Not Collective

6286:    Input Arguments:
6287: .  A - matrix of type Elemental

6289:    Output Arguments:
6290: +  rows - rows in which this process owns elements
6291: .  cols - columns in which this process owns elements

6293:    Level: intermediate

6295: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL, MatSetValues()
6296: @*/
6297: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6298: {
6299:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6302:   MatCheckPreallocated(A,1);
6303:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6304:   if (f) {
6305:     (*f)(A,rows,cols);
6306:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6307:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6308:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6309:   }
6310:   return(0);
6311: }

6315: /*@C
6316:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6317:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6318:    to complete the factorization.

6320:    Collective on Mat

6322:    Input Parameters:
6323: +  mat - the matrix
6324: .  row - row permutation
6325: .  column - column permutation
6326: -  info - structure containing
6327: $      levels - number of levels of fill.
6328: $      expected fill - as ratio of original fill.
6329: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6330:                 missing diagonal entries)

6332:    Output Parameters:
6333: .  fact - new matrix that has been symbolically factored

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

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

6341:    Level: developer

6343:   Concepts: matrices^symbolic LU factorization
6344:   Concepts: matrices^factorization
6345:   Concepts: LU^symbolic factorization

6347: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6348:           MatGetOrdering(), MatFactorInfo

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

6353: @*/
6354: PetscErrorCode  MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6355: {

6365:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6366:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6367:   if (!(fact)->ops->ilufactorsymbolic) {
6368:     const MatSolverPackage spackage;
6369:     MatFactorGetSolverPackage(fact,&spackage);
6370:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6371:   }
6372:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6373:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6374:   MatCheckPreallocated(mat,2);

6376:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6377:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6378:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6379:   return(0);
6380: }

6384: /*@C
6385:    MatICCFactorSymbolic - Performs symbolic incomplete
6386:    Cholesky factorization for a symmetric matrix.  Use
6387:    MatCholeskyFactorNumeric() to complete the factorization.

6389:    Collective on Mat

6391:    Input Parameters:
6392: +  mat - the matrix
6393: .  perm - row and column permutation
6394: -  info - structure containing
6395: $      levels - number of levels of fill.
6396: $      expected fill - as ratio of original fill.

6398:    Output Parameter:
6399: .  fact - the factored matrix

6401:    Notes:
6402:    Most users should employ the KSP interface for linear solvers
6403:    instead of working directly with matrix algebra routines such as this.
6404:    See, e.g., KSPCreate().

6406:    Level: developer

6408:   Concepts: matrices^symbolic incomplete Cholesky factorization
6409:   Concepts: matrices^factorization
6410:   Concepts: Cholsky^symbolic factorization

6412: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

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

6417: @*/
6418: PetscErrorCode  MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6419: {

6428:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6429:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6430:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6431:   if (!(fact)->ops->iccfactorsymbolic) {
6432:     const MatSolverPackage spackage;
6433:     MatFactorGetSolverPackage(fact,&spackage);
6434:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6435:   }
6436:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6437:   MatCheckPreallocated(mat,2);

6439:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6440:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6441:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6442:   return(0);
6443: }

6447: /*@C
6448:    MatGetSubMatrices - Extracts several submatrices from a matrix. If submat
6449:    points to an array of valid matrices, they may be reused to store the new
6450:    submatrices.

6452:    Collective on Mat

6454:    Input Parameters:
6455: +  mat - the matrix
6456: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6457: .  irow, icol - index sets of rows and columns to extract (must be sorted)
6458: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6460:    Output Parameter:
6461: .  submat - the array of submatrices

6463:    Notes:
6464:    MatGetSubMatrices() can extract ONLY sequential submatrices
6465:    (from both sequential and parallel matrices). Use MatGetSubMatrix()
6466:    to extract a parallel submatrix.

6468:    Currently both row and column indices must be sorted to guarantee
6469:    correctness with all matrix types.

6471:    When extracting submatrices from a parallel matrix, each processor can
6472:    form a different submatrix by setting the rows and columns of its
6473:    individual index sets according to the local submatrix desired.

6475:    When finished using the submatrices, the user should destroy
6476:    them with MatDestroyMatrices().

6478:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6479:    original matrix has not changed from that last call to MatGetSubMatrices().

6481:    This routine creates the matrices in submat; you should NOT create them before
6482:    calling it. It also allocates the array of matrix pointers submat.

6484:    For BAIJ matrices the index sets must respect the block structure, that is if they
6485:    request one row/column in a block, they must request all rows/columns that are in
6486:    that block. For example, if the block size is 2 you cannot request just row 0 and
6487:    column 0.

6489:    Fortran Note:
6490:    The Fortran interface is slightly different from that given below; it
6491:    requires one to pass in  as submat a Mat (integer) array of size at least m.

6493:    Level: advanced

6495:    Concepts: matrices^accessing submatrices
6496:    Concepts: submatrices

6498: .seealso: MatDestroyMatrices(), MatGetSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6499: @*/
6500: PetscErrorCode  MatGetSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6501: {
6503:   PetscInt       i;
6504:   PetscBool      eq;

6509:   if (n) {
6514:   }
6516:   if (n && scall == MAT_REUSE_MATRIX) {
6519:   }
6520:   if (!mat->ops->getsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6521:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6522:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6523:   MatCheckPreallocated(mat,1);

6525:   PetscLogEventBegin(MAT_GetSubMatrices,mat,0,0,0);
6526:   (*mat->ops->getsubmatrices)(mat,n,irow,icol,scall,submat);
6527:   PetscLogEventEnd(MAT_GetSubMatrices,mat,0,0,0);
6528:   for (i=0; i<n; i++) {
6529:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6530:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6531:       ISEqual(irow[i],icol[i],&eq);
6532:       if (eq) {
6533:         if (mat->symmetric) {
6534:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6535:         } else if (mat->hermitian) {
6536:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6537:         } else if (mat->structurally_symmetric) {
6538:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6539:         }
6540:       }
6541:     }
6542:   }
6543:   return(0);
6544: }

6548: PetscErrorCode  MatGetSubMatricesParallel(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6549: {
6551:   PetscInt       i;
6552:   PetscBool      eq;

6557:   if (n) {
6562:   }
6564:   if (n && scall == MAT_REUSE_MATRIX) {
6567:   }
6568:   if (!mat->ops->getsubmatricesparallel) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6569:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6570:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6571:   MatCheckPreallocated(mat,1);

6573:   PetscLogEventBegin(MAT_GetSubMatrices,mat,0,0,0);
6574:   (*mat->ops->getsubmatricesparallel)(mat,n,irow,icol,scall,submat);
6575:   PetscLogEventEnd(MAT_GetSubMatrices,mat,0,0,0);
6576:   for (i=0; i<n; i++) {
6577:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6578:       ISEqual(irow[i],icol[i],&eq);
6579:       if (eq) {
6580:         if (mat->symmetric) {
6581:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6582:         } else if (mat->hermitian) {
6583:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6584:         } else if (mat->structurally_symmetric) {
6585:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6586:         }
6587:       }
6588:     }
6589:   }
6590:   return(0);
6591: }

6595: /*@C
6596:    MatDestroyMatrices - Destroys a set of matrices obtained with MatGetSubMatrices().

6598:    Collective on Mat

6600:    Input Parameters:
6601: +  n - the number of local matrices
6602: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6603:                        sequence of MatGetSubMatrices())

6605:    Level: advanced

6607:     Notes: Frees not only the matrices, but also the array that contains the matrices
6608:            In Fortran will not free the array.

6610: .seealso: MatGetSubMatrices()
6611: @*/
6612: PetscErrorCode  MatDestroyMatrices(PetscInt n,Mat *mat[])
6613: {
6615:   PetscInt       i;

6618:   if (!*mat) return(0);
6619:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6621:   for (i=0; i<n; i++) {
6622:     MatDestroy(&(*mat)[i]);
6623:   }
6624:   /* memory is allocated even if n = 0 */
6625:   PetscFree(*mat);
6626:   *mat = NULL;
6627:   return(0);
6628: }

6632: /*@C
6633:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6635:    Collective on Mat

6637:    Input Parameters:
6638: .  mat - the matrix

6640:    Output Parameter:
6641: .  matstruct - the sequential matrix with the nonzero structure of mat

6643:   Level: intermediate

6645: .seealso: MatDestroySeqNonzeroStructure(), MatGetSubMatrices(), MatDestroyMatrices()
6646: @*/
6647: PetscErrorCode  MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6648: {


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

6659:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6660:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6661:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6662:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6663:   return(0);
6664: }

6668: /*@C
6669:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6671:    Collective on Mat

6673:    Input Parameters:
6674: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6675:                        sequence of MatGetSequentialNonzeroStructure())

6677:    Level: advanced

6679:     Notes: Frees not only the matrices, but also the array that contains the matrices

6681: .seealso: MatGetSeqNonzeroStructure()
6682: @*/
6683: PetscErrorCode  MatDestroySeqNonzeroStructure(Mat *mat)
6684: {

6689:   MatDestroy(mat);
6690:   return(0);
6691: }

6695: /*@
6696:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6697:    replaces the index sets by larger ones that represent submatrices with
6698:    additional overlap.

6700:    Collective on Mat

6702:    Input Parameters:
6703: +  mat - the matrix
6704: .  n   - the number of index sets
6705: .  is  - the array of index sets (these index sets will changed during the call)
6706: -  ov  - the additional overlap requested

6708:    Level: developer

6710:    Concepts: overlap
6711:    Concepts: ASM^computing overlap

6713: .seealso: MatGetSubMatrices()
6714: @*/
6715: PetscErrorCode  MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6716: {

6722:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6723:   if (n) {
6726:   }
6727:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6728:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6729:   MatCheckPreallocated(mat,1);

6731:   if (!ov) return(0);
6732:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6733:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6734:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
6735:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6736:   return(0);
6737: }

6741: /*@
6742:    MatGetBlockSize - Returns the matrix block size.

6744:    Not Collective

6746:    Input Parameter:
6747: .  mat - the matrix

6749:    Output Parameter:
6750: .  bs - block size

6752:    Notes:
6753:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

6755:    If the block size has not been set yet this routine returns 1.

6757:    Level: intermediate

6759:    Concepts: matrices^block size

6761: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
6762: @*/
6763: PetscErrorCode  MatGetBlockSize(Mat mat,PetscInt *bs)
6764: {
6768:   *bs = PetscAbs(mat->rmap->bs);
6769:   return(0);
6770: }

6774: /*@
6775:    MatGetBlockSizes - Returns the matrix block row and column sizes.

6777:    Not Collective

6779:    Input Parameter:
6780: .  mat - the matrix

6782:    Output Parameter:
6783: .  rbs - row block size
6784: .  cbs - coumn block size

6786:    Notes:
6787:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6788:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

6790:    If a block size has not been set yet this routine returns 1.

6792:    Level: intermediate

6794:    Concepts: matrices^block size

6796: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
6797: @*/
6798: PetscErrorCode  MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
6799: {
6804:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
6805:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
6806:   return(0);
6807: }

6811: /*@
6812:    MatSetBlockSize - Sets the matrix block size.

6814:    Logically Collective on Mat

6816:    Input Parameters:
6817: +  mat - the matrix
6818: -  bs - block size

6820:    Notes:
6821:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

6823:      This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later

6825:    Level: intermediate

6827:    Concepts: matrices^block size

6829: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
6830: @*/
6831: PetscErrorCode  MatSetBlockSize(Mat mat,PetscInt bs)
6832: {

6838:   PetscLayoutSetBlockSize(mat->rmap,bs);
6839:   PetscLayoutSetBlockSize(mat->cmap,bs);
6840:   return(0);
6841: }

6845: /*@
6846:    MatSetBlockSizes - Sets the matrix block row and column sizes.

6848:    Logically Collective on Mat

6850:    Input Parameters:
6851: +  mat - the matrix
6852: -  rbs - row block size
6853: -  cbs - column block size

6855:    Notes:
6856:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6857:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

6859:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later

6861:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

6863:    Level: intermediate

6865:    Concepts: matrices^block size

6867: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
6868: @*/
6869: PetscErrorCode  MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
6870: {

6877:   PetscLayoutSetBlockSize(mat->rmap,rbs);
6878:   PetscLayoutSetBlockSize(mat->cmap,cbs);
6879:   return(0);
6880: }

6884: /*@
6885:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

6887:    Logically Collective on Mat

6889:    Input Parameters:
6890: +  mat - the matrix
6891: .  fromRow - matrix from which to copy row block size
6892: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

6894:    Level: developer

6896:    Concepts: matrices^block size

6898: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
6899: @*/
6900: PetscErrorCode  MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
6901: {

6908:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
6909:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
6910:   return(0);
6911: }

6915: /*@
6916:    MatResidual - Default routine to calculate the residual.

6918:    Collective on Mat and Vec

6920:    Input Parameters:
6921: +  mat - the matrix
6922: .  b   - the right-hand-side
6923: -  x   - the approximate solution

6925:    Output Parameter:
6926: .  r - location to store the residual

6928:    Level: developer

6930: .keywords: MG, default, multigrid, residual

6932: .seealso: PCMGSetResidual()
6933: @*/
6934: PetscErrorCode  MatResidual(Mat mat,Vec b,Vec x,Vec r)
6935: {

6944:   MatCheckPreallocated(mat,1);
6945:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
6946:   if (!mat->ops->residual) {
6947:     MatMult(mat,x,r);
6948:     VecAYPX(r,-1.0,b);
6949:   } else {
6950:     (*mat->ops->residual)(mat,b,x,r);
6951:   }
6952:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
6953:   return(0);
6954: }

6958: /*@C
6959:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

6961:    Collective on Mat

6963:     Input Parameters:
6964: +   mat - the matrix
6965: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
6966: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
6967: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
6968:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
6969:                  always used.

6971:     Output Parameters:
6972: +   n - number of rows in the (possibly compressed) matrix
6973: .   ia - the row pointers [of length n+1]
6974: .   ja - the column indices
6975: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
6976:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

6978:     Level: developer

6980:     Notes: You CANNOT change any of the ia[] or ja[] values.

6982:            Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values

6984:     Fortran Node

6986:            In Fortran use
6987: $           PetscInt ia(1), ja(1)
6988: $           PetscOffset iia, jja
6989: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
6990: $
6991: $          or
6992: $
6993: $           PetscScalar, pointer :: xx_v(:)
6994: $    call  MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)


6997:        Acess the ith and jth entries via ia(iia + i) and ja(jja + j)

6999: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7000: @*/
7001: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7002: {

7012:   MatCheckPreallocated(mat,1);
7013:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7014:   else {
7015:     *done = PETSC_TRUE;
7016:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7017:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7018:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7019:   }
7020:   return(0);
7021: }

7025: /*@C
7026:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7028:     Collective on Mat

7030:     Input Parameters:
7031: +   mat - the matrix
7032: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7033: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7034:                 symmetrized
7035: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7036:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7037:                  always used.
7038: .   n - number of columns in the (possibly compressed) matrix
7039: .   ia - the column pointers
7040: -   ja - the row indices

7042:     Output Parameters:
7043: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7045:     Note:
7046:     This routine zeros out n, ia, and ja. This is to prevent accidental
7047:     us of the array after it has been restored. If you pass NULL, it will
7048:     not zero the pointers.  Use of ia or ja after MatRestoreColumnIJ() is invalid.

7050:     Level: developer

7052: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7053: @*/
7054: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7055: {

7065:   MatCheckPreallocated(mat,1);
7066:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7067:   else {
7068:     *done = PETSC_TRUE;
7069:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7070:   }
7071:   return(0);
7072: }

7076: /*@C
7077:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7078:     MatGetRowIJ().

7080:     Collective on Mat

7082:     Input Parameters:
7083: +   mat - the matrix
7084: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7085: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7086:                 symmetrized
7087: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7088:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7089:                  always used.
7090: .   n - size of (possibly compressed) matrix
7091: .   ia - the row pointers
7092: -   ja - the column indices

7094:     Output Parameters:
7095: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7097:     Note:
7098:     This routine zeros out n, ia, and ja. This is to prevent accidental
7099:     us of the array after it has been restored. If you pass NULL, it will
7100:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7102:     Level: developer

7104: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7105: @*/
7106: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7107: {

7116:   MatCheckPreallocated(mat,1);

7118:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7119:   else {
7120:     *done = PETSC_TRUE;
7121:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7122:     if (n)  *n = 0;
7123:     if (ia) *ia = NULL;
7124:     if (ja) *ja = NULL;
7125:   }
7126:   return(0);
7127: }

7131: /*@C
7132:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7133:     MatGetColumnIJ().

7135:     Collective on Mat

7137:     Input Parameters:
7138: +   mat - the matrix
7139: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7140: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7141:                 symmetrized
7142: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7143:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7144:                  always used.

7146:     Output Parameters:
7147: +   n - size of (possibly compressed) matrix
7148: .   ia - the column pointers
7149: .   ja - the row indices
7150: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7152:     Level: developer

7154: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7155: @*/
7156: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7157: {

7166:   MatCheckPreallocated(mat,1);

7168:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7169:   else {
7170:     *done = PETSC_TRUE;
7171:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7172:     if (n)  *n = 0;
7173:     if (ia) *ia = NULL;
7174:     if (ja) *ja = NULL;
7175:   }
7176:   return(0);
7177: }

7181: /*@C
7182:     MatColoringPatch -Used inside matrix coloring routines that
7183:     use MatGetRowIJ() and/or MatGetColumnIJ().

7185:     Collective on Mat

7187:     Input Parameters:
7188: +   mat - the matrix
7189: .   ncolors - max color value
7190: .   n   - number of entries in colorarray
7191: -   colorarray - array indicating color for each column

7193:     Output Parameters:
7194: .   iscoloring - coloring generated using colorarray information

7196:     Level: developer

7198: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7200: @*/
7201: PetscErrorCode  MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7202: {

7210:   MatCheckPreallocated(mat,1);

7212:   if (!mat->ops->coloringpatch) {
7213:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7214:   } else {
7215:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7216:   }
7217:   return(0);
7218: }


7223: /*@
7224:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7226:    Logically Collective on Mat

7228:    Input Parameter:
7229: .  mat - the factored matrix to be reset

7231:    Notes:
7232:    This routine should be used only with factored matrices formed by in-place
7233:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7234:    format).  This option can save memory, for example, when solving nonlinear
7235:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7236:    ILU(0) preconditioner.

7238:    Note that one can specify in-place ILU(0) factorization by calling
7239: .vb
7240:      PCType(pc,PCILU);
7241:      PCFactorSeUseInPlace(pc);
7242: .ve
7243:    or by using the options -pc_type ilu -pc_factor_in_place

7245:    In-place factorization ILU(0) can also be used as a local
7246:    solver for the blocks within the block Jacobi or additive Schwarz
7247:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7248:    for details on setting local solver options.

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

7254:    Level: developer

7256: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7258:    Concepts: matrices^unfactored

7260: @*/
7261: PetscErrorCode  MatSetUnfactored(Mat mat)
7262: {

7268:   MatCheckPreallocated(mat,1);
7269:   mat->factortype = MAT_FACTOR_NONE;
7270:   if (!mat->ops->setunfactored) return(0);
7271:   (*mat->ops->setunfactored)(mat);
7272:   return(0);
7273: }

7275: /*MC
7276:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7278:     Synopsis:
7279:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7281:     Not collective

7283:     Input Parameter:
7284: .   x - matrix

7286:     Output Parameters:
7287: +   xx_v - the Fortran90 pointer to the array
7288: -   ierr - error code

7290:     Example of Usage:
7291: .vb
7292:       PetscScalar, pointer xx_v(:,:)
7293:       ....
7294:       call MatDenseGetArrayF90(x,xx_v,ierr)
7295:       a = xx_v(3)
7296:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7297: .ve

7299:     Level: advanced

7301: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7303:     Concepts: matrices^accessing array

7305: M*/

7307: /*MC
7308:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7309:     accessed with MatDenseGetArrayF90().

7311:     Synopsis:
7312:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7314:     Not collective

7316:     Input Parameters:
7317: +   x - matrix
7318: -   xx_v - the Fortran90 pointer to the array

7320:     Output Parameter:
7321: .   ierr - error code

7323:     Example of Usage:
7324: .vb
7325:        PetscScalar, pointer xx_v(:)
7326:        ....
7327:        call MatDenseGetArrayF90(x,xx_v,ierr)
7328:        a = xx_v(3)
7329:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7330: .ve

7332:     Level: advanced

7334: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7336: M*/


7339: /*MC
7340:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7342:     Synopsis:
7343:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7345:     Not collective

7347:     Input Parameter:
7348: .   x - matrix

7350:     Output Parameters:
7351: +   xx_v - the Fortran90 pointer to the array
7352: -   ierr - error code

7354:     Example of Usage:
7355: .vb
7356:       PetscScalar, pointer xx_v(:,:)
7357:       ....
7358:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7359:       a = xx_v(3)
7360:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7361: .ve

7363:     Level: advanced

7365: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7367:     Concepts: matrices^accessing array

7369: M*/

7371: /*MC
7372:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7373:     accessed with MatSeqAIJGetArrayF90().

7375:     Synopsis:
7376:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7378:     Not collective

7380:     Input Parameters:
7381: +   x - matrix
7382: -   xx_v - the Fortran90 pointer to the array

7384:     Output Parameter:
7385: .   ierr - error code

7387:     Example of Usage:
7388: .vb
7389:        PetscScalar, pointer xx_v(:)
7390:        ....
7391:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7392:        a = xx_v(3)
7393:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7394: .ve

7396:     Level: advanced

7398: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7400: M*/


7405: /*@
7406:     MatGetSubMatrix - Gets a single submatrix on the same number of processors
7407:                       as the original matrix.

7409:     Collective on Mat

7411:     Input Parameters:
7412: +   mat - the original matrix
7413: .   isrow - parallel IS containing the rows this processor should obtain
7414: .   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.
7415: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7417:     Output Parameter:
7418: .   newmat - the new submatrix, of the same type as the old

7420:     Level: advanced

7422:     Notes:
7423:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7425:     The rows in isrow will be sorted into the same order as the original matrix on each process.

7427:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7428:    the MatGetSubMatrix() routine will create the newmat for you. Any additional calls
7429:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7430:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7431:    you are finished using it.

7433:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7434:     the input matrix.

7436:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7438:    Example usage:
7439:    Consider the following 8x8 matrix with 34 non-zero values, that is
7440:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7441:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7442:    as follows:

7444: .vb
7445:             1  2  0  |  0  3  0  |  0  4
7446:     Proc0   0  5  6  |  7  0  0  |  8  0
7447:             9  0 10  | 11  0  0  | 12  0
7448:     -------------------------------------
7449:            13  0 14  | 15 16 17  |  0  0
7450:     Proc1   0 18  0  | 19 20 21  |  0  0
7451:             0  0  0  | 22 23  0  | 24  0
7452:     -------------------------------------
7453:     Proc2  25 26 27  |  0  0 28  | 29  0
7454:            30  0  0  | 31 32 33  |  0 34
7455: .ve

7457:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7459: .vb
7460:             2  0  |  0  3  0  |  0
7461:     Proc0   5  6  |  7  0  0  |  8
7462:     -------------------------------
7463:     Proc1  18  0  | 19 20 21  |  0
7464:     -------------------------------
7465:     Proc2  26 27  |  0  0 28  | 29
7466:             0  0  | 31 32 33  |  0
7467: .ve


7470:     Concepts: matrices^submatrices

7472: .seealso: MatGetSubMatrices()
7473: @*/
7474: PetscErrorCode  MatGetSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7475: {
7477:   PetscMPIInt    size;
7478:   Mat            *local;
7479:   IS             iscoltmp;

7488:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7489:   MatCheckPreallocated(mat,1);
7490:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7492:   if (!iscol) {
7493:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7494:   } else {
7495:     iscoltmp = iscol;
7496:   }

7498:   /* if original matrix is on just one processor then use submatrix generated */
7499:   if (mat->ops->getsubmatrices && !mat->ops->getsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7500:     MatGetSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7501:     if (!iscol) {ISDestroy(&iscoltmp);}
7502:     return(0);
7503:   } else if (mat->ops->getsubmatrices && !mat->ops->getsubmatrix && size == 1) {
7504:     MatGetSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7505:     *newmat = *local;
7506:     PetscFree(local);
7507:     if (!iscol) {ISDestroy(&iscoltmp);}
7508:     return(0);
7509:   } else if (!mat->ops->getsubmatrix) {
7510:     /* Create a new matrix type that implements the operation using the full matrix */
7511:     switch (cll) {
7512:     case MAT_INITIAL_MATRIX:
7513:       MatCreateSubMatrix(mat,isrow,iscoltmp,newmat);
7514:       break;
7515:     case MAT_REUSE_MATRIX:
7516:       MatSubMatrixUpdate(*newmat,mat,isrow,iscoltmp);
7517:       break;
7518:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7519:     }
7520:     if (!iscol) {ISDestroy(&iscoltmp);}
7521:     return(0);
7522:   }

7524:   if (!mat->ops->getsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7525:   (*mat->ops->getsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7526:   if (!iscol) {ISDestroy(&iscoltmp);}
7527:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7528:   return(0);
7529: }

7533: /*@
7534:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7535:    used during the assembly process to store values that belong to
7536:    other processors.

7538:    Not Collective

7540:    Input Parameters:
7541: +  mat   - the matrix
7542: .  size  - the initial size of the stash.
7543: -  bsize - the initial size of the block-stash(if used).

7545:    Options Database Keys:
7546: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7547: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7549:    Level: intermediate

7551:    Notes:
7552:      The block-stash is used for values set with MatSetValuesBlocked() while
7553:      the stash is used for values set with MatSetValues()

7555:      Run with the option -info and look for output of the form
7556:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7557:      to determine the appropriate value, MM, to use for size and
7558:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7559:      to determine the value, BMM to use for bsize

7561:    Concepts: stash^setting matrix size
7562:    Concepts: matrices^stash

7564: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

7566: @*/
7567: PetscErrorCode  MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7568: {

7574:   MatStashSetInitialSize_Private(&mat->stash,size);
7575:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
7576:   return(0);
7577: }

7581: /*@
7582:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7583:      the matrix

7585:    Neighbor-wise Collective on Mat

7587:    Input Parameters:
7588: +  mat   - the matrix
7589: .  x,y - the vectors
7590: -  w - where the result is stored

7592:    Level: intermediate

7594:    Notes:
7595:     w may be the same vector as y.

7597:     This allows one to use either the restriction or interpolation (its transpose)
7598:     matrix to do the interpolation

7600:     Concepts: interpolation

7602: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

7604: @*/
7605: PetscErrorCode  MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
7606: {
7608:   PetscInt       M,N,Ny;

7616:   MatCheckPreallocated(A,1);
7617:   MatGetSize(A,&M,&N);
7618:   VecGetSize(y,&Ny);
7619:   if (M == Ny) {
7620:     MatMultAdd(A,x,y,w);
7621:   } else {
7622:     MatMultTransposeAdd(A,x,y,w);
7623:   }
7624:   return(0);
7625: }

7629: /*@
7630:    MatInterpolate - y = A*x or A'*x depending on the shape of
7631:      the matrix

7633:    Neighbor-wise Collective on Mat

7635:    Input Parameters:
7636: +  mat   - the matrix
7637: -  x,y - the vectors

7639:    Level: intermediate

7641:    Notes:
7642:     This allows one to use either the restriction or interpolation (its transpose)
7643:     matrix to do the interpolation

7645:    Concepts: matrices^interpolation

7647: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

7649: @*/
7650: PetscErrorCode  MatInterpolate(Mat A,Vec x,Vec y)
7651: {
7653:   PetscInt       M,N,Ny;

7660:   MatCheckPreallocated(A,1);
7661:   MatGetSize(A,&M,&N);
7662:   VecGetSize(y,&Ny);
7663:   if (M == Ny) {
7664:     MatMult(A,x,y);
7665:   } else {
7666:     MatMultTranspose(A,x,y);
7667:   }
7668:   return(0);
7669: }

7673: /*@
7674:    MatRestrict - y = A*x or A'*x

7676:    Neighbor-wise Collective on Mat

7678:    Input Parameters:
7679: +  mat   - the matrix
7680: -  x,y - the vectors

7682:    Level: intermediate

7684:    Notes:
7685:     This allows one to use either the restriction or interpolation (its transpose)
7686:     matrix to do the restriction

7688:    Concepts: matrices^restriction

7690: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

7692: @*/
7693: PetscErrorCode  MatRestrict(Mat A,Vec x,Vec y)
7694: {
7696:   PetscInt       M,N,Ny;

7703:   MatCheckPreallocated(A,1);

7705:   MatGetSize(A,&M,&N);
7706:   VecGetSize(y,&Ny);
7707:   if (M == Ny) {
7708:     MatMult(A,x,y);
7709:   } else {
7710:     MatMultTranspose(A,x,y);
7711:   }
7712:   return(0);
7713: }

7717: /*@
7718:    MatGetNullSpace - retrieves the null space to a matrix.

7720:    Logically Collective on Mat and MatNullSpace

7722:    Input Parameters:
7723: +  mat - the matrix
7724: -  nullsp - the null space object

7726:    Level: developer

7728:    Notes:
7729:       This null space is used by solvers. Overwrites any previous null space that may have been attached

7731:    Concepts: null space^attaching to matrix

7733: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace()
7734: @*/
7735: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
7736: {
7741:   *nullsp = mat->nullsp;
7742:   return(0);
7743: }

7747: /*@
7748:    MatSetNullSpace - attaches a null space to a matrix.
7749:         This null space will be removed from the resulting vector whenever
7750:         MatMult() is called

7752:    Logically Collective on Mat and MatNullSpace

7754:    Input Parameters:
7755: +  mat - the matrix
7756: -  nullsp - the null space object

7758:    Level: advanced

7760:    Notes:
7761:       This null space is used by solvers. Overwrites any previous null space that may have been attached

7763:    Concepts: null space^attaching to matrix

7765: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace()
7766: @*/
7767: PetscErrorCode  MatSetNullSpace(Mat mat,MatNullSpace nullsp)
7768: {

7775:   MatCheckPreallocated(mat,1);
7776:   PetscObjectReference((PetscObject)nullsp);
7777:   MatNullSpaceDestroy(&mat->nullsp);

7779:   mat->nullsp = nullsp;
7780:   return(0);
7781: }

7785: /*@
7786:    MatSetNearNullSpace - attaches a null space to a matrix.
7787:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

7789:    Logically Collective on Mat and MatNullSpace

7791:    Input Parameters:
7792: +  mat - the matrix
7793: -  nullsp - the null space object

7795:    Level: advanced

7797:    Notes:
7798:       Overwrites any previous near null space that may have been attached

7800:    Concepts: null space^attaching to matrix

7802: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace()
7803: @*/
7804: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
7805: {

7812:   MatCheckPreallocated(mat,1);
7813:   PetscObjectReference((PetscObject)nullsp);
7814:   MatNullSpaceDestroy(&mat->nearnullsp);

7816:   mat->nearnullsp = nullsp;
7817:   return(0);
7818: }

7822: /*@
7823:    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()

7825:    Not Collective

7827:    Input Parameters:
7828: .  mat - the matrix

7830:    Output Parameters:
7831: .  nullsp - the null space object, NULL if not set

7833:    Level: developer

7835:    Concepts: null space^attaching to matrix

7837: .seealso: MatSetNearNullSpace(), MatGetNullSpace()
7838: @*/
7839: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
7840: {
7845:   MatCheckPreallocated(mat,1);
7846:   *nullsp = mat->nearnullsp;
7847:   return(0);
7848: }

7852: /*@C
7853:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

7855:    Collective on Mat

7857:    Input Parameters:
7858: +  mat - the matrix
7859: .  row - row/column permutation
7860: .  fill - expected fill factor >= 1.0
7861: -  level - level of fill, for ICC(k)

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

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

7871:    Level: developer

7873:    Concepts: matrices^incomplete Cholesky factorization
7874:    Concepts: Cholesky factorization

7876: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

7881: @*/
7882: PetscErrorCode  MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
7883: {

7891:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
7892:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7893:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7894:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7895:   MatCheckPreallocated(mat,1);
7896:   (*mat->ops->iccfactor)(mat,row,info);
7897:   PetscObjectStateIncrease((PetscObject)mat);
7898:   return(0);
7899: }

7903: /*@
7904:    MatSetValuesAdifor - Sets values computed with automatic differentiation into a matrix.

7906:    Not Collective

7908:    Input Parameters:
7909: +  mat - the matrix
7910: .  nl - leading dimension of v
7911: -  v - the values compute with ADIFOR

7913:    Level: developer

7915:    Notes:
7916:      Must call MatSetColoring() before using this routine. Also this matrix must already
7917:      have its nonzero pattern determined.

7919: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
7920:           MatSetValues(), MatSetColoring()
7921: @*/
7922: PetscErrorCode  MatSetValuesAdifor(Mat mat,PetscInt nl,void *v)
7923: {


7931:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
7932:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
7933:   if (!mat->ops->setvaluesadifor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7934:   (*mat->ops->setvaluesadifor)(mat,nl,v);
7935:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
7936:   PetscObjectStateIncrease((PetscObject)mat);
7937:   return(0);
7938: }

7942: /*@
7943:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
7944:          ghosted ones.

7946:    Not Collective

7948:    Input Parameters:
7949: +  mat - the matrix
7950: -  diag = the diagonal values, including ghost ones

7952:    Level: developer

7954:    Notes: Works only for MPIAIJ and MPIBAIJ matrices

7956: .seealso: MatDiagonalScale()
7957: @*/
7958: PetscErrorCode  MatDiagonalScaleLocal(Mat mat,Vec diag)
7959: {
7961:   PetscMPIInt    size;


7968:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
7969:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
7970:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
7971:   if (size == 1) {
7972:     PetscInt n,m;
7973:     VecGetSize(diag,&n);
7974:     MatGetSize(mat,0,&m);
7975:     if (m == n) {
7976:       MatDiagonalScale(mat,0,diag);
7977:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
7978:   } else {
7979:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
7980:   }
7981:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
7982:   PetscObjectStateIncrease((PetscObject)mat);
7983:   return(0);
7984: }

7988: /*@
7989:    MatGetInertia - Gets the inertia from a factored matrix

7991:    Collective on Mat

7993:    Input Parameter:
7994: .  mat - the matrix

7996:    Output Parameters:
7997: +   nneg - number of negative eigenvalues
7998: .   nzero - number of zero eigenvalues
7999: -   npos - number of positive eigenvalues

8001:    Level: advanced

8003:    Notes: Matrix must have been factored by MatCholeskyFactor()


8006: @*/
8007: PetscErrorCode  MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8008: {

8014:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8015:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8016:   if (!mat->ops->getinertia) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8017:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8018:   return(0);
8019: }

8021: /* ----------------------------------------------------------------*/
8024: /*@C
8025:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8027:    Neighbor-wise Collective on Mat and Vecs

8029:    Input Parameters:
8030: +  mat - the factored matrix
8031: -  b - the right-hand-side vectors

8033:    Output Parameter:
8034: .  x - the result vectors

8036:    Notes:
8037:    The vectors b and x cannot be the same.  I.e., one cannot
8038:    call MatSolves(A,x,x).

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

8045:    Level: developer

8047:    Concepts: matrices^triangular solves

8049: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8050: @*/
8051: PetscErrorCode  MatSolves(Mat mat,Vecs b,Vecs x)
8052: {

8058:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8059:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8060:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8062:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8063:   MatCheckPreallocated(mat,1);
8064:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8065:   (*mat->ops->solves)(mat,b,x);
8066:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8067:   return(0);
8068: }

8072: /*@
8073:    MatIsSymmetric - Test whether a matrix is symmetric

8075:    Collective on Mat

8077:    Input Parameter:
8078: +  A - the matrix to test
8079: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8081:    Output Parameters:
8082: .  flg - the result

8084:    Notes: For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8086:    Level: intermediate

8088:    Concepts: matrix^symmetry

8090: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8091: @*/
8092: PetscErrorCode  MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8093: {


8100:   if (!A->symmetric_set) {
8101:     if (!A->ops->issymmetric) {
8102:       MatType mattype;
8103:       MatGetType(A,&mattype);
8104:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8105:     }
8106:     (*A->ops->issymmetric)(A,tol,flg);
8107:     if (!tol) {
8108:       A->symmetric_set = PETSC_TRUE;
8109:       A->symmetric     = *flg;
8110:       if (A->symmetric) {
8111:         A->structurally_symmetric_set = PETSC_TRUE;
8112:         A->structurally_symmetric     = PETSC_TRUE;
8113:       }
8114:     }
8115:   } else if (A->symmetric) {
8116:     *flg = PETSC_TRUE;
8117:   } else if (!tol) {
8118:     *flg = PETSC_FALSE;
8119:   } else {
8120:     if (!A->ops->issymmetric) {
8121:       MatType mattype;
8122:       MatGetType(A,&mattype);
8123:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8124:     }
8125:     (*A->ops->issymmetric)(A,tol,flg);
8126:   }
8127:   return(0);
8128: }

8132: /*@
8133:    MatIsHermitian - Test whether a matrix is Hermitian

8135:    Collective on Mat

8137:    Input Parameter:
8138: +  A - the matrix to test
8139: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8141:    Output Parameters:
8142: .  flg - the result

8144:    Level: intermediate

8146:    Concepts: matrix^symmetry

8148: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8149:           MatIsSymmetricKnown(), MatIsSymmetric()
8150: @*/
8151: PetscErrorCode  MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8152: {


8159:   if (!A->hermitian_set) {
8160:     if (!A->ops->ishermitian) {
8161:       MatType mattype;
8162:       MatGetType(A,&mattype);
8163:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8164:     }
8165:     (*A->ops->ishermitian)(A,tol,flg);
8166:     if (!tol) {
8167:       A->hermitian_set = PETSC_TRUE;
8168:       A->hermitian     = *flg;
8169:       if (A->hermitian) {
8170:         A->structurally_symmetric_set = PETSC_TRUE;
8171:         A->structurally_symmetric     = PETSC_TRUE;
8172:       }
8173:     }
8174:   } else if (A->hermitian) {
8175:     *flg = PETSC_TRUE;
8176:   } else if (!tol) {
8177:     *flg = PETSC_FALSE;
8178:   } else {
8179:     if (!A->ops->ishermitian) {
8180:       MatType mattype;
8181:       MatGetType(A,&mattype);
8182:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8183:     }
8184:     (*A->ops->ishermitian)(A,tol,flg);
8185:   }
8186:   return(0);
8187: }

8191: /*@
8192:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8194:    Not Collective

8196:    Input Parameter:
8197: .  A - the matrix to check

8199:    Output Parameters:
8200: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8201: -  flg - the result

8203:    Level: advanced

8205:    Concepts: matrix^symmetry

8207:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8208:          if you want it explicitly checked

8210: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8211: @*/
8212: PetscErrorCode  MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8213: {
8218:   if (A->symmetric_set) {
8219:     *set = PETSC_TRUE;
8220:     *flg = A->symmetric;
8221:   } else {
8222:     *set = PETSC_FALSE;
8223:   }
8224:   return(0);
8225: }

8229: /*@
8230:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8232:    Not Collective

8234:    Input Parameter:
8235: .  A - the matrix to check

8237:    Output Parameters:
8238: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8239: -  flg - the result

8241:    Level: advanced

8243:    Concepts: matrix^symmetry

8245:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8246:          if you want it explicitly checked

8248: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8249: @*/
8250: PetscErrorCode  MatIsHermitianKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8251: {
8256:   if (A->hermitian_set) {
8257:     *set = PETSC_TRUE;
8258:     *flg = A->hermitian;
8259:   } else {
8260:     *set = PETSC_FALSE;
8261:   }
8262:   return(0);
8263: }

8267: /*@
8268:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8270:    Collective on Mat

8272:    Input Parameter:
8273: .  A - the matrix to test

8275:    Output Parameters:
8276: .  flg - the result

8278:    Level: intermediate

8280:    Concepts: matrix^symmetry

8282: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8283: @*/
8284: PetscErrorCode  MatIsStructurallySymmetric(Mat A,PetscBool  *flg)
8285: {

8291:   if (!A->structurally_symmetric_set) {
8292:     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8293:     (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);

8295:     A->structurally_symmetric_set = PETSC_TRUE;
8296:   }
8297:   *flg = A->structurally_symmetric;
8298:   return(0);
8299: }

8303: extern PetscErrorCode MatStashGetInfo_Private(MatStash*,PetscInt*,PetscInt*);
8304: /*@
8305:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8306:        to be communicated to other processors during the MatAssemblyBegin/End() process

8308:     Not collective

8310:    Input Parameter:
8311: .   vec - the vector

8313:    Output Parameters:
8314: +   nstash   - the size of the stash
8315: .   reallocs - the number of additional mallocs incurred.
8316: .   bnstash   - the size of the block stash
8317: -   breallocs - the number of additional mallocs incurred.in the block stash

8319:    Level: advanced

8321: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8323: @*/
8324: PetscErrorCode  MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8325: {

8329:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8330:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8331:   return(0);
8332: }

8336: /*@C
8337:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8338:      parallel layout

8340:    Collective on Mat

8342:    Input Parameter:
8343: .  mat - the matrix

8345:    Output Parameter:
8346: +   right - (optional) vector that the matrix can be multiplied against
8347: -   left - (optional) vector that the matrix vector product can be stored in

8349:    Notes:
8350:     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().

8352:   Notes: These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8354:   Level: advanced

8356: .seealso: MatCreate(), VecDestroy()
8357: @*/
8358: PetscErrorCode  MatCreateVecs(Mat mat,Vec *right,Vec *left)
8359: {

8365:   MatCheckPreallocated(mat,1);
8366:   if (mat->ops->getvecs) {
8367:     (*mat->ops->getvecs)(mat,right,left);
8368:   } else {
8369:     PetscMPIInt size;
8370:     PetscInt    rbs,cbs;
8371:     MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size);
8372:     MatGetBlockSizes(mat,&rbs,&cbs);
8373:     if (right) {
8374:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8375:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8376:       VecSetBlockSize(*right,cbs);
8377:       VecSetType(*right,VECSTANDARD);
8378:       PetscLayoutReference(mat->cmap,&(*right)->map);
8379:     }
8380:     if (left) {
8381:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8382:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8383:       VecSetBlockSize(*left,rbs);
8384:       VecSetType(*left,VECSTANDARD);
8385:       PetscLayoutReference(mat->rmap,&(*left)->map);
8386:     }
8387:   }
8388:   return(0);
8389: }

8393: /*@C
8394:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8395:      with default values.

8397:    Not Collective

8399:    Input Parameters:
8400: .    info - the MatFactorInfo data structure


8403:    Notes: The solvers are generally used through the KSP and PC objects, for example
8404:           PCLU, PCILU, PCCHOLESKY, PCICC

8406:    Level: developer

8408: .seealso: MatFactorInfo

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

8413: @*/

8415: PetscErrorCode  MatFactorInfoInitialize(MatFactorInfo *info)
8416: {

8420:   PetscMemzero(info,sizeof(MatFactorInfo));
8421:   return(0);
8422: }

8426: /*@
8427:    MatPtAP - Creates the matrix product C = P^T * A * P

8429:    Neighbor-wise Collective on Mat

8431:    Input Parameters:
8432: +  A - the matrix
8433: .  P - the projection matrix
8434: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8435: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P))

8437:    Output Parameters:
8438: .  C - the product matrix

8440:    Notes:
8441:    C will be created and must be destroyed by the user with MatDestroy().

8443:    This routine is currently only implemented for pairs of AIJ matrices and classes
8444:    which inherit from AIJ.

8446:    Level: intermediate

8448: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
8449: @*/
8450: PetscErrorCode  MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
8451: {
8453:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
8454:   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
8455:   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
8456:   PetscBool      viatranspose=PETSC_FALSE,viamatmatmatmult=PETSC_FALSE;

8459:   PetscOptionsGetBool(((PetscObject)A)->prefix,"-matptap_viatranspose",&viatranspose,NULL);
8460:   PetscOptionsGetBool(((PetscObject)A)->prefix,"-matptap_viamatmatmatmult",&viamatmatmatmult,NULL);

8464:   MatCheckPreallocated(A,1);
8465:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8466:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8469:   MatCheckPreallocated(P,2);
8470:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8471:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8473:   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);
8474:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

8476:   if (scall == MAT_REUSE_MATRIX) {
8479:     if (viatranspose || viamatmatmatmult) {
8480:       Mat Pt;
8481:       MatTranspose(P,MAT_INITIAL_MATRIX,&Pt);
8482:       if (viamatmatmatmult) {
8483:         MatMatMatMult(Pt,A,P,scall,fill,C);
8484:       } else {
8485:         Mat AP;
8486:         MatMatMult(A,P,MAT_INITIAL_MATRIX,fill,&AP);
8487:         MatMatMult(Pt,AP,scall,fill,C);
8488:         MatDestroy(&AP);
8489:       }
8490:       MatDestroy(&Pt);
8491:     } else {
8492:       PetscLogEventBegin(MAT_PtAP,A,P,0,0);
8493:       PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
8494:       (*(*C)->ops->ptapnumeric)(A,P,*C);
8495:       PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
8496:       PetscLogEventEnd(MAT_PtAP,A,P,0,0);
8497:     }
8498:     return(0);
8499:   }

8501:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
8502:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

8504:   fA = A->ops->ptap;
8505:   fP = P->ops->ptap;
8506:   if (fP == fA) {
8507:     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatPtAP not supported for A of type %s",((PetscObject)A)->type_name);
8508:     ptap = fA;
8509:   } else {
8510:     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
8511:     char ptapname[256];
8512:     PetscStrcpy(ptapname,"MatPtAP_");
8513:     PetscStrcat(ptapname,((PetscObject)A)->type_name);
8514:     PetscStrcat(ptapname,"_");
8515:     PetscStrcat(ptapname,((PetscObject)P)->type_name);
8516:     PetscStrcat(ptapname,"_C"); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
8517:     PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
8518:     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);
8519:   }

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:       PetscInfo(*C,"MatPtAP via MatMatMatMult\n");
8527:     } else {
8528:       Mat AP;
8529:       MatMatMult(A,P,MAT_INITIAL_MATRIX,fill,&AP);
8530:       MatMatMult(Pt,AP,scall,fill,C);
8531:       MatDestroy(&AP);
8532:       PetscInfo(*C,"MatPtAP via MatTranspose and MatMatMult\n");
8533:     }
8534:     MatDestroy(&Pt);
8535:   } else {
8536:     PetscLogEventBegin(MAT_PtAP,A,P,0,0);
8537:     (*ptap)(A,P,scall,fill,C);
8538:     PetscLogEventEnd(MAT_PtAP,A,P,0,0);
8539:   }
8540:   return(0);
8541: }

8545: /*@
8546:    MatPtAPNumeric - Computes the matrix product C = P^T * A * P

8548:    Neighbor-wise Collective on Mat

8550:    Input Parameters:
8551: +  A - the matrix
8552: -  P - the projection matrix

8554:    Output Parameters:
8555: .  C - the product matrix

8557:    Notes:
8558:    C must have been created by calling MatPtAPSymbolic and must be destroyed by
8559:    the user using MatDeatroy().

8561:    This routine is currently only implemented for pairs of AIJ matrices and classes
8562:    which inherit from AIJ.  C will be of type MATAIJ.

8564:    Level: intermediate

8566: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
8567: @*/
8568: PetscErrorCode  MatPtAPNumeric(Mat A,Mat P,Mat C)
8569: {

8575:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8576:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8579:   MatCheckPreallocated(P,2);
8580:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8581:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8584:   MatCheckPreallocated(C,3);
8585:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8586:   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);
8587:   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);
8588:   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);
8589:   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);
8590:   MatCheckPreallocated(A,1);

8592:   PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
8593:   (*C->ops->ptapnumeric)(A,P,C);
8594:   PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
8595:   return(0);
8596: }

8600: /*@
8601:    MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P

8603:    Neighbor-wise Collective on Mat

8605:    Input Parameters:
8606: +  A - the matrix
8607: -  P - the projection matrix

8609:    Output Parameters:
8610: .  C - the (i,j) structure of the product matrix

8612:    Notes:
8613:    C will be created and must be destroyed by the user with MatDestroy().

8615:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
8616:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
8617:    this (i,j) structure by calling MatPtAPNumeric().

8619:    Level: intermediate

8621: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
8622: @*/
8623: PetscErrorCode  MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
8624: {

8630:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8631:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8632:   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8635:   MatCheckPreallocated(P,2);
8636:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8637:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8640:   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);
8641:   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);
8642:   MatCheckPreallocated(A,1);
8643:   PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);
8644:   (*A->ops->ptapsymbolic)(A,P,fill,C);
8645:   PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);

8647:   /* MatSetBlockSize(*C,A->rmap->bs); NO! this is not always true -ma */
8648:   return(0);
8649: }

8653: /*@
8654:    MatRARt - Creates the matrix product C = R * A * R^T

8656:    Neighbor-wise Collective on Mat

8658:    Input Parameters:
8659: +  A - the matrix
8660: .  R - the projection matrix
8661: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8662: -  fill - expected fill as ratio of nnz(C)/nnz(A)

8664:    Output Parameters:
8665: .  C - the product matrix

8667:    Notes:
8668:    C will be created and must be destroyed by the user with MatDestroy().

8670:    This routine is currently only implemented for pairs of AIJ matrices and classes
8671:    which inherit from AIJ.

8673:    Level: intermediate

8675: .seealso: MatRARtSymbolic(), MatRARtNumeric(), MatMatMult(), MatPtAP()
8676: @*/
8677: PetscErrorCode  MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
8678: {

8684:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8685:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8688:   MatCheckPreallocated(R,2);
8689:   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8690:   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8692:   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);
8693:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8694:   MatCheckPreallocated(A,1);

8696:   if (!A->ops->rart) {
8697:     MatType mattype;
8698:     MatGetType(A,&mattype);
8699:     SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type <%s> does not support RARt",mattype);
8700:   }
8701:   PetscLogEventBegin(MAT_RARt,A,R,0,0);
8702:   (*A->ops->rart)(A,R,scall,fill,C);
8703:   PetscLogEventEnd(MAT_RARt,A,R,0,0);
8704:   return(0);
8705: }

8709: /*@
8710:    MatRARtNumeric - Computes the matrix product C = R * A * R^T

8712:    Neighbor-wise Collective on Mat

8714:    Input Parameters:
8715: +  A - the matrix
8716: -  R - the projection matrix

8718:    Output Parameters:
8719: .  C - the product matrix

8721:    Notes:
8722:    C must have been created by calling MatRARtSymbolic and must be destroyed by
8723:    the user using MatDeatroy().

8725:    This routine is currently only implemented for pairs of AIJ matrices and classes
8726:    which inherit from AIJ.  C will be of type MATAIJ.

8728:    Level: intermediate

8730: .seealso: MatRARt(), MatRARtSymbolic(), MatMatMultNumeric()
8731: @*/
8732: PetscErrorCode  MatRARtNumeric(Mat A,Mat R,Mat C)
8733: {

8739:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8740:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8743:   MatCheckPreallocated(R,2);
8744:   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8745:   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8748:   MatCheckPreallocated(C,3);
8749:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8750:   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);
8751:   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);
8752:   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);
8753:   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);
8754:   MatCheckPreallocated(A,1);

8756:   PetscLogEventBegin(MAT_RARtNumeric,A,R,0,0);
8757:   (*A->ops->rartnumeric)(A,R,C);
8758:   PetscLogEventEnd(MAT_RARtNumeric,A,R,0,0);
8759:   return(0);
8760: }

8764: /*@
8765:    MatRARtSymbolic - Creates the (i,j) structure of the matrix product C = R * A * R^T

8767:    Neighbor-wise Collective on Mat

8769:    Input Parameters:
8770: +  A - the matrix
8771: -  R - the projection matrix

8773:    Output Parameters:
8774: .  C - the (i,j) structure of the product matrix

8776:    Notes:
8777:    C will be created and must be destroyed by the user with MatDestroy().

8779:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
8780:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
8781:    this (i,j) structure by calling MatRARtNumeric().

8783:    Level: intermediate

8785: .seealso: MatRARt(), MatRARtNumeric(), MatMatMultSymbolic()
8786: @*/
8787: PetscErrorCode  MatRARtSymbolic(Mat A,Mat R,PetscReal fill,Mat *C)
8788: {

8794:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8795:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8796:   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8799:   MatCheckPreallocated(R,2);
8800:   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8801:   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8804:   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);
8805:   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);
8806:   MatCheckPreallocated(A,1);
8807:   PetscLogEventBegin(MAT_RARtSymbolic,A,R,0,0);
8808:   (*A->ops->rartsymbolic)(A,R,fill,C);
8809:   PetscLogEventEnd(MAT_RARtSymbolic,A,R,0,0);

8811:   MatSetBlockSizes(*C,PetscAbs(R->rmap->bs),PetscAbs(R->rmap->bs));
8812:   return(0);
8813: }

8817: /*@
8818:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

8820:    Neighbor-wise Collective on Mat

8822:    Input Parameters:
8823: +  A - the left matrix
8824: .  B - the right matrix
8825: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8826: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
8827:           if the result is a dense matrix this is irrelevent

8829:    Output Parameters:
8830: .  C - the product matrix

8832:    Notes:
8833:    Unless scall is MAT_REUSE_MATRIX C will be created.

8835:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

8837:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
8838:    actually needed.

8840:    If you have many matrices with the same non-zero structure to multiply, you
8841:    should either
8842: $   1) use MAT_REUSE_MATRIX in all calls but the first or
8843: $   2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed

8845:    Level: intermediate

8847: .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatTransposeMatMult(),  MatMatTransposeMult(), MatPtAP()
8848: @*/
8849: PetscErrorCode  MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
8850: {
8852:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
8853:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
8854:   PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;

8859:   MatCheckPreallocated(A,1);
8860:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8861:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8864:   MatCheckPreallocated(B,2);
8865:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8866:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8868:   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);
8869:   if (scall == MAT_REUSE_MATRIX) {
8872:     PetscLogEventBegin(MAT_MatMult,A,B,0,0);
8873:     PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
8874:     (*(*C)->ops->matmultnumeric)(A,B,*C);
8875:     PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
8876:     PetscLogEventEnd(MAT_MatMult,A,B,0,0);
8877:     return(0);
8878:   }
8879:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
8880:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

8882:   fA = A->ops->matmult;
8883:   fB = B->ops->matmult;
8884:   if (fB == fA) {
8885:     if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",((PetscObject)B)->type_name);
8886:     mult = fB;
8887:   } else {
8888:     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
8889:     char multname[256];
8890:     PetscStrcpy(multname,"MatMatMult_");
8891:     PetscStrcat(multname,((PetscObject)A)->type_name);
8892:     PetscStrcat(multname,"_");
8893:     PetscStrcat(multname,((PetscObject)B)->type_name);
8894:     PetscStrcat(multname,"_C"); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
8895:     PetscObjectQueryFunction((PetscObject)B,multname,&mult);
8896:     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);
8897:   }
8898:   PetscLogEventBegin(MAT_MatMult,A,B,0,0);
8899:   (*mult)(A,B,scall,fill,C);
8900:   PetscLogEventEnd(MAT_MatMult,A,B,0,0);
8901:   return(0);
8902: }

8906: /*@
8907:    MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
8908:    of the matrix-matrix product C=A*B.  Call this routine before calling MatMatMultNumeric().

8910:    Neighbor-wise Collective on Mat

8912:    Input Parameters:
8913: +  A - the left matrix
8914: .  B - the right matrix
8915: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate,
8916:       if C is a dense matrix this is irrelevent

8918:    Output Parameters:
8919: .  C - the product matrix

8921:    Notes:
8922:    Unless scall is MAT_REUSE_MATRIX C will be created.

8924:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
8925:    actually needed.

8927:    This routine is currently implemented for
8928:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type AIJ
8929:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
8930:     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.

8932:    Level: intermediate

8934:    Developers Note: There are ways to estimate the number of nonzeros in the resulting product, see for example, http://arxiv.org/abs/1006.4173
8935:      We should incorporate them into PETSc.

8937: .seealso: MatMatMult(), MatMatMultNumeric()
8938: @*/
8939: PetscErrorCode  MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
8940: {
8942:   PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat*);
8943:   PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat*);
8944:   PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat*)=NULL;

8949:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8950:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8954:   MatCheckPreallocated(B,2);
8955:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8956:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

8959:   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);
8960:   if (fill == PETSC_DEFAULT) fill = 2.0;
8961:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
8962:   MatCheckPreallocated(A,1);

8964:   Asymbolic = A->ops->matmultsymbolic;
8965:   Bsymbolic = B->ops->matmultsymbolic;
8966:   if (Asymbolic == Bsymbolic) {
8967:     if (!Bsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
8968:     symbolic = Bsymbolic;
8969:   } else { /* dispatch based on the type of A and B */
8970:     char symbolicname[256];
8971:     PetscStrcpy(symbolicname,"MatMatMultSymbolic_");
8972:     PetscStrcat(symbolicname,((PetscObject)A)->type_name);
8973:     PetscStrcat(symbolicname,"_");
8974:     PetscStrcat(symbolicname,((PetscObject)B)->type_name);
8975:     PetscStrcat(symbolicname,"_C");
8976:     PetscObjectQueryFunction((PetscObject)B,symbolicname,&symbolic);
8977:     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);
8978:   }
8979:   PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
8980:   (*symbolic)(A,B,fill,C);
8981:   PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
8982:   return(0);
8983: }

8987: /*@
8988:    MatMatMultNumeric - Performs the numeric matrix-matrix product.
8989:    Call this routine after first calling MatMatMultSymbolic().

8991:    Neighbor-wise Collective on Mat

8993:    Input Parameters:
8994: +  A - the left matrix
8995: -  B - the right matrix

8997:    Output Parameters:
8998: .  C - the product matrix, which was created by from MatMatMultSymbolic() or a call to MatMatMult().

9000:    Notes:
9001:    C must have been created with MatMatMultSymbolic().

9003:    This routine is currently implemented for
9004:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
9005:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9006:     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.

9008:    Level: intermediate

9010: .seealso: MatMatMult(), MatMatMultSymbolic()
9011: @*/
9012: PetscErrorCode  MatMatMultNumeric(Mat A,Mat B,Mat C)
9013: {

9017:   MatMatMult(A,B,MAT_REUSE_MATRIX,0.0,&C);
9018:   return(0);
9019: }

9023: /*@
9024:    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.

9026:    Neighbor-wise Collective on Mat

9028:    Input Parameters:
9029: +  A - the left matrix
9030: .  B - the right matrix
9031: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9032: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9034:    Output Parameters:
9035: .  C - the product matrix

9037:    Notes:
9038:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9040:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

9042:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9043:    actually needed.

9045:    This routine is currently only implemented for pairs of SeqAIJ matrices.  C will be of type MATSEQAIJ.

9047:    Level: intermediate

9049: .seealso: MatMatTransposeMultSymbolic(), MatMatTransposeMultNumeric(), MatMatMult(), MatTransposeMatMult() MatPtAP()
9050: @*/
9051: PetscErrorCode  MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9052: {
9054:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9055:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);

9060:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9061:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9064:   MatCheckPreallocated(B,2);
9065:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9066:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9068:   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);
9069:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9070:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9071:   MatCheckPreallocated(A,1);

9073:   fA = A->ops->mattransposemult;
9074:   if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for A of type %s",((PetscObject)A)->type_name);
9075:   fB = B->ops->mattransposemult;
9076:   if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for B of type %s",((PetscObject)B)->type_name);
9077:   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);

9079:   PetscLogEventBegin(MAT_MatTransposeMult,A,B,0,0);
9080:   if (scall == MAT_INITIAL_MATRIX) {
9081:     PetscLogEventBegin(MAT_MatTransposeMultSymbolic,A,B,0,0);
9082:     (*A->ops->mattransposemultsymbolic)(A,B,fill,C);
9083:     PetscLogEventEnd(MAT_MatTransposeMultSymbolic,A,B,0,0);
9084:   }
9085:   PetscLogEventBegin(MAT_MatTransposeMultNumeric,A,B,0,0);
9086:   (*A->ops->mattransposemultnumeric)(A,B,*C);
9087:   PetscLogEventEnd(MAT_MatTransposeMultNumeric,A,B,0,0);
9088:   PetscLogEventEnd(MAT_MatTransposeMult,A,B,0,0);
9089:   return(0);
9090: }

9094: /*@
9095:    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.

9097:    Neighbor-wise Collective on Mat

9099:    Input Parameters:
9100: +  A - the left matrix
9101: .  B - the right matrix
9102: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9103: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9105:    Output Parameters:
9106: .  C - the product matrix

9108:    Notes:
9109:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9111:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

9113:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9114:    actually needed.

9116:    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9117:    which inherit from SeqAIJ.  C will be of same type as the input matrices.

9119:    Level: intermediate

9121: .seealso: MatTransposeMatMultSymbolic(), MatTransposeMatMultNumeric(), MatMatMult(), MatMatTransposeMult(), MatPtAP()
9122: @*/
9123: PetscErrorCode  MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9124: {
9126:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9127:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9128:   PetscErrorCode (*transposematmult)(Mat,Mat,MatReuse,PetscReal,Mat*) = NULL;

9133:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9134:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9137:   MatCheckPreallocated(B,2);
9138:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9139:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9141:   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);
9142:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9143:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9144:   MatCheckPreallocated(A,1);

9146:   fA = A->ops->transposematmult;
9147:   fB = B->ops->transposematmult;
9148:   if (fB==fA) {
9149:     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatTransposeMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9150:     transposematmult = fA;
9151:   } else {
9152:     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9153:     char multname[256];
9154:     PetscStrcpy(multname,"MatTransposeMatMult_");
9155:     PetscStrcat(multname,((PetscObject)A)->type_name);
9156:     PetscStrcat(multname,"_");
9157:     PetscStrcat(multname,((PetscObject)B)->type_name);
9158:     PetscStrcat(multname,"_C"); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9159:     PetscObjectQueryFunction((PetscObject)B,multname,&transposematmult);
9160:     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);
9161:   }
9162:   PetscLogEventBegin(MAT_TransposeMatMult,A,B,0,0);
9163:   (*transposematmult)(A,B,scall,fill,C);
9164:   PetscLogEventEnd(MAT_TransposeMatMult,A,B,0,0);
9165:   return(0);
9166: }

9170: /*@
9171:    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.

9173:    Neighbor-wise Collective on Mat

9175:    Input Parameters:
9176: +  A - the left matrix
9177: .  B - the middle matrix
9178: .  C - the right matrix
9179: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9180: -  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
9181:           if the result is a dense matrix this is irrelevent

9183:    Output Parameters:
9184: .  D - the product matrix

9186:    Notes:
9187:    Unless scall is MAT_REUSE_MATRIX D will be created.

9189:    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call

9191:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9192:    actually needed.

9194:    If you have many matrices with the same non-zero structure to multiply, you
9195:    should either
9196: $   1) use MAT_REUSE_MATRIX in all calls but the first or
9197: $   2) call MatMatMatMultSymbolic() once and then MatMatMatMultNumeric() for each product needed

9199:    Level: intermediate

9201: .seealso: MatMatMult, MatPtAP()
9202: @*/
9203: PetscErrorCode  MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9204: {
9206:   PetscErrorCode (*fA)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9207:   PetscErrorCode (*fB)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9208:   PetscErrorCode (*fC)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9209:   PetscErrorCode (*mult)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;

9214:   MatCheckPreallocated(A,1);
9215:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9216:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9219:   MatCheckPreallocated(B,2);
9220:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9221:   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9224:   MatCheckPreallocated(C,3);
9225:   if (!C->assembled) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9226:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9227:   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);
9228:   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);
9229:   if (scall == MAT_REUSE_MATRIX) {
9232:     PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
9233:     (*(*D)->ops->matmatmult)(A,B,C,scall,fill,D);
9234:     PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
9235:     return(0);
9236:   }
9237:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9238:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9240:   fA = A->ops->matmatmult;
9241:   fB = B->ops->matmatmult;
9242:   fC = C->ops->matmatmult;
9243:   if (fA == fB && fA == fC) {
9244:     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9245:     mult = fA;
9246:   } else {
9247:     /* dispatch based on the type of A, B and C from their PetscObject's PetscFunctionLists. */
9248:     char multname[256];
9249:     PetscStrcpy(multname,"MatMatMatMult_");
9250:     PetscStrcat(multname,((PetscObject)A)->type_name);
9251:     PetscStrcat(multname,"_");
9252:     PetscStrcat(multname,((PetscObject)B)->type_name);
9253:     PetscStrcat(multname,"_");
9254:     PetscStrcat(multname,((PetscObject)C)->type_name);
9255:     PetscStrcat(multname,"_C");
9256:     PetscObjectQueryFunction((PetscObject)B,multname,&mult);
9257:     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);
9258:   }
9259:   PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
9260:   (*mult)(A,B,C,scall,fill,D);
9261:   PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
9262:   return(0);
9263: }

9267: /*@C
9268:    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

9270:    Collective on Mat

9272:    Input Parameters:
9273: +  mat - the matrix
9274: .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9275: .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9276: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9278:    Output Parameter:
9279: .  matredundant - redundant matrix

9281:    Notes:
9282:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9283:    original matrix has not changed from that last call to MatCreateRedundantMatrix().

9285:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9286:    calling it.

9288:    Level: advanced

9290:    Concepts: subcommunicator
9291:    Concepts: duplicate matrix

9293: .seealso: MatDestroy()
9294: @*/
9295: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9296: {
9298:   MPI_Comm       comm;
9299:   PetscMPIInt    size;
9300:   PetscInt       mloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9301:   Mat_Redundant  *redund=NULL;
9302:   PetscSubcomm   psubcomm=NULL;
9303:   MPI_Comm       subcomm_in=subcomm;
9304:   Mat            *matseq;
9305:   IS             isrow,iscol;
9306:   PetscBool      newsubcomm=PETSC_FALSE;
9307: 
9309:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
9310:   if (size == 1 || nsubcomm == 1) {
9311:     if (reuse == MAT_INITIAL_MATRIX) {
9312:       MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
9313:     } else {
9314:       MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
9315:     }
9316:     return(0);
9317:   }

9320:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9323:   }
9324:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9325:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9326:   MatCheckPreallocated(mat,1);

9328:   PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
9329:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9330:     /* create psubcomm, then get subcomm */
9331:     PetscObjectGetComm((PetscObject)mat,&comm);
9332:     MPI_Comm_size(comm,&size);
9333:     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);

9335:     PetscSubcommCreate(comm,&psubcomm);
9336:     PetscSubcommSetNumber(psubcomm,nsubcomm);
9337:     PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
9338:     PetscSubcommSetFromOptions(psubcomm);
9339:     PetscCommDuplicate(psubcomm->comm,&subcomm,NULL);
9340:     newsubcomm = PETSC_TRUE;
9341:     PetscSubcommDestroy(&psubcomm);
9342:   }

9344:   /* get isrow, iscol and a local sequential matrix matseq[0] */
9345:   if (reuse == MAT_INITIAL_MATRIX) {
9346:     mloc_sub = PETSC_DECIDE;
9347:     if (bs < 1) {
9348:       PetscSplitOwnership(subcomm,&mloc_sub,&M);
9349:     } else {
9350:       PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
9351:     }
9352:     MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
9353:     rstart = rend - mloc_sub;
9354:     ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
9355:     ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
9356:   } else { /* reuse == MAT_REUSE_MATRIX */
9357:     /* retrieve subcomm */
9358:     PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
9359:     redund = (*matredundant)->redundant;
9360:     isrow  = redund->isrow;
9361:     iscol  = redund->iscol;
9362:     matseq = redund->matseq;
9363:   }
9364:   MatGetSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);
9365: 
9366:   /* get matredundant over subcomm */
9367:   if (reuse == MAT_INITIAL_MATRIX) {
9368:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],mloc_sub,reuse,matredundant);

9370:     /* create a supporting struct and attach it to C for reuse */
9371:     PetscNewLog(*matredundant,&redund);
9372:     (*matredundant)->redundant = redund;
9373:     redund->isrow              = isrow;
9374:     redund->iscol              = iscol;
9375:     redund->matseq             = matseq;
9376:     if (newsubcomm) {
9377:       redund->subcomm          = subcomm;
9378:     } else {
9379:       redund->subcomm          = MPI_COMM_NULL;
9380:     }
9381:   } else {
9382:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
9383:   }
9384:   PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
9385:   return(0);
9386: }

9390: /*@C
9391:    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
9392:    a given 'mat' object. Each submatrix can span multiple procs.

9394:    Collective on Mat

9396:    Input Parameters:
9397: +  mat - the matrix
9398: .  subcomm - the subcommunicator obtained by com_split(comm)
9399: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9401:    Output Parameter:
9402: .  subMat - 'parallel submatrices each spans a given subcomm

9404:   Notes:
9405:   The submatrix partition across processors is dictated by 'subComm' a
9406:   communicator obtained by com_split(comm). The comm_split
9407:   is not restriced to be grouped with consecutive original ranks.

9409:   Due the comm_split() usage, the parallel layout of the submatrices
9410:   map directly to the layout of the original matrix [wrt the local
9411:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
9412:   into the 'DiagonalMat' of the subMat, hence it is used directly from
9413:   the subMat. However the offDiagMat looses some columns - and this is
9414:   reconstructed with MatSetValues()

9416:   Level: advanced

9418:   Concepts: subcommunicator
9419:   Concepts: submatrices

9421: .seealso: MatGetSubMatrices()
9422: @*/
9423: PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
9424: {
9426:   PetscMPIInt    commsize,subCommSize;

9429:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
9430:   MPI_Comm_size(subComm,&subCommSize);
9431:   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);

9433:   PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
9434:   (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
9435:   PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
9436:   return(0);
9437: }

9441: /*@
9442:    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

9444:    Not Collective

9446:    Input Arguments:
9447:    mat - matrix to extract local submatrix from
9448:    isrow - local row indices for submatrix
9449:    iscol - local column indices for submatrix

9451:    Output Arguments:
9452:    submat - the submatrix

9454:    Level: intermediate

9456:    Notes:
9457:    The submat should be returned with MatRestoreLocalSubMatrix().

9459:    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
9460:    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.

9462:    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
9463:    MatSetValuesBlockedLocal() will also be implemented.

9465: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef()
9466: @*/
9467: PetscErrorCode  MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9468: {


9478:   if (mat->ops->getlocalsubmatrix) {
9479:     (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
9480:   } else {
9481:     MatCreateLocalRef(mat,isrow,iscol,submat);
9482:   }
9483:   return(0);
9484: }

9488: /*@
9489:    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering

9491:    Not Collective

9493:    Input Arguments:
9494:    mat - matrix to extract local submatrix from
9495:    isrow - local row indices for submatrix
9496:    iscol - local column indices for submatrix
9497:    submat - the submatrix

9499:    Level: intermediate

9501: .seealso: MatGetLocalSubMatrix()
9502: @*/
9503: PetscErrorCode  MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9504: {

9513:   if (*submat) {
9515:   }

9517:   if (mat->ops->restorelocalsubmatrix) {
9518:     (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
9519:   } else {
9520:     MatDestroy(submat);
9521:   }
9522:   *submat = NULL;
9523:   return(0);
9524: }

9526: /* --------------------------------------------------------*/
9529: /*@
9530:    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no entry in the matrix

9532:    Collective on Mat

9534:    Input Parameter:
9535: .  mat - the matrix

9537:    Output Parameter:
9538: .  is - if any rows have zero diagonals this contains the list of them

9540:    Level: developer

9542:    Concepts: matrix-vector product

9544: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9545: @*/
9546: PetscErrorCode  MatFindZeroDiagonals(Mat mat,IS *is)
9547: {

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

9556:   if (!mat->ops->findzerodiagonals) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find zero diagonals defined");
9557:   (*mat->ops->findzerodiagonals)(mat,is);
9558:   return(0);
9559: }

9563: /*@
9564:    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

9566:    Collective on Mat

9568:    Input Parameter:
9569: .  mat - the matrix

9571:    Output Parameter:
9572: .  is - contains the list of rows with off block diagonal entries

9574:    Level: developer

9576:    Concepts: matrix-vector product

9578: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9579: @*/
9580: PetscErrorCode  MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
9581: {

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

9590:   if (!mat->ops->findoffblockdiagonalentries) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find off block diagonal entries defined");
9591:   (*mat->ops->findoffblockdiagonalentries)(mat,is);
9592:   return(0);
9593: }

9597: /*@C
9598:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

9600:   Collective on Mat

9602:   Input Parameters:
9603: . mat - the matrix

9605:   Output Parameters:
9606: . values - the block inverses in column major order (FORTRAN-like)

9608:    Note:
9609:    This routine is not available from Fortran.

9611:   Level: advanced
9612: @*/
9613: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
9614: {

9619:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9620:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9621:   if (!mat->ops->invertblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
9622:   (*mat->ops->invertblockdiagonal)(mat,values);
9623:   return(0);
9624: }

9628: /*@C
9629:     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
9630:     via MatTransposeColoringCreate().

9632:     Collective on MatTransposeColoring

9634:     Input Parameter:
9635: .   c - coloring context

9637:     Level: intermediate

9639: .seealso: MatTransposeColoringCreate()
9640: @*/
9641: PetscErrorCode  MatTransposeColoringDestroy(MatTransposeColoring *c)
9642: {
9643:   PetscErrorCode       ierr;
9644:   MatTransposeColoring matcolor=*c;

9647:   if (!matcolor) return(0);
9648:   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; return(0);}

9650:   PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
9651:   PetscFree(matcolor->rows);
9652:   PetscFree(matcolor->den2sp);
9653:   PetscFree(matcolor->colorforcol);
9654:   PetscFree(matcolor->columns);
9655:   if (matcolor->brows>0) {
9656:     PetscFree(matcolor->lstart);
9657:   }
9658:   PetscHeaderDestroy(c);
9659:   return(0);
9660: }

9664: /*@C
9665:     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
9666:     a MatTransposeColoring context has been created, computes a dense B^T by Apply
9667:     MatTransposeColoring to sparse B.

9669:     Collective on MatTransposeColoring

9671:     Input Parameters:
9672: +   B - sparse matrix B
9673: .   Btdense - symbolic dense matrix B^T
9674: -   coloring - coloring context created with MatTransposeColoringCreate()

9676:     Output Parameter:
9677: .   Btdense - dense matrix B^T

9679:     Options Database Keys:
9680: +    -mat_transpose_coloring_view - Activates basic viewing or coloring
9681: .    -mat_transpose_coloring_view_draw - Activates drawing of coloring
9682: -    -mat_transpose_coloring_view_info - Activates viewing of coloring info

9684:     Level: intermediate

9686: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy()

9688: .keywords: coloring
9689: @*/
9690: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
9691: {


9699:   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
9700:   (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
9701:   return(0);
9702: }

9706: /*@C
9707:     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
9708:     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
9709:     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
9710:     Csp from Cden.

9712:     Collective on MatTransposeColoring

9714:     Input Parameters:
9715: +   coloring - coloring context created with MatTransposeColoringCreate()
9716: -   Cden - matrix product of a sparse matrix and a dense matrix Btdense

9718:     Output Parameter:
9719: .   Csp - sparse matrix

9721:     Options Database Keys:
9722: +    -mat_multtranspose_coloring_view - Activates basic viewing or coloring
9723: .    -mat_multtranspose_coloring_view_draw - Activates drawing of coloring
9724: -    -mat_multtranspose_coloring_view_info - Activates viewing of coloring info

9726:     Level: intermediate

9728: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()

9730: .keywords: coloring
9731: @*/
9732: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
9733: {


9741:   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
9742:   (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
9743:   return(0);
9744: }

9748: /*@C
9749:    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.

9751:    Collective on Mat

9753:    Input Parameters:
9754: +  mat - the matrix product C
9755: -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()

9757:     Output Parameter:
9758: .   color - the new coloring context

9760:     Level: intermediate

9762: .seealso: MatTransposeColoringDestroy(), MatTransposeColoringSetFromOptions(), MatTransColoringApplySpToDen(),
9763:            MatTransColoringApplyDenToSp(), MatTransposeColoringView(),
9764: @*/
9765: PetscErrorCode  MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
9766: {
9767:   MatTransposeColoring c;
9768:   MPI_Comm             comm;
9769:   PetscErrorCode       ierr;

9772:   PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
9773:   PetscObjectGetComm((PetscObject)mat,&comm);
9774:   PetscHeaderCreate(c,_p_MatTransposeColoring,int,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,0);

9776:   c->ctype = iscoloring->ctype;
9777:   if (mat->ops->transposecoloringcreate) {
9778:     (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
9779:   } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for this matrix type");

9781:   *color = c;
9782:   PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
9783:   return(0);
9784: }

9788: /*@
9789:       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the 
9790:         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the 
9791:         same, otherwise it will be larger

9793:      Not Collective

9795:   Input Parameter:
9796: .    A  - the matrix

9798:   Output Parameter:
9799: .    state - the current state

9801:   Notes: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between 
9802:          different matrices

9804:   Level: intermediate

9806: @*/
9807: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
9808: {
9810:   *state = mat->nonzerostate;
9811:   return(0);
9812: }

9816: /*@
9817:       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
9818:                  matrices from each processor

9820:     Collective on MPI_Comm

9822:    Input Parameters:
9823: +    comm - the communicators the parallel matrix will live on
9824: .    seqmat - the input sequential matrices
9825: .    n - number of local columns (or PETSC_DECIDE)
9826: -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9828:    Output Parameter:
9829: .    mpimat - the parallel matrix generated

9831:     Level: advanced

9833:    Notes: The number of columns of the matrix in EACH processor MUST be the same.

9835: @*/
9836: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
9837: {
9839:   PetscMPIInt    size;

9842:   MPI_Comm_size(comm,&size);
9843:   if (size == 1) {
9844:     if (reuse == MAT_INITIAL_MATRIX) {
9845:       MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);
9846:     } else {
9847:       MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);
9848:     }
9849:     return(0);
9850:   }

9852:   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
9853:   PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
9854:   (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
9855:   PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
9856:   return(0);
9857: }