Actual source code: matrix.c

petsc-master 2019-04-21
Report Typos and Errors

  2: /*
  3:    This is where the abstract matrix operations are defined
  4: */

  6:  #include <petsc/private/matimpl.h>
  7:  #include <petsc/private/isimpl.h>
  8:  #include <petsc/private/vecimpl.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,MAT_MatTrSolve;
 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_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
 22: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
 23: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
 24: PetscLogEvent MAT_TransposeColoringCreate;
 25: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
 26: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
 27: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
 28: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
 29: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
 30: PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
 31: PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_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_CUSPARSECopyToGPU, MAT_SetValuesBatch;
 36: PetscLogEvent MAT_ViennaCLCopyToGPU;
 37: PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
 38: PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;

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

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

 45:    Logically Collective on Mat

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

 52:    Output Parameter:
 53: .  x  - the matrix

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

 62:    Level: intermediate

 64:    Concepts: matrix^setting to random
 65:    Concepts: random^matrix

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


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

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

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

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

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

102:    Logically Collective on Mat

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

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

112:    Level: advanced

114:    Notes:
115:     This routine does not work for factorizations done with external packages.
116:    This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT

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

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

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

134:    Logically Collective on Mat

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

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

142:    Level: advanced

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

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

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

160:    Logically Collective on Mat

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

165:    Level: developer

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

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

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

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

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

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

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

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

240:   Level: intermediate

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

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

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

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

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

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

273:   Level: intermediate

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


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

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

302:    Not Collective

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

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

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

315:    Level: advanced

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

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

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

342:    Collective on Mat

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

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

350:    Level: advanced

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

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

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

369:    Logically Collective on Mat

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

374:    Level: advanced


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

386:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
387:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
388:   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
389:   MatCheckPreallocated(mat,1);
390:   (*mat->ops->realpart)(mat);
391: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
392:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
393:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
394:   }
395: #endif
396:   return(0);
397: }

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

402:    Collective on Mat

404:    Input Parameter:
405: .  mat - the matrix

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

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

414:    Level: advanced

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

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


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

439:    Logically Collective on Mat

441:    Input Parameters:
442: .  mat - the matrix

444:    Level: advanced


447: .seealso: MatRealPart()
448: @*/
449: PetscErrorCode MatImaginaryPart(Mat mat)
450: {

456:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
457:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
458:   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
459:   MatCheckPreallocated(mat,1);
460:   (*mat->ops->imaginarypart)(mat);
461: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
462:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
463:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
464:   }
465: #endif
466:   return(0);
467: }

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

472:    Not Collective

474:    Input Parameter:
475: .  mat - the matrix

477:    Output Parameters:
478: +  missing - is any diagonal missing
479: -  dd - first diagonal entry that is missing (optional) on this process

481:    Level: advanced


484: .seealso: MatRealPart()
485: @*/
486: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
487: {

493:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
494:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
495:   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
496:   (*mat->ops->missingdiagonal)(mat,missing,dd);
497:   return(0);
498: }

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

505:    Not Collective

507:    Input Parameters:
508: +  mat - the matrix
509: -  row - the row to get

511:    Output Parameters:
512: +  ncols -  if not NULL, the number of nonzeros in the row
513: .  cols - if not NULL, the column numbers
514: -  vals - if not NULL, the values

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

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

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

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

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

538:    Fortran Notes:
539:    The calling sequence from Fortran is
540: .vb
541:    MatGetRow(matrix,row,ncols,cols,values,ierr)
542:          Mat     matrix (input)
543:          integer row    (input)
544:          integer ncols  (output)
545:          integer cols(maxcols) (output)
546:          double precision (or double complex) values(maxcols) output
547: .ve
548:    where maxcols >= maximum nonzeros in any row of the matrix.


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

555:    Level: advanced

557:    Concepts: matrices^row access

559: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
560: @*/
561: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
562: {
564:   PetscInt       incols;

569:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
570:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
571:   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
572:   MatCheckPreallocated(mat,1);
573:   PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
574:   (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
575:   if (ncols) *ncols = incols;
576:   PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
577:   return(0);
578: }

580: /*@
581:    MatConjugate - replaces the matrix values with their complex conjugates

583:    Logically Collective on Mat

585:    Input Parameters:
586: .  mat - the matrix

588:    Level: advanced

590: .seealso:  VecConjugate()
591: @*/
592: PetscErrorCode MatConjugate(Mat mat)
593: {
594: #if defined(PETSC_USE_COMPLEX)

599:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
600:   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");
601:   (*mat->ops->conjugate)(mat);
602: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
603:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
604:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
605:   }
606: #endif
607:   return(0);
608: #else
609:   return 0;
610: #endif
611: }

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

616:    Not Collective

618:    Input Parameters:
619: +  mat - the matrix
620: .  row - the row to get
621: .  ncols, cols - the number of nonzeros and their columns
622: -  vals - if nonzero the column values

624:    Notes:
625:    This routine should be called after you have finished examining the entries.

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

631:    Fortran Notes:
632:    The calling sequence from Fortran is
633: .vb
634:    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
635:       Mat     matrix (input)
636:       integer row    (input)
637:       integer ncols  (output)
638:       integer cols(maxcols) (output)
639:       double precision (or double complex) values(maxcols) output
640: .ve
641:    Where maxcols >= maximum nonzeros in any row of the matrix.

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

646:    Level: advanced

648: .seealso:  MatGetRow()
649: @*/
650: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
651: {

657:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
658:   if (!mat->ops->restorerow) return(0);
659:   (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
660:   if (ncols) *ncols = 0;
661:   if (cols)  *cols = NULL;
662:   if (vals)  *vals = NULL;
663:   return(0);
664: }

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

670:    Not Collective

672:    Input Parameters:
673: +  mat - the matrix

675:    Notes:
676:    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.

678:    Level: advanced

680:    Concepts: matrices^row access

682: .seealso: MatRestoreRowRowUpperTriangular()
683: @*/
684: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
685: {

691:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
692:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
693:   if (!mat->ops->getrowuppertriangular) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
694:   MatCheckPreallocated(mat,1);
695:   (*mat->ops->getrowuppertriangular)(mat);
696:   return(0);
697: }

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

702:    Not Collective

704:    Input Parameters:
705: +  mat - the matrix

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


711:    Level: advanced

713: .seealso:  MatGetRowUpperTriangular()
714: @*/
715: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
716: {

721:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
722:   if (!mat->ops->restorerowuppertriangular) return(0);
723:   (*mat->ops->restorerowuppertriangular)(mat);
724:   return(0);
725: }

727: /*@C
728:    MatSetOptionsPrefix - Sets the prefix used for searching for all
729:    Mat options in the database.

731:    Logically Collective on Mat

733:    Input Parameter:
734: +  A - the Mat context
735: -  prefix - the prefix to prepend to all option names

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

741:    Level: advanced

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

745: .seealso: MatSetFromOptions()
746: @*/
747: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
748: {

753:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
754:   return(0);
755: }

757: /*@C
758:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
759:    Mat options in the database.

761:    Logically Collective on Mat

763:    Input Parameters:
764: +  A - the Mat context
765: -  prefix - the prefix to prepend to all option names

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

771:    Level: advanced

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

775: .seealso: MatGetOptionsPrefix()
776: @*/
777: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
778: {

783:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
784:   return(0);
785: }

787: /*@C
788:    MatGetOptionsPrefix - Sets the prefix used for searching for all
789:    Mat options in the database.

791:    Not Collective

793:    Input Parameter:
794: .  A - the Mat context

796:    Output Parameter:
797: .  prefix - pointer to the prefix string used

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

803:    Level: advanced

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

807: .seealso: MatAppendOptionsPrefix()
808: @*/
809: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
810: {

815:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
816:   return(0);
817: }

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

822:    Collective on Mat

824:    Input Parameters:
825: .  A - the Mat context

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

831:    Level: beginner

833: .keywords: Mat, ResetPreallocation

835: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
836: @*/
837: PetscErrorCode MatResetPreallocation(Mat A)
838: {

844:   PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
845:   return(0);
846: }


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

852:    Collective on Mat

854:    Input Parameters:
855: .  A - the Mat context

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

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

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

864:    Level: beginner

866: .keywords: Mat, setup

868: .seealso: MatCreate(), MatDestroy()
869: @*/
870: PetscErrorCode MatSetUp(Mat A)
871: {
872:   PetscMPIInt    size;

877:   if (!((PetscObject)A)->type_name) {
878:     MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
879:     if (size == 1) {
880:       MatSetType(A, MATSEQAIJ);
881:     } else {
882:       MatSetType(A, MATMPIAIJ);
883:     }
884:   }
885:   if (!A->preallocated && A->ops->setup) {
886:     PetscInfo(A,"Warning not preallocating matrix storage\n");
887:     (*A->ops->setup)(A);
888:   }
889:   PetscLayoutSetUp(A->rmap);
890:   PetscLayoutSetUp(A->cmap);
891:   A->preallocated = PETSC_TRUE;
892:   return(0);
893: }

895: #if defined(PETSC_HAVE_SAWS)
896:  #include <petscviewersaws.h>
897: #endif
898: /*@C
899:    MatView - Visualizes a matrix object.

901:    Collective on Mat

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

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

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

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

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

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

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

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

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

970:    Concepts: matrices^viewing
971:    Concepts: matrices^plotting
972:    Concepts: matrices^printing

974: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
975:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
976: @*/
977: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
978: {
979:   PetscErrorCode    ierr;
980:   PetscInt          rows,cols,rbs,cbs;
981:   PetscBool         iascii,ibinary;
982:   PetscViewerFormat format;
983:   PetscMPIInt       size;
984: #if defined(PETSC_HAVE_SAWS)
985:   PetscBool         issaws;
986: #endif

991:   if (!viewer) {
992:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
993:   }
996:   MatCheckPreallocated(mat,1);
997:   PetscViewerGetFormat(viewer,&format);
998:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
999:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
1000:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
1001:   if (ibinary) {
1002:     PetscBool mpiio;
1003:     PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);
1004:     if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
1005:   }

1007:   PetscLogEventBegin(MAT_View,mat,viewer,0,0);
1008:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1009:   if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
1010:     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
1011:   }

1013: #if defined(PETSC_HAVE_SAWS)
1014:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1015: #endif
1016:   if (iascii) {
1017:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1018:     PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
1019:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1020:       MatNullSpace nullsp,transnullsp;

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

1053:     PetscObjectName((PetscObject)mat);
1054:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1055:     if (!((PetscObject)mat)->amsmem && !rank) {
1056:       PetscObjectViewSAWs((PetscObject)mat,viewer);
1057:     }
1058: #endif
1059:   }
1060:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1061:     PetscViewerASCIIPushTab(viewer);
1062:     (*mat->ops->viewnative)(mat,viewer);
1063:     PetscViewerASCIIPopTab(viewer);
1064:   } else if (mat->ops->view) {
1065:     PetscViewerASCIIPushTab(viewer);
1066:     (*mat->ops->view)(mat,viewer);
1067:     PetscViewerASCIIPopTab(viewer);
1068:   }
1069:   if (iascii) {
1070:     PetscViewerGetFormat(viewer,&format);
1071:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1072:       PetscViewerASCIIPopTab(viewer);
1073:     }
1074:   }
1075:   PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1076:   return(0);
1077: }

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

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

1098:    Collective on PetscViewer

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

1105:    Options Database Keys:
1106:    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1107:    block size
1108: .    -matload_block_size <bs>

1110:    Level: beginner

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

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

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

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

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

1145:    See the example src/ksp/ksp/examples/tutorials/ex27.c with the first approach,
1146:    and src/mat/examples/tutorials/ex10.c with the second approach.

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

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

1159: $    int    MAT_FILE_CLASSID
1160: $    int    number of rows
1161: $    int    number of columns
1162: $    int    total number of nonzeros
1163: $    int    *number nonzeros in each row
1164: $    int    *column indices of all nonzeros (starting index is zero)
1165: $    PetscScalar *values of all nonzeros

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

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

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

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

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

1193:    Current HDF5 (MAT-File) limitations:
1194:    This reader currently supports only real MATSEQAIJ and MATMPIAIJ matrices.

1196:    Corresponding MatView() is not yet implemented.

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

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

1207: .keywords: matrix, load, binary, input, HDF5

1209: .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), PetscViewerHDF5SetAIJNames(), MatView(), VecLoad()

1211:  @*/
1212: PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1213: {
1215:   PetscBool      flg;


1221:   if (!((PetscObject)newmat)->type_name) {
1222:     MatSetType(newmat,MATAIJ);
1223:   }

1225:   flg  = PETSC_FALSE;
1226:   PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);
1227:   if (flg) {
1228:     MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);
1229:     MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1230:   }
1231:   flg  = PETSC_FALSE;
1232:   PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);
1233:   if (flg) {
1234:     MatSetOption(newmat,MAT_SPD,PETSC_TRUE);
1235:   }

1237:   if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
1238:   PetscLogEventBegin(MAT_Load,viewer,0,0,0);
1239:   (*newmat->ops->load)(newmat,viewer);
1240:   PetscLogEventEnd(MAT_Load,viewer,0,0,0);
1241:   return(0);
1242: }

1244: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1245: {
1247:   Mat_Redundant  *redund = *redundant;
1248:   PetscInt       i;

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

1267:     if (redund->subcomm) {
1268:       PetscCommDestroy(&redund->subcomm);
1269:     }
1270:     PetscFree(redund);
1271:   }
1272:   return(0);
1273: }

1275: /*@
1276:    MatDestroy - Frees space taken by a matrix.

1278:    Collective on Mat

1280:    Input Parameter:
1281: .  A - the matrix

1283:    Level: beginner

1285: @*/
1286: PetscErrorCode MatDestroy(Mat *A)
1287: {

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

1295:   /* if memory was published with SAWs then destroy it */
1296:   PetscObjectSAWsViewOff((PetscObject)*A);
1297:   if ((*A)->ops->destroy) {
1298:     (*(*A)->ops->destroy)(*A);
1299:   }

1301:   PetscFree((*A)->defaultvectype);
1302:   PetscFree((*A)->bsizes);
1303:   PetscFree((*A)->solvertype);
1304:   MatDestroy_Redundant(&(*A)->redundant);
1305:   MatNullSpaceDestroy(&(*A)->nullsp);
1306:   MatNullSpaceDestroy(&(*A)->transnullsp);
1307:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1308:   MatDestroy(&(*A)->schur);
1309:   PetscLayoutDestroy(&(*A)->rmap);
1310:   PetscLayoutDestroy(&(*A)->cmap);
1311:   PetscHeaderDestroy(A);
1312:   return(0);
1313: }

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

1320:    Not Collective

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

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

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

1337:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1338:    options cannot be mixed without intervening calls to the assembly
1339:    routines.

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

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

1349:    Efficiency Alert:
1350:    The routine MatSetValuesBlocked() may offer much better efficiency
1351:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1353:    Level: beginner

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

1359:    Concepts: matrices^putting entries in

1361: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1362:           InsertMode, INSERT_VALUES, ADD_VALUES
1363: @*/
1364: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1365: {
1367: #if defined(PETSC_USE_DEBUG)
1368:   PetscInt       i,j;
1369: #endif

1374:   if (!m || !n) return(0); /* no values to insert */
1378:   MatCheckPreallocated(mat,1);
1379:   if (mat->insertmode == NOT_SET_VALUES) {
1380:     mat->insertmode = addv;
1381:   }
1382: #if defined(PETSC_USE_DEBUG)
1383:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1384:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1385:   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

1387:   for (i=0; i<m; i++) {
1388:     for (j=0; j<n; j++) {
1389:       if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1390: #if defined(PETSC_USE_COMPLEX)
1391:         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]);
1392: #else
1393:         SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1394: #endif
1395:     }
1396:   }
1397: #endif

1399:   if (mat->assembled) {
1400:     mat->was_assembled = PETSC_TRUE;
1401:     mat->assembled     = PETSC_FALSE;
1402:   }
1403:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1404:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1405:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1406: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1407:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1408:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1409:   }
1410: #endif
1411:   return(0);
1412: }


1415: /*@
1416:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1417:         values into a matrix

1419:    Not Collective

1421:    Input Parameters:
1422: +  mat - the matrix
1423: .  row - the (block) row to set
1424: -  v - a logically two-dimensional array of values

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

1429:    All the nonzeros in the row must be provided

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

1433:    The row must belong to this process

1435:    Level: intermediate

1437:    Concepts: matrices^putting entries in

1439: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1440:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1441: @*/
1442: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1443: {
1445:   PetscInt       globalrow;

1451:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1452:   MatSetValuesRow(mat,globalrow,v);
1453: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1454:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1455:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1456:   }
1457: #endif
1458:   return(0);
1459: }

1461: /*@
1462:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1463:         values into a matrix

1465:    Not Collective

1467:    Input Parameters:
1468: +  mat - the matrix
1469: .  row - the (block) row to set
1470: -  v - a logically two-dimensional (column major) array of values for  block matrices with blocksize larger than one, otherwise a one dimensional array of values

1472:    Notes:
1473:    The values, v, are column-oriented for the block version.

1475:    All the nonzeros in the row must be provided

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

1479:    The row must belong to this process

1481:    Level: advanced

1483:    Concepts: matrices^putting entries in

1485: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1486:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1487: @*/
1488: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1489: {

1495:   MatCheckPreallocated(mat,1);
1497: #if defined(PETSC_USE_DEBUG)
1498:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1499:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1500: #endif
1501:   mat->insertmode = INSERT_VALUES;

1503:   if (mat->assembled) {
1504:     mat->was_assembled = PETSC_TRUE;
1505:     mat->assembled     = PETSC_FALSE;
1506:   }
1507:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1508:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1509:   (*mat->ops->setvaluesrow)(mat,row,v);
1510:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1511: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1512:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1513:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1514:   }
1515: #endif
1516:   return(0);
1517: }

1519: /*@
1520:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1521:      Using structured grid indexing

1523:    Not Collective

1525:    Input Parameters:
1526: +  mat - the matrix
1527: .  m - number of rows being entered
1528: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1529: .  n - number of columns being entered
1530: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1531: .  v - a logically two-dimensional array of values
1532: -  addv - either ADD_VALUES or INSERT_VALUES, where
1533:    ADD_VALUES adds values to any existing entries, and
1534:    INSERT_VALUES replaces existing entries with new values

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

1539:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1540:    options cannot be mixed without intervening calls to the assembly
1541:    routines.

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

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

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

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

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

1559:    In Fortran idxm and idxn should be declared as
1560: $     MatStencil idxm(4,m),idxn(4,n)
1561:    and the values inserted using
1562: $    idxm(MatStencil_i,1) = i
1563: $    idxm(MatStencil_j,1) = j
1564: $    idxm(MatStencil_k,1) = k
1565: $    idxm(MatStencil_c,1) = c
1566:    etc

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

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

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

1579:    Efficiency Alert:
1580:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1581:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1583:    Level: beginner

1585:    Concepts: matrices^putting entries in

1587: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1588:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1589: @*/
1590: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1591: {
1593:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1594:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1595:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1605:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1606:     jdxm = buf; jdxn = buf+m;
1607:   } else {
1608:     PetscMalloc2(m,&bufm,n,&bufn);
1609:     jdxm = bufm; jdxn = bufn;
1610:   }
1611:   for (i=0; i<m; i++) {
1612:     for (j=0; j<3-sdim; j++) dxm++;
1613:     tmp = *dxm++ - starts[0];
1614:     for (j=0; j<dim-1; j++) {
1615:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1616:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1617:     }
1618:     if (mat->stencil.noc) dxm++;
1619:     jdxm[i] = tmp;
1620:   }
1621:   for (i=0; i<n; i++) {
1622:     for (j=0; j<3-sdim; j++) dxn++;
1623:     tmp = *dxn++ - starts[0];
1624:     for (j=0; j<dim-1; j++) {
1625:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1626:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1627:     }
1628:     if (mat->stencil.noc) dxn++;
1629:     jdxn[i] = tmp;
1630:   }
1631:   MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1632:   PetscFree2(bufm,bufn);
1633:   return(0);
1634: }

1636: /*@
1637:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1638:      Using structured grid indexing

1640:    Not Collective

1642:    Input Parameters:
1643: +  mat - the matrix
1644: .  m - number of rows being entered
1645: .  idxm - grid coordinates for matrix rows being entered
1646: .  n - number of columns being entered
1647: .  idxn - grid coordinates for matrix columns being entered
1648: .  v - a logically two-dimensional array of values
1649: -  addv - either ADD_VALUES or INSERT_VALUES, where
1650:    ADD_VALUES adds values to any existing entries, and
1651:    INSERT_VALUES replaces existing entries with new values

1653:    Notes:
1654:    By default the values, v, are row-oriented and unsorted.
1655:    See MatSetOption() for other options.

1657:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1658:    options cannot be mixed without intervening calls to the assembly
1659:    routines.

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

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

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

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

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

1677:    In Fortran idxm and idxn should be declared as
1678: $     MatStencil idxm(4,m),idxn(4,n)
1679:    and the values inserted using
1680: $    idxm(MatStencil_i,1) = i
1681: $    idxm(MatStencil_j,1) = j
1682: $    idxm(MatStencil_k,1) = k
1683:    etc

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

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

1693:    Level: beginner

1695:    Concepts: matrices^putting entries in

1697: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1698:           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1699:           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1700: @*/
1701: PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1702: {
1704:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1705:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1706:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1716:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1717:     jdxm = buf; jdxn = buf+m;
1718:   } else {
1719:     PetscMalloc2(m,&bufm,n,&bufn);
1720:     jdxm = bufm; jdxn = bufn;
1721:   }
1722:   for (i=0; i<m; i++) {
1723:     for (j=0; j<3-sdim; j++) dxm++;
1724:     tmp = *dxm++ - starts[0];
1725:     for (j=0; j<sdim-1; j++) {
1726:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1727:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1728:     }
1729:     dxm++;
1730:     jdxm[i] = tmp;
1731:   }
1732:   for (i=0; i<n; i++) {
1733:     for (j=0; j<3-sdim; j++) dxn++;
1734:     tmp = *dxn++ - starts[0];
1735:     for (j=0; j<sdim-1; j++) {
1736:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1737:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1738:     }
1739:     dxn++;
1740:     jdxn[i] = tmp;
1741:   }
1742:   MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1743:   PetscFree2(bufm,bufn);
1744: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1745:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1746:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1747:   }
1748: #endif
1749:   return(0);
1750: }

1752: /*@
1753:    MatSetStencil - Sets the grid information for setting values into a matrix via
1754:         MatSetValuesStencil()

1756:    Not Collective

1758:    Input Parameters:
1759: +  mat - the matrix
1760: .  dim - dimension of the grid 1, 2, or 3
1761: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1762: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1763: -  dof - number of degrees of freedom per node


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

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

1772:    Level: beginner

1774:    Concepts: matrices^putting entries in

1776: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1777:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1778: @*/
1779: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1780: {
1781:   PetscInt i;


1788:   mat->stencil.dim = dim + (dof > 1);
1789:   for (i=0; i<dim; i++) {
1790:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1791:     mat->stencil.starts[i] = starts[dim-i-1];
1792:   }
1793:   mat->stencil.dims[dim]   = dof;
1794:   mat->stencil.starts[dim] = 0;
1795:   mat->stencil.noc         = (PetscBool)(dof == 1);
1796:   return(0);
1797: }

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

1802:    Not Collective

1804:    Input Parameters:
1805: +  mat - the matrix
1806: .  v - a logically two-dimensional array of values
1807: .  m, idxm - the number of block rows and their global block indices
1808: .  n, idxn - the number of block columns and their global block indices
1809: -  addv - either ADD_VALUES or INSERT_VALUES, where
1810:    ADD_VALUES adds values to any existing entries, and
1811:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

1829:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1830:    options cannot be mixed without intervening calls to the assembly
1831:    routines.

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

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

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

1847:    Example:
1848: $   Suppose m=n=2 and block size(bs) = 2 The array is
1849: $
1850: $   1  2  | 3  4
1851: $   5  6  | 7  8
1852: $   - - - | - - -
1853: $   9  10 | 11 12
1854: $   13 14 | 15 16
1855: $
1856: $   v[] should be passed in like
1857: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1858: $
1859: $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1860: $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]

1862:    Level: intermediate

1864:    Concepts: matrices^putting entries in blocked

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

1875:   if (!m || !n) return(0); /* no values to insert */
1879:   MatCheckPreallocated(mat,1);
1880:   if (mat->insertmode == NOT_SET_VALUES) {
1881:     mat->insertmode = addv;
1882:   }
1883: #if defined(PETSC_USE_DEBUG)
1884:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1885:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1886:   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1887: #endif

1889:   if (mat->assembled) {
1890:     mat->was_assembled = PETSC_TRUE;
1891:     mat->assembled     = PETSC_FALSE;
1892:   }
1893:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1894:   if (mat->ops->setvaluesblocked) {
1895:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1896:   } else {
1897:     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1898:     PetscInt i,j,bs,cbs;
1899:     MatGetBlockSizes(mat,&bs,&cbs);
1900:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1901:       iidxm = buf; iidxn = buf + m*bs;
1902:     } else {
1903:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1904:       iidxm = bufr; iidxn = bufc;
1905:     }
1906:     for (i=0; i<m; i++) {
1907:       for (j=0; j<bs; j++) {
1908:         iidxm[i*bs+j] = bs*idxm[i] + j;
1909:       }
1910:     }
1911:     for (i=0; i<n; i++) {
1912:       for (j=0; j<cbs; j++) {
1913:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1914:       }
1915:     }
1916:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1917:     PetscFree2(bufr,bufc);
1918:   }
1919:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1920: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1921:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1922:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1923:   }
1924: #endif
1925:   return(0);
1926: }

1928: /*@
1929:    MatGetValues - Gets a block of values from a matrix.

1931:    Not Collective; currently only returns a local block

1933:    Input Parameters:
1934: +  mat - the matrix
1935: .  v - a logically two-dimensional array for storing the values
1936: .  m, idxm - the number of rows and their global indices
1937: -  n, idxn - the number of columns and their global indices

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

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

1947:    MatGetValues() requires that the matrix has been assembled
1948:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1949:    MatSetValues() and MatGetValues() CANNOT be made in succession
1950:    without intermediate matrix assembly.

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

1955:    Level: advanced

1957:    Concepts: matrices^accessing values

1959: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1960: @*/
1961: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1962: {

1968:   if (!m || !n) return(0);
1972:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1973:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1974:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1975:   MatCheckPreallocated(mat,1);

1977:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1978:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1979:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1980:   return(0);
1981: }

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

1987:   Not Collective

1989:   Input Parameters:
1990: + mat - the matrix
1991: . nb - the number of blocks
1992: . bs - the number of rows (and columns) in each block
1993: . rows - a concatenation of the rows for each block
1994: - v - a concatenation of logically two-dimensional arrays of values

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

1999:   Level: advanced

2001:   Concepts: matrices^putting entries in

2003: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2004:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2005: @*/
2006: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2007: {

2015: #if defined(PETSC_USE_DEBUG)
2016:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2017: #endif

2019:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2020:   if (mat->ops->setvaluesbatch) {
2021:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2022:   } else {
2023:     PetscInt b;
2024:     for (b = 0; b < nb; ++b) {
2025:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2026:     }
2027:   }
2028:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2029:   return(0);
2030: }

2032: /*@
2033:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2034:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2035:    using a local (per-processor) numbering.

2037:    Not Collective

2039:    Input Parameters:
2040: +  x - the matrix
2041: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2042: - cmapping - column mapping

2044:    Level: intermediate

2046:    Concepts: matrices^local to global mapping
2047:    Concepts: local to global mapping^for matrices

2049: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2050: @*/
2051: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2052: {


2061:   if (x->ops->setlocaltoglobalmapping) {
2062:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2063:   } else {
2064:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2065:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2066:   }
2067:   return(0);
2068: }


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

2074:    Not Collective

2076:    Input Parameters:
2077: .  A - the matrix

2079:    Output Parameters:
2080: + rmapping - row mapping
2081: - cmapping - column mapping

2083:    Level: advanced

2085:    Concepts: matrices^local to global mapping
2086:    Concepts: local to global mapping^for matrices

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

2102: /*@
2103:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2105:    Not Collective

2107:    Input Parameters:
2108: .  A - the matrix

2110:    Output Parameters:
2111: + rmap - row layout
2112: - cmap - column layout

2114:    Level: advanced

2116: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2117: @*/
2118: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2119: {
2125:   if (rmap) *rmap = A->rmap;
2126:   if (cmap) *cmap = A->cmap;
2127:   return(0);
2128: }

2130: /*@C
2131:    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2132:    using a local ordering of the nodes.

2134:    Not Collective

2136:    Input Parameters:
2137: +  mat - the matrix
2138: .  nrow, irow - number of rows and their local indices
2139: .  ncol, icol - number of columns and their local indices
2140: .  y -  a logically two-dimensional array of values
2141: -  addv - either INSERT_VALUES or ADD_VALUES, where
2142:    ADD_VALUES adds values to any existing entries, and
2143:    INSERT_VALUES replaces existing entries with new values

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

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

2151:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2152:    options cannot be mixed without intervening calls to the assembly
2153:    routines.

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

2158:    Level: intermediate

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

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

2166: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2167:            MatSetValueLocal()
2168: @*/
2169: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2170: {

2176:   MatCheckPreallocated(mat,1);
2177:   if (!nrow || !ncol) return(0); /* no values to insert */
2181:   if (mat->insertmode == NOT_SET_VALUES) {
2182:     mat->insertmode = addv;
2183:   }
2184: #if defined(PETSC_USE_DEBUG)
2185:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2186:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2187:   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2188: #endif

2190:   if (mat->assembled) {
2191:     mat->was_assembled = PETSC_TRUE;
2192:     mat->assembled     = PETSC_FALSE;
2193:   }
2194:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2195:   if (mat->ops->setvalueslocal) {
2196:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2197:   } else {
2198:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2199:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2200:       irowm = buf; icolm = buf+nrow;
2201:     } else {
2202:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2203:       irowm = bufr; icolm = bufc;
2204:     }
2205:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2206:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2207:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2208:     PetscFree2(bufr,bufc);
2209:   }
2210:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2211: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2212:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2213:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2214:   }
2215: #endif
2216:   return(0);
2217: }

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

2223:    Not Collective

2225:    Input Parameters:
2226: +  x - the matrix
2227: .  nrow, irow - number of rows and their local indices
2228: .  ncol, icol - number of columns and their local indices
2229: .  y -  a logically two-dimensional array of values
2230: -  addv - either INSERT_VALUES or ADD_VALUES, where
2231:    ADD_VALUES adds values to any existing entries, and
2232:    INSERT_VALUES replaces existing entries with new values

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

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

2241:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2242:    options cannot be mixed without intervening calls to the assembly
2243:    routines.

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

2248:    Level: intermediate

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

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

2256: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2257:            MatSetValuesLocal(),  MatSetValuesBlocked()
2258: @*/
2259: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2260: {

2266:   MatCheckPreallocated(mat,1);
2267:   if (!nrow || !ncol) return(0); /* no values to insert */
2271:   if (mat->insertmode == NOT_SET_VALUES) {
2272:     mat->insertmode = addv;
2273:   }
2274: #if defined(PETSC_USE_DEBUG)
2275:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2276:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2277:   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);
2278: #endif

2280:   if (mat->assembled) {
2281:     mat->was_assembled = PETSC_TRUE;
2282:     mat->assembled     = PETSC_FALSE;
2283:   }
2284: #if defined(PETSC_USE_DEBUG)
2285:   /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2286:   if (mat->rmap->mapping) {
2287:     PetscInt irbs, rbs;
2288:     MatGetBlockSizes(mat, &rbs, NULL);
2289:     ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2290:     if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2291:   }
2292:   if (mat->cmap->mapping) {
2293:     PetscInt icbs, cbs;
2294:     MatGetBlockSizes(mat,NULL,&cbs);
2295:     ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2296:     if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2297:   }
2298: #endif
2299:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2300:   if (mat->ops->setvaluesblockedlocal) {
2301:     (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2302:   } else {
2303:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2304:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2305:       irowm = buf; icolm = buf + nrow;
2306:     } else {
2307:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2308:       irowm = bufr; icolm = bufc;
2309:     }
2310:     ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2311:     ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2312:     MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2313:     PetscFree2(bufr,bufc);
2314:   }
2315:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2316: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2317:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2318:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2319:   }
2320: #endif
2321:   return(0);
2322: }

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

2327:    Collective on Mat and Vec

2329:    Input Parameters:
2330: +  mat - the matrix
2331: -  x   - the vector to be multiplied

2333:    Output Parameters:
2334: .  y - the result

2336:    Notes:
2337:    The vectors x and y cannot be the same.  I.e., one cannot
2338:    call MatMult(A,y,y).

2340:    Level: developer

2342:    Concepts: matrix-vector product

2344: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2345: @*/
2346: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2347: {


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

2361:   if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2362:   (*mat->ops->multdiagonalblock)(mat,x,y);
2363:   PetscObjectStateIncrease((PetscObject)y);
2364:   return(0);
2365: }

2367: /* --------------------------------------------------------*/
2368: /*@
2369:    MatMult - Computes the matrix-vector product, y = Ax.

2371:    Neighbor-wise Collective on Mat and Vec

2373:    Input Parameters:
2374: +  mat - the matrix
2375: -  x   - the vector to be multiplied

2377:    Output Parameters:
2378: .  y - the result

2380:    Notes:
2381:    The vectors x and y cannot be the same.  I.e., one cannot
2382:    call MatMult(A,y,y).

2384:    Level: beginner

2386:    Concepts: matrix-vector product

2388: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2389: @*/
2390: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2391: {

2399:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2400:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2401:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2402: #if !defined(PETSC_HAVE_CONSTRAINTS)
2403:   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);
2404:   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);
2405:   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);
2406: #endif
2407:   VecSetErrorIfLocked(y,3);
2408:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2409:   MatCheckPreallocated(mat,1);

2411:   VecLockReadPush(x);
2412:   if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2413:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2414:   (*mat->ops->mult)(mat,x,y);
2415:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2416:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2417:   VecLockReadPop(x);
2418:   return(0);
2419: }

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

2424:    Neighbor-wise Collective on Mat and Vec

2426:    Input Parameters:
2427: +  mat - the matrix
2428: -  x   - the vector to be multiplied

2430:    Output Parameters:
2431: .  y - the result

2433:    Notes:
2434:    The vectors x and y cannot be the same.  I.e., one cannot
2435:    call MatMultTranspose(A,y,y).

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

2440:    Level: beginner

2442:    Concepts: matrix vector product^transpose

2444: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2445: @*/
2446: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2447: {


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

2466:   if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2467:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2468:   VecLockReadPush(x);
2469:   (*mat->ops->multtranspose)(mat,x,y);
2470:   VecLockReadPop(x);
2471:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2472:   PetscObjectStateIncrease((PetscObject)y);
2473:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2474:   return(0);
2475: }

2477: /*@
2478:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2480:    Neighbor-wise Collective on Mat and Vec

2482:    Input Parameters:
2483: +  mat - the matrix
2484: -  x   - the vector to be multilplied

2486:    Output Parameters:
2487: .  y - the result

2489:    Notes:
2490:    The vectors x and y cannot be the same.  I.e., one cannot
2491:    call MatMultHermitianTranspose(A,y,y).

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

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

2497:    Level: beginner

2499:    Concepts: matrix vector product^transpose

2501: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2502: @*/
2503: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2504: {
2506:   Vec            w;


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

2523:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2524:   if (mat->ops->multhermitiantranspose) {
2525:     VecLockReadPush(x);
2526:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2527:     VecLockReadPop(x);
2528:   } else {
2529:     VecDuplicate(x,&w);
2530:     VecCopy(x,w);
2531:     VecConjugate(w);
2532:     MatMultTranspose(mat,w,y);
2533:     VecDestroy(&w);
2534:     VecConjugate(y);
2535:   }
2536:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2537:   PetscObjectStateIncrease((PetscObject)y);
2538:   return(0);
2539: }

2541: /*@
2542:     MatMultAdd -  Computes v3 = v2 + A * v1.

2544:     Neighbor-wise Collective on Mat and Vec

2546:     Input Parameters:
2547: +   mat - the matrix
2548: -   v1, v2 - the vectors

2550:     Output Parameters:
2551: .   v3 - the result

2553:     Notes:
2554:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2555:     call MatMultAdd(A,v1,v2,v1).

2557:     Level: beginner

2559:     Concepts: matrix vector product^addition

2561: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2562: @*/
2563: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2564: {


2574:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2575:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2576:   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);
2577:   /* 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);
2578:      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); */
2579:   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);
2580:   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);
2581:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2582:   MatCheckPreallocated(mat,1);

2584:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2585:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2586:   VecLockReadPush(v1);
2587:   (*mat->ops->multadd)(mat,v1,v2,v3);
2588:   VecLockReadPop(v1);
2589:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2590:   PetscObjectStateIncrease((PetscObject)v3);
2591:   return(0);
2592: }

2594: /*@
2595:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2597:    Neighbor-wise Collective on Mat and Vec

2599:    Input Parameters:
2600: +  mat - the matrix
2601: -  v1, v2 - the vectors

2603:    Output Parameters:
2604: .  v3 - the result

2606:    Notes:
2607:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2608:    call MatMultTransposeAdd(A,v1,v2,v1).

2610:    Level: beginner

2612:    Concepts: matrix vector product^transpose and addition

2614: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2615: @*/
2616: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2617: {


2627:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2628:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2629:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2630:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2631:   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);
2632:   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);
2633:   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);
2634:   MatCheckPreallocated(mat,1);

2636:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2637:   VecLockReadPush(v1);
2638:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2639:   VecLockReadPop(v1);
2640:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2641:   PetscObjectStateIncrease((PetscObject)v3);
2642:   return(0);
2643: }

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

2648:    Neighbor-wise Collective on Mat and Vec

2650:    Input Parameters:
2651: +  mat - the matrix
2652: -  v1, v2 - the vectors

2654:    Output Parameters:
2655: .  v3 - the result

2657:    Notes:
2658:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2659:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2661:    Level: beginner

2663:    Concepts: matrix vector product^transpose and addition

2665: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2666: @*/
2667: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2668: {


2678:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2679:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2680:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2681:   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);
2682:   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);
2683:   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);
2684:   MatCheckPreallocated(mat,1);

2686:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2687:   VecLockReadPush(v1);
2688:   if (mat->ops->multhermitiantransposeadd) {
2689:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2690:   } else {
2691:     Vec w,z;
2692:     VecDuplicate(v1,&w);
2693:     VecCopy(v1,w);
2694:     VecConjugate(w);
2695:     VecDuplicate(v3,&z);
2696:     MatMultTranspose(mat,w,z);
2697:     VecDestroy(&w);
2698:     VecConjugate(z);
2699:     if (v2 != v3) {
2700:       VecWAXPY(v3,1.0,v2,z);
2701:     } else {
2702:       VecAXPY(v3,1.0,z);
2703:     }
2704:     VecDestroy(&z);
2705:   }
2706:   VecLockReadPop(v1);
2707:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2708:   PetscObjectStateIncrease((PetscObject)v3);
2709:   return(0);
2710: }

2712: /*@
2713:    MatMultConstrained - The inner multiplication routine for a
2714:    constrained matrix P^T A P.

2716:    Neighbor-wise Collective on Mat and Vec

2718:    Input Parameters:
2719: +  mat - the matrix
2720: -  x   - the vector to be multilplied

2722:    Output Parameters:
2723: .  y - the result

2725:    Notes:
2726:    The vectors x and y cannot be the same.  I.e., one cannot
2727:    call MatMult(A,y,y).

2729:    Level: beginner

2731: .keywords: matrix, multiply, matrix-vector product, constraint
2732: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2733: @*/
2734: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2735: {

2742:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2743:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2744:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2745:   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);
2746:   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);
2747:   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);

2749:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2750:   VecLockReadPush(x);
2751:   (*mat->ops->multconstrained)(mat,x,y);
2752:   VecLockReadPop(x);
2753:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2754:   PetscObjectStateIncrease((PetscObject)y);
2755:   return(0);
2756: }

2758: /*@
2759:    MatMultTransposeConstrained - The inner multiplication routine for a
2760:    constrained matrix P^T A^T P.

2762:    Neighbor-wise Collective on Mat and Vec

2764:    Input Parameters:
2765: +  mat - the matrix
2766: -  x   - the vector to be multilplied

2768:    Output Parameters:
2769: .  y - the result

2771:    Notes:
2772:    The vectors x and y cannot be the same.  I.e., one cannot
2773:    call MatMult(A,y,y).

2775:    Level: beginner

2777: .keywords: matrix, multiply, matrix-vector product, constraint
2778: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2779: @*/
2780: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2781: {

2788:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2789:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2790:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2791:   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);
2792:   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);

2794:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2795:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2796:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2797:   PetscObjectStateIncrease((PetscObject)y);
2798:   return(0);
2799: }

2801: /*@C
2802:    MatGetFactorType - gets the type of factorization it is

2804:    Not Collective

2806:    Input Parameters:
2807: .  mat - the matrix

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

2812:    Level: intermediate

2814: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2815: @*/
2816: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2817: {
2822:   *t = mat->factortype;
2823:   return(0);
2824: }

2826: /*@C
2827:    MatSetFactorType - sets the type of factorization it is

2829:    Logically Collective on Mat

2831:    Input Parameters:
2832: +  mat - the matrix
2833: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2835:    Level: intermediate

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

2848: /* ------------------------------------------------------------*/
2849: /*@C
2850:    MatGetInfo - Returns information about matrix storage (number of
2851:    nonzeros, memory, etc.).

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

2855:    Input Parameters:
2856: .  mat - the matrix

2858:    Output Parameters:
2859: +  flag - flag indicating the type of parameters to be returned
2860:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2861:    MAT_GLOBAL_SUM - sum over all processors)
2862: -  info - matrix information context

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

2873:    Example for C/C++ Users:
2874:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2875:    data within the MatInfo context.  For example,
2876: .vb
2877:       MatInfo info;
2878:       Mat     A;
2879:       double  mal, nz_a, nz_u;

2881:       MatGetInfo(A,MAT_LOCAL,&info);
2882:       mal  = info.mallocs;
2883:       nz_a = info.nz_allocated;
2884: .ve

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

2897:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2898:       mal = info(MAT_INFO_MALLOCS)
2899:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2900: .ve

2902:     Level: intermediate

2904:     Concepts: matrices^getting information on

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

2909: .seealso: MatStashGetInfo()

2911: @*/
2912: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2913: {

2920:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2921:   MatCheckPreallocated(mat,1);
2922:   (*mat->ops->getinfo)(mat,flag,info);
2923:   return(0);
2924: }

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

2935:   PetscMemzero(info,sizeof(MatInfo));
2936:   return(0);
2937: }

2939: /* ----------------------------------------------------------*/

2941: /*@C
2942:    MatLUFactor - Performs in-place LU factorization of matrix.

2944:    Collective on Mat

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

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

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

2963:    Level: developer

2965:    Concepts: matrices^LU factorization

2967: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2968:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

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

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

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

3001: /*@C
3002:    MatILUFactor - Performs in-place ILU factorization of matrix.

3004:    Collective on Mat

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

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

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

3024:    Level: developer

3026:    Concepts: matrices^ILU factorization

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

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

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

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

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

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

3061:    Collective on Mat

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


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

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

3080:    Level: developer

3082:    Concepts: matrices^LU symbolic factorization

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

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

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

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

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

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

3121:    Collective on Mat

3123:    Input Parameters:
3124: +  fact - the factor matrix obtained with MatGetFactor()
3125: .  mat - the matrix
3126: -  info - options for factorization

3128:    Notes:
3129:    See MatLUFactor() for in-place factorization.  See
3130:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3136:    Level: developer

3138:    Concepts: matrices^LU numeric factorization

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

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

3145: @*/
3146: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3147: {

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

3158:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3159:   MatCheckPreallocated(mat,2);
3160:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3161:   (fact->ops->lufactornumeric)(fact,mat,info);
3162:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3163:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3164:   PetscObjectStateIncrease((PetscObject)fact);
3165:   return(0);
3166: }

3168: /*@C
3169:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3170:    symmetric matrix.

3172:    Collective on Mat

3174:    Input Parameters:
3175: +  mat - the matrix
3176: .  perm - row and column permutations
3177: -  f - expected fill as ratio of original fill

3179:    Notes:
3180:    See MatLUFactor() for the nonsymmetric case.  See also
3181:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3187:    Level: developer

3189:    Concepts: matrices^Cholesky factorization

3191: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3192:           MatGetOrdering()

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

3197: @*/
3198: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3199: {

3207:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3208:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3209:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3210:   if (!mat->ops->choleskyfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"In-place factorization for Mat type %s is not supported, try out-of-place factorization. See MatCholeskyFactorSymbolic/Numeric",((PetscObject)mat)->type_name);
3211:   MatCheckPreallocated(mat,1);

3213:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3214:   (*mat->ops->choleskyfactor)(mat,perm,info);
3215:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3216:   PetscObjectStateIncrease((PetscObject)mat);
3217:   return(0);
3218: }

3220: /*@C
3221:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3222:    of a symmetric matrix.

3224:    Collective on Mat

3226:    Input Parameters:
3227: +  fact - the factor matrix obtained with MatGetFactor()
3228: .  mat - the matrix
3229: .  perm - row and column permutations
3230: -  info - options for factorization, includes
3231: $          fill - expected fill as ratio of original fill.
3232: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3233: $                   Run with the option -info to determine an optimal value to use

3235:    Notes:
3236:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3237:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3243:    Level: developer

3245:    Concepts: matrices^Cholesky symbolic factorization

3247: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3248:           MatGetOrdering()

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

3253: @*/
3254: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3255: {

3264:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3265:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3266:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3267:   if (!(fact)->ops->choleskyfactorsymbolic) {
3268:     MatSolverType spackage;
3269:     MatFactorGetSolverType(fact,&spackage);
3270:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3271:   }
3272:   MatCheckPreallocated(mat,2);

3274:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3275:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3276:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3277:   PetscObjectStateIncrease((PetscObject)fact);
3278:   return(0);
3279: }

3281: /*@C
3282:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3283:    of a symmetric matrix. Call this routine after first calling
3284:    MatCholeskyFactorSymbolic().

3286:    Collective on Mat

3288:    Input Parameters:
3289: +  fact - the factor matrix obtained with MatGetFactor()
3290: .  mat - the initial matrix
3291: .  info - options for factorization
3292: -  fact - the symbolic factor of mat


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

3300:    Level: developer

3302:    Concepts: matrices^Cholesky numeric factorization

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

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

3309: @*/
3310: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3311: {

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

3324:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3325:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3326:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3327:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3328:   PetscObjectStateIncrease((PetscObject)fact);
3329:   return(0);
3330: }

3332: /* ----------------------------------------------------------------*/
3333: /*@
3334:    MatSolve - Solves A x = b, given a factored matrix.

3336:    Neighbor-wise Collective on Mat and Vec

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

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

3345:    Notes:
3346:    The vectors b and x cannot be the same.  I.e., one cannot
3347:    call MatSolve(A,x,x).

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

3354:    Level: developer

3356:    Concepts: matrices^triangular solves

3358: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3359: @*/
3360: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3361: {

3371:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3372:   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);
3373:   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);
3374:   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);
3375:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3376:   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3377:   MatCheckPreallocated(mat,1);

3379:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3380:   if (mat->factorerrortype) {
3381:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3382:     VecSetInf(x);
3383:   } else {
3384:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3385:     (*mat->ops->solve)(mat,b,x);
3386:   }
3387:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3388:   PetscObjectStateIncrease((PetscObject)x);
3389:   return(0);
3390: }

3392: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X, PetscBool trans)
3393: {
3395:   Vec            b,x;
3396:   PetscInt       m,N,i;
3397:   PetscScalar    *bb,*xx;
3398:   PetscBool      flg;

3401:   PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3402:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
3403:   PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3404:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");

3406:   MatDenseGetArray(B,&bb);
3407:   MatDenseGetArray(X,&xx);
3408:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3409:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3410:   MatCreateVecs(A,&x,&b);
3411:   for (i=0; i<N; i++) {
3412:     VecPlaceArray(b,bb + i*m);
3413:     VecPlaceArray(x,xx + i*m);
3414:     if (trans) {
3415:       MatSolveTranspose(A,b,x);
3416:     } else {
3417:       MatSolve(A,b,x);
3418:     }
3419:     VecResetArray(x);
3420:     VecResetArray(b);
3421:   }
3422:   VecDestroy(&b);
3423:   VecDestroy(&x);
3424:   MatDenseRestoreArray(B,&bb);
3425:   MatDenseRestoreArray(X,&xx);
3426:   return(0);
3427: }

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

3432:    Neighbor-wise Collective on Mat

3434:    Input Parameters:
3435: +  A - the factored matrix
3436: -  B - the right-hand-side matrix  (dense matrix)

3438:    Output Parameter:
3439: .  X - the result matrix (dense matrix)

3441:    Notes:
3442:    The matrices b and x cannot be the same.  I.e., one cannot
3443:    call MatMatSolve(A,x,x).

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

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

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

3456:    Level: developer

3458:    Concepts: matrices^triangular solves

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

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

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

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

3496:    Neighbor-wise Collective on Mat

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

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

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

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

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

3517:    Level: developer

3519:    Concepts: matrices^triangular solves

3521: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3522: @*/
3523: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3524: {

3534:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3535:   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);
3536:   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);
3537:   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);
3538:   if (X->cmap->N < B->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3539:   if (!A->rmap->N && !A->cmap->N) return(0);
3540:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3541:   MatCheckPreallocated(A,1);

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

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

3558:    Neighbor-wise Collective on Mat

3560:    Input Parameters:
3561: +  A - the factored matrix
3562: -  Bt - the transpose of right-hand-side matrix

3564:    Output Parameter:
3565: .  X - the result matrix (dense matrix)

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

3573:    For MUMPS, it only supports centralized sparse compressed column format on the host processor for right hand side matrix. User must create B^T in sparse compressed row format on the host processor and call MatMatTransposeSolve() to implement MUMPS' MatMatSolve().

3575:    Level: developer

3577:    Concepts: matrices^triangular solves

3579: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3580: @*/
3581: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3582: {


3593:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3594:   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);
3595:   if (A->rmap->N != Bt->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat Bt: global dim %D %D",A->rmap->N,Bt->cmap->N);
3596:   if (X->cmap->N < Bt->rmap->N) SETERRQ(PetscObjectComm((PetscObject)X),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as row number of the rhs matrix");
3597:   if (!A->rmap->N && !A->cmap->N) return(0);
3598:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3599:   MatCheckPreallocated(A,1);

3601:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3602:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3603:   (*A->ops->mattransposesolve)(A,Bt,X);
3604:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3605:   PetscObjectStateIncrease((PetscObject)X);
3606:   return(0);
3607: }

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

3613:    Neighbor-wise Collective on Mat and Vec

3615:    Input Parameters:
3616: +  mat - the factored matrix
3617: -  b - the right-hand-side vector

3619:    Output Parameter:
3620: .  x - the result vector

3622:    Notes:
3623:    MatSolve() should be used for most applications, as it performs
3624:    a forward solve followed by a backward solve.

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

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

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

3639:    Level: developer

3641:    Concepts: matrices^forward solves

3643: .seealso: MatSolve(), MatBackwardSolve()
3644: @*/
3645: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3646: {

3656:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3657:   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);
3658:   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);
3659:   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);
3660:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3661:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3662:   MatCheckPreallocated(mat,1);

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

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

3676:    Neighbor-wise Collective on Mat and Vec

3678:    Input Parameters:
3679: +  mat - the factored matrix
3680: -  b - the right-hand-side vector

3682:    Output Parameter:
3683: .  x - the result vector

3685:    Notes:
3686:    MatSolve() should be used for most applications, as it performs
3687:    a forward solve followed by a backward solve.

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

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

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

3702:    Level: developer

3704:    Concepts: matrices^backward solves

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

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

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

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

3738:    Neighbor-wise Collective on Mat and Vec

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

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

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

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

3756:    Level: developer

3758:    Concepts: matrices^triangular solves

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

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

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

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

3812:    Neighbor-wise Collective on Mat and Vec

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

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

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

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

3829:    Level: developer

3831:    Concepts: matrices^triangular solves

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

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

3865: /*@
3866:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3867:                       factored matrix.

3869:    Neighbor-wise Collective on Mat and Vec

3871:    Input Parameters:
3872: +  mat - the factored matrix
3873: .  b - the right-hand-side vector
3874: -  y - the vector to be added to

3876:    Output Parameter:
3877: .  x - the result vector

3879:    Notes:
3880:    The vectors b and x cannot be the same.  I.e., one cannot
3881:    call MatSolveTransposeAdd(A,x,y,x).

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

3887:    Level: developer

3889:    Concepts: matrices^triangular solves

3891: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3892: @*/
3893: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3894: {
3895:   PetscScalar    one = 1.0;
3897:   Vec            tmp;

3908:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3909:   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);
3910:   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);
3911:   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);
3912:   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);
3913:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3914:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3915:   MatCheckPreallocated(mat,1);

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

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

3948:    Neighbor-wise Collective on Mat and Vec

3950:    Input Parameters:
3951: +  mat - the matrix
3952: .  b - the right hand side
3953: .  omega - the relaxation factor
3954: .  flag - flag indicating the type of SOR (see below)
3955: .  shift -  diagonal shift
3956: .  its - the number of iterations
3957: -  lits - the number of local iterations

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

3962:    SOR Flags:
3963: .     SOR_FORWARD_SWEEP - forward SOR
3964: .     SOR_BACKWARD_SWEEP - backward SOR
3965: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3966: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3967: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3968: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3969: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3970:          upper/lower triangular part of matrix to
3971:          vector (with omega)
3972: .     SOR_ZERO_INITIAL_GUESS - zero initial guess

3974:    Notes:
3975:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3976:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3977:    on each processor.

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

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

3985:    Notes for Advanced Users:
3986:    The flags are implemented as bitwise inclusive or operations.
3987:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3988:    to specify a zero initial guess for SSOR.

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

3994:    Vectors x and b CANNOT be the same

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

3998:    Level: developer

4000:    Concepts: matrices^relaxation
4001:    Concepts: matrices^SOR
4002:    Concepts: matrices^Gauss-Seidel

4004: @*/
4005: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
4006: {

4016:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4017:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4018:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4019:   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);
4020:   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);
4021:   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);
4022:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
4023:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
4024:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

4026:   MatCheckPreallocated(mat,1);
4027:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
4028:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
4029:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
4030:   PetscObjectStateIncrease((PetscObject)x);
4031:   return(0);
4032: }

4034: /*
4035:       Default matrix copy routine.
4036: */
4037: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4038: {
4039:   PetscErrorCode    ierr;
4040:   PetscInt          i,rstart = 0,rend = 0,nz;
4041:   const PetscInt    *cwork;
4042:   const PetscScalar *vwork;

4045:   if (B->assembled) {
4046:     MatZeroEntries(B);
4047:   }
4048:   if (str == SAME_NONZERO_PATTERN) {
4049:     MatGetOwnershipRange(A,&rstart,&rend);
4050:     for (i=rstart; i<rend; i++) {
4051:       MatGetRow(A,i,&nz,&cwork,&vwork);
4052:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
4053:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
4054:     }
4055:   } else {
4056:     MatAYPX(B,0.0,A,str);
4057:   }
4058:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4059:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4060:   return(0);
4061: }

4063: /*@
4064:    MatCopy - Copies a matrix to another matrix.

4066:    Collective on Mat

4068:    Input Parameters:
4069: +  A - the matrix
4070: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4072:    Output Parameter:
4073: .  B - where the copy is put

4075:    Notes:
4076:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4077:    same nonzero pattern or the routine will crash.

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

4083:    Level: intermediate

4085:    Concepts: matrices^copying

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

4089: @*/
4090: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4091: {
4093:   PetscInt       i;

4101:   MatCheckPreallocated(B,2);
4102:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4103:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4104:   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);
4105:   MatCheckPreallocated(A,1);
4106:   if (A == B) return(0);

4108:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4109:   if (A->ops->copy) {
4110:     (*A->ops->copy)(A,B,str);
4111:   } else { /* generic conversion */
4112:     MatCopy_Basic(A,B,str);
4113:   }

4115:   B->stencil.dim = A->stencil.dim;
4116:   B->stencil.noc = A->stencil.noc;
4117:   for (i=0; i<=A->stencil.dim; i++) {
4118:     B->stencil.dims[i]   = A->stencil.dims[i];
4119:     B->stencil.starts[i] = A->stencil.starts[i];
4120:   }

4122:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4123:   PetscObjectStateIncrease((PetscObject)B);
4124:   return(0);
4125: }

4127: /*@C
4128:    MatConvert - Converts a matrix to another matrix, either of the same
4129:    or different type.

4131:    Collective on Mat

4133:    Input Parameters:
4134: +  mat - the matrix
4135: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4136:    same type as the original matrix.
4137: -  reuse - denotes if the destination matrix is to be created or reused.
4138:    Use MAT_INPLACE_MATRIX for inplace conversion (that is when you want the input mat to be changed to contain the matrix in the new format), otherwise use
4139:    MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX (can only be used after the first call was made with MAT_INITIAL_MATRIX, causes the matrix space in M to be reused).

4141:    Output Parameter:
4142: .  M - pointer to place new matrix

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

4149:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4150:    the MPI communicator of the generated matrix is always the same as the communicator
4151:    of the input matrix.

4153:    Level: intermediate

4155:    Concepts: matrices^converting between storage formats

4157: .seealso: MatCopy(), MatDuplicate()
4158: @*/
4159: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4160: {
4162:   PetscBool      sametype,issame,flg;
4163:   char           convname[256],mtype[256];
4164:   Mat            B;

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

4174:   PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
4175:   if (flg) {
4176:     newtype = mtype;
4177:   }
4178:   PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4179:   PetscStrcmp(newtype,"same",&issame);
4180:   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4181:   if ((reuse == MAT_REUSE_MATRIX) && (mat == *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");

4183:   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) return(0);

4185:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4186:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4187:   } else {
4188:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4189:     const char     *prefix[3] = {"seq","mpi",""};
4190:     PetscInt       i;
4191:     /*
4192:        Order of precedence:
4193:        0) See if newtype is a superclass of the current matrix.
4194:        1) See if a specialized converter is known to the current matrix.
4195:        2) See if a specialized converter is known to the desired matrix class.
4196:        3) See if a good general converter is registered for the desired class
4197:           (as of 6/27/03 only MATMPIADJ falls into this category).
4198:        4) See if a good general converter is known for the current matrix.
4199:        5) Use a really basic converter.
4200:     */

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

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

4250:     /* 3) See if a good general converter is registered for the desired class */
4251:     conv = B->ops->convertfrom;
4252:     MatDestroy(&B);
4253:     if (conv) goto foundconv;

4255:     /* 4) See if a good general converter is known for the current matrix */
4256:     if (mat->ops->convert) {
4257:       conv = mat->ops->convert;
4258:     }
4259:     if (conv) goto foundconv;

4261:     /* 5) Use a really basic converter. */
4262:     conv = MatConvert_Basic;

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

4286:   /* Copy Mat options */
4287:   if (mat->symmetric) {MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);}
4288:   if (mat->hermitian) {MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);}
4289:   return(0);
4290: }

4292: /*@C
4293:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4295:    Not Collective

4297:    Input Parameter:
4298: .  mat - the matrix, must be a factored matrix

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

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

4307:    Level: intermediate

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

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

4328: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4329: struct _MatSolverTypeForSpecifcType {
4330:   MatType                        mtype;
4331:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4332:   MatSolverTypeForSpecifcType next;
4333: };

4335: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4336: struct _MatSolverTypeHolder {
4337:   char                           *name;
4338:   MatSolverTypeForSpecifcType handlers;
4339:   MatSolverTypeHolder         next;
4340: };

4342: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

4344: /*@C
4345:    MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type

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

4353:     Level: intermediate

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

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

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

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

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

4417:     Level: intermediate

4419: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4420: @*/
4421: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4422: {
4423:   PetscErrorCode                 ierr;
4424:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4425:   PetscBool                      flg;
4426:   MatSolverTypeForSpecifcType inext;

4429:   if (foundpackage) *foundpackage = PETSC_FALSE;
4430:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4431:   if (getfactor)    *getfactor    = NULL;

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

4470: PetscErrorCode MatSolverTypeDestroy(void)
4471: {
4472:   PetscErrorCode              ierr;
4473:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4474:   MatSolverTypeForSpecifcType inext,iprev;

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

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

4497:    Collective on Mat

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

4504:    Output Parameters:
4505: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4507:    Notes:
4508:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4509:      such as pastix, superlu, mumps etc.

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

4513:    Level: intermediate

4515: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4516: @*/
4517: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4518: {
4519:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4520:   PetscBool      foundpackage,foundmtype;


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

4529:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4530:   if (!foundpackage) {
4531:     if (type) {
4532:       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4533:     } else {
4534:       SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4535:     }
4536:   }

4538:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4539:   if (!conv) SETERRQ3(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support factorization type %s for  matrix type %s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name);

4541: #if defined(PETSC_USE_COMPLEX)
4542:   if (mat->hermitian && !mat->symmetric && (ftype == MAT_FACTOR_CHOLESKY||ftype == MAT_FACTOR_ICC)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Hermitian CHOLESKY or ICC Factor is not supported");
4543: #endif

4545:   (*conv)(mat,ftype,f);
4546:   return(0);
4547: }

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

4552:    Not Collective

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

4559:    Output Parameter:
4560: .    flg - PETSC_TRUE if the factorization is available

4562:    Notes:
4563:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4564:      such as pastix, superlu, mumps etc.

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

4568:    Level: intermediate

4570: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4571: @*/
4572: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4573: {
4574:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4583:   *flg = PETSC_FALSE;
4584:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4585:   if (gconv) {
4586:     *flg = PETSC_TRUE;
4587:   }
4588:   return(0);
4589: }

4591:  #include <petscdmtypes.h>

4593: /*@
4594:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4596:    Collective on Mat

4598:    Input Parameters:
4599: +  mat - the matrix
4600: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4601:         See the manual page for MatDuplicateOption for an explanation of these options.

4603:    Output Parameter:
4604: .  M - pointer to place new matrix

4606:    Level: intermediate

4608:    Concepts: matrices^duplicating

4610:    Notes:
4611:     You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4612:     When original mat is a product of matrix operation, e.g., an output of MatMatMult() or MatCreateSubMatrix(), only the simple matrix data structure of mat is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated. User should not use MatDuplicate() to create new matrix M if M is intended to be reused as the product of matrix operation.

4614: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4615: @*/
4616: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4617: {
4619:   Mat            B;
4620:   PetscInt       i;
4621:   DM             dm;
4622:   void           (*viewf)(void);

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

4632:   *M = 0;
4633:   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4634:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4635:   (*mat->ops->duplicate)(mat,op,M);
4636:   B    = *M;

4638:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4639:   if (viewf) {
4640:     MatSetOperation(B,MATOP_VIEW,viewf);
4641:   }

4643:   B->stencil.dim = mat->stencil.dim;
4644:   B->stencil.noc = mat->stencil.noc;
4645:   for (i=0; i<=mat->stencil.dim; i++) {
4646:     B->stencil.dims[i]   = mat->stencil.dims[i];
4647:     B->stencil.starts[i] = mat->stencil.starts[i];
4648:   }

4650:   B->nooffproczerorows = mat->nooffproczerorows;
4651:   B->nooffprocentries  = mat->nooffprocentries;

4653:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4654:   if (dm) {
4655:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4656:   }
4657:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4658:   PetscObjectStateIncrease((PetscObject)B);
4659:   return(0);
4660: }

4662: /*@
4663:    MatGetDiagonal - Gets the diagonal of a matrix.

4665:    Logically Collective on Mat and Vec

4667:    Input Parameters:
4668: +  mat - the matrix
4669: -  v - the vector for storing the diagonal

4671:    Output Parameter:
4672: .  v - the diagonal of the matrix

4674:    Level: intermediate

4676:    Note:
4677:    Currently only correct in parallel for square matrices.

4679:    Concepts: matrices^accessing diagonals

4681: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4682: @*/
4683: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4684: {

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

4695:   (*mat->ops->getdiagonal)(mat,v);
4696:   PetscObjectStateIncrease((PetscObject)v);
4697:   return(0);
4698: }

4700: /*@C
4701:    MatGetRowMin - Gets the minimum value (of the real part) of each
4702:         row of the matrix

4704:    Logically Collective on Mat and Vec

4706:    Input Parameters:
4707: .  mat - the matrix

4709:    Output Parameter:
4710: +  v - the vector for storing the maximums
4711: -  idx - the indices of the column found for each row (optional)

4713:    Level: intermediate

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

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

4721:    Concepts: matrices^getting row maximums

4723: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4724:           MatGetRowMax()
4725: @*/
4726: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4727: {

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

4738:   (*mat->ops->getrowmin)(mat,v,idx);
4739:   PetscObjectStateIncrease((PetscObject)v);
4740:   return(0);
4741: }

4743: /*@C
4744:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4745:         row of the matrix

4747:    Logically Collective on Mat and Vec

4749:    Input Parameters:
4750: .  mat - the matrix

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

4756:    Level: intermediate

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

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

4764:    Concepts: matrices^getting row maximums

4766: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4767: @*/
4768: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4769: {

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

4781:   (*mat->ops->getrowminabs)(mat,v,idx);
4782:   PetscObjectStateIncrease((PetscObject)v);
4783:   return(0);
4784: }

4786: /*@C
4787:    MatGetRowMax - Gets the maximum value (of the real part) of each
4788:         row of the matrix

4790:    Logically Collective on Mat and Vec

4792:    Input Parameters:
4793: .  mat - the matrix

4795:    Output Parameter:
4796: +  v - the vector for storing the maximums
4797: -  idx - the indices of the column found for each row (optional)

4799:    Level: intermediate

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

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

4807:    Concepts: matrices^getting row maximums

4809: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4810: @*/
4811: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4812: {

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

4823:   (*mat->ops->getrowmax)(mat,v,idx);
4824:   PetscObjectStateIncrease((PetscObject)v);
4825:   return(0);
4826: }

4828: /*@C
4829:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4830:         row of the matrix

4832:    Logically Collective on Mat and Vec

4834:    Input Parameters:
4835: .  mat - the matrix

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

4841:    Level: intermediate

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

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

4849:    Concepts: matrices^getting row maximums

4851: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4852: @*/
4853: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4854: {

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

4866:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4867:   PetscObjectStateIncrease((PetscObject)v);
4868:   return(0);
4869: }

4871: /*@
4872:    MatGetRowSum - Gets the sum of each row of the matrix

4874:    Logically or Neighborhood Collective on Mat and Vec

4876:    Input Parameters:
4877: .  mat - the matrix

4879:    Output Parameter:
4880: .  v - the vector for storing the sum of rows

4882:    Level: intermediate

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

4887:    Concepts: matrices^getting row sums

4889: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4890: @*/
4891: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4892: {
4893:   Vec            ones;

4900:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4901:   MatCheckPreallocated(mat,1);
4902:   MatCreateVecs(mat,&ones,NULL);
4903:   VecSet(ones,1.);
4904:   MatMult(mat,ones,v);
4905:   VecDestroy(&ones);
4906:   return(0);
4907: }

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

4912:    Collective on Mat

4914:    Input Parameter:
4915: +  mat - the matrix to transpose
4916: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4918:    Output Parameters:
4919: .  B - the transpose

4921:    Notes:
4922:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4928:    Level: intermediate

4930:    Concepts: matrices^transposing

4932: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4933: @*/
4934: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4935: {

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

4948:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4949:   (*mat->ops->transpose)(mat,reuse,B);
4950:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4951:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4952:   return(0);
4953: }

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

4959:    Collective on Mat

4961:    Input Parameter:
4962: +  A - the matrix to test
4963: -  B - the matrix to test against, this can equal the first parameter

4965:    Output Parameters:
4966: .  flg - the result

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

4973:    Level: intermediate

4975:    Concepts: matrices^transposing, matrix^symmetry

4977: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4978: @*/
4979: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4980: {
4981:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4987:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4988:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4989:   *flg = PETSC_FALSE;
4990:   if (f && g) {
4991:     if (f == g) {
4992:       (*f)(A,B,tol,flg);
4993:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4994:   } else {
4995:     MatType mattype;
4996:     if (!f) {
4997:       MatGetType(A,&mattype);
4998:     } else {
4999:       MatGetType(B,&mattype);
5000:     }
5001:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
5002:   }
5003:   return(0);
5004: }

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

5009:    Collective on Mat

5011:    Input Parameter:
5012: +  mat - the matrix to transpose and complex conjugate
5013: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

5015:    Output Parameters:
5016: .  B - the Hermitian

5018:    Level: intermediate

5020:    Concepts: matrices^transposing, complex conjugatex

5022: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5023: @*/
5024: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5025: {

5029:   MatTranspose(mat,reuse,B);
5030: #if defined(PETSC_USE_COMPLEX)
5031:   MatConjugate(*B);
5032: #endif
5033:   return(0);
5034: }

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

5039:    Collective on Mat

5041:    Input Parameter:
5042: +  A - the matrix to test
5043: -  B - the matrix to test against, this can equal the first parameter

5045:    Output Parameters:
5046: .  flg - the result

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

5053:    Level: intermediate

5055:    Concepts: matrices^transposing, matrix^symmetry

5057: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5058: @*/
5059: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5060: {
5061:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5067:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5068:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5069:   if (f && g) {
5070:     if (f==g) {
5071:       (*f)(A,B,tol,flg);
5072:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5073:   }
5074:   return(0);
5075: }

5077: /*@
5078:    MatPermute - Creates a new matrix with rows and columns permuted from the
5079:    original.

5081:    Collective on Mat

5083:    Input Parameters:
5084: +  mat - the matrix to permute
5085: .  row - row permutation, each processor supplies only the permutation for its rows
5086: -  col - column permutation, each processor supplies only the permutation for its columns

5088:    Output Parameters:
5089: .  B - the permuted matrix

5091:    Level: advanced

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

5097:    Concepts: matrices^permuting

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

5101: @*/
5102: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5103: {

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

5117:   (*mat->ops->permute)(mat,row,col,B);
5118:   PetscObjectStateIncrease((PetscObject)*B);
5119:   return(0);
5120: }

5122: /*@
5123:    MatEqual - Compares two matrices.

5125:    Collective on Mat

5127:    Input Parameters:
5128: +  A - the first matrix
5129: -  B - the second matrix

5131:    Output Parameter:
5132: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5134:    Level: intermediate

5136:    Concepts: matrices^equality between
5137: @*/
5138: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5139: {

5149:   MatCheckPreallocated(B,2);
5150:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5151:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5152:   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);
5153:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5154:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5155:   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);
5156:   MatCheckPreallocated(A,1);

5158:   (*A->ops->equal)(A,B,flg);
5159:   return(0);
5160: }

5162: /*@
5163:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5164:    matrices that are stored as vectors.  Either of the two scaling
5165:    matrices can be NULL.

5167:    Collective on Mat

5169:    Input Parameters:
5170: +  mat - the matrix to be scaled
5171: .  l - the left scaling vector (or NULL)
5172: -  r - the right scaling vector (or NULL)

5174:    Notes:
5175:    MatDiagonalScale() computes A = LAR, where
5176:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5177:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5179:    Level: intermediate

5181:    Concepts: matrices^diagonal scaling
5182:    Concepts: diagonal scaling of matrices

5184: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5185: @*/
5186: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5187: {

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

5200:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5201:   (*mat->ops->diagonalscale)(mat,l,r);
5202:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5203:   PetscObjectStateIncrease((PetscObject)mat);
5204: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5205:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5206:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5207:   }
5208: #endif
5209:   return(0);
5210: }

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

5215:     Logically Collective on Mat

5217:     Input Parameters:
5218: +   mat - the matrix to be scaled
5219: -   a  - the scaling value

5221:     Output Parameter:
5222: .   mat - the scaled matrix

5224:     Level: intermediate

5226:     Concepts: matrices^scaling all entries

5228: .seealso: MatDiagonalScale()
5229: @*/
5230: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5231: {

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

5243:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5244:   if (a != (PetscScalar)1.0) {
5245:     (*mat->ops->scale)(mat,a);
5246:     PetscObjectStateIncrease((PetscObject)mat);
5247: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5248:     if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5249:       mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5250:     }
5251: #endif
5252:   }
5253:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5254:   return(0);
5255: }

5257: /*@
5258:    MatNorm - Calculates various norms of a matrix.

5260:    Collective on Mat

5262:    Input Parameters:
5263: +  mat - the matrix
5264: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5266:    Output Parameters:
5267: .  nrm - the resulting norm

5269:    Level: intermediate

5271:    Concepts: matrices^norm
5272:    Concepts: norm^of matrix
5273: @*/
5274: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5275: {


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

5288:   (*mat->ops->norm)(mat,type,nrm);
5289:   return(0);
5290: }

5292: /*
5293:      This variable is used to prevent counting of MatAssemblyBegin() that
5294:    are called from within a MatAssemblyEnd().
5295: */
5296: static PetscInt MatAssemblyEnd_InUse = 0;
5297: /*@
5298:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5299:    be called after completing all calls to MatSetValues().

5301:    Collective on Mat

5303:    Input Parameters:
5304: +  mat - the matrix
5305: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5307:    Notes:
5308:    MatSetValues() generally caches the values.  The matrix is ready to
5309:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5310:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5311:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5312:    using the matrix.

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

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

5322:    Level: beginner

5324:    Concepts: matrices^assembling

5326: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5327: @*/
5328: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5329: {

5335:   MatCheckPreallocated(mat,1);
5336:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5337:   if (mat->assembled) {
5338:     mat->was_assembled = PETSC_TRUE;
5339:     mat->assembled     = PETSC_FALSE;
5340:   }
5341:   if (!MatAssemblyEnd_InUse) {
5342:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5343:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5344:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5345:   } else if (mat->ops->assemblybegin) {
5346:     (*mat->ops->assemblybegin)(mat,type);
5347:   }
5348:   return(0);
5349: }

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

5355:    Not Collective

5357:    Input Parameter:
5358: .  mat - the matrix

5360:    Output Parameter:
5361: .  assembled - PETSC_TRUE or PETSC_FALSE

5363:    Level: advanced

5365:    Concepts: matrices^assembled?

5367: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5368: @*/
5369: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5370: {
5374:   *assembled = mat->assembled;
5375:   return(0);
5376: }

5378: /*@
5379:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5380:    be called after MatAssemblyBegin().

5382:    Collective on Mat

5384:    Input Parameters:
5385: +  mat - the matrix
5386: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5388:    Options Database Keys:
5389: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5390: .  -mat_view ::ascii_info_detail - Prints more detailed info
5391: .  -mat_view - Prints matrix in ASCII format
5392: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5393: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5394: .  -display <name> - Sets display name (default is host)
5395: .  -draw_pause <sec> - Sets number of seconds to pause after display
5396: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5397: .  -viewer_socket_machine <machine> - Machine to use for socket
5398: .  -viewer_socket_port <port> - Port number to use for socket
5399: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5401:    Notes:
5402:    MatSetValues() generally caches the values.  The matrix is ready to
5403:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5404:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5405:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5406:    using the matrix.

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

5412:    Level: beginner

5414: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5415: @*/
5416: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5417: {
5418:   PetscErrorCode  ierr;
5419:   static PetscInt inassm = 0;
5420:   PetscBool       flg    = PETSC_FALSE;


5426:   inassm++;
5427:   MatAssemblyEnd_InUse++;
5428:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5429:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5430:     if (mat->ops->assemblyend) {
5431:       (*mat->ops->assemblyend)(mat,type);
5432:     }
5433:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5434:   } else if (mat->ops->assemblyend) {
5435:     (*mat->ops->assemblyend)(mat,type);
5436:   }

5438:   /* Flush assembly is not a true assembly */
5439:   if (type != MAT_FLUSH_ASSEMBLY) {
5440:     mat->assembled = PETSC_TRUE; mat->num_ass++;
5441:   }
5442:   mat->insertmode = NOT_SET_VALUES;
5443:   MatAssemblyEnd_InUse--;
5444:   PetscObjectStateIncrease((PetscObject)mat);
5445:   if (!mat->symmetric_eternal) {
5446:     mat->symmetric_set              = PETSC_FALSE;
5447:     mat->hermitian_set              = PETSC_FALSE;
5448:     mat->structurally_symmetric_set = PETSC_FALSE;
5449:   }
5450: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5451:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5452:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5453:   }
5454: #endif
5455:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5456:     MatViewFromOptions(mat,NULL,"-mat_view");

5458:     if (mat->checksymmetryonassembly) {
5459:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5460:       if (flg) {
5461:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5462:       } else {
5463:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5464:       }
5465:     }
5466:     if (mat->nullsp && mat->checknullspaceonassembly) {
5467:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5468:     }
5469:   }
5470:   inassm--;
5471:   return(0);
5472: }

5474: /*@
5475:    MatSetOption - Sets a parameter option for a matrix. Some options
5476:    may be specific to certain storage formats.  Some options
5477:    determine how values will be inserted (or added). Sorted,
5478:    row-oriented input will generally assemble the fastest. The default
5479:    is row-oriented.

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

5483:    Input Parameters:
5484: +  mat - the matrix
5485: .  option - the option, one of those listed below (and possibly others),
5486: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5488:   Options Describing Matrix Structure:
5489: +    MAT_SPD - symmetric positive definite
5490: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5491: .    MAT_HERMITIAN - transpose is the complex conjugation
5492: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5493: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5494:                             you set to be kept with all future use of the matrix
5495:                             including after MatAssemblyBegin/End() which could
5496:                             potentially change the symmetry structure, i.e. you
5497:                             KNOW the matrix will ALWAYS have the property you set.


5500:    Options For Use with MatSetValues():
5501:    Insert a logically dense subblock, which can be
5502: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

5540:    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5541:    that would generate a new entry in the nonzero structure instead produces
5542:    an error. (Currently supported for AIJ and BAIJ formats only.) If this option is set then the MatAssemblyBegin/End() processes has one less global reduction

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

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

5556:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5557:    searches during matrix assembly. When this flag is set, the hash table
5558:    is created during the first Matrix Assembly. This hash table is
5559:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5560:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5561:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5562:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5581:    Level: intermediate

5583:    Concepts: matrices^setting options

5585: .seealso:  MatOption, Mat

5587: @*/
5588: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5589: {

5595:   if (op > 0) {
5598:   }

5600:   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);
5601:   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()");

5603:   switch (op) {
5604:   case MAT_NO_OFF_PROC_ENTRIES:
5605:     mat->nooffprocentries = flg;
5606:     return(0);
5607:     break;
5608:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5609:     mat->subsetoffprocentries = flg;
5610:     return(0);
5611:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5612:     mat->nooffproczerorows = flg;
5613:     return(0);
5614:     break;
5615:   case MAT_SPD:
5616:     mat->spd_set = PETSC_TRUE;
5617:     mat->spd     = flg;
5618:     if (flg) {
5619:       mat->symmetric                  = PETSC_TRUE;
5620:       mat->structurally_symmetric     = PETSC_TRUE;
5621:       mat->symmetric_set              = PETSC_TRUE;
5622:       mat->structurally_symmetric_set = PETSC_TRUE;
5623:     }
5624:     break;
5625:   case MAT_SYMMETRIC:
5626:     mat->symmetric = flg;
5627:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5628:     mat->symmetric_set              = PETSC_TRUE;
5629:     mat->structurally_symmetric_set = flg;
5630: #if !defined(PETSC_USE_COMPLEX)
5631:     mat->hermitian     = flg;
5632:     mat->hermitian_set = PETSC_TRUE;
5633: #endif
5634:     break;
5635:   case MAT_HERMITIAN:
5636:     mat->hermitian = flg;
5637:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5638:     mat->hermitian_set              = PETSC_TRUE;
5639:     mat->structurally_symmetric_set = flg;
5640: #if !defined(PETSC_USE_COMPLEX)
5641:     mat->symmetric     = flg;
5642:     mat->symmetric_set = PETSC_TRUE;
5643: #endif
5644:     break;
5645:   case MAT_STRUCTURALLY_SYMMETRIC:
5646:     mat->structurally_symmetric     = flg;
5647:     mat->structurally_symmetric_set = PETSC_TRUE;
5648:     break;
5649:   case MAT_SYMMETRY_ETERNAL:
5650:     mat->symmetric_eternal = flg;
5651:     break;
5652:   case MAT_STRUCTURE_ONLY:
5653:     mat->structure_only = flg;
5654:     break;
5655:   default:
5656:     break;
5657:   }
5658:   if (mat->ops->setoption) {
5659:     (*mat->ops->setoption)(mat,op,flg);
5660:   }
5661:   return(0);
5662: }

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

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

5669:    Input Parameters:
5670: +  mat - the matrix
5671: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5679:    Level: intermediate

5681:    Concepts: matrices^setting options

5683: .seealso:  MatOption, MatSetOption()

5685: @*/
5686: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5687: {

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

5695:   switch (op) {
5696:   case MAT_NO_OFF_PROC_ENTRIES:
5697:     *flg = mat->nooffprocentries;
5698:     break;
5699:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5700:     *flg = mat->nooffproczerorows;
5701:     break;
5702:   case MAT_SYMMETRIC:
5703:     *flg = mat->symmetric;
5704:     break;
5705:   case MAT_HERMITIAN:
5706:     *flg = mat->hermitian;
5707:     break;
5708:   case MAT_STRUCTURALLY_SYMMETRIC:
5709:     *flg = mat->structurally_symmetric;
5710:     break;
5711:   case MAT_SYMMETRY_ETERNAL:
5712:     *flg = mat->symmetric_eternal;
5713:     break;
5714:   case MAT_SPD:
5715:     *flg = mat->spd;
5716:     break;
5717:   default:
5718:     break;
5719:   }
5720:   return(0);
5721: }

5723: /*@
5724:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5725:    this routine retains the old nonzero structure.

5727:    Logically Collective on Mat

5729:    Input Parameters:
5730: .  mat - the matrix

5732:    Level: intermediate

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

5738:    Concepts: matrices^zeroing

5740: .seealso: MatZeroRows()
5741: @*/
5742: PetscErrorCode MatZeroEntries(Mat mat)
5743: {

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

5754:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5755:   (*mat->ops->zeroentries)(mat);
5756:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5757:   PetscObjectStateIncrease((PetscObject)mat);
5758: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5759:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5760:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5761:   }
5762: #endif
5763:   return(0);
5764: }

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

5770:    Collective on Mat

5772:    Input Parameters:
5773: +  mat - the matrix
5774: .  numRows - the number of rows to remove
5775: .  rows - the global row indices
5776: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5777: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5778: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5797:    Level: intermediate

5799:    Concepts: matrices^zeroing rows

5801: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5802:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5803: @*/
5804: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5805: {

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

5817:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5818:   MatViewFromOptions(mat,NULL,"-mat_view");
5819:   PetscObjectStateIncrease((PetscObject)mat);
5820: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5821:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5822:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5823:   }
5824: #endif
5825:   return(0);
5826: }

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

5832:    Collective on Mat

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

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

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

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

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

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

5858:    Level: intermediate

5860:    Concepts: matrices^zeroing rows

5862: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5863:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5864: @*/
5865: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5866: {
5868:   PetscInt       numRows;
5869:   const PetscInt *rows;

5876:   ISGetLocalSize(is,&numRows);
5877:   ISGetIndices(is,&rows);
5878:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5879:   ISRestoreIndices(is,&rows);
5880:   return(0);
5881: }

5883: /*@
5884:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5885:    of a set of rows of a matrix.

5887:    Collective on Mat

5889:    Input Parameters:
5890: +  mat - the matrix
5891: .  numRows - the number of rows to remove
5892: .  rows - the global row indices
5893: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5894: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5895: -  b - optional vector of right hand side, that will be adjusted by provided solution

5897:    Notes:
5898:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5899:    but does not release memory.  For the dense and block diagonal
5900:    formats this does not alter the nonzero structure.

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

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

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

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

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

5921:    Level: intermediate

5923:    Concepts: matrices^zeroing rows

5925: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5926:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5927: @*/
5928: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5929: {

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

5941:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5942:   MatViewFromOptions(mat,NULL,"-mat_view");
5943:   PetscObjectStateIncrease((PetscObject)mat);
5944: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5945:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5946:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5947:   }
5948: #endif
5949:   return(0);
5950: }

5952: /*@
5953:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5954:    of a set of rows of a matrix.

5956:    Collective on Mat

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

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

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

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

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

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

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

5989:    Level: intermediate

5991:    Concepts: matrices^zeroing rows

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

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

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

6017:    Collective on Mat

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

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

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

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

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

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

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

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

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

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

6067:    Level: intermediate

6069:    Concepts: matrices^zeroing rows

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


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

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

6118:    Collective on Mat

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

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

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

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

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

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

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

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

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

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

6168:    Level: intermediate

6170:    Concepts: matrices^zeroing rows

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


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

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

6219:    Collective on Mat

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

6229:    Notes:
6230:    Before calling MatZeroRowsLocal(), the user must first set the
6231:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6233:    For the AIJ matrix formats this removes the old nonzero structure,
6234:    but does not release memory.  For the dense and block diagonal
6235:    formats this does not alter the nonzero structure.

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

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

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

6248:    Level: intermediate

6250:    Concepts: matrices^zeroing

6252: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6253:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6254: @*/
6255: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6256: {

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

6267:   if (mat->ops->zerorowslocal) {
6268:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6269:   } else {
6270:     IS             is, newis;
6271:     const PetscInt *newRows;

6273:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6274:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6275:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6276:     ISGetIndices(newis,&newRows);
6277:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6278:     ISRestoreIndices(newis,&newRows);
6279:     ISDestroy(&newis);
6280:     ISDestroy(&is);
6281:   }
6282:   PetscObjectStateIncrease((PetscObject)mat);
6283: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6284:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6285:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6286:   }
6287: #endif
6288:   return(0);
6289: }

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

6295:    Collective on Mat

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

6304:    Notes:
6305:    Before calling MatZeroRowsLocalIS(), the user must first set the
6306:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6308:    For the AIJ matrix formats this removes the old nonzero structure,
6309:    but does not release memory.  For the dense and block diagonal
6310:    formats this does not alter the nonzero structure.

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

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

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

6323:    Level: intermediate

6325:    Concepts: matrices^zeroing

6327: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6328:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6329: @*/
6330: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6331: {
6333:   PetscInt       numRows;
6334:   const PetscInt *rows;

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

6344:   ISGetLocalSize(is,&numRows);
6345:   ISGetIndices(is,&rows);
6346:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6347:   ISRestoreIndices(is,&rows);
6348:   return(0);
6349: }

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

6355:    Collective on Mat

6357:    Input Parameters:
6358: +  mat - the matrix
6359: .  numRows - the number of rows to remove
6360: .  rows - the global row indices
6361: .  diag - value put in all diagonals of eliminated rows
6362: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6363: -  b - optional vector of right hand side, that will be adjusted by provided solution

6365:    Notes:
6366:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6367:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6373:    Level: intermediate

6375:    Concepts: matrices^zeroing

6377: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6378:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6379: @*/
6380: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6381: {
6383:   IS             is, newis;
6384:   const PetscInt *newRows;

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

6394:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6395:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6396:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6397:   ISGetIndices(newis,&newRows);
6398:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6399:   ISRestoreIndices(newis,&newRows);
6400:   ISDestroy(&newis);
6401:   ISDestroy(&is);
6402:   PetscObjectStateIncrease((PetscObject)mat);
6403: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6404:   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6405:     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6406:   }
6407: #endif
6408:   return(0);
6409: }

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

6415:    Collective on Mat

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

6424:    Notes:
6425:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6426:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6432:    Level: intermediate

6434:    Concepts: matrices^zeroing

6436: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6437:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6438: @*/
6439: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6440: {
6442:   PetscInt       numRows;
6443:   const PetscInt *rows;

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

6453:   ISGetLocalSize(is,&numRows);
6454:   ISGetIndices(is,&rows);
6455:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6456:   ISRestoreIndices(is,&rows);
6457:   return(0);
6458: }

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

6463:    Not Collective

6465:    Input Parameter:
6466: .  mat - the matrix

6468:    Output Parameters:
6469: +  m - the number of global rows
6470: -  n - the number of global columns

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

6474:    Level: beginner

6476:    Concepts: matrices^size

6478: .seealso: MatGetLocalSize()
6479: @*/
6480: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6481: {
6484:   if (m) *m = mat->rmap->N;
6485:   if (n) *n = mat->cmap->N;
6486:   return(0);
6487: }

6489: /*@C
6490:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6491:    stored locally.  This information may be implementation dependent, so
6492:    use with care.

6494:    Not Collective

6496:    Input Parameters:
6497: .  mat - the matrix

6499:    Output Parameters:
6500: +  m - the number of local rows
6501: -  n - the number of local columns

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

6505:    Level: beginner

6507:    Concepts: matrices^local size

6509: .seealso: MatGetSize()
6510: @*/
6511: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6512: {
6517:   if (m) *m = mat->rmap->n;
6518:   if (n) *n = mat->cmap->n;
6519:   return(0);
6520: }

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

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

6528:    Input Parameters:
6529: .  mat - the matrix

6531:    Output Parameters:
6532: +  m - the global index of the first local column
6533: -  n - one more than the global index of the last local column

6535:    Notes:
6536:     both output parameters can be NULL on input.

6538:    Level: developer

6540:    Concepts: matrices^column ownership

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

6544: @*/
6545: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6546: {
6552:   MatCheckPreallocated(mat,1);
6553:   if (m) *m = mat->cmap->rstart;
6554:   if (n) *n = mat->cmap->rend;
6555:   return(0);
6556: }

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

6564:    Not Collective

6566:    Input Parameters:
6567: .  mat - the matrix

6569:    Output Parameters:
6570: +  m - the global index of the first local row
6571: -  n - one more than the global index of the last local row

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

6578:    Level: beginner

6580:    Concepts: matrices^row ownership

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

6584: @*/
6585: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6586: {
6592:   MatCheckPreallocated(mat,1);
6593:   if (m) *m = mat->rmap->rstart;
6594:   if (n) *n = mat->rmap->rend;
6595:   return(0);
6596: }

6598: /*@C
6599:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6600:    each process

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

6604:    Input Parameters:
6605: .  mat - the matrix

6607:    Output Parameters:
6608: .  ranges - start of each processors portion plus one more than the total length at the end

6610:    Level: beginner

6612:    Concepts: matrices^row ownership

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

6616: @*/
6617: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6618: {

6624:   MatCheckPreallocated(mat,1);
6625:   PetscLayoutGetRanges(mat->rmap,ranges);
6626:   return(0);
6627: }

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

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

6635:    Input Parameters:
6636: .  mat - the matrix

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

6641:    Level: beginner

6643:    Concepts: matrices^column ownership

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

6647: @*/
6648: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6649: {

6655:   MatCheckPreallocated(mat,1);
6656:   PetscLayoutGetRanges(mat->cmap,ranges);
6657:   return(0);
6658: }

6660: /*@C
6661:    MatGetOwnershipIS - Get row and column ownership as index sets

6663:    Not Collective

6665:    Input Arguments:
6666: .  A - matrix of type Elemental

6668:    Output Arguments:
6669: +  rows - rows in which this process owns elements
6670: .  cols - columns in which this process owns elements

6672:    Level: intermediate

6674: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6675: @*/
6676: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6677: {
6678:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6681:   MatCheckPreallocated(A,1);
6682:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6683:   if (f) {
6684:     (*f)(A,rows,cols);
6685:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6686:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6687:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6688:   }
6689:   return(0);
6690: }

6692: /*@C
6693:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6694:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6695:    to complete the factorization.

6697:    Collective on Mat

6699:    Input Parameters:
6700: +  mat - the matrix
6701: .  row - row permutation
6702: .  column - column permutation
6703: -  info - structure containing
6704: $      levels - number of levels of fill.
6705: $      expected fill - as ratio of original fill.
6706: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6707:                 missing diagonal entries)

6709:    Output Parameters:
6710: .  fact - new matrix that has been symbolically factored

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

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

6719:    Level: developer

6721:   Concepts: matrices^symbolic LU factorization
6722:   Concepts: matrices^factorization
6723:   Concepts: LU^symbolic factorization

6725: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6726:           MatGetOrdering(), MatFactorInfo

6728:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6733:    References:
6734:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6735: @*/
6736: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6737: {

6747:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6748:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6749:   if (!(fact)->ops->ilufactorsymbolic) {
6750:     MatSolverType spackage;
6751:     MatFactorGetSolverType(fact,&spackage);
6752:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6753:   }
6754:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6755:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6756:   MatCheckPreallocated(mat,2);

6758:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6759:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6760:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6761:   return(0);
6762: }

6764: /*@C
6765:    MatICCFactorSymbolic - Performs symbolic incomplete
6766:    Cholesky factorization for a symmetric matrix.  Use
6767:    MatCholeskyFactorNumeric() to complete the factorization.

6769:    Collective on Mat

6771:    Input Parameters:
6772: +  mat - the matrix
6773: .  perm - row and column permutation
6774: -  info - structure containing
6775: $      levels - number of levels of fill.
6776: $      expected fill - as ratio of original fill.

6778:    Output Parameter:
6779: .  fact - the factored matrix

6781:    Notes:
6782:    Most users should employ the KSP interface for linear solvers
6783:    instead of working directly with matrix algebra routines such as this.
6784:    See, e.g., KSPCreate().

6786:    Level: developer

6788:   Concepts: matrices^symbolic incomplete Cholesky factorization
6789:   Concepts: matrices^factorization
6790:   Concepts: Cholsky^symbolic factorization

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

6794:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6799:    References:
6800:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6801: @*/
6802: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6803: {

6812:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6813:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6814:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6815:   if (!(fact)->ops->iccfactorsymbolic) {
6816:     MatSolverType spackage;
6817:     MatFactorGetSolverType(fact,&spackage);
6818:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6819:   }
6820:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6821:   MatCheckPreallocated(mat,2);

6823:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6824:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6825:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6826:   return(0);
6827: }

6829: /*@C
6830:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6831:    points to an array of valid matrices, they may be reused to store the new
6832:    submatrices.

6834:    Collective on Mat

6836:    Input Parameters:
6837: +  mat - the matrix
6838: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6839: .  irow, icol - index sets of rows and columns to extract
6840: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6842:    Output Parameter:
6843: .  submat - the array of submatrices

6845:    Notes:
6846:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6847:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6848:    to extract a parallel submatrix.

6850:    Some matrix types place restrictions on the row and column
6851:    indices, such as that they be sorted or that they be equal to each other.

6853:    The index sets may not have duplicate entries.

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

6859:    When finished using the submatrices, the user should destroy
6860:    them with MatDestroySubMatrices().

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

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

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

6873:    Fortran Note:
6874:    The Fortran interface is slightly different from that given below; it
6875:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6877:    Level: advanced

6879:    Concepts: matrices^accessing submatrices
6880:    Concepts: submatrices

6882: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6883: @*/
6884: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6885: {
6887:   PetscInt       i;
6888:   PetscBool      eq;

6893:   if (n) {
6898:   }
6900:   if (n && scall == MAT_REUSE_MATRIX) {
6903:   }
6904:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6905:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6906:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6907:   MatCheckPreallocated(mat,1);

6909:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6910:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6911:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6912:   for (i=0; i<n; i++) {
6913:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6914:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6915:       ISEqual(irow[i],icol[i],&eq);
6916:       if (eq) {
6917:         if (mat->symmetric) {
6918:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6919:         } else if (mat->hermitian) {
6920:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6921:         } else if (mat->structurally_symmetric) {
6922:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6923:         }
6924:       }
6925:     }
6926:   }
6927:   return(0);
6928: }

6930: /*@C
6931:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6933:    Collective on Mat

6935:    Input Parameters:
6936: +  mat - the matrix
6937: .  n   - the number of submatrixes to be extracted
6938: .  irow, icol - index sets of rows and columns to extract
6939: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6941:    Output Parameter:
6942: .  submat - the array of submatrices

6944:    Level: advanced

6946:    Concepts: matrices^accessing submatrices
6947:    Concepts: submatrices

6949: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6950: @*/
6951: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6952: {
6954:   PetscInt       i;
6955:   PetscBool      eq;

6960:   if (n) {
6965:   }
6967:   if (n && scall == MAT_REUSE_MATRIX) {
6970:   }
6971:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6972:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6973:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6974:   MatCheckPreallocated(mat,1);

6976:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6977:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6978:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6979:   for (i=0; i<n; i++) {
6980:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6981:       ISEqual(irow[i],icol[i],&eq);
6982:       if (eq) {
6983:         if (mat->symmetric) {
6984:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6985:         } else if (mat->hermitian) {
6986:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6987:         } else if (mat->structurally_symmetric) {
6988:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6989:         }
6990:       }
6991:     }
6992:   }
6993:   return(0);
6994: }

6996: /*@C
6997:    MatDestroyMatrices - Destroys an array of matrices.

6999:    Collective on Mat

7001:    Input Parameters:
7002: +  n - the number of local matrices
7003: -  mat - the matrices (note that this is a pointer to the array of matrices)

7005:    Level: advanced

7007:     Notes:
7008:     Frees not only the matrices, but also the array that contains the matrices
7009:            In Fortran will not free the array.

7011: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
7012: @*/
7013: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
7014: {
7016:   PetscInt       i;

7019:   if (!*mat) return(0);
7020:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

7023:   for (i=0; i<n; i++) {
7024:     MatDestroy(&(*mat)[i]);
7025:   }

7027:   /* memory is allocated even if n = 0 */
7028:   PetscFree(*mat);
7029:   return(0);
7030: }

7032: /*@C
7033:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

7035:    Collective on Mat

7037:    Input Parameters:
7038: +  n - the number of local matrices
7039: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
7040:                        sequence of MatCreateSubMatrices())

7042:    Level: advanced

7044:     Notes:
7045:     Frees not only the matrices, but also the array that contains the matrices
7046:            In Fortran will not free the array.

7048: .seealso: MatCreateSubMatrices()
7049: @*/
7050: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
7051: {
7053:   Mat            mat0;

7056:   if (!*mat) return(0);
7057:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7058:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

7061:   mat0 = (*mat)[0];
7062:   if (mat0 && mat0->ops->destroysubmatrices) {
7063:     (mat0->ops->destroysubmatrices)(n,mat);
7064:   } else {
7065:     MatDestroyMatrices(n,mat);
7066:   }
7067:   return(0);
7068: }

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

7073:    Collective on Mat

7075:    Input Parameters:
7076: .  mat - the matrix

7078:    Output Parameter:
7079: .  matstruct - the sequential matrix with the nonzero structure of mat

7081:   Level: intermediate

7083: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7084: @*/
7085: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7086: {


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

7097:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7098:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7099:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
7100:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7101:   return(0);
7102: }

7104: /*@C
7105:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

7107:    Collective on Mat

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

7113:    Level: advanced

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

7118: .seealso: MatGetSeqNonzeroStructure()
7119: @*/
7120: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7121: {

7126:   MatDestroy(mat);
7127:   return(0);
7128: }

7130: /*@
7131:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7132:    replaces the index sets by larger ones that represent submatrices with
7133:    additional overlap.

7135:    Collective on Mat

7137:    Input Parameters:
7138: +  mat - the matrix
7139: .  n   - the number of index sets
7140: .  is  - the array of index sets (these index sets will changed during the call)
7141: -  ov  - the additional overlap requested

7143:    Options Database:
7144: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7146:    Level: developer

7148:    Concepts: overlap
7149:    Concepts: ASM^computing overlap

7151: .seealso: MatCreateSubMatrices()
7152: @*/
7153: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7154: {

7160:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7161:   if (n) {
7164:   }
7165:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7166:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7167:   MatCheckPreallocated(mat,1);

7169:   if (!ov) return(0);
7170:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7171:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7172:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7173:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7174:   return(0);
7175: }


7178: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7180: /*@
7181:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7182:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7183:    additional overlap.

7185:    Collective on Mat

7187:    Input Parameters:
7188: +  mat - the matrix
7189: .  n   - the number of index sets
7190: .  is  - the array of index sets (these index sets will changed during the call)
7191: -  ov  - the additional overlap requested

7193:    Options Database:
7194: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7196:    Level: developer

7198:    Concepts: overlap
7199:    Concepts: ASM^computing overlap

7201: .seealso: MatCreateSubMatrices()
7202: @*/
7203: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7204: {
7205:   PetscInt       i;

7211:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7212:   if (n) {
7215:   }
7216:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7217:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7218:   MatCheckPreallocated(mat,1);
7219:   if (!ov) return(0);
7220:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7221:   for(i=0; i<n; i++){
7222:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7223:   }
7224:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7225:   return(0);
7226: }




7231: /*@
7232:    MatGetBlockSize - Returns the matrix block size.

7234:    Not Collective

7236:    Input Parameter:
7237: .  mat - the matrix

7239:    Output Parameter:
7240: .  bs - block size

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

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

7247:    Level: intermediate

7249:    Concepts: matrices^block size

7251: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7252: @*/
7253: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7254: {
7258:   *bs = PetscAbs(mat->rmap->bs);
7259:   return(0);
7260: }

7262: /*@
7263:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7265:    Not Collective

7267:    Input Parameter:
7268: .  mat - the matrix

7270:    Output Parameter:
7271: .  rbs - row block size
7272: .  cbs - column block size

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

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

7280:    Level: intermediate

7282:    Concepts: matrices^block size

7284: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7285: @*/
7286: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7287: {
7292:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7293:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7294:   return(0);
7295: }

7297: /*@
7298:    MatSetBlockSize - Sets the matrix block size.

7300:    Logically Collective on Mat

7302:    Input Parameters:
7303: +  mat - the matrix
7304: -  bs - block size

7306:    Notes:
7307:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7308:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7310:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7311:     is compatible with the matrix local sizes.

7313:    Level: intermediate

7315:    Concepts: matrices^block size

7317: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7318: @*/
7319: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7320: {

7326:   MatSetBlockSizes(mat,bs,bs);
7327:   return(0);
7328: }

7330: /*@
7331:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7333:    Logically Collective on Mat

7335:    Input Parameters:
7336: +  mat - the matrix
7337: .  nblocks - the number of blocks on this process
7338: -  bsizes - the block sizes

7340:    Notes:
7341:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7343:    Level: intermediate

7345:    Concepts: matrices^block size

7347: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7348: @*/
7349: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7350: {
7352:   PetscInt       i,ncnt = 0, nlocal;

7356:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7357:   MatGetLocalSize(mat,&nlocal,NULL);
7358:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7359:   if (ncnt != nlocal) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Sum of local block sizes %D does not equal local size of matrix %D",ncnt,nlocal);
7360:   PetscFree(mat->bsizes);
7361:   mat->nblocks = nblocks;
7362:   PetscMalloc1(nblocks,&mat->bsizes);
7363:   PetscMemcpy(mat->bsizes,bsizes,nblocks*sizeof(PetscInt));
7364:   return(0);
7365: }

7367: /*@C
7368:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7370:    Logically Collective on Mat

7372:    Input Parameters:
7373: .  mat - the matrix

7375:    Output Parameters:
7376: +  nblocks - the number of blocks on this process
7377: -  bsizes - the block sizes

7379:    Notes: Currently not supported from Fortran

7381:    Level: intermediate

7383:    Concepts: matrices^block size

7385: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7386: @*/
7387: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7388: {
7391:   *nblocks = mat->nblocks;
7392:   *bsizes  = mat->bsizes;
7393:   return(0);
7394: }

7396: /*@
7397:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7399:    Logically Collective on Mat

7401:    Input Parameters:
7402: +  mat - the matrix
7403: -  rbs - row block size
7404: -  cbs - column block size

7406:    Notes:
7407:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7408:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7409:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later

7411:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7412:     are compatible with the matrix local sizes.

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

7416:    Level: intermediate

7418:    Concepts: matrices^block size

7420: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7421: @*/
7422: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7423: {

7430:   if (mat->ops->setblocksizes) {
7431:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7432:   }
7433:   if (mat->rmap->refcnt) {
7434:     ISLocalToGlobalMapping l2g = NULL;
7435:     PetscLayout            nmap = NULL;

7437:     PetscLayoutDuplicate(mat->rmap,&nmap);
7438:     if (mat->rmap->mapping) {
7439:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7440:     }
7441:     PetscLayoutDestroy(&mat->rmap);
7442:     mat->rmap = nmap;
7443:     mat->rmap->mapping = l2g;
7444:   }
7445:   if (mat->cmap->refcnt) {
7446:     ISLocalToGlobalMapping l2g = NULL;
7447:     PetscLayout            nmap = NULL;

7449:     PetscLayoutDuplicate(mat->cmap,&nmap);
7450:     if (mat->cmap->mapping) {
7451:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7452:     }
7453:     PetscLayoutDestroy(&mat->cmap);
7454:     mat->cmap = nmap;
7455:     mat->cmap->mapping = l2g;
7456:   }
7457:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7458:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7459:   return(0);
7460: }

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

7465:    Logically Collective on Mat

7467:    Input Parameters:
7468: +  mat - the matrix
7469: .  fromRow - matrix from which to copy row block size
7470: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7472:    Level: developer

7474:    Concepts: matrices^block size

7476: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7477: @*/
7478: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7479: {

7486:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7487:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7488:   return(0);
7489: }

7491: /*@
7492:    MatResidual - Default routine to calculate the residual.

7494:    Collective on Mat and Vec

7496:    Input Parameters:
7497: +  mat - the matrix
7498: .  b   - the right-hand-side
7499: -  x   - the approximate solution

7501:    Output Parameter:
7502: .  r - location to store the residual

7504:    Level: developer

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

7508: .seealso: PCMGSetResidual()
7509: @*/
7510: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7511: {

7520:   MatCheckPreallocated(mat,1);
7521:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7522:   if (!mat->ops->residual) {
7523:     MatMult(mat,x,r);
7524:     VecAYPX(r,-1.0,b);
7525:   } else {
7526:     (*mat->ops->residual)(mat,b,x,r);
7527:   }
7528:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7529:   return(0);
7530: }

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

7535:    Collective on Mat

7537:     Input Parameters:
7538: +   mat - the matrix
7539: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7540: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7541: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7542:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7543:                  always used.

7545:     Output Parameters:
7546: +   n - number of rows in the (possibly compressed) matrix
7547: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7548: .   ja - the column indices
7549: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7550:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7552:     Level: developer

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

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

7559:     Fortran Notes:
7560:     In Fortran use
7561: $
7562: $      PetscInt ia(1), ja(1)
7563: $      PetscOffset iia, jja
7564: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7565: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7567:      or
7568: $
7569: $    PetscInt, pointer :: ia(:),ja(:)
7570: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7571: $    ! Access the ith and jth entries via ia(i) and ja(j)

7573: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7574: @*/
7575: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7576: {

7586:   MatCheckPreallocated(mat,1);
7587:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7588:   else {
7589:     *done = PETSC_TRUE;
7590:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7591:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7592:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7593:   }
7594:   return(0);
7595: }

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

7600:     Collective on Mat

7602:     Input Parameters:
7603: +   mat - the matrix
7604: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7605: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7606:                 symmetrized
7607: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7608:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7609:                  always used.
7610: .   n - number of columns in the (possibly compressed) matrix
7611: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7612: -   ja - the row indices

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

7617:     Level: developer

7619: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7620: @*/
7621: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7622: {

7632:   MatCheckPreallocated(mat,1);
7633:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7634:   else {
7635:     *done = PETSC_TRUE;
7636:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7637:   }
7638:   return(0);
7639: }

7641: /*@C
7642:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7643:     MatGetRowIJ().

7645:     Collective on Mat

7647:     Input Parameters:
7648: +   mat - the matrix
7649: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7650: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7651:                 symmetrized
7652: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7653:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7654:                  always used.
7655: .   n - size of (possibly compressed) matrix
7656: .   ia - the row pointers
7657: -   ja - the column indices

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

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

7667:     Level: developer

7669: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7670: @*/
7671: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7672: {

7681:   MatCheckPreallocated(mat,1);

7683:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7684:   else {
7685:     *done = PETSC_TRUE;
7686:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7687:     if (n)  *n = 0;
7688:     if (ia) *ia = NULL;
7689:     if (ja) *ja = NULL;
7690:   }
7691:   return(0);
7692: }

7694: /*@C
7695:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7696:     MatGetColumnIJ().

7698:     Collective on Mat

7700:     Input Parameters:
7701: +   mat - the matrix
7702: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7703: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7704:                 symmetrized
7705: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7706:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7707:                  always used.

7709:     Output Parameters:
7710: +   n - size of (possibly compressed) matrix
7711: .   ia - the column pointers
7712: .   ja - the row indices
7713: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7715:     Level: developer

7717: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7718: @*/
7719: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7720: {

7729:   MatCheckPreallocated(mat,1);

7731:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7732:   else {
7733:     *done = PETSC_TRUE;
7734:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7735:     if (n)  *n = 0;
7736:     if (ia) *ia = NULL;
7737:     if (ja) *ja = NULL;
7738:   }
7739:   return(0);
7740: }

7742: /*@C
7743:     MatColoringPatch -Used inside matrix coloring routines that
7744:     use MatGetRowIJ() and/or MatGetColumnIJ().

7746:     Collective on Mat

7748:     Input Parameters:
7749: +   mat - the matrix
7750: .   ncolors - max color value
7751: .   n   - number of entries in colorarray
7752: -   colorarray - array indicating color for each column

7754:     Output Parameters:
7755: .   iscoloring - coloring generated using colorarray information

7757:     Level: developer

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

7761: @*/
7762: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7763: {

7771:   MatCheckPreallocated(mat,1);

7773:   if (!mat->ops->coloringpatch) {
7774:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7775:   } else {
7776:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7777:   }
7778:   return(0);
7779: }


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

7785:    Logically Collective on Mat

7787:    Input Parameter:
7788: .  mat - the factored matrix to be reset

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

7797:    Note that one can specify in-place ILU(0) factorization by calling
7798: .vb
7799:      PCType(pc,PCILU);
7800:      PCFactorSeUseInPlace(pc);
7801: .ve
7802:    or by using the options -pc_type ilu -pc_factor_in_place

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

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

7813:    Level: developer

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

7817:    Concepts: matrices^unfactored

7819: @*/
7820: PetscErrorCode MatSetUnfactored(Mat mat)
7821: {

7827:   MatCheckPreallocated(mat,1);
7828:   mat->factortype = MAT_FACTOR_NONE;
7829:   if (!mat->ops->setunfactored) return(0);
7830:   (*mat->ops->setunfactored)(mat);
7831:   return(0);
7832: }

7834: /*MC
7835:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7837:     Synopsis:
7838:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7840:     Not collective

7842:     Input Parameter:
7843: .   x - matrix

7845:     Output Parameters:
7846: +   xx_v - the Fortran90 pointer to the array
7847: -   ierr - error code

7849:     Example of Usage:
7850: .vb
7851:       PetscScalar, pointer xx_v(:,:)
7852:       ....
7853:       call MatDenseGetArrayF90(x,xx_v,ierr)
7854:       a = xx_v(3)
7855:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7856: .ve

7858:     Level: advanced

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

7862:     Concepts: matrices^accessing array

7864: M*/

7866: /*MC
7867:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7868:     accessed with MatDenseGetArrayF90().

7870:     Synopsis:
7871:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7873:     Not collective

7875:     Input Parameters:
7876: +   x - matrix
7877: -   xx_v - the Fortran90 pointer to the array

7879:     Output Parameter:
7880: .   ierr - error code

7882:     Example of Usage:
7883: .vb
7884:        PetscScalar, pointer xx_v(:,:)
7885:        ....
7886:        call MatDenseGetArrayF90(x,xx_v,ierr)
7887:        a = xx_v(3)
7888:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7889: .ve

7891:     Level: advanced

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

7895: M*/


7898: /*MC
7899:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7901:     Synopsis:
7902:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7904:     Not collective

7906:     Input Parameter:
7907: .   x - matrix

7909:     Output Parameters:
7910: +   xx_v - the Fortran90 pointer to the array
7911: -   ierr - error code

7913:     Example of Usage:
7914: .vb
7915:       PetscScalar, pointer xx_v(:)
7916:       ....
7917:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7918:       a = xx_v(3)
7919:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7920: .ve

7922:     Level: advanced

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

7926:     Concepts: matrices^accessing array

7928: M*/

7930: /*MC
7931:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7932:     accessed with MatSeqAIJGetArrayF90().

7934:     Synopsis:
7935:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7937:     Not collective

7939:     Input Parameters:
7940: +   x - matrix
7941: -   xx_v - the Fortran90 pointer to the array

7943:     Output Parameter:
7944: .   ierr - error code

7946:     Example of Usage:
7947: .vb
7948:        PetscScalar, pointer xx_v(:)
7949:        ....
7950:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7951:        a = xx_v(3)
7952:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7953: .ve

7955:     Level: advanced

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

7959: M*/


7962: /*@
7963:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7964:                       as the original matrix.

7966:     Collective on Mat

7968:     Input Parameters:
7969: +   mat - the original matrix
7970: .   isrow - parallel IS containing the rows this processor should obtain
7971: .   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.
7972: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7974:     Output Parameter:
7975: .   newmat - the new submatrix, of the same type as the old

7977:     Level: advanced

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

7982:     Some matrix types place restrictions on the row and column indices, such
7983:     as that they be sorted or that they be equal to each other.

7985:     The index sets may not have duplicate entries.

7987:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7988:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7989:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7990:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7991:    you are finished using it.

7993:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7994:     the input matrix.

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

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

8004: .vb
8005:             1  2  0  |  0  3  0  |  0  4
8006:     Proc0   0  5  6  |  7  0  0  |  8  0
8007:             9  0 10  | 11  0  0  | 12  0
8008:     -------------------------------------
8009:            13  0 14  | 15 16 17  |  0  0
8010:     Proc1   0 18  0  | 19 20 21  |  0  0
8011:             0  0  0  | 22 23  0  | 24  0
8012:     -------------------------------------
8013:     Proc2  25 26 27  |  0  0 28  | 29  0
8014:            30  0  0  | 31 32 33  |  0 34
8015: .ve

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

8019: .vb
8020:             2  0  |  0  3  0  |  0
8021:     Proc0   5  6  |  7  0  0  |  8
8022:     -------------------------------
8023:     Proc1  18  0  | 19 20 21  |  0
8024:     -------------------------------
8025:     Proc2  26 27  |  0  0 28  | 29
8026:             0  0  | 31 32 33  |  0
8027: .ve


8030:     Concepts: matrices^submatrices

8032: .seealso: MatCreateSubMatrices()
8033: @*/
8034: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
8035: {
8037:   PetscMPIInt    size;
8038:   Mat            *local;
8039:   IS             iscoltmp;

8048:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8049:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

8051:   MatCheckPreallocated(mat,1);
8052:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

8054:   if (!iscol || isrow == iscol) {
8055:     PetscBool   stride;
8056:     PetscMPIInt grabentirematrix = 0,grab;
8057:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
8058:     if (stride) {
8059:       PetscInt first,step,n,rstart,rend;
8060:       ISStrideGetInfo(isrow,&first,&step);
8061:       if (step == 1) {
8062:         MatGetOwnershipRange(mat,&rstart,&rend);
8063:         if (rstart == first) {
8064:           ISGetLocalSize(isrow,&n);
8065:           if (n == rend-rstart) {
8066:             grabentirematrix = 1;
8067:           }
8068:         }
8069:       }
8070:     }
8071:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
8072:     if (grab) {
8073:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
8074:       if (cll == MAT_INITIAL_MATRIX) {
8075:         *newmat = mat;
8076:         PetscObjectReference((PetscObject)mat);
8077:       }
8078:       return(0);
8079:     }
8080:   }

8082:   if (!iscol) {
8083:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
8084:   } else {
8085:     iscoltmp = iscol;
8086:   }

8088:   /* if original matrix is on just one processor then use submatrix generated */
8089:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8090:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
8091:     goto setproperties;
8092:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8093:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
8094:     *newmat = *local;
8095:     PetscFree(local);
8096:     goto setproperties;
8097:   } else if (!mat->ops->createsubmatrix) {
8098:     /* Create a new matrix type that implements the operation using the full matrix */
8099:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8100:     switch (cll) {
8101:     case MAT_INITIAL_MATRIX:
8102:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
8103:       break;
8104:     case MAT_REUSE_MATRIX:
8105:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
8106:       break;
8107:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8108:     }
8109:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8110:     goto setproperties;
8111:   }

8113:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8114:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8115:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
8116:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

8118:   /* Propagate symmetry information for diagonal blocks */
8119: setproperties:
8120:   if (isrow == iscoltmp) {
8121:     if (mat->symmetric_set && mat->symmetric) {
8122:       MatSetOption(*newmat,MAT_SYMMETRIC,PETSC_TRUE);
8123:     }
8124:     if (mat->structurally_symmetric_set && mat->structurally_symmetric) {
8125:       MatSetOption(*newmat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
8126:     }
8127:     if (mat->hermitian_set && mat->hermitian) {
8128:       MatSetOption(*newmat,MAT_HERMITIAN,PETSC_TRUE);
8129:     }
8130:     if (mat->spd_set && mat->spd) {
8131:       MatSetOption(*newmat,MAT_SPD,PETSC_TRUE);
8132:     }
8133:   }

8135:   if (!iscol) {ISDestroy(&iscoltmp);}
8136:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
8137:   return(0);
8138: }

8140: /*@
8141:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8142:    used during the assembly process to store values that belong to
8143:    other processors.

8145:    Not Collective

8147:    Input Parameters:
8148: +  mat   - the matrix
8149: .  size  - the initial size of the stash.
8150: -  bsize - the initial size of the block-stash(if used).

8152:    Options Database Keys:
8153: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8154: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

8156:    Level: intermediate

8158:    Notes:
8159:      The block-stash is used for values set with MatSetValuesBlocked() while
8160:      the stash is used for values set with MatSetValues()

8162:      Run with the option -info and look for output of the form
8163:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8164:      to determine the appropriate value, MM, to use for size and
8165:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8166:      to determine the value, BMM to use for bsize

8168:    Concepts: stash^setting matrix size
8169:    Concepts: matrices^stash

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

8173: @*/
8174: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8175: {

8181:   MatStashSetInitialSize_Private(&mat->stash,size);
8182:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8183:   return(0);
8184: }

8186: /*@
8187:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8188:      the matrix

8190:    Neighbor-wise Collective on Mat

8192:    Input Parameters:
8193: +  mat   - the matrix
8194: .  x,y - the vectors
8195: -  w - where the result is stored

8197:    Level: intermediate

8199:    Notes:
8200:     w may be the same vector as y.

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

8205:     Concepts: interpolation

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

8209: @*/
8210: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8211: {
8213:   PetscInt       M,N,Ny;

8221:   MatCheckPreallocated(A,1);
8222:   MatGetSize(A,&M,&N);
8223:   VecGetSize(y,&Ny);
8224:   if (M == Ny) {
8225:     MatMultAdd(A,x,y,w);
8226:   } else {
8227:     MatMultTransposeAdd(A,x,y,w);
8228:   }
8229:   return(0);
8230: }

8232: /*@
8233:    MatInterpolate - y = A*x or A'*x depending on the shape of
8234:      the matrix

8236:    Neighbor-wise Collective on Mat

8238:    Input Parameters:
8239: +  mat   - the matrix
8240: -  x,y - the vectors

8242:    Level: intermediate

8244:    Notes:
8245:     This allows one to use either the restriction or interpolation (its transpose)
8246:     matrix to do the interpolation

8248:    Concepts: matrices^interpolation

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

8252: @*/
8253: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8254: {
8256:   PetscInt       M,N,Ny;

8263:   MatCheckPreallocated(A,1);
8264:   MatGetSize(A,&M,&N);
8265:   VecGetSize(y,&Ny);
8266:   if (M == Ny) {
8267:     MatMult(A,x,y);
8268:   } else {
8269:     MatMultTranspose(A,x,y);
8270:   }
8271:   return(0);
8272: }

8274: /*@
8275:    MatRestrict - y = A*x or A'*x

8277:    Neighbor-wise Collective on Mat

8279:    Input Parameters:
8280: +  mat   - the matrix
8281: -  x,y - the vectors

8283:    Level: intermediate

8285:    Notes:
8286:     This allows one to use either the restriction or interpolation (its transpose)
8287:     matrix to do the restriction

8289:    Concepts: matrices^restriction

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

8293: @*/
8294: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8295: {
8297:   PetscInt       M,N,Ny;

8304:   MatCheckPreallocated(A,1);

8306:   MatGetSize(A,&M,&N);
8307:   VecGetSize(y,&Ny);
8308:   if (M == Ny) {
8309:     MatMult(A,x,y);
8310:   } else {
8311:     MatMultTranspose(A,x,y);
8312:   }
8313:   return(0);
8314: }

8316: /*@
8317:    MatGetNullSpace - retrieves the null space of a matrix.

8319:    Logically Collective on Mat and MatNullSpace

8321:    Input Parameters:
8322: +  mat - the matrix
8323: -  nullsp - the null space object

8325:    Level: developer

8327:    Concepts: null space^attaching to matrix

8329: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8330: @*/
8331: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8332: {
8336:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8337:   return(0);
8338: }

8340: /*@
8341:    MatSetNullSpace - attaches a null space to a matrix.

8343:    Logically Collective on Mat and MatNullSpace

8345:    Input Parameters:
8346: +  mat - the matrix
8347: -  nullsp - the null space object

8349:    Level: advanced

8351:    Notes:
8352:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8354:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8355:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8357:       You can remove the null space by calling this routine with an nullsp of NULL


8360:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8361:    the domain of a matrix A (from R^n to R^m (m rows, n columns) R^n = the direct sum of the null space of A, n(A), + the range of A^T, R(A^T).
8362:    Similarly R^m = direct sum n(A^T) + R(A).  Hence the linear system A x = b has a solution only if b in R(A) (or correspondingly b is orthogonal to
8363:    n(A^T)) and if x is a solution then x + alpha n(A) is a solution for any alpha. The minimum norm solution is orthogonal to n(A). For problems without a solution
8364:    the solution that minimizes the norm of the residual (the least squares solution) can be obtained by solving A x = \hat{b} where \hat{b} is b orthogonalized to the n(A^T).

8366:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8368:     If the matrix is known to be symmetric because it is an SBAIJ matrix or one as called MatSetOption(mat,MAT_SYMMETRIC or MAT_SYMMETRIC_ETERNAL,PETSC_TRUE); this
8369:     routine also automatically calls MatSetTransposeNullSpace().

8371:    Concepts: null space^attaching to matrix

8373: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8374: @*/
8375: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8376: {

8382:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8383:   MatNullSpaceDestroy(&mat->nullsp);
8384:   mat->nullsp = nullsp;
8385:   if (mat->symmetric_set && mat->symmetric) {
8386:     MatSetTransposeNullSpace(mat,nullsp);
8387:   }
8388:   return(0);
8389: }

8391: /*@
8392:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8394:    Logically Collective on Mat and MatNullSpace

8396:    Input Parameters:
8397: +  mat - the matrix
8398: -  nullsp - the null space object

8400:    Level: developer

8402:    Concepts: null space^attaching to matrix

8404: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8405: @*/
8406: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8407: {
8412:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8413:   return(0);
8414: }

8416: /*@
8417:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8419:    Logically Collective on Mat and MatNullSpace

8421:    Input Parameters:
8422: +  mat - the matrix
8423: -  nullsp - the null space object

8425:    Level: advanced

8427:    Notes:
8428:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) this allows the linear system to be solved in a least squares sense.
8429:       You must also call MatSetNullSpace()


8432:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8433:    the domain of a matrix A (from R^n to R^m (m rows, n columns) R^n = the direct sum of the null space of A, n(A), + the range of A^T, R(A^T).
8434:    Similarly R^m = direct sum n(A^T) + R(A).  Hence the linear system A x = b has a solution only if b in R(A) (or correspondingly b is orthogonal to
8435:    n(A^T)) and if x is a solution then x + alpha n(A) is a solution for any alpha. The minimum norm solution is orthogonal to n(A). For problems without a solution
8436:    the solution that minimizes the norm of the residual (the least squares solution) can be obtained by solving A x = \hat{b} where \hat{b} is b orthogonalized to the n(A^T).

8438:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8440:    Concepts: null space^attaching to matrix

8442: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8443: @*/
8444: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8445: {

8451:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8452:   MatNullSpaceDestroy(&mat->transnullsp);
8453:   mat->transnullsp = nullsp;
8454:   return(0);
8455: }

8457: /*@
8458:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8459:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8461:    Logically Collective on Mat and MatNullSpace

8463:    Input Parameters:
8464: +  mat - the matrix
8465: -  nullsp - the null space object

8467:    Level: advanced

8469:    Notes:
8470:       Overwrites any previous near null space that may have been attached

8472:       You can remove the null space by calling this routine with an nullsp of NULL

8474:    Concepts: null space^attaching to matrix

8476: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8477: @*/
8478: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8479: {

8486:   MatCheckPreallocated(mat,1);
8487:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8488:   MatNullSpaceDestroy(&mat->nearnullsp);
8489:   mat->nearnullsp = nullsp;
8490:   return(0);
8491: }

8493: /*@
8494:    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()

8496:    Not Collective

8498:    Input Parameters:
8499: .  mat - the matrix

8501:    Output Parameters:
8502: .  nullsp - the null space object, NULL if not set

8504:    Level: developer

8506:    Concepts: null space^attaching to matrix

8508: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8509: @*/
8510: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8511: {
8516:   MatCheckPreallocated(mat,1);
8517:   *nullsp = mat->nearnullsp;
8518:   return(0);
8519: }

8521: /*@C
8522:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8524:    Collective on Mat

8526:    Input Parameters:
8527: +  mat - the matrix
8528: .  row - row/column permutation
8529: .  fill - expected fill factor >= 1.0
8530: -  level - level of fill, for ICC(k)

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

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

8540:    Level: developer

8542:    Concepts: matrices^incomplete Cholesky factorization
8543:    Concepts: Cholesky factorization

8545: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8550: @*/
8551: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8552: {

8560:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8561:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8562:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8563:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8564:   MatCheckPreallocated(mat,1);
8565:   (*mat->ops->iccfactor)(mat,row,info);
8566:   PetscObjectStateIncrease((PetscObject)mat);
8567:   return(0);
8568: }

8570: /*@
8571:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8572:          ghosted ones.

8574:    Not Collective

8576:    Input Parameters:
8577: +  mat - the matrix
8578: -  diag = the diagonal values, including ghost ones

8580:    Level: developer

8582:    Notes:
8583:     Works only for MPIAIJ and MPIBAIJ matrices

8585: .seealso: MatDiagonalScale()
8586: @*/
8587: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8588: {
8590:   PetscMPIInt    size;


8597:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8598:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8599:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8600:   if (size == 1) {
8601:     PetscInt n,m;
8602:     VecGetSize(diag,&n);
8603:     MatGetSize(mat,0,&m);
8604:     if (m == n) {
8605:       MatDiagonalScale(mat,0,diag);
8606:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8607:   } else {
8608:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8609:   }
8610:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8611:   PetscObjectStateIncrease((PetscObject)mat);
8612:   return(0);
8613: }

8615: /*@
8616:    MatGetInertia - Gets the inertia from a factored matrix

8618:    Collective on Mat

8620:    Input Parameter:
8621: .  mat - the matrix

8623:    Output Parameters:
8624: +   nneg - number of negative eigenvalues
8625: .   nzero - number of zero eigenvalues
8626: -   npos - number of positive eigenvalues

8628:    Level: advanced

8630:    Notes:
8631:     Matrix must have been factored by MatCholeskyFactor()


8634: @*/
8635: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8636: {

8642:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8643:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8644:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8645:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8646:   return(0);
8647: }

8649: /* ----------------------------------------------------------------*/
8650: /*@C
8651:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8653:    Neighbor-wise Collective on Mat and Vecs

8655:    Input Parameters:
8656: +  mat - the factored matrix
8657: -  b - the right-hand-side vectors

8659:    Output Parameter:
8660: .  x - the result vectors

8662:    Notes:
8663:    The vectors b and x cannot be the same.  I.e., one cannot
8664:    call MatSolves(A,x,x).

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

8671:    Level: developer

8673:    Concepts: matrices^triangular solves

8675: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8676: @*/
8677: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8678: {

8684:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8685:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8686:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8688:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8689:   MatCheckPreallocated(mat,1);
8690:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8691:   (*mat->ops->solves)(mat,b,x);
8692:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8693:   return(0);
8694: }

8696: /*@
8697:    MatIsSymmetric - Test whether a matrix is symmetric

8699:    Collective on Mat

8701:    Input Parameter:
8702: +  A - the matrix to test
8703: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8705:    Output Parameters:
8706: .  flg - the result

8708:    Notes:
8709:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8711:    Level: intermediate

8713:    Concepts: matrix^symmetry

8715: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8716: @*/
8717: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8718: {


8725:   if (!A->symmetric_set) {
8726:     if (!A->ops->issymmetric) {
8727:       MatType mattype;
8728:       MatGetType(A,&mattype);
8729:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8730:     }
8731:     (*A->ops->issymmetric)(A,tol,flg);
8732:     if (!tol) {
8733:       A->symmetric_set = PETSC_TRUE;
8734:       A->symmetric     = *flg;
8735:       if (A->symmetric) {
8736:         A->structurally_symmetric_set = PETSC_TRUE;
8737:         A->structurally_symmetric     = PETSC_TRUE;
8738:       }
8739:     }
8740:   } else if (A->symmetric) {
8741:     *flg = PETSC_TRUE;
8742:   } else if (!tol) {
8743:     *flg = PETSC_FALSE;
8744:   } else {
8745:     if (!A->ops->issymmetric) {
8746:       MatType mattype;
8747:       MatGetType(A,&mattype);
8748:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8749:     }
8750:     (*A->ops->issymmetric)(A,tol,flg);
8751:   }
8752:   return(0);
8753: }

8755: /*@
8756:    MatIsHermitian - Test whether a matrix is Hermitian

8758:    Collective on Mat

8760:    Input Parameter:
8761: +  A - the matrix to test
8762: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8764:    Output Parameters:
8765: .  flg - the result

8767:    Level: intermediate

8769:    Concepts: matrix^symmetry

8771: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8772:           MatIsSymmetricKnown(), MatIsSymmetric()
8773: @*/
8774: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8775: {


8782:   if (!A->hermitian_set) {
8783:     if (!A->ops->ishermitian) {
8784:       MatType mattype;
8785:       MatGetType(A,&mattype);
8786:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8787:     }
8788:     (*A->ops->ishermitian)(A,tol,flg);
8789:     if (!tol) {
8790:       A->hermitian_set = PETSC_TRUE;
8791:       A->hermitian     = *flg;
8792:       if (A->hermitian) {
8793:         A->structurally_symmetric_set = PETSC_TRUE;
8794:         A->structurally_symmetric     = PETSC_TRUE;
8795:       }
8796:     }
8797:   } else if (A->hermitian) {
8798:     *flg = PETSC_TRUE;
8799:   } else if (!tol) {
8800:     *flg = PETSC_FALSE;
8801:   } else {
8802:     if (!A->ops->ishermitian) {
8803:       MatType mattype;
8804:       MatGetType(A,&mattype);
8805:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8806:     }
8807:     (*A->ops->ishermitian)(A,tol,flg);
8808:   }
8809:   return(0);
8810: }

8812: /*@
8813:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8815:    Not Collective

8817:    Input Parameter:
8818: .  A - the matrix to check

8820:    Output Parameters:
8821: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8822: -  flg - the result

8824:    Level: advanced

8826:    Concepts: matrix^symmetry

8828:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8829:          if you want it explicitly checked

8831: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8832: @*/
8833: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8834: {
8839:   if (A->symmetric_set) {
8840:     *set = PETSC_TRUE;
8841:     *flg = A->symmetric;
8842:   } else {
8843:     *set = PETSC_FALSE;
8844:   }
8845:   return(0);
8846: }

8848: /*@
8849:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8851:    Not Collective

8853:    Input Parameter:
8854: .  A - the matrix to check

8856:    Output Parameters:
8857: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8858: -  flg - the result

8860:    Level: advanced

8862:    Concepts: matrix^symmetry

8864:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8865:          if you want it explicitly checked

8867: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8868: @*/
8869: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8870: {
8875:   if (A->hermitian_set) {
8876:     *set = PETSC_TRUE;
8877:     *flg = A->hermitian;
8878:   } else {
8879:     *set = PETSC_FALSE;
8880:   }
8881:   return(0);
8882: }

8884: /*@
8885:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8887:    Collective on Mat

8889:    Input Parameter:
8890: .  A - the matrix to test

8892:    Output Parameters:
8893: .  flg - the result

8895:    Level: intermediate

8897:    Concepts: matrix^symmetry

8899: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8900: @*/
8901: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool  *flg)
8902: {

8908:   if (!A->structurally_symmetric_set) {
8909:     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8910:     (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);

8912:     A->structurally_symmetric_set = PETSC_TRUE;
8913:   }
8914:   *flg = A->structurally_symmetric;
8915:   return(0);
8916: }

8918: /*@
8919:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8920:        to be communicated to other processors during the MatAssemblyBegin/End() process

8922:     Not collective

8924:    Input Parameter:
8925: .   vec - the vector

8927:    Output Parameters:
8928: +   nstash   - the size of the stash
8929: .   reallocs - the number of additional mallocs incurred.
8930: .   bnstash   - the size of the block stash
8931: -   breallocs - the number of additional mallocs incurred.in the block stash

8933:    Level: advanced

8935: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8937: @*/
8938: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8939: {

8943:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8944:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8945:   return(0);
8946: }

8948: /*@C
8949:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8950:      parallel layout

8952:    Collective on Mat

8954:    Input Parameter:
8955: .  mat - the matrix

8957:    Output Parameter:
8958: +   right - (optional) vector that the matrix can be multiplied against
8959: -   left - (optional) vector that the matrix vector product can be stored in

8961:    Notes:
8962:     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().

8964:   Notes:
8965:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8967:   Level: advanced

8969: .seealso: MatCreate(), VecDestroy()
8970: @*/
8971: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8972: {

8978:   if (mat->ops->getvecs) {
8979:     (*mat->ops->getvecs)(mat,right,left);
8980:   } else {
8981:     PetscInt rbs,cbs;
8982:     MatGetBlockSizes(mat,&rbs,&cbs);
8983:     if (right) {
8984:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8985:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8986:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8987:       VecSetBlockSize(*right,cbs);
8988:       VecSetType(*right,mat->defaultvectype);
8989:       PetscLayoutReference(mat->cmap,&(*right)->map);
8990:     }
8991:     if (left) {
8992:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8993:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8994:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8995:       VecSetBlockSize(*left,rbs);
8996:       VecSetType(*left,mat->defaultvectype);
8997:       PetscLayoutReference(mat->rmap,&(*left)->map);
8998:     }
8999:   }
9000:   return(0);
9001: }

9003: /*@C
9004:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
9005:      with default values.

9007:    Not Collective

9009:    Input Parameters:
9010: .    info - the MatFactorInfo data structure


9013:    Notes:
9014:     The solvers are generally used through the KSP and PC objects, for example
9015:           PCLU, PCILU, PCCHOLESKY, PCICC

9017:    Level: developer

9019: .seealso: MatFactorInfo

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

9024: @*/

9026: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9027: {

9031:   PetscMemzero(info,sizeof(MatFactorInfo));
9032:   return(0);
9033: }

9035: /*@
9036:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

9038:    Collective on Mat

9040:    Input Parameters:
9041: +  mat - the factored matrix
9042: -  is - the index set defining the Schur indices (0-based)

9044:    Notes:
9045:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

9047:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

9049:    Level: developer

9051:    Concepts:

9053: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
9054:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

9056: @*/
9057: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
9058: {
9059:   PetscErrorCode ierr,(*f)(Mat,IS);

9067:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
9068:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
9069:   if (!f) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9070:   if (mat->schur) {
9071:     MatDestroy(&mat->schur);
9072:   }
9073:   (*f)(mat,is);
9074:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
9075:   MatFactorSetUpInPlaceSchur_Private(mat);
9076:   return(0);
9077: }

9079: /*@
9080:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

9082:    Logically Collective on Mat

9084:    Input Parameters:
9085: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
9086: .  S - location where to return the Schur complement, can be NULL
9087: -  status - the status of the Schur complement matrix, can be NULL

9089:    Notes:
9090:    You must call MatFactorSetSchurIS() before calling this routine.

9092:    The routine provides a copy of the Schur matrix stored within the solver data structures.
9093:    The caller must destroy the object when it is no longer needed.
9094:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

9096:    Use MatFactorGetSchurComplement() to get access to the Schur complement matrix inside the factored matrix instead of making a copy of it (which this function does)

9098:    Developer Notes:
9099:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9100:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

9102:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

9104:    Level: advanced

9106:    References:

9108: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
9109: @*/
9110: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9111: {

9118:   if (S) {
9119:     PetscErrorCode (*f)(Mat,Mat*);

9121:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
9122:     if (f) {
9123:       (*f)(F,S);
9124:     } else {
9125:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
9126:     }
9127:   }
9128:   if (status) *status = F->schur_status;
9129:   return(0);
9130: }

9132: /*@
9133:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

9135:    Logically Collective on Mat

9137:    Input Parameters:
9138: +  F - the factored matrix obtained by calling MatGetFactor()
9139: .  *S - location where to return the Schur complement, can be NULL
9140: -  status - the status of the Schur complement matrix, can be NULL

9142:    Notes:
9143:    You must call MatFactorSetSchurIS() before calling this routine.

9145:    Schur complement mode is currently implemented for sequential matrices.
9146:    The routine returns a the Schur Complement stored within the data strutures of the solver.
9147:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
9148:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

9150:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

9152:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

9154:    Level: advanced

9156:    References:

9158: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9159: @*/
9160: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9161: {
9166:   if (S) *S = F->schur;
9167:   if (status) *status = F->schur_status;
9168:   return(0);
9169: }

9171: /*@
9172:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

9174:    Logically Collective on Mat

9176:    Input Parameters:
9177: +  F - the factored matrix obtained by calling MatGetFactor()
9178: .  *S - location where the Schur complement is stored
9179: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

9181:    Notes:

9183:    Level: advanced

9185:    References:

9187: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9188: @*/
9189: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9190: {

9195:   if (S) {
9197:     *S = NULL;
9198:   }
9199:   F->schur_status = status;
9200:   MatFactorUpdateSchurStatus_Private(F);
9201:   return(0);
9202: }

9204: /*@
9205:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9207:    Logically Collective on Mat

9209:    Input Parameters:
9210: +  F - the factored matrix obtained by calling MatGetFactor()
9211: .  rhs - location where the right hand side of the Schur complement system is stored
9212: -  sol - location where the solution of the Schur complement system has to be returned

9214:    Notes:
9215:    The sizes of the vectors should match the size of the Schur complement

9217:    Must be called after MatFactorSetSchurIS()

9219:    Level: advanced

9221:    References:

9223: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9224: @*/
9225: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9226: {

9238:   MatFactorFactorizeSchurComplement(F);
9239:   switch (F->schur_status) {
9240:   case MAT_FACTOR_SCHUR_FACTORED:
9241:     MatSolveTranspose(F->schur,rhs,sol);
9242:     break;
9243:   case MAT_FACTOR_SCHUR_INVERTED:
9244:     MatMultTranspose(F->schur,rhs,sol);
9245:     break;
9246:   default:
9247:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9248:     break;
9249:   }
9250:   return(0);
9251: }

9253: /*@
9254:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9256:    Logically Collective on Mat

9258:    Input Parameters:
9259: +  F - the factored matrix obtained by calling MatGetFactor()
9260: .  rhs - location where the right hand side of the Schur complement system is stored
9261: -  sol - location where the solution of the Schur complement system has to be returned

9263:    Notes:
9264:    The sizes of the vectors should match the size of the Schur complement

9266:    Must be called after MatFactorSetSchurIS()

9268:    Level: advanced

9270:    References:

9272: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9273: @*/
9274: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9275: {

9287:   MatFactorFactorizeSchurComplement(F);
9288:   switch (F->schur_status) {
9289:   case MAT_FACTOR_SCHUR_FACTORED:
9290:     MatSolve(F->schur,rhs,sol);
9291:     break;
9292:   case MAT_FACTOR_SCHUR_INVERTED:
9293:     MatMult(F->schur,rhs,sol);
9294:     break;
9295:   default:
9296:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9297:     break;
9298:   }
9299:   return(0);
9300: }

9302: /*@
9303:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9305:    Logically Collective on Mat

9307:    Input Parameters:
9308: +  F - the factored matrix obtained by calling MatGetFactor()

9310:    Notes:
9311:     Must be called after MatFactorSetSchurIS().

9313:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9315:    Level: advanced

9317:    References:

9319: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9320: @*/
9321: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9322: {

9328:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9329:   MatFactorFactorizeSchurComplement(F);
9330:   MatFactorInvertSchurComplement_Private(F);
9331:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9332:   return(0);
9333: }

9335: /*@
9336:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9338:    Logically Collective on Mat

9340:    Input Parameters:
9341: +  F - the factored matrix obtained by calling MatGetFactor()

9343:    Notes:
9344:     Must be called after MatFactorSetSchurIS().

9346:    Level: advanced

9348:    References:

9350: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9351: @*/
9352: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9353: {

9359:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9360:   MatFactorFactorizeSchurComplement_Private(F);
9361:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9362:   return(0);
9363: }

9365: /*@
9366:    MatPtAP - Creates the matrix product C = P^T * A * P

9368:    Neighbor-wise Collective on Mat

9370:    Input Parameters:
9371: +  A - the matrix
9372: .  P - the projection matrix
9373: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9374: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9375:           if the result is a dense matrix this is irrelevent

9377:    Output Parameters:
9378: .  C - the product matrix

9380:    Notes:
9381:    C will be created and must be destroyed by the user with MatDestroy().

9383:    This routine is currently only implemented for pairs of sequential dense matrices, AIJ matrices and classes
9384:    which inherit from AIJ.

9386:    Level: intermediate

9388: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9389: @*/
9390: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9391: {
9393:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9394:   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9395:   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9396:   PetscBool      sametype;

9401:   MatCheckPreallocated(A,1);
9402:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9403:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9404:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9407:   MatCheckPreallocated(P,2);
9408:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9409:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9411:   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);
9412:   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);
9413:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9414:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9416:   if (scall == MAT_REUSE_MATRIX) {

9420:     if (!(*C)->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You cannot use MAT_REUSE_MATRIX");
9421:     PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9422:     PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9423:     (*(*C)->ops->ptapnumeric)(A,P,*C);
9424:     PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9425:     PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9426:     return(0);
9427:   }

9429:   if (fill == PETSC_DEFAULT || fill ==