Actual source code: matrix.c

petsc-main 2021-04-20
Report Typos and Errors
  1: /*
  2:    This is where the abstract matrix operations are defined
  3: */

  5: #include <petsc/private/matimpl.h>
  6: #include <petsc/private/isimpl.h>
  7: #include <petsc/private/vecimpl.h>

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

 15: PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
 16: PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve,MAT_MatTrSolve;
 17: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
 18: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
 19: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
 20: PetscLogEvent MAT_QRFactorNumeric, MAT_QRFactorSymbolic, MAT_QRFactor;
 21: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
 22: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
 23: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
 24: PetscLogEvent MAT_TransposeColoringCreate;
 25: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
 26: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
 27: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
 28: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
 29: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
 30: PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
 31: PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
 32: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
 33: PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
 34: PetscLogEvent MAT_GetMultiProcBlock;
 35: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_CUSPARSECopyFromGPU, MAT_CUSPARSEGenerateTranspose, MAT_CUSPARSESolveAnalysis;
 36: PetscLogEvent MAT_PreallCOO, MAT_SetVCOO;
 37: PetscLogEvent MAT_SetValuesBatch;
 38: PetscLogEvent MAT_ViennaCLCopyToGPU;
 39: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
 40: PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
 41: PetscLogEvent MAT_FactorFactS,MAT_FactorInvS;
 42: PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;

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

 46: /*@
 47:    MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated but not been assembled it randomly selects appropriate locations,
 48:                   for sparse matrices that already have locations it fills the locations with random numbers

 50:    Logically Collective on Mat

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

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

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

 67:    Level: intermediate


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


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

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

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

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

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

105:    Logically Collective on Mat

107:    Input Parameters:
108: .  mat - the factored matrix

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

115:    Level: advanced

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

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

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

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

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

138:    Logically Collective on Mat

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

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

146:    Level: advanced

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

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

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

164:    Logically Collective on Mat

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

169:    Level: developer

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

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

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

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

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

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

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

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

244:   Level: intermediate

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

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

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

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

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

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

277:   Level: intermediate

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


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

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

306:    Not Collective

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

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

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

319:    Level: advanced

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

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

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

346:    Collective on Mat

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

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

354:    Level: advanced

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

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

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

373:    Logically Collective on Mat

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

378:    Level: advanced


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

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

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

401:    Collective on Mat

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

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

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

413:    Level: advanced

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

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


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

438:    Logically Collective on Mat

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

443:    Level: advanced


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

455:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
456:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
457:   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
458:   MatCheckPreallocated(mat,1);
459:   (*mat->ops->imaginarypart)(mat);
460:   return(0);
461: }

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

466:    Not Collective

468:    Input Parameter:
469: .  mat - the matrix

471:    Output Parameters:
472: +  missing - is any diagonal missing
473: -  dd - first diagonal entry that is missing (optional) on this process

475:    Level: advanced


478: .seealso: MatRealPart()
479: @*/
480: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
481: {

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

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

500:    Not Collective

502:    Input Parameters:
503: +  mat - the matrix
504: -  row - the row to get

506:    Output Parameters:
507: +  ncols -  if not NULL, the number of nonzeros in the row
508: .  cols - if not NULL, the column numbers
509: -  vals - if not NULL, the values

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

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

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

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

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

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


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

550:    Level: advanced

552: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
553: @*/
554: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
555: {
557:   PetscInt       incols;

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

574: /*@
575:    MatConjugate - replaces the matrix values with their complex conjugates

577:    Logically Collective on Mat

579:    Input Parameters:
580: .  mat - the matrix

582:    Level: advanced

584: .seealso:  VecConjugate()
585: @*/
586: PetscErrorCode MatConjugate(Mat mat)
587: {
588: #if defined(PETSC_USE_COMPLEX)

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

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

605:    Not Collective

607:    Input Parameters:
608: +  mat - the matrix
609: .  row - the row to get
610: .  ncols, cols - the number of nonzeros and their columns
611: -  vals - if nonzero the column values

613:    Notes:
614:    This routine should be called after you have finished examining the entries.

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

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

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

635:    Level: advanced

637: .seealso:  MatGetRow()
638: @*/
639: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
640: {

646:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
647:   if (!mat->ops->restorerow) return(0);
648:   (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
649:   if (ncols) *ncols = 0;
650:   if (cols)  *cols = NULL;
651:   if (vals)  *vals = NULL;
652:   return(0);
653: }

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

659:    Not Collective

661:    Input Parameters:
662: .  mat - the matrix

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

667:    Level: advanced

669: .seealso: MatRestoreRowUpperTriangular()
670: @*/
671: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
672: {

678:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
679:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
680:   MatCheckPreallocated(mat,1);
681:   if (!mat->ops->getrowuppertriangular) return(0);
682:   (*mat->ops->getrowuppertriangular)(mat);
683:   return(0);
684: }

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

689:    Not Collective

691:    Input Parameters:
692: .  mat - the matrix

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


698:    Level: advanced

700: .seealso:  MatGetRowUpperTriangular()
701: @*/
702: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
703: {

709:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
710:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
711:   MatCheckPreallocated(mat,1);
712:   if (!mat->ops->restorerowuppertriangular) return(0);
713:   (*mat->ops->restorerowuppertriangular)(mat);
714:   return(0);
715: }

717: /*@C
718:    MatSetOptionsPrefix - Sets the prefix used for searching for all
719:    Mat options in the database.

721:    Logically Collective on Mat

723:    Input Parameter:
724: +  A - the Mat context
725: -  prefix - the prefix to prepend to all option names

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

731:    Level: advanced

733: .seealso: MatSetFromOptions()
734: @*/
735: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
736: {

741:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
742:   return(0);
743: }

745: /*@C
746:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
747:    Mat options in the database.

749:    Logically Collective on Mat

751:    Input Parameters:
752: +  A - the Mat context
753: -  prefix - the prefix to prepend to all option names

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

759:    Level: advanced

761: .seealso: MatGetOptionsPrefix()
762: @*/
763: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
764: {

769:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
770:   return(0);
771: }

773: /*@C
774:    MatGetOptionsPrefix - Gets the prefix used for searching for all
775:    Mat options in the database.

777:    Not Collective

779:    Input Parameter:
780: .  A - the Mat context

782:    Output Parameter:
783: .  prefix - pointer to the prefix string used

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

789:    Level: advanced

791: .seealso: MatAppendOptionsPrefix()
792: @*/
793: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
794: {

799:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
800:   return(0);
801: }

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

806:    Collective on Mat

808:    Input Parameters:
809: .  A - the Mat context

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

815:    Level: beginner

817: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
818: @*/
819: PetscErrorCode MatResetPreallocation(Mat A)
820: {

826:   PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
827:   return(0);
828: }


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

834:    Collective on Mat

836:    Input Parameters:
837: .  A - the Mat context

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

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

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

846:    Level: beginner

848: .seealso: MatCreate(), MatDestroy()
849: @*/
850: PetscErrorCode MatSetUp(Mat A)
851: {
852:   PetscMPIInt    size;

857:   if (!((PetscObject)A)->type_name) {
858:     MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
859:     if (size == 1) {
860:       MatSetType(A, MATSEQAIJ);
861:     } else {
862:       MatSetType(A, MATMPIAIJ);
863:     }
864:   }
865:   if (!A->preallocated && A->ops->setup) {
866:     PetscInfo(A,"Warning not preallocating matrix storage\n");
867:     (*A->ops->setup)(A);
868:   }
869:   PetscLayoutSetUp(A->rmap);
870:   PetscLayoutSetUp(A->cmap);
871:   A->preallocated = PETSC_TRUE;
872:   return(0);
873: }

875: #if defined(PETSC_HAVE_SAWS)
876: #include <petscviewersaws.h>
877: #endif

879: /*@C
880:    MatViewFromOptions - View from Options

882:    Collective on Mat

884:    Input Parameters:
885: +  A - the Mat context
886: .  obj - Optional object
887: -  name - command line option

889:    Level: intermediate
890: .seealso:  Mat, MatView, PetscObjectViewFromOptions(), MatCreate()
891: @*/
892: PetscErrorCode  MatViewFromOptions(Mat A,PetscObject obj,const char name[])
893: {

898:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
899:   return(0);
900: }

902: /*@C
903:    MatView - Visualizes a matrix object.

905:    Collective on Mat

907:    Input Parameters:
908: +  mat - the matrix
909: -  viewer - visualization context

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

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

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

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

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

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

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

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

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

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

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

995:   PetscViewerGetFormat(viewer,&format);
996:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
997:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);

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

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

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

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

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

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

1099:    Collective on PetscViewer

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

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

1111:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

1180:    As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1181:    by default the same structure and naming of the AIJ arrays and column count
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/tutorials/ex10.c and src/ksp/ksp/tutorials/ex27.c

1193:    Current HDF5 (MAT-File) limitations:
1194:    This reader currently supports only real MATSEQAIJ, MATMPIAIJ, MATSEQDENSE and MATMPIDENSE 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: .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), MatView(), VecLoad()

1209:  @*/
1210: PetscErrorCode MatLoad(Mat mat,PetscViewer viewer)
1211: {
1213:   PetscBool      flg;


1219:   if (!((PetscObject)mat)->type_name) {
1220:     MatSetType(mat,MATAIJ);
1221:   }

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

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

1242: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1243: {
1245:   Mat_Redundant  *redund = *redundant;
1246:   PetscInt       i;

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

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

1273: /*@C
1274:    MatDestroy - Frees space taken by a matrix.

1276:    Collective on Mat

1278:    Input Parameter:
1279: .  A - the matrix

1281:    Level: beginner

1283: @*/
1284: PetscErrorCode MatDestroy(Mat *A)
1285: {

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

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

1299:   PetscFree((*A)->defaultvectype);
1300:   PetscFree((*A)->bsizes);
1301:   PetscFree((*A)->solvertype);
1302:   for (PetscInt i=0; i<MAT_FACTOR_NUM_TYPES; i++) {
1303:     PetscFree((*A)->preferredordering[i]);
1304:   }
1305:   MatDestroy_Redundant(&(*A)->redundant);
1306:   MatProductClear(*A);
1307:   MatNullSpaceDestroy(&(*A)->nullsp);
1308:   MatNullSpaceDestroy(&(*A)->transnullsp);
1309:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1310:   MatDestroy(&(*A)->schur);
1311:   PetscLayoutDestroy(&(*A)->rmap);
1312:   PetscLayoutDestroy(&(*A)->cmap);
1313:   PetscHeaderDestroy(A);
1314:   return(0);
1315: }

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

1322:    Not Collective

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

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

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

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

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

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

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

1355:    Level: beginner

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

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

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

1376:   if (mat->insertmode == NOT_SET_VALUES) {
1377:     mat->insertmode = addv;
1378:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1379:   if (PetscDefined(USE_DEBUG)) {
1380:     PetscInt       i,j;

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

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

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:   return(0);
1407: }


1410: /*@
1411:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1412:         values into a matrix

1414:    Not Collective

1416:    Input Parameters:
1417: +  mat - the matrix
1418: .  row - the (block) row to set
1419: -  v - a logically two-dimensional array of values

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

1424:    All the nonzeros in the row must be provided

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

1428:    The row must belong to this process

1430:    Level: intermediate

1432: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1433:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1434: @*/
1435: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1436: {
1438:   PetscInt       globalrow;

1444:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1445:   MatSetValuesRow(mat,globalrow,v);
1446:   return(0);
1447: }

1449: /*@
1450:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1451:         values into a matrix

1453:    Not Collective

1455:    Input Parameters:
1456: +  mat - the matrix
1457: .  row - the (block) row to set
1458: -  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

1460:    Notes:
1461:    The values, v, are column-oriented for the block version.

1463:    All the nonzeros in the row must be provided

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

1467:    The row must belong to this process

1469:    Level: advanced

1471: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1472:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1473: @*/
1474: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1475: {

1481:   MatCheckPreallocated(mat,1);
1483:   if (PetscUnlikely(mat->insertmode == ADD_VALUES)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1484:   if (PetscUnlikely(mat->factortype)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1485:   mat->insertmode = INSERT_VALUES;

1487:   if (mat->assembled) {
1488:     mat->was_assembled = PETSC_TRUE;
1489:     mat->assembled     = PETSC_FALSE;
1490:   }
1491:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1492:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1493:   (*mat->ops->setvaluesrow)(mat,row,v);
1494:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1495:   return(0);
1496: }

1498: /*@
1499:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1500:      Using structured grid indexing

1502:    Not Collective

1504:    Input Parameters:
1505: +  mat - the matrix
1506: .  m - number of rows being entered
1507: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1508: .  n - number of columns being entered
1509: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1510: .  v - a logically two-dimensional array of values
1511: -  addv - either ADD_VALUES or INSERT_VALUES, where
1512:    ADD_VALUES adds values to any existing entries, and
1513:    INSERT_VALUES replaces existing entries with new values

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

1518:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1519:    options cannot be mixed without intervening calls to the assembly
1520:    routines.

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

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

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

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

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

1538:    In Fortran idxm and idxn should be declared as
1539: $     MatStencil idxm(4,m),idxn(4,n)
1540:    and the values inserted using
1541: $    idxm(MatStencil_i,1) = i
1542: $    idxm(MatStencil_j,1) = j
1543: $    idxm(MatStencil_k,1) = k
1544: $    idxm(MatStencil_c,1) = c
1545:    etc

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

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

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

1558:    Efficiency Alert:
1559:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1560:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1562:    Level: beginner

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

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

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

1612: /*@
1613:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1614:      Using structured grid indexing

1616:    Not Collective

1618:    Input Parameters:
1619: +  mat - the matrix
1620: .  m - number of rows being entered
1621: .  idxm - grid coordinates for matrix rows being entered
1622: .  n - number of columns being entered
1623: .  idxn - grid coordinates for matrix columns being entered
1624: .  v - a logically two-dimensional array of values
1625: -  addv - either ADD_VALUES or INSERT_VALUES, where
1626:    ADD_VALUES adds values to any existing entries, and
1627:    INSERT_VALUES replaces existing entries with new values

1629:    Notes:
1630:    By default the values, v, are row-oriented and unsorted.
1631:    See MatSetOption() for other options.

1633:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1634:    options cannot be mixed without intervening calls to the assembly
1635:    routines.

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

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

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

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

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

1653:    In Fortran idxm and idxn should be declared as
1654: $     MatStencil idxm(4,m),idxn(4,n)
1655:    and the values inserted using
1656: $    idxm(MatStencil_i,1) = i
1657: $    idxm(MatStencil_j,1) = j
1658: $    idxm(MatStencil_k,1) = k
1659:    etc

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

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

1669:    Level: beginner

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

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

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

1721: /*@
1722:    MatSetStencil - Sets the grid information for setting values into a matrix via
1723:         MatSetValuesStencil()

1725:    Not Collective

1727:    Input Parameters:
1728: +  mat - the matrix
1729: .  dim - dimension of the grid 1, 2, or 3
1730: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1731: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1732: -  dof - number of degrees of freedom per node


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

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

1741:    Level: beginner

1743: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1744:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1745: @*/
1746: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1747: {
1748:   PetscInt i;


1755:   mat->stencil.dim = dim + (dof > 1);
1756:   for (i=0; i<dim; i++) {
1757:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1758:     mat->stencil.starts[i] = starts[dim-i-1];
1759:   }
1760:   mat->stencil.dims[dim]   = dof;
1761:   mat->stencil.starts[dim] = 0;
1762:   mat->stencil.noc         = (PetscBool)(dof == 1);
1763:   return(0);
1764: }

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

1769:    Not Collective

1771:    Input Parameters:
1772: +  mat - the matrix
1773: .  v - a logically two-dimensional array of values
1774: .  m, idxm - the number of block rows and their global block indices
1775: .  n, idxn - the number of block columns and their global block indices
1776: -  addv - either ADD_VALUES or INSERT_VALUES, where
1777:    ADD_VALUES adds values to any existing entries, and
1778:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

1796:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1797:    options cannot be mixed without intervening calls to the assembly
1798:    routines.

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

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

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

1814:    Example:
1815: $   Suppose m=n=2 and block size(bs) = 2 The array is
1816: $
1817: $   1  2  | 3  4
1818: $   5  6  | 7  8
1819: $   - - - | - - -
1820: $   9  10 | 11 12
1821: $   13 14 | 15 16
1822: $
1823: $   v[] should be passed in like
1824: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1825: $
1826: $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1827: $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]

1829:    Level: intermediate

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

1840:   if (!m || !n) return(0); /* no values to insert */
1844:   MatCheckPreallocated(mat,1);
1845:   if (mat->insertmode == NOT_SET_VALUES) {
1846:     mat->insertmode = addv;
1847:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1848:   if (PetscDefined(USE_DEBUG)) {
1849:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1850:     if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1851:   }
1852:   if (PetscDefined(USE_DEBUG)) {
1853:     PetscInt rbs,cbs,M,N,i;
1854:     MatGetBlockSizes(mat,&rbs,&cbs);
1855:     MatGetSize(mat,&M,&N);
1856:     for (i=0; i<m; i++) {
1857:       if (idxm[i]*rbs >= M) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row block index %D (index %D) greater than row length %D",i,idxm[i],M);
1858:     }
1859:     for (i=0; i<n; i++) {
1860:       if (idxn[i]*cbs >= N) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column block index %D (index %D) great than column length %D",i,idxn[i],N);
1861:     }
1862:   }
1863:   if (mat->assembled) {
1864:     mat->was_assembled = PETSC_TRUE;
1865:     mat->assembled     = PETSC_FALSE;
1866:   }
1867:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1868:   if (mat->ops->setvaluesblocked) {
1869:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1870:   } else {
1871:     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*iidxm,*iidxn;
1872:     PetscInt i,j,bs,cbs;
1873:     MatGetBlockSizes(mat,&bs,&cbs);
1874:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1875:       iidxm = buf; iidxn = buf + m*bs;
1876:     } else {
1877:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1878:       iidxm = bufr; iidxn = bufc;
1879:     }
1880:     for (i=0; i<m; i++) {
1881:       for (j=0; j<bs; j++) {
1882:         iidxm[i*bs+j] = bs*idxm[i] + j;
1883:       }
1884:     }
1885:     for (i=0; i<n; i++) {
1886:       for (j=0; j<cbs; j++) {
1887:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1888:       }
1889:     }
1890:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1891:     PetscFree2(bufr,bufc);
1892:   }
1893:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1894:   return(0);
1895: }

1897: /*@C
1898:    MatGetValues - Gets a block of values from a matrix.

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

1902:    Input Parameters:
1903: +  mat - the matrix
1904: .  v - a logically two-dimensional array for storing the values
1905: .  m, idxm - the number of rows and their global indices
1906: -  n, idxn - the number of columns and their global indices

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

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

1916:      MatGetValues() requires that the matrix has been assembled
1917:      with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1918:      MatSetValues() and MatGetValues() CANNOT be made in succession
1919:      without intermediate matrix assembly.

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

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

1928:    Level: advanced

1930: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues(), MatGetOwnershipRange(), MatGetValuesLocal()
1931: @*/
1932: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1933: {

1939:   if (!m || !n) return(0);
1943:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1944:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1945:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1946:   MatCheckPreallocated(mat,1);

1948:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1949:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1950:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1951:   return(0);
1952: }

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

1958:    Not Collective

1960:    Input Parameters:
1961: +  mat - the matrix
1962: .  nrow, irow - number of rows and their local indices
1963: -  ncol, icol - number of columns and their local indices

1965:    Output Parameter:
1966: .  y -  a logically two-dimensional array of values

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

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

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

1980:    Level: advanced

1982: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1983:            MatSetValuesLocal(), MatGetValues()
1984: @*/
1985: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1986: {

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

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

2027:   Not Collective

2029:   Input Parameters:
2030: + mat - the matrix
2031: . nb - the number of blocks
2032: . bs - the number of rows (and columns) in each block
2033: . rows - a concatenation of the rows for each block
2034: - v - a concatenation of logically two-dimensional arrays of values

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

2039:   Level: advanced

2041: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2042:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2043: @*/
2044: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2045: {

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

2055:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2056:   if (mat->ops->setvaluesbatch) {
2057:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2058:   } else {
2059:     PetscInt b;
2060:     for (b = 0; b < nb; ++b) {
2061:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2062:     }
2063:   }
2064:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2065:   return(0);
2066: }

2068: /*@
2069:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2070:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2071:    using a local (per-processor) numbering.

2073:    Not Collective

2075:    Input Parameters:
2076: +  x - the matrix
2077: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2078: - cmapping - column mapping

2080:    Level: intermediate


2083: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal(), MatGetValuesLocal()
2084: @*/
2085: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2086: {


2095:   if (x->ops->setlocaltoglobalmapping) {
2096:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2097:   } else {
2098:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2099:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2100:   }
2101:   return(0);
2102: }


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

2108:    Not Collective

2110:    Input Parameters:
2111: .  A - the matrix

2113:    Output Parameters:
2114: + rmapping - row mapping
2115: - cmapping - column mapping

2117:    Level: advanced


2120: .seealso:  MatSetValuesLocal()
2121: @*/
2122: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2123: {
2129:   if (rmapping) *rmapping = A->rmap->mapping;
2130:   if (cmapping) *cmapping = A->cmap->mapping;
2131:   return(0);
2132: }

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

2137:    Logically Collective on A

2139:    Input Parameters:
2140: +  A - the matrix
2141: . rmap - row layout
2142: - cmap - column layout

2144:    Level: advanced

2146: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatGetLayouts()
2147: @*/
2148: PetscErrorCode MatSetLayouts(Mat A,PetscLayout rmap,PetscLayout cmap)
2149: {


2155:   PetscLayoutReference(rmap,&A->rmap);
2156:   PetscLayoutReference(cmap,&A->cmap);
2157:   return(0);
2158: }

2160: /*@
2161:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2163:    Not Collective

2165:    Input Parameters:
2166: .  A - the matrix

2168:    Output Parameters:
2169: + rmap - row layout
2170: - cmap - column layout

2172:    Level: advanced

2174: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatSetLayouts()
2175: @*/
2176: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2177: {
2183:   if (rmap) *rmap = A->rmap;
2184:   if (cmap) *cmap = A->cmap;
2185:   return(0);
2186: }

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

2192:    Not Collective

2194:    Input Parameters:
2195: +  mat - the matrix
2196: .  nrow, irow - number of rows and their local indices
2197: .  ncol, icol - number of columns and their local indices
2198: .  y -  a logically two-dimensional array of values
2199: -  addv - either INSERT_VALUES or ADD_VALUES, where
2200:    ADD_VALUES adds values to any existing entries, and
2201:    INSERT_VALUES replaces existing entries with new values

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

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

2209:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2210:    options cannot be mixed without intervening calls to the assembly
2211:    routines.

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

2216:    Level: intermediate

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

2222: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2223:            MatSetValueLocal(), MatGetValuesLocal()
2224: @*/
2225: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2226: {

2232:   MatCheckPreallocated(mat,1);
2233:   if (!nrow || !ncol) return(0); /* no values to insert */
2236:   if (mat->insertmode == NOT_SET_VALUES) {
2237:     mat->insertmode = addv;
2238:   }
2239:   else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2240:   if (PetscDefined(USE_DEBUG)) {
2241:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2242:     if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2243:   }

2245:   if (mat->assembled) {
2246:     mat->was_assembled = PETSC_TRUE;
2247:     mat->assembled     = PETSC_FALSE;
2248:   }
2249:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2250:   if (mat->ops->setvalueslocal) {
2251:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2252:   } else {
2253:     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*irowm,*icolm;
2254:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2255:       irowm = buf; icolm = buf+nrow;
2256:     } else {
2257:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2258:       irowm = bufr; icolm = bufc;
2259:     }
2260:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2261:     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2262:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2263:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2264:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2265:     PetscFree2(bufr,bufc);
2266:   }
2267:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2268:   return(0);
2269: }

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

2275:    Not Collective

2277:    Input Parameters:
2278: +  x - the matrix
2279: .  nrow, irow - number of rows and their local indices
2280: .  ncol, icol - number of columns and their local indices
2281: .  y -  a logically two-dimensional array of values
2282: -  addv - either INSERT_VALUES or ADD_VALUES, where
2283:    ADD_VALUES adds values to any existing entries, and
2284:    INSERT_VALUES replaces existing entries with new values

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

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

2293:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2294:    options cannot be mixed without intervening calls to the assembly
2295:    routines.

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

2300:    Level: intermediate

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

2306: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2307:            MatSetValuesLocal(),  MatSetValuesBlocked()
2308: @*/
2309: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2310: {

2316:   MatCheckPreallocated(mat,1);
2317:   if (!nrow || !ncol) return(0); /* no values to insert */
2321:   if (mat->insertmode == NOT_SET_VALUES) {
2322:     mat->insertmode = addv;
2323:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2324:   if (PetscDefined(USE_DEBUG)) {
2325:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2326:     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);
2327:   }

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

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

2368:    Collective on Mat

2370:    Input Parameters:
2371: +  mat - the matrix
2372: -  x   - the vector to be multiplied

2374:    Output Parameters:
2375: .  y - the result

2377:    Notes:
2378:    The vectors x and y cannot be the same.  I.e., one cannot
2379:    call MatMult(A,y,y).

2381:    Level: developer

2383: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2384: @*/
2385: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2386: {


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

2400:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2401:   (*mat->ops->multdiagonalblock)(mat,x,y);
2402:   PetscObjectStateIncrease((PetscObject)y);
2403:   return(0);
2404: }

2406: /* --------------------------------------------------------*/
2407: /*@
2408:    MatMult - Computes the matrix-vector product, y = Ax.

2410:    Neighbor-wise Collective on Mat

2412:    Input Parameters:
2413: +  mat - the matrix
2414: -  x   - the vector to be multiplied

2416:    Output Parameters:
2417: .  y - the result

2419:    Notes:
2420:    The vectors x and y cannot be the same.  I.e., one cannot
2421:    call MatMult(A,y,y).

2423:    Level: beginner

2425: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2426: @*/
2427: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2428: {

2436:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2437:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2438:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2439: #if !defined(PETSC_HAVE_CONSTRAINTS)
2440:   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);
2441:   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);
2442:   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);
2443: #endif
2444:   VecSetErrorIfLocked(y,3);
2445:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2446:   MatCheckPreallocated(mat,1);

2448:   VecLockReadPush(x);
2449:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2450:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2451:   (*mat->ops->mult)(mat,x,y);
2452:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2453:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2454:   VecLockReadPop(x);
2455:   return(0);
2456: }

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

2461:    Neighbor-wise Collective on Mat

2463:    Input Parameters:
2464: +  mat - the matrix
2465: -  x   - the vector to be multiplied

2467:    Output Parameters:
2468: .  y - the result

2470:    Notes:
2471:    The vectors x and y cannot be the same.  I.e., one cannot
2472:    call MatMultTranspose(A,y,y).

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

2477:    Level: beginner

2479: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2480: @*/
2481: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2482: {
2483:   PetscErrorCode (*op)(Mat,Vec,Vec)=NULL,ierr;


2491:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2492:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2493:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2494: #if !defined(PETSC_HAVE_CONSTRAINTS)
2495:   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);
2496:   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);
2497: #endif
2498:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2499:   MatCheckPreallocated(mat,1);

2501:   if (!mat->ops->multtranspose) {
2502:     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
2503:     if (!op) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined or is symmetric and does not have a multiply defined",((PetscObject)mat)->type_name);
2504:   } else op = mat->ops->multtranspose;
2505:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2506:   VecLockReadPush(x);
2507:   (*op)(mat,x,y);
2508:   VecLockReadPop(x);
2509:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2510:   PetscObjectStateIncrease((PetscObject)y);
2511:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2512:   return(0);
2513: }

2515: /*@
2516:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2518:    Neighbor-wise Collective on Mat

2520:    Input Parameters:
2521: +  mat - the matrix
2522: -  x   - the vector to be multilplied

2524:    Output Parameters:
2525: .  y - the result

2527:    Notes:
2528:    The vectors x and y cannot be the same.  I.e., one cannot
2529:    call MatMultHermitianTranspose(A,y,y).

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

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

2535:    Level: beginner

2537: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2538: @*/
2539: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2540: {


2549:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2550:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2551:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2552: #if !defined(PETSC_HAVE_CONSTRAINTS)
2553:   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);
2554:   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);
2555: #endif
2556:   MatCheckPreallocated(mat,1);

2558:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2559: #if defined(PETSC_USE_COMPLEX)
2560:   if (mat->ops->multhermitiantranspose || (mat->hermitian && mat->ops->mult)) {
2561:     VecLockReadPush(x);
2562:     if (mat->ops->multhermitiantranspose) {
2563:       (*mat->ops->multhermitiantranspose)(mat,x,y);
2564:     } else {
2565:       (*mat->ops->mult)(mat,x,y);
2566:     }
2567:     VecLockReadPop(x);
2568:   } else {
2569:     Vec w;
2570:     VecDuplicate(x,&w);
2571:     VecCopy(x,w);
2572:     VecConjugate(w);
2573:     MatMultTranspose(mat,w,y);
2574:     VecDestroy(&w);
2575:     VecConjugate(y);
2576:   }
2577:   PetscObjectStateIncrease((PetscObject)y);
2578: #else
2579:   MatMultTranspose(mat,x,y);
2580: #endif
2581:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2582:   return(0);
2583: }

2585: /*@
2586:     MatMultAdd -  Computes v3 = v2 + A * v1.

2588:     Neighbor-wise Collective on Mat

2590:     Input Parameters:
2591: +   mat - the matrix
2592: -   v1, v2 - the vectors

2594:     Output Parameters:
2595: .   v3 - the result

2597:     Notes:
2598:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2599:     call MatMultAdd(A,v1,v2,v1).

2601:     Level: beginner

2603: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2604: @*/
2605: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2606: {


2616:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2617:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2618:   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);
2619:   /* 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);
2620:      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); */
2621:   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);
2622:   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);
2623:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2624:   MatCheckPreallocated(mat,1);

2626:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2627:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2628:   VecLockReadPush(v1);
2629:   (*mat->ops->multadd)(mat,v1,v2,v3);
2630:   VecLockReadPop(v1);
2631:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2632:   PetscObjectStateIncrease((PetscObject)v3);
2633:   return(0);
2634: }

2636: /*@
2637:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2639:    Neighbor-wise Collective on Mat

2641:    Input Parameters:
2642: +  mat - the matrix
2643: -  v1, v2 - the vectors

2645:    Output Parameters:
2646: .  v3 - the result

2648:    Notes:
2649:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2650:    call MatMultTransposeAdd(A,v1,v2,v1).

2652:    Level: beginner

2654: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2655: @*/
2656: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2657: {


2667:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2668:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2669:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2670:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2671:   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);
2672:   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);
2673:   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);
2674:   MatCheckPreallocated(mat,1);

2676:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2677:   VecLockReadPush(v1);
2678:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2679:   VecLockReadPop(v1);
2680:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2681:   PetscObjectStateIncrease((PetscObject)v3);
2682:   return(0);
2683: }

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

2688:    Neighbor-wise Collective on Mat

2690:    Input Parameters:
2691: +  mat - the matrix
2692: -  v1, v2 - the vectors

2694:    Output Parameters:
2695: .  v3 - the result

2697:    Notes:
2698:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2699:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2701:    Level: beginner

2703: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2704: @*/
2705: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2706: {


2716:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2717:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2718:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2719:   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);
2720:   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);
2721:   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);
2722:   MatCheckPreallocated(mat,1);

2724:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2725:   VecLockReadPush(v1);
2726:   if (mat->ops->multhermitiantransposeadd) {
2727:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2728:   } else {
2729:     Vec w,z;
2730:     VecDuplicate(v1,&w);
2731:     VecCopy(v1,w);
2732:     VecConjugate(w);
2733:     VecDuplicate(v3,&z);
2734:     MatMultTranspose(mat,w,z);
2735:     VecDestroy(&w);
2736:     VecConjugate(z);
2737:     if (v2 != v3) {
2738:       VecWAXPY(v3,1.0,v2,z);
2739:     } else {
2740:       VecAXPY(v3,1.0,z);
2741:     }
2742:     VecDestroy(&z);
2743:   }
2744:   VecLockReadPop(v1);
2745:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2746:   PetscObjectStateIncrease((PetscObject)v3);
2747:   return(0);
2748: }

2750: /*@
2751:    MatMultConstrained - The inner multiplication routine for a
2752:    constrained matrix P^T A P.

2754:    Neighbor-wise Collective on Mat

2756:    Input Parameters:
2757: +  mat - the matrix
2758: -  x   - the vector to be multilplied

2760:    Output Parameters:
2761: .  y - the result

2763:    Notes:
2764:    The vectors x and y cannot be the same.  I.e., one cannot
2765:    call MatMult(A,y,y).

2767:    Level: beginner

2769: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2770: @*/
2771: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2772: {

2779:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2780:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2781:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2782:   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);
2783:   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);
2784:   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);

2786:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2787:   VecLockReadPush(x);
2788:   (*mat->ops->multconstrained)(mat,x,y);
2789:   VecLockReadPop(x);
2790:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2791:   PetscObjectStateIncrease((PetscObject)y);
2792:   return(0);
2793: }

2795: /*@
2796:    MatMultTransposeConstrained - The inner multiplication routine for a
2797:    constrained matrix P^T A^T P.

2799:    Neighbor-wise Collective on Mat

2801:    Input Parameters:
2802: +  mat - the matrix
2803: -  x   - the vector to be multilplied

2805:    Output Parameters:
2806: .  y - the result

2808:    Notes:
2809:    The vectors x and y cannot be the same.  I.e., one cannot
2810:    call MatMult(A,y,y).

2812:    Level: beginner

2814: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2815: @*/
2816: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2817: {

2824:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2825:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2826:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2827:   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);
2828:   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);

2830:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2831:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2832:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2833:   PetscObjectStateIncrease((PetscObject)y);
2834:   return(0);
2835: }

2837: /*@C
2838:    MatGetFactorType - gets the type of factorization it is

2840:    Not Collective

2842:    Input Parameters:
2843: .  mat - the matrix

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

2848:    Level: intermediate

2850: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2851: @*/
2852: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2853: {
2858:   *t = mat->factortype;
2859:   return(0);
2860: }

2862: /*@C
2863:    MatSetFactorType - sets the type of factorization it is

2865:    Logically Collective on Mat

2867:    Input Parameters:
2868: +  mat - the matrix
2869: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2871:    Level: intermediate

2873: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2874: @*/
2875: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2876: {
2880:   mat->factortype = t;
2881:   return(0);
2882: }

2884: /* ------------------------------------------------------------*/
2885: /*@C
2886:    MatGetInfo - Returns information about matrix storage (number of
2887:    nonzeros, memory, etc.).

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

2891:    Input Parameters:
2892: .  mat - the matrix

2894:    Output Parameters:
2895: +  flag - flag indicating the type of parameters to be returned
2896:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2897:    MAT_GLOBAL_SUM - sum over all processors)
2898: -  info - matrix information context

2900:    Notes:
2901:    The MatInfo context contains a variety of matrix data, including
2902:    number of nonzeros allocated and used, number of mallocs during
2903:    matrix assembly, etc.  Additional information for factored matrices
2904:    is provided (such as the fill ratio, number of mallocs during
2905:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2906:    when using the runtime options
2907: $       -info -mat_view ::ascii_info

2909:    Example for C/C++ Users:
2910:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2911:    data within the MatInfo context.  For example,
2912: .vb
2913:       MatInfo info;
2914:       Mat     A;
2915:       double  mal, nz_a, nz_u;

2917:       MatGetInfo(A,MAT_LOCAL,&info);
2918:       mal  = info.mallocs;
2919:       nz_a = info.nz_allocated;
2920: .ve

2922:    Example for Fortran Users:
2923:    Fortran users should declare info as a double precision
2924:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2925:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2926:    a complete list of parameter names.
2927: .vb
2928:       double  precision info(MAT_INFO_SIZE)
2929:       double  precision mal, nz_a
2930:       Mat     A
2931:       integer ierr

2933:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2934:       mal = info(MAT_INFO_MALLOCS)
2935:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2936: .ve

2938:     Level: intermediate

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

2943: .seealso: MatStashGetInfo()

2945: @*/
2946: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2947: {

2954:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2955:   MatCheckPreallocated(mat,1);
2956:   (*mat->ops->getinfo)(mat,flag,info);
2957:   return(0);
2958: }

2960: /*
2961:    This is used by external packages where it is not easy to get the info from the actual
2962:    matrix factorization.
2963: */
2964: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2965: {

2969:   PetscMemzero(info,sizeof(MatInfo));
2970:   return(0);
2971: }

2973: /* ----------------------------------------------------------*/

2975: /*@C
2976:    MatLUFactor - Performs in-place LU factorization of matrix.

2978:    Collective on Mat

2980:    Input Parameters:
2981: +  mat - the matrix
2982: .  row - row permutation
2983: .  col - column permutation
2984: -  info - options for factorization, includes
2985: $          fill - expected fill as ratio of original fill.
2986: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2987: $                   Run with the option -info to determine an optimal value to use

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

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

2997:    Level: developer

2999: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
3000:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

3005: @*/
3006: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3007: {
3009:   MatFactorInfo  tinfo;

3017:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3018:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3019:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3020:   MatCheckPreallocated(mat,1);
3021:   if (!info) {
3022:     MatFactorInfoInitialize(&tinfo);
3023:     info = &tinfo;
3024:   }

3026:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
3027:   (*mat->ops->lufactor)(mat,row,col,info);
3028:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
3029:   PetscObjectStateIncrease((PetscObject)mat);
3030:   return(0);
3031: }

3033: /*@C
3034:    MatILUFactor - Performs in-place ILU factorization of matrix.

3036:    Collective on Mat

3038:    Input Parameters:
3039: +  mat - the matrix
3040: .  row - row permutation
3041: .  col - column permutation
3042: -  info - structure containing
3043: $      levels - number of levels of fill.
3044: $      expected fill - as ratio of original fill.
3045: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3046:                 missing diagonal entries)

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

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

3056:    Level: developer

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

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

3063: @*/
3064: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3065: {

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

3080:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3081:   (*mat->ops->ilufactor)(mat,row,col,info);
3082:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3083:   PetscObjectStateIncrease((PetscObject)mat);
3084:   return(0);
3085: }

3087: /*@C
3088:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3089:    Call this routine before calling MatLUFactorNumeric().

3091:    Collective on Mat

3093:    Input Parameters:
3094: +  fact - the factor matrix obtained with MatGetFactor()
3095: .  mat - the matrix
3096: .  row, col - row and column permutations
3097: -  info - options for factorization, includes
3098: $          fill - expected fill as ratio of original fill.
3099: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3100: $                   Run with the option -info to determine an optimal value to use


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

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

3110:    Level: developer

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

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

3117: @*/
3118: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3119: {
3121:   MatFactorInfo  tinfo;

3130:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3131:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3132:   if (!(fact)->ops->lufactorsymbolic) {
3133:     MatSolverType stype;
3134:     MatFactorGetSolverType(fact,&stype);
3135:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,stype);
3136:   }
3137:   MatCheckPreallocated(mat,2);
3138:   if (!info) {
3139:     MatFactorInfoInitialize(&tinfo);
3140:     info = &tinfo;
3141:   }

3143:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3144:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3145:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3146:   PetscObjectStateIncrease((PetscObject)fact);
3147:   return(0);
3148: }

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

3154:    Collective on Mat

3156:    Input Parameters:
3157: +  fact - the factor matrix obtained with MatGetFactor()
3158: .  mat - the matrix
3159: -  info - options for factorization

3161:    Notes:
3162:    See MatLUFactor() for in-place factorization.  See
3163:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3169:    Level: developer

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

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

3176: @*/
3177: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3178: {
3179:   MatFactorInfo  tinfo;

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

3190:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3191:   MatCheckPreallocated(mat,2);
3192:   if (!info) {
3193:     MatFactorInfoInitialize(&tinfo);
3194:     info = &tinfo;
3195:   }

3197:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3198:   (fact->ops->lufactornumeric)(fact,mat,info);
3199:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3200:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3201:   PetscObjectStateIncrease((PetscObject)fact);
3202:   return(0);
3203: }

3205: /*@C
3206:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3207:    symmetric matrix.

3209:    Collective on Mat

3211:    Input Parameters:
3212: +  mat - the matrix
3213: .  perm - row and column permutations
3214: -  f - expected fill as ratio of original fill

3216:    Notes:
3217:    See MatLUFactor() for the nonsymmetric case.  See also
3218:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3224:    Level: developer

3226: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3227:           MatGetOrdering()

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

3232: @*/
3233: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3234: {
3236:   MatFactorInfo  tinfo;

3243:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3244:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3245:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3246:   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);
3247:   MatCheckPreallocated(mat,1);
3248:   if (!info) {
3249:     MatFactorInfoInitialize(&tinfo);
3250:     info = &tinfo;
3251:   }

3253:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3254:   (*mat->ops->choleskyfactor)(mat,perm,info);
3255:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3256:   PetscObjectStateIncrease((PetscObject)mat);
3257:   return(0);
3258: }

3260: /*@C
3261:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3262:    of a symmetric matrix.

3264:    Collective on Mat

3266:    Input Parameters:
3267: +  fact - the factor matrix obtained with MatGetFactor()
3268: .  mat - the matrix
3269: .  perm - row and column permutations
3270: -  info - options for factorization, includes
3271: $          fill - expected fill as ratio of original fill.
3272: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3273: $                   Run with the option -info to determine an optimal value to use

3275:    Notes:
3276:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3277:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3283:    Level: developer

3285: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3286:           MatGetOrdering()

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

3291: @*/
3292: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3293: {
3295:   MatFactorInfo  tinfo;

3303:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3304:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3305:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3306:   if (!(fact)->ops->choleskyfactorsymbolic) {
3307:     MatSolverType stype;
3308:     MatFactorGetSolverType(fact,&stype);
3309:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,stype);
3310:   }
3311:   MatCheckPreallocated(mat,2);
3312:   if (!info) {
3313:     MatFactorInfoInitialize(&tinfo);
3314:     info = &tinfo;
3315:   }

3317:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3318:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3319:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3320:   PetscObjectStateIncrease((PetscObject)fact);
3321:   return(0);
3322: }

3324: /*@C
3325:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3326:    of a symmetric matrix. Call this routine after first calling
3327:    MatCholeskyFactorSymbolic().

3329:    Collective on Mat

3331:    Input Parameters:
3332: +  fact - the factor matrix obtained with MatGetFactor()
3333: .  mat - the initial matrix
3334: .  info - options for factorization
3335: -  fact - the symbolic factor of mat


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

3343:    Level: developer

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

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

3350: @*/
3351: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3352: {
3353:   MatFactorInfo  tinfo;

3361:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3362:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3363:   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);
3364:   MatCheckPreallocated(mat,2);
3365:   if (!info) {
3366:     MatFactorInfoInitialize(&tinfo);
3367:     info = &tinfo;
3368:   }

3370:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3371:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3372:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3373:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3374:   PetscObjectStateIncrease((PetscObject)fact);
3375:   return(0);
3376: }

3378: /*@C
3379:    MatQRFactor - Performs in-place QR factorization of matrix.

3381:    Collective on Mat

3383:    Input Parameters:
3384: +  mat - the matrix
3385: .  col - column permutation
3386: -  info - options for factorization, includes
3387: $          fill - expected fill as ratio of original fill.
3388: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3389: $                   Run with the option -info to determine an optimal value to use

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

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

3399:    Level: developer

3401: .seealso: MatQRFactorSymbolic(), MatQRFactorNumeric(), MatLUFactor(),
3402:           MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

3407: @*/
3408: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3409: {

3417:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3418:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3419:   MatCheckPreallocated(mat,1);
3420:   PetscLogEventBegin(MAT_QRFactor,mat,col,0,0);
3421:   PetscUseMethod(mat,"MatQRFactor_C", (Mat,IS,const MatFactorInfo*), (mat, col, info));
3422:   PetscLogEventEnd(MAT_QRFactor,mat,col,0,0);
3423:   PetscObjectStateIncrease((PetscObject)mat);
3424:   return(0);
3425: }

3427: /*@C
3428:    MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3429:    Call this routine before calling MatQRFactorNumeric().

3431:    Collective on Mat

3433:    Input Parameters:
3434: +  fact - the factor matrix obtained with MatGetFactor()
3435: .  mat - the matrix
3436: .  col - column permutation
3437: -  info - options for factorization, includes
3438: $          fill - expected fill as ratio of original fill.
3439: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3440: $                   Run with the option -info to determine an optimal value to use

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

3446:    Level: developer

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

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

3453: @*/
3454: PetscErrorCode MatQRFactorSymbolic(Mat fact,Mat mat,IS col,const MatFactorInfo *info)
3455: {
3457:   MatFactorInfo  tinfo;

3465:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3466:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3467:   MatCheckPreallocated(mat,2);
3468:   if (!info) {
3469:     MatFactorInfoInitialize(&tinfo);
3470:     info = &tinfo;
3471:   }

3473:   PetscLogEventBegin(MAT_QRFactorSymbolic,fact,mat,col,0);
3474:   PetscUseMethod(fact,"MatQRFactorSymbolic_C", (Mat,Mat,IS,const MatFactorInfo*), (fact, mat, col, info));
3475:   PetscLogEventEnd(MAT_QRFactorSymbolic,fact,mat,col,0);
3476:   PetscObjectStateIncrease((PetscObject)fact);
3477:   return(0);
3478: }

3480: /*@C
3481:    MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3482:    Call this routine after first calling MatQRFactorSymbolic().

3484:    Collective on Mat

3486:    Input Parameters:
3487: +  fact - the factor matrix obtained with MatGetFactor()
3488: .  mat - the matrix
3489: -  info - options for factorization

3491:    Notes:
3492:    See MatQRFactor() for in-place factorization.

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

3498:    Level: developer

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

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

3505: @*/
3506: PetscErrorCode MatQRFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3507: {
3508:   MatFactorInfo  tinfo;

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

3519:   MatCheckPreallocated(mat,2);
3520:   if (!info) {
3521:     MatFactorInfoInitialize(&tinfo);
3522:     info = &tinfo;
3523:   }

3525:   PetscLogEventBegin(MAT_QRFactorNumeric,mat,fact,0,0);
3526:   PetscUseMethod(fact,"MatQRFactorNumeric_C", (Mat,Mat,const MatFactorInfo*), (fact, mat, info));
3527:   PetscLogEventEnd(MAT_QRFactorNumeric,mat,fact,0,0);
3528:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3529:   PetscObjectStateIncrease((PetscObject)fact);
3530:   return(0);
3531: }

3533: /* ----------------------------------------------------------------*/
3534: /*@
3535:    MatSolve - Solves A x = b, given a factored matrix.

3537:    Neighbor-wise Collective on Mat

3539:    Input Parameters:
3540: +  mat - the factored matrix
3541: -  b - the right-hand-side vector

3543:    Output Parameter:
3544: .  x - the result vector

3546:    Notes:
3547:    The vectors b and x cannot be the same.  I.e., one cannot
3548:    call MatSolve(A,x,x).

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

3555:    Level: developer

3557: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3558: @*/
3559: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3560: {

3570:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3571:   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);
3572:   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);
3573:   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);
3574:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3575:   MatCheckPreallocated(mat,1);

3577:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3578:   if (mat->factorerrortype) {
3579:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3580:     VecSetInf(x);
3581:   } else {
3582:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3583:     (*mat->ops->solve)(mat,b,x);
3584:   }
3585:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3586:   PetscObjectStateIncrease((PetscObject)x);
3587:   return(0);
3588: }

3590: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3591: {
3593:   Vec            b,x;
3594:   PetscInt       m,N,i;
3595:   PetscScalar    *bb,*xx;
3596:   PetscErrorCode (*f)(Mat,Vec,Vec);

3599:   if (A->factorerrortype) {
3600:     PetscInfo1(A,"MatFactorError %D\n",A->factorerrortype);
3601:     MatSetInf(X);
3602:     return(0);
3603:   }
3604:   f = trans ? A->ops->solvetranspose : A->ops->solve;
3605:   if (!f) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);

3607:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3608:   MatDenseGetArray(X,&xx);
3609:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3610:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3611:   MatCreateVecs(A,&x,&b);
3612:   for (i=0; i<N; i++) {
3613:     VecPlaceArray(b,bb + i*m);
3614:     VecPlaceArray(x,xx + i*m);
3615:     (*f)(A,b,x);
3616:     VecResetArray(x);
3617:     VecResetArray(b);
3618:   }
3619:   VecDestroy(&b);
3620:   VecDestroy(&x);
3621:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3622:   MatDenseRestoreArray(X,&xx);
3623:   return(0);
3624: }

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

3629:    Neighbor-wise Collective on Mat

3631:    Input Parameters:
3632: +  A - the factored matrix
3633: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3635:    Output Parameter:
3636: .  X - the result matrix (dense matrix)

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

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

3648:    Level: developer

3650: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3651: @*/
3652: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3653: {

3663:   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);
3664:   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);
3665:   if (X->cmap->N != B->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3666:   if (!A->rmap->N && !A->cmap->N) return(0);
3667:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3668:   MatCheckPreallocated(A,1);

3670:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3671:   if (!A->ops->matsolve) {
3672:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3673:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3674:   } else {
3675:     (*A->ops->matsolve)(A,B,X);
3676:   }
3677:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3678:   PetscObjectStateIncrease((PetscObject)X);
3679:   return(0);
3680: }

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

3685:    Neighbor-wise Collective on Mat

3687:    Input Parameters:
3688: +  A - the factored matrix
3689: -  B - the right-hand-side matrix  (dense matrix)

3691:    Output Parameter:
3692: .  X - the result matrix (dense matrix)

3694:    Notes:
3695:    The matrices B and X cannot be the same.  I.e., one cannot
3696:    call MatMatSolveTranspose(A,X,X).

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

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

3706:    Level: developer

3708: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3709: @*/
3710: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3711: {

3721:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3722:   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);
3723:   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);
3724:   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);
3725:   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");
3726:   if (!A->rmap->N && !A->cmap->N) return(0);
3727:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3728:   MatCheckPreallocated(A,1);

3730:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3731:   if (!A->ops->matsolvetranspose) {
3732:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3733:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3734:   } else {
3735:     (*A->ops->matsolvetranspose)(A,B,X);
3736:   }
3737:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3738:   PetscObjectStateIncrease((PetscObject)X);
3739:   return(0);
3740: }

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

3745:    Neighbor-wise Collective on Mat

3747:    Input Parameters:
3748: +  A - the factored matrix
3749: -  Bt - the transpose of right-hand-side matrix

3751:    Output Parameter:
3752: .  X - the result matrix (dense matrix)

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

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

3762:    Level: developer

3764: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3765: @*/
3766: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3767: {


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

3786:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3787:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3788:   (*A->ops->mattransposesolve)(A,Bt,X);
3789:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3790:   PetscObjectStateIncrease((PetscObject)X);
3791:   return(0);
3792: }

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

3798:    Neighbor-wise Collective on Mat

3800:    Input Parameters:
3801: +  mat - the factored matrix
3802: -  b - the right-hand-side vector

3804:    Output Parameter:
3805: .  x - the result vector

3807:    Notes:
3808:    MatSolve() should be used for most applications, as it performs
3809:    a forward solve followed by a backward solve.

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

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

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

3824:    Level: developer

3826: .seealso: MatSolve(), MatBackwardSolve()
3827: @*/
3828: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3829: {

3839:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3840:   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);
3841:   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);
3842:   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);
3843:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3844:   MatCheckPreallocated(mat,1);

3846:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3847:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3848:   (*mat->ops->forwardsolve)(mat,b,x);
3849:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3850:   PetscObjectStateIncrease((PetscObject)x);
3851:   return(0);
3852: }

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

3858:    Neighbor-wise Collective on Mat

3860:    Input Parameters:
3861: +  mat - the factored matrix
3862: -  b - the right-hand-side vector

3864:    Output Parameter:
3865: .  x - the result vector

3867:    Notes:
3868:    MatSolve() should be used for most applications, as it performs
3869:    a forward solve followed by a backward solve.

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

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

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

3884:    Level: developer

3886: .seealso: MatSolve(), MatForwardSolve()
3887: @*/
3888: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3889: {

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

3906:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3907:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3908:   (*mat->ops->backwardsolve)(mat,b,x);
3909:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3910:   PetscObjectStateIncrease((PetscObject)x);
3911:   return(0);
3912: }

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

3917:    Neighbor-wise Collective on Mat

3919:    Input Parameters:
3920: +  mat - the factored matrix
3921: .  b - the right-hand-side vector
3922: -  y - the vector to be added to

3924:    Output Parameter:
3925: .  x - the result vector

3927:    Notes:
3928:    The vectors b and x cannot be the same.  I.e., one cannot
3929:    call MatSolveAdd(A,x,y,x).

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

3935:    Level: developer

3937: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3938: @*/
3939: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3940: {
3941:   PetscScalar    one = 1.0;
3942:   Vec            tmp;

3954:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3955:   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);
3956:   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);
3957:   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);
3958:   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);
3959:   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);
3960:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3961:    MatCheckPreallocated(mat,1);

3963:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3964:   if (mat->factorerrortype) {
3965:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3966:     VecSetInf(x);
3967:   } else if (mat->ops->solveadd) {
3968:     (*mat->ops->solveadd)(mat,b,y,x);
3969:   } else {
3970:     /* do the solve then the add manually */
3971:     if (x != y) {
3972:       MatSolve(mat,b,x);
3973:       VecAXPY(x,one,y);
3974:     } else {
3975:       VecDuplicate(x,&tmp);
3976:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3977:       VecCopy(x,tmp);
3978:       MatSolve(mat,b,x);
3979:       VecAXPY(x,one,tmp);
3980:       VecDestroy(&tmp);
3981:     }
3982:   }
3983:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3984:   PetscObjectStateIncrease((PetscObject)x);
3985:   return(0);
3986: }

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

3991:    Neighbor-wise Collective on Mat

3993:    Input Parameters:
3994: +  mat - the factored matrix
3995: -  b - the right-hand-side vector

3997:    Output Parameter:
3998: .  x - the result vector

4000:    Notes:
4001:    The vectors b and x cannot be the same.  I.e., one cannot
4002:    call MatSolveTranspose(A,x,x).

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

4008:    Level: developer

4010: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
4011: @*/
4012: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
4013: {

4023:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
4024:   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);
4025:   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);
4026:   if (!mat->rmap->N && !mat->cmap->N) return(0);
4027:   MatCheckPreallocated(mat,1);
4028:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
4029:   if (mat->factorerrortype) {
4030:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
4031:     VecSetInf(x);
4032:   } else {
4033:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
4034:     (*mat->ops->solvetranspose)(mat,b,x);
4035:   }
4036:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
4037:   PetscObjectStateIncrease((PetscObject)x);
4038:   return(0);
4039: }

4041: /*@
4042:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
4043:                       factored matrix.

4045:    Neighbor-wise Collective on Mat

4047:    Input Parameters:
4048: +  mat - the factored matrix
4049: .  b - the right-hand-side vector
4050: -  y - the vector to be added to

4052:    Output Parameter:
4053: .  x - the result vector

4055:    Notes:
4056:    The vectors b and x cannot be the same.  I.e., one cannot
4057:    call MatSolveTransposeAdd(A,x,y,x).

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

4063:    Level: developer

4065: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
4066: @*/
4067: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
4068: {
4069:   PetscScalar    one = 1.0;
4071:   Vec            tmp;

4082:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
4083:   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);
4084:   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);
4085:   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);
4086:   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);
4087:   if (!mat->rmap->N && !mat->cmap->N) return(0);
4088:    MatCheckPreallocated(mat,1);

4090:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
4091:   if (mat->factorerrortype) {
4092:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
4093:     VecSetInf(x);
4094:   } else if (mat->ops->solvetransposeadd){
4095:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
4096:   } else {
4097:     /* do the solve then the add manually */
4098:     if (x != y) {
4099:       MatSolveTranspose(mat,b,x);
4100:       VecAXPY(x,one,y);
4101:     } else {
4102:       VecDuplicate(x,&tmp);
4103:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
4104:       VecCopy(x,tmp);
4105:       MatSolveTranspose(mat,b,x);
4106:       VecAXPY(x,one,tmp);
4107:       VecDestroy(&tmp);
4108:     }
4109:   }
4110:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
4111:   PetscObjectStateIncrease((PetscObject)x);
4112:   return(0);
4113: }
4114: /* ----------------------------------------------------------------*/

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

4119:    Neighbor-wise Collective on Mat

4121:    Input Parameters:
4122: +  mat - the matrix
4123: .  b - the right hand side
4124: .  omega - the relaxation factor
4125: .  flag - flag indicating the type of SOR (see below)
4126: .  shift -  diagonal shift
4127: .  its - the number of iterations
4128: -  lits - the number of local iterations

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

4133:    SOR Flags:
4134: +     SOR_FORWARD_SWEEP - forward SOR
4135: .     SOR_BACKWARD_SWEEP - backward SOR
4136: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
4137: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
4138: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
4139: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
4140: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
4141:          upper/lower triangular part of matrix to
4142:          vector (with omega)
4143: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

4145:    Notes:
4146:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
4147:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
4148:    on each processor.

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

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

4156:    Notes for Advanced Users:
4157:    The flags are implemented as bitwise inclusive or operations.
4158:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
4159:    to specify a zero initial guess for SSOR.

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

4165:    Vectors x and b CANNOT be the same

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

4169:    Level: developer

4171: @*/
4172: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
4173: {

4183:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4184:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4185:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4186:   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);
4187:   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);
4188:   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);
4189:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
4190:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
4191:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

4193:   MatCheckPreallocated(mat,1);
4194:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
4195:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
4196:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
4197:   PetscObjectStateIncrease((PetscObject)x);
4198:   return(0);
4199: }

4201: /*
4202:       Default matrix copy routine.
4203: */
4204: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4205: {
4206:   PetscErrorCode    ierr;
4207:   PetscInt          i,rstart = 0,rend = 0,nz;
4208:   const PetscInt    *cwork;
4209:   const PetscScalar *vwork;

4212:   if (B->assembled) {
4213:     MatZeroEntries(B);
4214:   }
4215:   if (str == SAME_NONZERO_PATTERN) {
4216:     MatGetOwnershipRange(A,&rstart,&rend);
4217:     for (i=rstart; i<rend; i++) {
4218:       MatGetRow(A,i,&nz,&cwork,&vwork);
4219:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
4220:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
4221:     }
4222:   } else {
4223:     MatAYPX(B,0.0,A,str);
4224:   }
4225:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4226:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4227:   return(0);
4228: }

4230: /*@
4231:    MatCopy - Copies a matrix to another matrix.

4233:    Collective on Mat

4235:    Input Parameters:
4236: +  A - the matrix
4237: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4239:    Output Parameter:
4240: .  B - where the copy is put

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

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

4249:    Level: intermediate

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

4253: @*/
4254: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4255: {
4257:   PetscInt       i;

4265:   MatCheckPreallocated(B,2);
4266:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4267:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4268:   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);
4269:   MatCheckPreallocated(A,1);
4270:   if (A == B) return(0);

4272:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4273:   if (A->ops->copy) {
4274:     (*A->ops->copy)(A,B,str);
4275:   } else { /* generic conversion */
4276:     MatCopy_Basic(A,B,str);
4277:   }

4279:   B->stencil.dim = A->stencil.dim;
4280:   B->stencil.noc = A->stencil.noc;
4281:   for (i=0; i<=A->stencil.dim; i++) {
4282:     B->stencil.dims[i]   = A->stencil.dims[i];
4283:     B->stencil.starts[i] = A->stencil.starts[i];
4284:   }

4286:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4287:   PetscObjectStateIncrease((PetscObject)B);
4288:   return(0);
4289: }

4291: /*@C
4292:    MatConvert - Converts a matrix to another matrix, either of the same
4293:    or different type.

4295:    Collective on Mat

4297:    Input Parameters:
4298: +  mat - the matrix
4299: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4300:    same type as the original matrix.
4301: -  reuse - denotes if the destination matrix is to be created or reused.
4302:    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
4303:    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).

4305:    Output Parameter:
4306: .  M - pointer to place new matrix

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

4313:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4314:    the MPI communicator of the generated matrix is always the same as the communicator
4315:    of the input matrix.

4317:    Level: intermediate

4319: .seealso: MatCopy(), MatDuplicate()
4320: @*/
4321: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4322: {
4324:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4325:   char           convname[256],mtype[256];
4326:   Mat            B;

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

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

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

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

4349:   /* Cache Mat options because some converter use MatHeaderReplace  */
4350:   issymmetric = mat->symmetric;
4351:   ishermitian = mat->hermitian;

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

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

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

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

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

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

4437:     /* 5) Use a really basic converter. */
4438:     PetscInfo(mat,"Using MatConvert_Basic\n");
4439:     conv = MatConvert_Basic;

4441: foundconv:
4442:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4443:     (*conv)(mat,newtype,reuse,M);
4444:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4445:       /* the block sizes must be same if the mappings are copied over */
4446:       (*M)->rmap->bs = mat->rmap->bs;
4447:       (*M)->cmap->bs = mat->cmap->bs;
4448:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4449:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4450:       (*M)->rmap->mapping = mat->rmap->mapping;
4451:       (*M)->cmap->mapping = mat->cmap->mapping;
4452:     }
4453:     (*M)->stencil.dim = mat->stencil.dim;
4454:     (*M)->stencil.noc = mat->stencil.noc;
4455:     for (i=0; i<=mat->stencil.dim; i++) {
4456:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4457:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4458:     }
4459:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4460:   }
4461:   PetscObjectStateIncrease((PetscObject)*M);

4463:   /* Copy Mat options */
4464:   if (issymmetric) {
4465:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4466:   }
4467:   if (ishermitian) {
4468:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4469:   }
4470:   return(0);
4471: }

4473: /*@C
4474:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4476:    Not Collective

4478:    Input Parameter:
4479: .  mat - the matrix, must be a factored matrix

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

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

4488:    Level: intermediate

4490: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4491: @*/
4492: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4493: {
4494:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4499:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4500:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4501:   if (!conv) {
4502:     *type = MATSOLVERPETSC;
4503:   } else {
4504:     (*conv)(mat,type);
4505:   }
4506:   return(0);
4507: }

4509: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4510: struct _MatSolverTypeForSpecifcType {
4511:   MatType                        mtype;
4512:   PetscErrorCode                 (*createfactor[MAT_FACTOR_NUM_TYPES])(Mat,MatFactorType,Mat*);
4513:   MatSolverTypeForSpecifcType next;
4514: };

4516: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4517: struct _MatSolverTypeHolder {
4518:   char                        *name;
4519:   MatSolverTypeForSpecifcType handlers;
4520:   MatSolverTypeHolder         next;
4521: };

4523: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4528:    Input Parameters:
4529: +    package - name of the package, for example petsc or superlu
4530: .    mtype - the matrix type that works with this package
4531: .    ftype - the type of factorization supported by the package
4532: -    createfactor - routine that will create the factored matrix ready to be used

4534:     Level: intermediate

4536: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4537: @*/
4538: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*createfactor)(Mat,MatFactorType,Mat*))
4539: {
4540:   PetscErrorCode              ierr;
4541:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4542:   PetscBool                   flg;
4543:   MatSolverTypeForSpecifcType inext,iprev = NULL;

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

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

4588:    Input Parameters:
4589: +    type - name of the package, for example petsc or superlu
4590: .    ftype - the type of factorization supported by the type
4591: -    mtype - the matrix type that works with this type

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

4598:     Level: intermediate

4600: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatSolverTypeRegister(), MatGetFactor()
4601: @*/
4602: PetscErrorCode MatSolverTypeGet(MatSolverType type,MatType mtype,MatFactorType ftype,PetscBool *foundtype,PetscBool *foundmtype,PetscErrorCode (**createfactor)(Mat,MatFactorType,Mat*))
4603: {
4604:   PetscErrorCode              ierr;
4605:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4606:   PetscBool                   flg;
4607:   MatSolverTypeForSpecifcType inext;

4610:   if (foundtype) *foundtype = PETSC_FALSE;
4611:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4612:   if (createfactor) *createfactor    = NULL;

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

4667: PetscErrorCode MatSolverTypeDestroy(void)
4668: {
4669:   PetscErrorCode              ierr;
4670:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4671:   MatSolverTypeForSpecifcType inext,iprev;

4674:   while (next) {
4675:     PetscFree(next->name);
4676:     inext = next->handlers;
4677:     while (inext) {
4678:       PetscFree(inext->mtype);
4679:       iprev = inext;
4680:       inext = inext->next;
4681:       PetscFree(iprev);
4682:     }
4683:     prev = next;
4684:     next = next->next;
4685:     PetscFree(prev);
4686:   }
4687:   MatSolverTypeHolders = NULL;
4688:   return(0);
4689: }

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

4694:    Logically Collective on Mat

4696:    Input Parameters:
4697: .  mat - the matrix

4699:    Output Parameters:
4700: .  flg - PETSC_TRUE if uses the ordering

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

4706:    Level: developer

4708: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4709: @*/
4710: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4711: {
4713:   *flg = mat->canuseordering;
4714:   return(0);
4715: }

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

4720:    Logically Collective on Mat

4722:    Input Parameters:
4723: .  mat - the matrix

4725:    Output Parameters:
4726: .  otype - the preferred type

4728:    Level: developer

4730: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4731: @*/
4732: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4733: {
4735:   *otype = mat->preferredordering[ftype];
4736:   if (!*otype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatFactor did not have a preferred ordering");
4737:   return(0);
4738: }

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

4743:    Collective on Mat

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

4750:    Output Parameters:
4751: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4753:    Notes:
4754:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4755:      such as pastix, superlu, mumps etc.

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

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

4762:    Level: intermediate

4764: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetCanUseOrdering(), MatSolverTypeRegister()
4765: @*/
4766: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4767: {
4768:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4769:   PetscBool      foundtype,foundmtype;


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

4778:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundtype,&foundmtype,&conv);
4779:   if (!foundtype) {
4780:     if (type) {
4781:       SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver type %s for factorization type %s and matrix type %s. Perhaps you must ./configure with --download-%s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name,type);
4782:     } else {
4783:       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver type for factorization type %s and matrix type %s.",MatFactorTypes[ftype],((PetscObject)mat)->type_name);
4784:     }
4785:   }
4786:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4787:   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);

4789:   (*conv)(mat,ftype,f);
4790:   return(0);
4791: }

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

4796:    Not Collective

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

4803:    Output Parameter:
4804: .    flg - PETSC_TRUE if the factorization is available

4806:    Notes:
4807:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4808:      such as pastix, superlu, mumps etc.

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

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

4815:    Level: intermediate

4817: .seealso: MatCopy(), MatDuplicate(), MatGetFactor(), MatSolverTypeRegister()
4818: @*/
4819: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4820: {
4821:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4830:   *flg = PETSC_FALSE;
4831:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4832:   if (gconv) {
4833:     *flg = PETSC_TRUE;
4834:   }
4835:   return(0);
4836: }

4838: #include <petscdmtypes.h>

4840: /*@
4841:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4843:    Collective on Mat

4845:    Input Parameters:
4846: +  mat - the matrix
4847: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4848:         See the manual page for MatDuplicateOption for an explanation of these options.

4850:    Output Parameter:
4851: .  M - pointer to place new matrix

4853:    Level: intermediate

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

4859: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4860: @*/
4861: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4862: {
4864:   Mat            B;
4865:   PetscInt       i;
4866:   DM             dm;
4867:   void           (*viewf)(void);

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

4877:   *M = NULL;
4878:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4879:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4880:   (*mat->ops->duplicate)(mat,op,M);
4881:   B    = *M;

4883:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4884:   if (viewf) {
4885:     MatSetOperation(B,MATOP_VIEW,viewf);
4886:   }

4888:   B->stencil.dim = mat->stencil.dim;
4889:   B->stencil.noc = mat->stencil.noc;
4890:   for (i=0; i<=mat->stencil.dim; i++) {
4891:     B->stencil.dims[i]   = mat->stencil.dims[i];
4892:     B->stencil.starts[i] = mat->stencil.starts[i];
4893:   }

4895:   B->nooffproczerorows = mat->nooffproczerorows;
4896:   B->nooffprocentries  = mat->nooffprocentries;

4898:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4899:   if (dm) {
4900:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4901:   }
4902:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4903:   PetscObjectStateIncrease((PetscObject)B);
4904:   return(0);
4905: }

4907: /*@
4908:    MatGetDiagonal - Gets the diagonal of a matrix.

4910:    Logically Collective on Mat

4912:    Input Parameters:
4913: +  mat - the matrix
4914: -  v - the vector for storing the diagonal

4916:    Output Parameter:
4917: .  v - the diagonal of the matrix

4919:    Level: intermediate

4921:    Note:
4922:    Currently only correct in parallel for square matrices.

4924: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4925: @*/
4926: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4927: {

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

4938:   (*mat->ops->getdiagonal)(mat,v);
4939:   PetscObjectStateIncrease((PetscObject)v);
4940:   return(0);
4941: }

4943: /*@C
4944:    MatGetRowMin - Gets the minimum value (of the real part) of each
4945:         row of the matrix

4947:    Logically Collective on Mat

4949:    Input Parameters:
4950: .  mat - the matrix

4952:    Output Parameter:
4953: +  v - the vector for storing the maximums
4954: -  idx - the indices of the column found for each row (optional)

4956:    Level: intermediate

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

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

4964: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4965:           MatGetRowMax()
4966: @*/
4967: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4968: {

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

4977:   if (!mat->cmap->N) {
4978:     VecSet(v,PETSC_MAX_REAL);
4979:     if (idx) {
4980:       PetscInt i,m = mat->rmap->n;
4981:       for (i=0; i<m; i++) idx[i] = -1;
4982:     }
4983:   } else {
4984:     if (!mat->ops->getrowmin) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4985:     MatCheckPreallocated(mat,1);
4986:   }
4987:   (*mat->ops->getrowmin)(mat,v,idx);
4988:   PetscObjectStateIncrease((PetscObject)v);
4989:   return(0);
4990: }

4992: /*@C
4993:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4994:         row of the matrix

4996:    Logically Collective on Mat

4998:    Input Parameters:
4999: .  mat - the matrix

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

5005:    Level: intermediate

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

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

5013: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
5014: @*/
5015: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
5016: {

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

5026:   if (!mat->cmap->N) {
5027:     VecSet(v,0.0);
5028:     if (idx) {
5029:       PetscInt i,m = mat->rmap->n;
5030:       for (i=0; i<m; i++) idx[i] = -1;
5031:     }
5032:   } else {
5033:     if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5034:     MatCheckPreallocated(mat,1);
5035:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
5036:     (*mat->ops->getrowminabs)(mat,v,idx);
5037:   }
5038:   PetscObjectStateIncrease((PetscObject)v);
5039:   return(0);
5040: }

5042: /*@C
5043:    MatGetRowMax - Gets the maximum value (of the real part) of each
5044:         row of the matrix

5046:    Logically Collective on Mat

5048:    Input Parameters:
5049: .  mat - the matrix

5051:    Output Parameter:
5052: +  v - the vector for storing the maximums
5053: -  idx - the indices of the column found for each row (optional)

5055:    Level: intermediate

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

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

5063: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
5064: @*/
5065: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
5066: {

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

5075:   if (!mat->cmap->N) {
5076:     VecSet(v,PETSC_MIN_REAL);
5077:     if (idx) {
5078:       PetscInt i,m = mat->rmap->n;
5079:       for (i=0; i<m; i++) idx[i] = -1;
5080:     }
5081:   } else {
5082:     if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5083:     MatCheckPreallocated(mat,1);
5084:     (*mat->ops->getrowmax)(mat,v,idx);
5085:   }
5086:   PetscObjectStateIncrease((PetscObject)v);
5087:   return(0);
5088: }

5090: /*@C
5091:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5092:         row of the matrix

5094:    Logically Collective on Mat

5096:    Input Parameters:
5097: .  mat - the matrix

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

5103:    Level: intermediate

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

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

5111: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
5112: @*/
5113: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
5114: {

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

5123:   if (!mat->cmap->N) {
5124:     VecSet(v,0.0);
5125:     if (idx) {
5126:       PetscInt i,m = mat->rmap->n;
5127:       for (i=0; i<m; i++) idx[i] = -1;
5128:     }
5129:   } else {
5130:     if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5131:     MatCheckPreallocated(mat,1);
5132:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
5133:     (*mat->ops->getrowmaxabs)(mat,v,idx);
5134:   }
5135:   PetscObjectStateIncrease((PetscObject)v);
5136:   return(0);
5137: }

5139: /*@
5140:    MatGetRowSum - Gets the sum of each row of the matrix

5142:    Logically or Neighborhood Collective on Mat

5144:    Input Parameters:
5145: .  mat - the matrix

5147:    Output Parameter:
5148: .  v - the vector for storing the sum of rows

5150:    Level: intermediate

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

5155: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
5156: @*/
5157: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5158: {
5159:   Vec            ones;

5166:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5167:   MatCheckPreallocated(mat,1);
5168:   MatCreateVecs(mat,&ones,NULL);
5169:   VecSet(ones,1.);
5170:   MatMult(mat,ones,v);
5171:   VecDestroy(&ones);
5172:   return(0);
5173: }

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

5178:    Collective on Mat

5180:    Input Parameters:
5181: +  mat - the matrix to transpose
5182: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

5184:    Output Parameter:
5185: .  B - the transpose

5187:    Notes:
5188:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

5194:    Level: intermediate

5196: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5197: @*/
5198: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
5199: {

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

5212:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
5213:   (*mat->ops->transpose)(mat,reuse,B);
5214:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
5215:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
5216:   return(0);
5217: }

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

5223:    Collective on Mat

5225:    Input Parameter:
5226: +  A - the matrix to test
5227: -  B - the matrix to test against, this can equal the first parameter

5229:    Output Parameters:
5230: .  flg - the result

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

5237:    Level: intermediate

5239: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
5240: @*/
5241: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5242: {
5243:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

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

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

5271:    Collective on Mat

5273:    Input Parameters:
5274: +  mat - the matrix to transpose and complex conjugate
5275: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

5277:    Output Parameter:
5278: .  B - the Hermitian

5280:    Level: intermediate

5282: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5283: @*/
5284: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5285: {

5289:   MatTranspose(mat,reuse,B);
5290: #if defined(PETSC_USE_COMPLEX)
5291:   MatConjugate(*B);
5292: #endif
5293:   return(0);
5294: }

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

5299:    Collective on Mat

5301:    Input Parameter:
5302: +  A - the matrix to test
5303: -  B - the matrix to test against, this can equal the first parameter

5305:    Output Parameters:
5306: .  flg - the result

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

5313:    Level: intermediate

5315: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5316: @*/
5317: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5318: {
5319:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5325:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5326:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5327:   if (f && g) {
5328:     if (f==g) {
5329:       (*f)(A,B,tol,flg);
5330:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5331:   }
5332:   return(0);
5333: }

5335: /*@
5336:    MatPermute - Creates a new matrix with rows and columns permuted from the
5337:    original.

5339:    Collective on Mat

5341:    Input Parameters:
5342: +  mat - the matrix to permute
5343: .  row - row permutation, each processor supplies only the permutation for its rows
5344: -  col - column permutation, each processor supplies only the permutation for its columns

5346:    Output Parameters:
5347: .  B - the permuted matrix

5349:    Level: advanced

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

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

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

5362: @*/
5363: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5364: {

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

5380:   if (mat->ops->permute) {
5381:     (*mat->ops->permute)(mat,row,col,B);
5382:     PetscObjectStateIncrease((PetscObject)*B);
5383:   } else {
5384:     MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B);
5385:   }
5386:   return(0);
5387: }

5389: /*@
5390:    MatEqual - Compares two matrices.

5392:    Collective on Mat

5394:    Input Parameters:
5395: +  A - the first matrix
5396: -  B - the second matrix

5398:    Output Parameter:
5399: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5401:    Level: intermediate

5403: @*/
5404: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5405: {

5415:   MatCheckPreallocated(B,2);
5416:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5417:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5418:   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);
5419:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5420:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5421:   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);
5422:   MatCheckPreallocated(A,1);

5424:   (*A->ops->equal)(A,B,flg);
5425:   return(0);
5426: }

5428: /*@
5429:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5430:    matrices that are stored as vectors.  Either of the two scaling
5431:    matrices can be NULL.

5433:    Collective on Mat

5435:    Input Parameters:
5436: +  mat - the matrix to be scaled
5437: .  l - the left scaling vector (or NULL)
5438: -  r - the right scaling vector (or NULL)

5440:    Notes:
5441:    MatDiagonalScale() computes A = LAR, where
5442:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5443:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5445:    Level: intermediate


5448: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5449: @*/
5450: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5451: {

5459:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5460:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5461:   MatCheckPreallocated(mat,1);
5462:   if (!l && !r) return(0);

5464:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5465:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5466:   (*mat->ops->diagonalscale)(mat,l,r);
5467:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5468:   PetscObjectStateIncrease((PetscObject)mat);
5469:   return(0);
5470: }

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

5475:     Logically Collective on Mat

5477:     Input Parameters:
5478: +   mat - the matrix to be scaled
5479: -   a  - the scaling value

5481:     Output Parameter:
5482: .   mat - the scaled matrix

5484:     Level: intermediate

5486: .seealso: MatDiagonalScale()
5487: @*/
5488: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5489: {

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

5501:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5502:   if (a != (PetscScalar)1.0) {
5503:     (*mat->ops->scale)(mat,a);
5504:     PetscObjectStateIncrease((PetscObject)mat);
5505:   }
5506:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5507:   return(0);
5508: }

5510: /*@
5511:    MatNorm - Calculates various norms of a matrix.

5513:    Collective on Mat

5515:    Input Parameters:
5516: +  mat - the matrix
5517: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5519:    Output Parameters:
5520: .  nrm - the resulting norm

5522:    Level: intermediate

5524: @*/
5525: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5526: {


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

5539:   (*mat->ops->norm)(mat,type,nrm);
5540:   return(0);
5541: }

5543: /*
5544:      This variable is used to prevent counting of MatAssemblyBegin() that
5545:    are called from within a MatAssemblyEnd().
5546: */
5547: static PetscInt MatAssemblyEnd_InUse = 0;
5548: /*@
5549:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5550:    be called after completing all calls to MatSetValues().

5552:    Collective on Mat

5554:    Input Parameters:
5555: +  mat - the matrix
5556: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5558:    Notes:
5559:    MatSetValues() generally caches the values.  The matrix is ready to
5560:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5561:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5562:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5563:    using the matrix.

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

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

5573:    Level: beginner

5575: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5576: @*/
5577: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5578: {

5584:   MatCheckPreallocated(mat,1);
5585:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5586:   if (mat->assembled) {
5587:     mat->was_assembled = PETSC_TRUE;
5588:     mat->assembled     = PETSC_FALSE;
5589:   }

5591:   if (!MatAssemblyEnd_InUse) {
5592:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5593:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5594:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5595:   } else if (mat->ops->assemblybegin) {
5596:     (*mat->ops->assemblybegin)(mat,type);
5597:   }
5598:   return(0);
5599: }

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

5605:    Not Collective

5607:    Input Parameter:
5608: .  mat - the matrix

5610:    Output Parameter:
5611: .  assembled - PETSC_TRUE or PETSC_FALSE

5613:    Level: advanced

5615: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5616: @*/
5617: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5618: {
5622:   *assembled = mat->assembled;
5623:   return(0);
5624: }

5626: /*@
5627:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5628:    be called after MatAssemblyBegin().

5630:    Collective on Mat

5632:    Input Parameters:
5633: +  mat - the matrix
5634: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

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

5649:    Notes:
5650:    MatSetValues() generally caches the values.  The matrix is ready to
5651:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5652:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5653:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5654:    using the matrix.

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

5660:    Level: beginner

5662: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5663: @*/
5664: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5665: {
5666:   PetscErrorCode  ierr;
5667:   static PetscInt inassm = 0;
5668:   PetscBool       flg    = PETSC_FALSE;


5674:   inassm++;
5675:   MatAssemblyEnd_InUse++;
5676:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5677:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5678:     if (mat->ops->assemblyend) {
5679:       (*mat->ops->assemblyend)(mat,type);
5680:     }
5681:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5682:   } else if (mat->ops->assemblyend) {
5683:     (*mat->ops->assemblyend)(mat,type);
5684:   }

5686:   /* Flush assembly is not a true assembly */
5687:   if (type != MAT_FLUSH_ASSEMBLY) {
5688:     mat->num_ass++;
5689:     mat->assembled        = PETSC_TRUE;
5690:     mat->ass_nonzerostate = mat->nonzerostate;
5691:   }

5693:   mat->insertmode = NOT_SET_VALUES;
5694:   MatAssemblyEnd_InUse--;
5695:   PetscObjectStateIncrease((PetscObject)mat);
5696:   if (!mat->symmetric_eternal) {
5697:     mat->symmetric_set              = PETSC_FALSE;
5698:     mat->hermitian_set              = PETSC_FALSE;
5699:     mat->structurally_symmetric_set = PETSC_FALSE;
5700:   }
5701:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5702:     MatViewFromOptions(mat,NULL,"-mat_view");

5704:     if (mat->checksymmetryonassembly) {
5705:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5706:       if (flg) {
5707:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5708:       } else {
5709:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5710:       }
5711:     }
5712:     if (mat->nullsp && mat->checknullspaceonassembly) {
5713:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5714:     }
5715:   }
5716:   inassm--;
5717:   return(0);
5718: }

5720: /*@
5721:    MatSetOption - Sets a parameter option for a matrix. Some options
5722:    may be specific to certain storage formats.  Some options
5723:    determine how values will be inserted (or added). Sorted,
5724:    row-oriented input will generally assemble the fastest. The default
5725:    is row-oriented.

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

5729:    Input Parameters:
5730: +  mat - the matrix
5731: .  option - the option, one of those listed below (and possibly others),
5732: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

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


5748:    Options For Use with MatSetValues():
5749:    Insert a logically dense subblock, which can be
5750: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5804:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5805:    searches during matrix assembly. When this flag is set, the hash table
5806:    is created during the first Matrix Assembly. This hash table is
5807:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5808:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5809:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5810:    supported by MATMPIBAIJ format only.

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

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

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

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

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

5826:    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5827:                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5828:                      with finite difference schemes with non-periodic boundary conditions.

5830:    Level: intermediate

5832: .seealso:  MatOption, Mat

5834: @*/
5835: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5836: {

5841:   if (op > 0) {
5844:   }

5846:   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);

5848:   switch (op) {
5849:   case MAT_FORCE_DIAGONAL_ENTRIES:
5850:     mat->force_diagonals = flg;
5851:     return(0);
5852:   case MAT_NO_OFF_PROC_ENTRIES:
5853:     mat->nooffprocentries = flg;
5854:     return(0);
5855:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5856:     mat->assembly_subset = flg;
5857:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5858: #if !defined(PETSC_HAVE_MPIUNI)
5859:       MatStashScatterDestroy_BTS(&mat->stash);
5860: #endif
5861:       mat->stash.first_assembly_done = PETSC_FALSE;
5862:     }
5863:     return(0);
5864:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5865:     mat->nooffproczerorows = flg;
5866:     return(0);
5867:   case MAT_SPD:
5868:     mat->spd_set = PETSC_TRUE;
5869:     mat->spd     = flg;
5870:     if (flg) {
5871:       mat->symmetric                  = PETSC_TRUE;
5872:       mat->structurally_symmetric     = PETSC_TRUE;
5873:       mat->symmetric_set              = PETSC_TRUE;
5874:       mat->structurally_symmetric_set = PETSC_TRUE;
5875:     }
5876:     break;
5877:   case MAT_SYMMETRIC:
5878:     mat->symmetric = flg;
5879:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5880:     mat->symmetric_set              = PETSC_TRUE;
5881:     mat->structurally_symmetric_set = flg;
5882: #if !defined(PETSC_USE_COMPLEX)
5883:     mat->hermitian     = flg;
5884:     mat->hermitian_set = PETSC_TRUE;
5885: #endif
5886:     break;
5887:   case MAT_HERMITIAN:
5888:     mat->hermitian = flg;
5889:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5890:     mat->hermitian_set              = PETSC_TRUE;
5891:     mat->structurally_symmetric_set = flg;
5892: #if !defined(PETSC_USE_COMPLEX)
5893:     mat->symmetric     = flg;
5894:     mat->symmetric_set = PETSC_TRUE;
5895: #endif
5896:     break;
5897:   case MAT_STRUCTURALLY_SYMMETRIC:
5898:     mat->structurally_symmetric     = flg;
5899:     mat->structurally_symmetric_set = PETSC_TRUE;
5900:     break;
5901:   case MAT_SYMMETRY_ETERNAL:
5902:     mat->symmetric_eternal = flg;
5903:     break;
5904:   case MAT_STRUCTURE_ONLY:
5905:     mat->structure_only = flg;
5906:     break;
5907:   case MAT_SORTED_FULL:
5908:     mat->sortedfull = flg;
5909:     break;
5910:   default:
5911:     break;
5912:   }
5913:   if (mat->ops->setoption) {
5914:     (*mat->ops->setoption)(mat,op,flg);
5915:   }
5916:   return(0);
5917: }

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

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

5924:    Input Parameters:
5925: +  mat - the matrix
5926: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5934:    Level: intermediate

5936: .seealso:  MatOption, MatSetOption()

5938: @*/
5939: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5940: {

5945:   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);
5946:   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()");

5948:   switch (op) {
5949:   case MAT_NO_OFF_PROC_ENTRIES:
5950:     *flg = mat->nooffprocentries;
5951:     break;
5952:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5953:     *flg = mat->nooffproczerorows;
5954:     break;
5955:   case MAT_SYMMETRIC:
5956:     *flg = mat->symmetric;
5957:     break;
5958:   case MAT_HERMITIAN:
5959:     *flg = mat->hermitian;
5960:     break;
5961:   case MAT_STRUCTURALLY_SYMMETRIC:
5962:     *flg = mat->structurally_symmetric;
5963:     break;
5964:   case MAT_SYMMETRY_ETERNAL:
5965:     *flg = mat->symmetric_eternal;
5966:     break;
5967:   case MAT_SPD:
5968:     *flg = mat->spd;
5969:     break;
5970:   default:
5971:     break;
5972:   }
5973:   return(0);
5974: }

5976: /*@
5977:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5978:    this routine retains the old nonzero structure.

5980:    Logically Collective on Mat

5982:    Input Parameters:
5983: .  mat - the matrix

5985:    Level: intermediate

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

5991: .seealso: MatZeroRows()
5992: @*/
5993: PetscErrorCode MatZeroEntries(Mat mat)
5994: {

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

6005:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
6006:   (*mat->ops->zeroentries)(mat);
6007:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
6008:   PetscObjectStateIncrease((PetscObject)mat);
6009:   return(0);
6010: }

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

6016:    Collective on Mat

6018:    Input Parameters:
6019: +  mat - the matrix
6020: .  numRows - the number of rows to remove
6021: .  rows - the global row indices
6022: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6023: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6024: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

6043:    Level: intermediate

6045: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6046:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6047: @*/
6048: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6049: {

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

6061:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
6062:   MatViewFromOptions(mat,NULL,"-mat_view");
6063:   PetscObjectStateIncrease((PetscObject)mat);
6064:   return(0);
6065: }

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

6071:    Collective on Mat

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

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

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

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

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

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

6097:    Level: intermediate

6099: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6100:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
6101: @*/
6102: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6103: {
6105:   PetscInt       numRows;
6106:   const PetscInt *rows;

6113:   ISGetLocalSize(is,&numRows);
6114:   ISGetIndices(is,&rows);
6115:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
6116:   ISRestoreIndices(is,&rows);
6117:   return(0);
6118: }

6120: /*@
6121:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
6122:    of a set of rows of a matrix.

6124:    Collective on Mat

6126:    Input Parameters:
6127: +  mat - the matrix
6128: .  numRows - the number of rows to remove
6129: .  rows - the global row indices
6130: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6131: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6132: -  b - optional vector of right hand side, that will be adjusted by provided solution

6134:    Notes:
6135:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6136:    but does not release memory.  For the dense and block diagonal
6137:    formats this does not alter the nonzero structure.

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

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

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

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

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

6158:    Level: intermediate

6160: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6161:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6162: @*/
6163: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6164: {

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

6176:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
6177:   MatViewFromOptions(mat,NULL,"-mat_view");
6178:   PetscObjectStateIncrease((PetscObject)mat);
6179:   return(0);
6180: }

6182: /*@
6183:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6184:    of a set of rows of a matrix.

6186:    Collective on Mat

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

6195:    Notes:
6196:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6197:    but does not release memory.  For the dense and block diagonal
6198:    formats this does not alter the nonzero structure.

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

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

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

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

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

6219:    Level: intermediate

6221: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6222:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6223: @*/
6224: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6225: {
6226:   PetscInt       numRows;
6227:   const PetscInt *rows;

6234:   ISGetLocalSize(is,&numRows);
6235:   ISGetIndices(is,&rows);
6236:   MatZeroRows(mat,numRows,rows,diag,x,b);
6237:   ISRestoreIndices(is,&rows);
6238:   return(0);
6239: }

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

6245:    Collective on Mat

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

6255:    Notes:
6256:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6257:    but does not release memory.  For the dense and block diagonal
6258:    formats this does not alter the nonzero structure.

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

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

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

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

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

6278:    In Fortran idxm and idxn should be declared as
6279: $     MatStencil idxm(4,m)
6280:    and the values inserted using
6281: $    idxm(MatStencil_i,1) = i
6282: $    idxm(MatStencil_j,1) = j
6283: $    idxm(MatStencil_k,1) = k
6284: $    idxm(MatStencil_c,1) = c
6285:    etc

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

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

6295:    Level: intermediate

6297: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6298:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6299: @*/
6300: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6301: {
6302:   PetscInt       dim     = mat->stencil.dim;
6303:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6304:   PetscInt       *dims   = mat->stencil.dims+1;
6305:   PetscInt       *starts = mat->stencil.starts;
6306:   PetscInt       *dxm    = (PetscInt*) rows;
6307:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6315:   PetscMalloc1(numRows, &jdxm);
6316:   for (i = 0; i < numRows; ++i) {
6317:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6318:     for (j = 0; j < 3-sdim; ++j) dxm++;
6319:     /* Local index in X dir */
6320:     tmp = *dxm++ - starts[0];
6321:     /* Loop over remaining dimensions */
6322:     for (j = 0; j < dim-1; ++j) {
6323:       /* If nonlocal, set index to be negative */
6324:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6325:       /* Update local index */
6326:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6327:     }
6328:     /* Skip component slot if necessary */
6329:     if (mat->stencil.noc) dxm++;
6330:     /* Local row number */
6331:     if (tmp >= 0) {
6332:       jdxm[numNewRows++] = tmp;
6333:     }
6334:   }
6335:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6336:   PetscFree(jdxm);
6337:   return(0);
6338: }

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

6344:    Collective on Mat

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

6354:    Notes:
6355:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6356:    but does not release memory.  For the dense and block diagonal
6357:    formats this does not alter the nonzero structure.

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

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

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

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

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

6377:    In Fortran idxm and idxn should be declared as
6378: $     MatStencil idxm(4,m)
6379:    and the values inserted using
6380: $    idxm(MatStencil_i,1) = i
6381: $    idxm(MatStencil_j,1) = j
6382: $    idxm(MatStencil_k,1) = k
6383: $    idxm(MatStencil_c,1) = c
6384:    etc

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

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

6394:    Level: intermediate

6396: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6397:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6398: @*/
6399: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6400: {
6401:   PetscInt       dim     = mat->stencil.dim;
6402:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6403:   PetscInt       *dims   = mat->stencil.dims+1;
6404:   PetscInt       *starts = mat->stencil.starts;
6405:   PetscInt       *dxm    = (PetscInt*) rows;
6406:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6414:   PetscMalloc1(numRows, &jdxm);
6415:   for (i = 0; i < numRows; ++i) {
6416:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6417:     for (j = 0; j < 3-sdim; ++j) dxm++;
6418:     /* Local index in X dir */
6419:     tmp = *dxm++ - starts[0];
6420:     /* Loop over remaining dimensions */
6421:     for (j = 0; j < dim-1; ++j) {
6422:       /* If nonlocal, set index to be negative */
6423:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6424:       /* Update local index */
6425:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6426:     }
6427:     /* Skip component slot if necessary */
6428:     if (mat->stencil.noc) dxm++;
6429:     /* Local row number */
6430:     if (tmp >= 0) {
6431:       jdxm[numNewRows++] = tmp;
6432:     }
6433:   }
6434:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6435:   PetscFree(jdxm);
6436:   return(0);
6437: }

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

6443:    Collective on Mat

6445:    Input Parameters:
6446: +  mat - the matrix
6447: .  numRows - the number of rows to remove
6448: .  rows - the global row indices
6449: .  diag - value put in all diagonals of eliminated rows
6450: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6451: -  b - optional vector of right hand side, that will be adjusted by provided solution

6453:    Notes:
6454:    Before calling MatZeroRowsLocal(), the user must first set the
6455:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6457:    For the AIJ matrix formats this removes the old nonzero structure,
6458:    but does not release memory.  For the dense and block diagonal
6459:    formats this does not alter the nonzero structure.

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

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

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

6472:    Level: intermediate

6474: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6475:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6476: @*/
6477: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6478: {

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

6489:   if (mat->ops->zerorowslocal) {
6490:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6491:   } else {
6492:     IS             is, newis;
6493:     const PetscInt *newRows;

6495:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6496:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6497:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6498:     ISGetIndices(newis,&newRows);
6499:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6500:     ISRestoreIndices(newis,&newRows);
6501:     ISDestroy(&newis);
6502:     ISDestroy(&is);
6503:   }
6504:   PetscObjectStateIncrease((PetscObject)mat);
6505:   return(0);
6506: }

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

6512:    Collective on Mat

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

6521:    Notes:
6522:    Before calling MatZeroRowsLocalIS(), the user must first set the
6523:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6525:    For the AIJ matrix formats this removes the old nonzero structure,
6526:    but does not release memory.  For the dense and block diagonal
6527:    formats this does not alter the nonzero structure.

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

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

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

6540:    Level: intermediate

6542: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6543:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6544: @*/
6545: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6546: {
6548:   PetscInt       numRows;
6549:   const PetscInt *rows;

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

6559:   ISGetLocalSize(is,&numRows);
6560:   ISGetIndices(is,&rows);
6561:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6562:   ISRestoreIndices(is,&rows);
6563:   return(0);
6564: }

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

6570:    Collective on Mat

6572:    Input Parameters:
6573: +  mat - the matrix
6574: .  numRows - the number of rows to remove
6575: .  rows - the global row indices
6576: .  diag - value put in all diagonals of eliminated rows
6577: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6578: -  b - optional vector of right hand side, that will be adjusted by provided solution

6580:    Notes:
6581:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6582:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6588:    Level: intermediate

6590: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6591:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6592: @*/
6593: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6594: {
6596:   IS             is, newis;
6597:   const PetscInt *newRows;

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

6607:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6608:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6609:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6610:   ISGetIndices(newis,&newRows);
6611:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6612:   ISRestoreIndices(newis,&newRows);
6613:   ISDestroy(&newis);
6614:   ISDestroy(&is);
6615:   PetscObjectStateIncrease((PetscObject)mat);
6616:   return(0);
6617: }

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

6623:    Collective on Mat

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

6632:    Notes:
6633:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6634:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6640:    Level: intermediate

6642: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6643:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6644: @*/
6645: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6646: {
6648:   PetscInt       numRows;
6649:   const PetscInt *rows;

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

6659:   ISGetLocalSize(is,&numRows);
6660:   ISGetIndices(is,&rows);
6661:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6662:   ISRestoreIndices(is,&rows);
6663:   return(0);
6664: }

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

6669:    Not Collective

6671:    Input Parameter:
6672: .  mat - the matrix

6674:    Output Parameters:
6675: +  m - the number of global rows
6676: -  n - the number of global columns

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

6680:    Level: beginner

6682: .seealso: MatGetLocalSize()
6683: @*/
6684: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6685: {
6688:   if (m) *m = mat->rmap->N;
6689:   if (n) *n = mat->cmap->N;
6690:   return(0);
6691: }

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

6697:    Not Collective

6699:    Input Parameters:
6700: .  mat - the matrix

6702:    Output Parameters:
6703: +  m - the number of local rows
6704: -  n - the number of local columns

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

6708:    Level: beginner

6710: .seealso: MatGetSize()
6711: @*/
6712: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6713: {
6718:   if (m) *m = mat->rmap->n;
6719:   if (n) *n = mat->cmap->n;
6720:   return(0);
6721: }

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

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

6729:    Input Parameters:
6730: .  mat - the matrix

6732:    Output Parameters:
6733: +  m - the global index of the first local column
6734: -  n - one more than the global index of the last local column

6736:    Notes:
6737:     both output parameters can be NULL on input.

6739:    Level: developer

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

6743: @*/
6744: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6745: {
6751:   MatCheckPreallocated(mat,1);
6752:   if (m) *m = mat->cmap->rstart;
6753:   if (n) *n = mat->cmap->rend;
6754:   return(0);
6755: }

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

6763:    Not Collective

6765:    Input Parameters:
6766: .  mat - the matrix

6768:    Output Parameters:
6769: +  m - the global index of the first local row
6770: -  n - one more than the global index of the last local row

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

6777:    Level: beginner

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

6781: @*/
6782: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6783: {
6789:   MatCheckPreallocated(mat,1);
6790:   if (m) *m = mat->rmap->rstart;
6791:   if (n) *n = mat->rmap->rend;
6792:   return(0);
6793: }

6795: /*@C
6796:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6797:    each process

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

6801:    Input Parameters:
6802: .  mat - the matrix

6804:    Output Parameters:
6805: .  ranges - start of each processors portion plus one more than the total length at the end

6807:    Level: beginner

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

6811: @*/
6812: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6813: {

6819:   MatCheckPreallocated(mat,1);
6820:   PetscLayoutGetRanges(mat->rmap,ranges);
6821:   return(0);
6822: }

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

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

6830:    Input Parameters:
6831: .  mat - the matrix

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

6836:    Level: beginner

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

6840: @*/
6841: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6842: {

6848:   MatCheckPreallocated(mat,1);
6849:   PetscLayoutGetRanges(mat->cmap,ranges);
6850:   return(0);
6851: }

6853: /*@C
6854:    MatGetOwnershipIS - Get row and column ownership as index sets

6856:    Not Collective

6858:    Input Arguments:
6859: .  A - matrix of type Elemental or ScaLAPACK

6861:    Output Arguments:
6862: +  rows - rows in which this process owns elements
6863: -  cols - columns in which this process owns elements

6865:    Level: intermediate

6867: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6868: @*/
6869: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6870: {
6871:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6874:   MatCheckPreallocated(A,1);
6875:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6876:   if (f) {
6877:     (*f)(A,rows,cols);
6878:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6879:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6880:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6881:   }
6882:   return(0);
6883: }

6885: /*@C
6886:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6887:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6888:    to complete the factorization.

6890:    Collective on Mat

6892:    Input Parameters:
6893: +  mat - the matrix
6894: .  row - row permutation
6895: .  column - column permutation
6896: -  info - structure containing
6897: $      levels - number of levels of fill.
6898: $      expected fill - as ratio of original fill.
6899: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6900:                 missing diagonal entries)

6902:    Output Parameters:
6903: .  fact - new matrix that has been symbolically factored

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

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

6912:    Level: developer

6914: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6915:           MatGetOrdering(), MatFactorInfo

6917:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6922:    References:
6923:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6924: @*/
6925: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6926: {

6936:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6937:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6938:   if (!fact->ops->ilufactorsymbolic) {
6939:     MatSolverType stype;
6940:     MatFactorGetSolverType(fact,&stype);
6941:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver type %s",((PetscObject)mat)->type_name,stype);
6942:   }
6943:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6944:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6945:   MatCheckPreallocated(mat,2);

6947:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6948:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6949:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6950:   return(0);
6951: }

6953: /*@C
6954:    MatICCFactorSymbolic - Performs symbolic incomplete
6955:    Cholesky factorization for a symmetric matrix.  Use
6956:    MatCholeskyFactorNumeric() to complete the factorization.

6958:    Collective on Mat

6960:    Input Parameters:
6961: +  mat - the matrix
6962: .  perm - row and column permutation
6963: -  info - structure containing
6964: $      levels - number of levels of fill.
6965: $      expected fill - as ratio of original fill.

6967:    Output Parameter:
6968: .  fact - the factored matrix

6970:    Notes:
6971:    Most users should employ the KSP interface for linear solvers
6972:    instead of working directly with matrix algebra routines such as this.
6973:    See, e.g., KSPCreate().

6975:    Level: developer

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

6979:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6984:    References:
6985:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6986: @*/
6987: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6988: {

6997:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6998:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6999:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
7000:   if (!(fact)->ops->iccfactorsymbolic) {
7001:     MatSolverType stype;
7002:     MatFactorGetSolverType(fact,&stype);
7003:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver type %s",((PetscObject)mat)->type_name,stype);
7004:   }
7005:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7006:   MatCheckPreallocated(mat,2);

7008:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
7009:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
7010:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
7011:   return(0);
7012: }

7014: /*@C
7015:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7016:    points to an array of valid matrices, they may be reused to store the new
7017:    submatrices.

7019:    Collective on Mat

7021:    Input Parameters:
7022: +  mat - the matrix
7023: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
7024: .  irow, icol - index sets of rows and columns to extract
7025: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7027:    Output Parameter:
7028: .  submat - the array of submatrices

7030:    Notes:
7031:    MatCreateSubMatrices() can extract ONLY sequential submatrices
7032:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
7033:    to extract a parallel submatrix.

7035:    Some matrix types place restrictions on the row and column
7036:    indices, such as that they be sorted or that they be equal to each other.

7038:    The index sets may not have duplicate entries.

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

7044:    When finished using the submatrices, the user should destroy
7045:    them with MatDestroySubMatrices().

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

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

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

7058:    Fortran Note:
7059:    The Fortran interface is slightly different from that given below; it
7060:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

7062:    Level: advanced


7065: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
7066: @*/
7067: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
7068: {
7070:   PetscInt       i;
7071:   PetscBool      eq;

7076:   if (n) {
7081:   }
7083:   if (n && scall == MAT_REUSE_MATRIX) {
7086:   }
7087:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7088:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7089:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7090:   MatCheckPreallocated(mat,1);

7092:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
7093:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
7094:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
7095:   for (i=0; i<n; i++) {
7096:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
7097:     ISEqualUnsorted(irow[i],icol[i],&eq);
7098:     if (eq) {
7099:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
7100:     }
7101:   }
7102:   return(0);
7103: }

7105: /*@C
7106:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

7108:    Collective on Mat

7110:    Input Parameters:
7111: +  mat - the matrix
7112: .  n   - the number of submatrixes to be extracted
7113: .  irow, icol - index sets of rows and columns to extract
7114: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7116:    Output Parameter:
7117: .  submat - the array of submatrices

7119:    Level: advanced


7122: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
7123: @*/
7124: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
7125: {
7127:   PetscInt       i;
7128:   PetscBool      eq;

7133:   if (n) {
7138:   }
7140:   if (n && scall == MAT_REUSE_MATRIX) {
7143:   }
7144:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7145:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7146:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7147:   MatCheckPreallocated(mat,1);

7149:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
7150:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
7151:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
7152:   for (i=0; i<n; i++) {
7153:     ISEqualUnsorted(irow[i],icol[i],&eq);
7154:     if (eq) {
7155:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
7156:     }
7157:   }
7158:   return(0);
7159: }

7161: /*@C
7162:    MatDestroyMatrices - Destroys an array of matrices.

7164:    Collective on Mat

7166:    Input Parameters:
7167: +  n - the number of local matrices
7168: -  mat - the matrices (note that this is a pointer to the array of matrices)

7170:    Level: advanced

7172:     Notes:
7173:     Frees not only the matrices, but also the array that contains the matrices
7174:            In Fortran will not free the array.

7176: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
7177: @*/
7178: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
7179: {
7181:   PetscInt       i;

7184:   if (!*mat) return(0);
7185:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

7188:   for (i=0; i<n; i++) {
7189:     MatDestroy(&(*mat)[i]);
7190:   }

7192:   /* memory is allocated even if n = 0 */
7193:   PetscFree(*mat);
7194:   return(0);
7195: }

7197: /*@C
7198:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

7200:    Collective on Mat

7202:    Input Parameters:
7203: +  n - the number of local matrices
7204: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
7205:                        sequence of MatCreateSubMatrices())

7207:    Level: advanced

7209:     Notes:
7210:     Frees not only the matrices, but also the array that contains the matrices
7211:            In Fortran will not free the array.

7213: .seealso: MatCreateSubMatrices()
7214: @*/
7215: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
7216: {
7218:   Mat            mat0;

7221:   if (!*mat) return(0);
7222:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7223:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

7226:   mat0 = (*mat)[0];
7227:   if (mat0 && mat0->ops->destroysubmatrices) {
7228:     (mat0->ops->destroysubmatrices)(n,mat);
7229:   } else {
7230:     MatDestroyMatrices(n,mat);
7231:   }
7232:   return(0);
7233: }

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

7238:    Collective on Mat

7240:    Input Parameters:
7241: .  mat - the matrix

7243:    Output Parameter:
7244: .  matstruct - the sequential matrix with the nonzero structure of mat

7246:   Level: intermediate

7248: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7249: @*/
7250: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7251: {


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

7262:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7263:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7264:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
7265:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7266:   return(0);
7267: }

7269: /*@C
7270:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

7272:    Collective on Mat

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

7278:    Level: advanced

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

7283: .seealso: MatGetSeqNonzeroStructure()
7284: @*/
7285: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7286: {

7291:   MatDestroy(mat);
7292:   return(0);
7293: }

7295: /*@
7296:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7297:    replaces the index sets by larger ones that represent submatrices with
7298:    additional overlap.

7300:    Collective on Mat

7302:    Input Parameters:
7303: +  mat - the matrix
7304: .  n   - the number of index sets
7305: .  is  - the array of index sets (these index sets will changed during the call)
7306: -  ov  - the additional overlap requested

7308:    Options Database:
7309: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7311:    Level: developer


7314: .seealso: MatCreateSubMatrices()
7315: @*/
7316: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7317: {

7323:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7324:   if (n) {
7327:   }
7328:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7329:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7330:   MatCheckPreallocated(mat,1);

7332:   if (!ov) return(0);
7333:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7334:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7335:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7336:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7337:   return(0);
7338: }


7341: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7343: /*@
7344:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7345:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7346:    additional overlap.

7348:    Collective on Mat

7350:    Input Parameters:
7351: +  mat - the matrix
7352: .  n   - the number of index sets
7353: .  is  - the array of index sets (these index sets will changed during the call)
7354: -  ov  - the additional overlap requested

7356:    Options Database:
7357: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7359:    Level: developer


7362: .seealso: MatCreateSubMatrices()
7363: @*/
7364: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7365: {
7366:   PetscInt       i;

7372:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7373:   if (n) {
7376:   }
7377:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7378:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7379:   MatCheckPreallocated(mat,1);
7380:   if (!ov) return(0);
7381:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7382:   for (i=0; i<n; i++){
7383:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7384:   }
7385:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7386:   return(0);
7387: }




7392: /*@
7393:    MatGetBlockSize - Returns the matrix block size.

7395:    Not Collective

7397:    Input Parameter:
7398: .  mat - the matrix

7400:    Output Parameter:
7401: .  bs - block size

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

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

7408:    Level: intermediate

7410: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7411: @*/
7412: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7413: {
7417:   *bs = PetscAbs(mat->rmap->bs);
7418:   return(0);
7419: }

7421: /*@
7422:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7424:    Not Collective

7426:    Input Parameter:
7427: .  mat - the matrix

7429:    Output Parameter:
7430: +  rbs - row block size
7431: -  cbs - column block size

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

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

7439:    Level: intermediate

7441: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7442: @*/
7443: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7444: {
7449:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7450:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7451:   return(0);
7452: }

7454: /*@
7455:    MatSetBlockSize - Sets the matrix block size.

7457:    Logically Collective on Mat

7459:    Input Parameters:
7460: +  mat - the matrix
7461: -  bs - block size

7463:    Notes:
7464:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7465:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7467:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7468:     is compatible with the matrix local sizes.

7470:    Level: intermediate

7472: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7473: @*/
7474: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7475: {

7481:   MatSetBlockSizes(mat,bs,bs);
7482:   return(0);
7483: }

7485: /*@
7486:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7488:    Logically Collective on Mat

7490:    Input Parameters:
7491: +  mat - the matrix
7492: .  nblocks - the number of blocks on this process
7493: -  bsizes - the block sizes

7495:    Notes:
7496:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7498:    Level: intermediate

7500: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7501: @*/
7502: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7503: {
7505:   PetscInt       i,ncnt = 0, nlocal;

7509:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7510:   MatGetLocalSize(mat,&nlocal,NULL);
7511:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7512:   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);
7513:   PetscFree(mat->bsizes);
7514:   mat->nblocks = nblocks;
7515:   PetscMalloc1(nblocks,&mat->bsizes);
7516:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7517:   return(0);
7518: }

7520: /*@C
7521:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7523:    Logically Collective on Mat

7525:    Input Parameters:
7526: .  mat - the matrix

7528:    Output Parameters:
7529: +  nblocks - the number of blocks on this process
7530: -  bsizes - the block sizes

7532:    Notes: Currently not supported from Fortran

7534:    Level: intermediate

7536: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7537: @*/
7538: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7539: {
7542:   *nblocks = mat->nblocks;
7543:   *bsizes  = mat->bsizes;
7544:   return(0);
7545: }

7547: /*@
7548:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7550:    Logically Collective on Mat

7552:    Input Parameters:
7553: +  mat - the matrix
7554: .  rbs - row block size
7555: -  cbs - column block size

7557:    Notes:
7558:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7559:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7560:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7562:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7563:     are compatible with the matrix local sizes.

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

7567:    Level: intermediate

7569: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7570: @*/
7571: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7572: {

7579:   if (mat->ops->setblocksizes) {
7580:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7581:   }
7582:   if (mat->rmap->refcnt) {
7583:     ISLocalToGlobalMapping l2g = NULL;
7584:     PetscLayout            nmap = NULL;

7586:     PetscLayoutDuplicate(mat->rmap,&nmap);
7587:     if (mat->rmap->mapping) {
7588:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7589:     }
7590:     PetscLayoutDestroy(&mat->rmap);
7591:     mat->rmap = nmap;
7592:     mat->rmap->mapping = l2g;
7593:   }
7594:   if (mat->cmap->refcnt) {
7595:     ISLocalToGlobalMapping l2g = NULL;
7596:     PetscLayout            nmap = NULL;

7598:     PetscLayoutDuplicate(mat->cmap,&nmap);
7599:     if (mat->cmap->mapping) {
7600:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7601:     }
7602:     PetscLayoutDestroy(&mat->cmap);
7603:     mat->cmap = nmap;
7604:     mat->cmap->mapping = l2g;
7605:   }
7606:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7607:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7608:   return(0);
7609: }

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

7614:    Logically Collective on Mat

7616:    Input Parameters:
7617: +  mat - the matrix
7618: .  fromRow - matrix from which to copy row block size
7619: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7621:    Level: developer

7623: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7624: @*/
7625: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7626: {

7633:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7634:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7635:   return(0);
7636: }

7638: /*@
7639:    MatResidual - Default routine to calculate the residual.

7641:    Collective on Mat

7643:    Input Parameters:
7644: +  mat - the matrix
7645: .  b   - the right-hand-side
7646: -  x   - the approximate solution

7648:    Output Parameter:
7649: .  r - location to store the residual

7651:    Level: developer

7653: .seealso: PCMGSetResidual()
7654: @*/
7655: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7656: {

7665:   MatCheckPreallocated(mat,1);
7666:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7667:   if (!mat->ops->residual) {
7668:     MatMult(mat,x,r);
7669:     VecAYPX(r,-1.0,b);
7670:   } else {
7671:     (*mat->ops->residual)(mat,b,x,r);
7672:   }
7673:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7674:   return(0);
7675: }

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

7680:    Collective on Mat

7682:     Input Parameters:
7683: +   mat - the matrix
7684: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7685: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7686: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7687:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7688:                  always used.

7690:     Output Parameters:
7691: +   n - number of rows in the (possibly compressed) matrix
7692: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7693: .   ja - the column indices
7694: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7695:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7697:     Level: developer

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

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

7704:     Fortran Notes:
7705:     In Fortran use
7706: $
7707: $      PetscInt ia(1), ja(1)
7708: $      PetscOffset iia, jja
7709: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7710: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7712:      or
7713: $
7714: $    PetscInt, pointer :: ia(:),ja(:)
7715: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7716: $    ! Access the ith and jth entries via ia(i) and ja(j)

7718: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7719: @*/
7720: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7721: {

7731:   MatCheckPreallocated(mat,1);
7732:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7733:   else {
7734:     *done = PETSC_TRUE;
7735:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7736:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7737:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7738:   }
7739:   return(0);
7740: }

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

7745:     Collective on Mat

7747:     Input Parameters:
7748: +   mat - the matrix
7749: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7750: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7751:                 symmetrized
7752: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7753:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7754:                  always used.
7755: .   n - number of columns in the (possibly compressed) matrix
7756: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7757: -   ja - the row indices

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

7762:     Level: developer

7764: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7765: @*/
7766: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7767: {

7777:   MatCheckPreallocated(mat,1);
7778:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7779:   else {
7780:     *done = PETSC_TRUE;
7781:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7782:   }
7783:   return(0);
7784: }

7786: /*@C
7787:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7788:     MatGetRowIJ().

7790:     Collective on Mat

7792:     Input Parameters:
7793: +   mat - the matrix
7794: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7795: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7796:                 symmetrized
7797: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7798:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7799:                  always used.
7800: .   n - size of (possibly compressed) matrix
7801: .   ia - the row pointers
7802: -   ja - the column indices

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

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

7812:     Level: developer

7814: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7815: @*/
7816: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7817: {

7826:   MatCheckPreallocated(mat,1);

7828:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7829:   else {
7830:     *done = PETSC_TRUE;
7831:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7832:     if (n)  *n = 0;
7833:     if (ia) *ia = NULL;
7834:     if (ja) *ja = NULL;
7835:   }
7836:   return(0);
7837: }

7839: /*@C
7840:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7841:     MatGetColumnIJ().

7843:     Collective on Mat

7845:     Input Parameters:
7846: +   mat - the matrix
7847: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7848: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7849:                 symmetrized
7850: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7851:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7852:                  always used.

7854:     Output Parameters:
7855: +   n - size of (possibly compressed) matrix
7856: .   ia - the column pointers
7857: .   ja - the row indices
7858: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7860:     Level: developer

7862: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7863: @*/
7864: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7865: {

7874:   MatCheckPreallocated(mat,1);

7876:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7877:   else {
7878:     *done = PETSC_TRUE;
7879:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7880:     if (n)  *n = 0;
7881:     if (ia) *ia = NULL;
7882:     if (ja) *ja = NULL;
7883:   }
7884:   return(0);
7885: }

7887: /*@C
7888:     MatColoringPatch -Used inside matrix coloring routines that
7889:     use MatGetRowIJ() and/or MatGetColumnIJ().

7891:     Collective on Mat

7893:     Input Parameters:
7894: +   mat - the matrix
7895: .   ncolors - max color value
7896: .   n   - number of entries in colorarray
7897: -   colorarray - array indicating color for each column

7899:     Output Parameters:
7900: .   iscoloring - coloring generated using colorarray information

7902:     Level: developer

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

7906: @*/
7907: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7908: {

7916:   MatCheckPreallocated(mat,1);

7918:   if (!mat->ops->coloringpatch) {
7919:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7920:   } else {
7921:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7922:   }
7923:   return(0);
7924: }


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

7930:    Logically Collective on Mat

7932:    Input Parameter:
7933: .  mat - the factored matrix to be reset

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

7942:    Note that one can specify in-place ILU(0) factorization by calling
7943: .vb
7944:      PCType(pc,PCILU);
7945:      PCFactorSeUseInPlace(pc);
7946: .ve
7947:    or by using the options -pc_type ilu -pc_factor_in_place

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

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

7958:    Level: developer

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

7962: @*/
7963: PetscErrorCode MatSetUnfactored(Mat mat)
7964: {

7970:   MatCheckPreallocated(mat,1);
7971:   mat->factortype = MAT_FACTOR_NONE;
7972:   if (!mat->ops->setunfactored) return(0);
7973:   (*mat->ops->setunfactored)(mat);
7974:   return(0);
7975: }

7977: /*MC
7978:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7980:     Synopsis:
7981:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7983:     Not collective

7985:     Input Parameter:
7986: .   x - matrix

7988:     Output Parameters:
7989: +   xx_v - the Fortran90 pointer to the array
7990: -   ierr - error code

7992:     Example of Usage:
7993: .vb
7994:       PetscScalar, pointer xx_v(:,:)
7995:       ....
7996:       call MatDenseGetArrayF90(x,xx_v,ierr)
7997:       a = xx_v(3)
7998:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7999: .ve

8001:     Level: advanced

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

8005: M*/

8007: /*MC
8008:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
8009:     accessed with MatDenseGetArrayF90().

8011:     Synopsis:
8012:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

8014:     Not collective

8016:     Input Parameters:
8017: +   x - matrix
8018: -   xx_v - the Fortran90 pointer to the array

8020:     Output Parameter:
8021: .   ierr - error code

8023:     Example of Usage:
8024: .vb
8025:        PetscScalar, pointer xx_v(:,:)
8026:        ....
8027:        call MatDenseGetArrayF90(x,xx_v,ierr)
8028:        a = xx_v(3)
8029:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
8030: .ve

8032:     Level: advanced

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

8036: M*/


8039: /*MC
8040:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

8042:     Synopsis:
8043:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

8045:     Not collective

8047:     Input Parameter:
8048: .   x - matrix

8050:     Output Parameters:
8051: +   xx_v - the Fortran90 pointer to the array
8052: -   ierr - error code

8054:     Example of Usage:
8055: .vb
8056:       PetscScalar, pointer xx_v(:)
8057:       ....
8058:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8059:       a = xx_v(3)
8060:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8061: .ve

8063:     Level: advanced

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

8067: M*/

8069: /*MC
8070:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
8071:     accessed with MatSeqAIJGetArrayF90().

8073:     Synopsis:
8074:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

8076:     Not collective

8078:     Input Parameters:
8079: +   x - matrix
8080: -   xx_v - the Fortran90 pointer to the array

8082:     Output Parameter:
8083: .   ierr - error code

8085:     Example of Usage:
8086: .vb
8087:        PetscScalar, pointer xx_v(:)
8088:        ....
8089:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8090:        a = xx_v(3)
8091:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8092: .ve

8094:     Level: advanced

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

8098: M*/


8101: /*@
8102:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8103:                       as the original matrix.

8105:     Collective on Mat

8107:     Input Parameters:
8108: +   mat - the original matrix
8109: .   isrow - parallel IS containing the rows this processor should obtain
8110: .   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.
8111: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

8113:     Output Parameter:
8114: .   newmat - the new submatrix, of the same type as the old

8116:     Level: advanced

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

8121:     Some matrix types place restrictions on the row and column indices, such
8122:     as that they be sorted or that they be equal to each other.

8124:     The index sets may not have duplicate entries.

8126:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
8127:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
8128:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
8129:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
8130:    you are finished using it.

8132:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8133:     the input matrix.

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

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

8143: .vb
8144:             1  2  0  |  0  3  0  |  0  4
8145:     Proc0   0  5  6  |  7  0  0  |  8  0
8146:             9  0 10  | 11  0  0  | 12  0
8147:     -------------------------------------
8148:            13  0 14  | 15 16 17  |  0  0
8149:     Proc1   0 18  0  | 19 20 21  |  0  0
8150:             0  0  0  | 22 23  0  | 24  0
8151:     -------------------------------------
8152:     Proc2  25 26 27  |  0  0 28  | 29  0
8153:            30  0  0  | 31 32 33  |  0 34
8154: .ve

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

8158: .vb
8159:             2  0  |  0  3  0  |  0
8160:     Proc0   5  6  |  7  0  0  |  8
8161:     -------------------------------
8162:     Proc1  18  0  | 19 20 21  |  0
8163:     -------------------------------
8164:     Proc2  26 27  |  0  0 28  | 29
8165:             0  0  | 31 32 33  |  0
8166: .ve


8169: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
8170: @*/
8171: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
8172: {
8174:   PetscMPIInt    size;
8175:   Mat            *local;
8176:   IS             iscoltmp;
8177:   PetscBool      flg;

8186:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8187:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

8189:   MatCheckPreallocated(mat,1);
8190:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

8192:   if (!iscol || isrow == iscol) {
8193:     PetscBool   stride;
8194:     PetscMPIInt grabentirematrix = 0,grab;
8195:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
8196:     if (stride) {
8197:       PetscInt first,step,n,rstart,rend;
8198:       ISStrideGetInfo(isrow,&first,&step);
8199:       if (step == 1) {
8200:         MatGetOwnershipRange(mat,&rstart,&rend);
8201:         if (rstart == first) {
8202:           ISGetLocalSize(isrow,&n);
8203:           if (n == rend-rstart) {
8204:             grabentirematrix = 1;
8205:           }
8206:         }
8207:       }
8208:     }
8209:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
8210:     if (grab) {
8211:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
8212:       if (cll == MAT_INITIAL_MATRIX) {
8213:         *newmat = mat;
8214:         PetscObjectReference((PetscObject)mat);
8215:       }
8216:       return(0);
8217:     }
8218:   }

8220:   if (!iscol) {
8221:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
8222:   } else {
8223:     iscoltmp = iscol;
8224:   }

8226:   /* if original matrix is on just one processor then use submatrix generated */
8227:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8228:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
8229:     goto setproperties;
8230:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8231:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
8232:     *newmat = *local;
8233:     PetscFree(local);
8234:     goto setproperties;
8235:   } else if (!mat->ops->createsubmatrix) {
8236:     /* Create a new matrix type that implements the operation using the full matrix */
8237:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8238:     switch (cll) {
8239:     case MAT_INITIAL_MATRIX:
8240:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
8241:       break;
8242:     case MAT_REUSE_MATRIX:
8243:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
8244:       break;
8245:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8246:     }
8247:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8248:     goto setproperties;
8249:   }

8251:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8252:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8253:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
8254:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

8256: setproperties:
8257:   ISEqualUnsorted(isrow,iscoltmp,&flg);
8258:   if (flg) {
8259:     MatPropagateSymmetryOptions(mat,*newmat);
8260:   }
8261:   if (!iscol) {ISDestroy(&iscoltmp);}
8262:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
8263:   return(0);
8264: }

8266: /*@
8267:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8269:    Not Collective

8271:    Input Parameters:
8272: +  A - the matrix we wish to propagate options from
8273: -  B - the matrix we wish to propagate options to

8275:    Level: beginner

8277:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

8279: .seealso: MatSetOption()
8280: @*/
8281: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8282: {

8288:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
8289:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
8290:   }
8291:   if (A->structurally_symmetric_set) {
8292:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
8293:   }
8294:   if (A->hermitian_set) {
8295:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
8296:   }
8297:   if (A->spd_set) {
8298:     MatSetOption(B,MAT_SPD,A->spd);
8299:   }
8300:   if (A->symmetric_set) {
8301:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
8302:   }
8303:   return(0);
8304: }

8306: /*@
8307:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8308:    used during the assembly process to store values that belong to
8309:    other processors.

8311:    Not Collective

8313:    Input Parameters:
8314: +  mat   - the matrix
8315: .  size  - the initial size of the stash.
8316: -  bsize - the initial size of the block-stash(if used).

8318:    Options Database Keys:
8319: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8320: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

8322:    Level: intermediate

8324:    Notes:
8325:      The block-stash is used for values set with MatSetValuesBlocked() while
8326:      the stash is used for values set with MatSetValues()

8328:      Run with the option -info and look for output of the form
8329:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8330:      to determine the appropriate value, MM, to use for size and
8331:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8332:      to determine the value, BMM to use for bsize


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

8337: @*/
8338: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8339: {

8345:   MatStashSetInitialSize_Private(&mat->stash,size);
8346:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8347:   return(0);
8348: }

8350: /*@
8351:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8352:      the matrix

8354:    Neighbor-wise Collective on Mat

8356:    Input Parameters:
8357: +  mat   - the matrix
8358: .  x,y - the vectors
8359: -  w - where the result is stored

8361:    Level: intermediate

8363:    Notes:
8364:     w may be the same vector as y.

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

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

8371: @*/
8372: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8373: {
8375:   PetscInt       M,N,Ny;

8382:   MatGetSize(A,&M,&N);
8383:   VecGetSize(y,&Ny);
8384:   if (M == Ny) {
8385:     MatMultAdd(A,x,y,w);
8386:   } else {
8387:     MatMultTransposeAdd(A,x,y,w);
8388:   }
8389:   return(0);
8390: }

8392: /*@
8393:    MatInterpolate - y = A*x or A'*x depending on the shape of
8394:      the matrix

8396:    Neighbor-wise Collective on Mat

8398:    Input Parameters:
8399: +  mat   - the matrix
8400: -  x,y - the vectors

8402:    Level: intermediate

8404:    Notes:
8405:     This allows one to use either the restriction or interpolation (its transpose)
8406:     matrix to do the interpolation

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

8410: @*/
8411: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8412: {
8414:   PetscInt       M,N,Ny;

8420:   MatGetSize(A,&M,&N);
8421:   VecGetSize(y,&Ny);
8422:   if (M == Ny) {
8423:     MatMult(A,x,y);
8424:   } else {
8425:     MatMultTranspose(A,x,y);
8426:   }
8427:   return(0);
8428: }

8430: /*@
8431:    MatRestrict - y = A*x or A'*x

8433:    Neighbor-wise Collective on Mat

8435:    Input Parameters:
8436: +  mat   - the matrix
8437: -  x,y - the vectors

8439:    Level: intermediate

8441:    Notes:
8442:     This allows one to use either the restriction or interpolation (its transpose)
8443:     matrix to do the restriction

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

8447: @*/
8448: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8449: {
8451:   PetscInt       M,N,Ny;

8457:   MatGetSize(A,&M,&N);
8458:   VecGetSize(y,&Ny);
8459:   if (M == Ny) {
8460:     MatMult(A,x,y);
8461:   } else {
8462:     MatMultTranspose(A,x,y);
8463:   }
8464:   return(0);
8465: }

8467: /*@
8468:    MatMatInterpolateAdd - Y = W + A*X or W + A'*X

8470:    Neighbor-wise Collective on Mat

8472:    Input Parameters:
8473: +  mat   - the matrix
8474: -  w, x - the input dense matrices

8476:    Output Parameters:
8477: .  y - the output dense matrix

8479:    Level: intermediate

8481:    Notes:
8482:     This allows one to use either the restriction or interpolation (its transpose)
8483:     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
8484:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

8486: .seealso: MatInterpolateAdd(), MatMatInterpolate(), MatMatRestrict()

8488: @*/
8489: PetscErrorCode MatMatInterpolateAdd(Mat A,Mat x,Mat w,Mat *y)
8490: {
8492:   PetscInt       M,N,Mx,Nx,Mo,My = 0,Ny = 0;
8493:   PetscBool      trans = PETSC_TRUE;
8494:   MatReuse       reuse = MAT_INITIAL_MATRIX;

8502:   MatGetSize(A,&M,&N);
8503:   MatGetSize(x,&Mx,&Nx);
8504:   if (N == Mx) trans = PETSC_FALSE;
8505:   else if (M != Mx) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Size mismatch: A %Dx%D, X %Dx%D",M,N,Mx,Nx);
8506:   Mo = trans ? N : M;
8507:   if (*y) {
8508:     MatGetSize(*y,&My,&Ny);
8509:     if (Mo == My && Nx == Ny) { reuse = MAT_REUSE_MATRIX; }
8510:     else {
8511:       if (w && *y == w) SETERRQ6(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Cannot reuse y and w, size mismatch: A %Dx%D, X %Dx%D, Y %Dx%D",M,N,Mx,Nx,My,Ny);
8512:       MatDestroy(y);
8513:     }
8514:   }

8516:   if (w && *y == w) { /* this is to minimize changes in PCMG */
8517:     PetscBool flg;

8519:     PetscObjectQuery((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject*)&w);
8520:     if (w) {
8521:       PetscInt My,Ny,Mw,Nw;

8523:       PetscObjectTypeCompare((PetscObject)*y,((PetscObject)w)->type_name,&flg);
8524:       MatGetSize(*y,&My,&Ny);
8525:       MatGetSize(w,&Mw,&Nw);
8526:       if (!flg || My != Mw || Ny != Nw) w = NULL;
8527:     }
8528:     if (!w) {
8529:       MatDuplicate(*y,MAT_COPY_VALUES,&w);
8530:       PetscObjectCompose((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject)w);
8531:       PetscLogObjectParent((PetscObject)*y,(PetscObject)w);
8532:       PetscObjectDereference((PetscObject)w);
8533:     } else {
8534:       MatCopy(*y,w,UNKNOWN_NONZERO_PATTERN);
8535:     }
8536:   }
8537:   if (!trans) {
8538:     MatMatMult(A,x,reuse,PETSC_DEFAULT,y);
8539:   } else {
8540:     MatTransposeMatMult(A,x,reuse,PETSC_DEFAULT,y);
8541:   }
8542:   if (w) {
8543:     MatAXPY(*y,1.0,w,UNKNOWN_NONZERO_PATTERN);
8544:   }
8545:   return(0);
8546: }

8548: /*@
8549:    MatMatInterpolate - Y = A*X or A'*X

8551:    Neighbor-wise Collective on Mat

8553:    Input Parameters:
8554: +  mat   - the matrix
8555: -  x - the input dense matrix

8557:    Output Parameters:
8558: .  y - the output dense matrix


8561:    Level: intermediate

8563:    Notes:
8564:     This allows one to use either the restriction or interpolation (its transpose)
8565:     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
8566:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

8568: .seealso: MatInterpolate(), MatRestrict(), MatMatRestrict()

8570: @*/
8571: PetscErrorCode MatMatInterpolate(Mat A,Mat x,Mat *y)
8572: {

8576:   MatMatInterpolateAdd(A,x,NULL,y);
8577:   return(0);
8578: }

8580: /*@
8581:    MatMatRestrict - Y = A*X or A'*X

8583:    Neighbor-wise Collective on Mat

8585:    Input Parameters:
8586: +  mat   - the matrix
8587: -  x - the input dense matrix

8589:    Output Parameters:
8590: .  y - the output dense matrix


8593:    Level: intermediate

8595:    Notes:
8596:     This allows one to use either the restriction or interpolation (its transpose)
8597:     matrix to do the restriction. y matrix can be reused if already created with the proper sizes,
8598:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

8600: .seealso: MatRestrict(), MatInterpolate(), MatMatInterpolate()
8601: @*/
8602: PetscErrorCode MatMatRestrict(Mat A,Mat x,Mat *y)
8603: {

8607:   MatMatInterpolateAdd(A,x,NULL,y);
8608:   return(0);
8609: }

8611: /*@
8612:    MatGetNullSpace - retrieves the null space of a matrix.

8614:    Logically Collective on Mat

8616:    Input Parameters:
8617: +  mat - the matrix
8618: -  nullsp - the null space object

8620:    Level: developer

8622: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8623: @*/
8624: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8625: {
8629:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8630:   return(0);
8631: }

8633: /*@
8634:    MatSetNullSpace - attaches a null space to a matrix.

8636:    Logically Collective on Mat

8638:    Input Parameters:
8639: +  mat - the matrix
8640: -  nullsp - the null space object

8642:    Level: advanced

8644:    Notes:
8645:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8647:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8648:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8650:       You can remove the null space by calling this routine with an nullsp of NULL


8653:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8654:    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).
8655:    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
8656:    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
8657:    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).

8659:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8661:     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
8662:     routine also automatically calls MatSetTransposeNullSpace().

8664: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8665: @*/
8666: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8667: {

8673:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8674:   MatNullSpaceDestroy(&mat->nullsp);
8675:   mat->nullsp = nullsp;
8676:   if (mat->symmetric_set && mat->symmetric) {
8677:     MatSetTransposeNullSpace(mat,nullsp);
8678:   }
8679:   return(0);
8680: }

8682: /*@
8683:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8685:    Logically Collective on Mat

8687:    Input Parameters:
8688: +  mat - the matrix
8689: -  nullsp - the null space object

8691:    Level: developer

8693: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8694: @*/
8695: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8696: {
8701:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8702:   return(0);
8703: }

8705: /*@
8706:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8708:    Logically Collective on Mat

8710:    Input Parameters:
8711: +  mat - the matrix
8712: -  nullsp - the null space object

8714:    Level: advanced

8716:    Notes:
8717:       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.
8718:       You must also call MatSetNullSpace()


8721:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8722:    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).
8723:    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
8724:    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
8725:    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).

8727:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8729: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8730: @*/
8731: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8732: {

8738:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8739:   MatNullSpaceDestroy(&mat->transnullsp);
8740:   mat->transnullsp = nullsp;
8741:   return(0);
8742: }

8744: /*@
8745:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8746:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8748:    Logically Collective on Mat

8750:    Input Parameters:
8751: +  mat - the matrix
8752: -  nullsp - the null space object

8754:    Level: advanced

8756:    Notes:
8757:       Overwrites any previous near null space that may have been attached

8759:       You can remove the null space by calling this routine with an nullsp of NULL

8761: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8762: @*/
8763: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8764: {

8771:   MatCheckPreallocated(mat,1);
8772:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8773:   MatNullSpaceDestroy(&mat->nearnullsp);
8774:   mat->nearnullsp = nullsp;
8775:   return(0);
8776: }

8778: /*@
8779:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8781:    Not Collective

8783:    Input Parameter:
8784: .  mat - the matrix

8786:    Output Parameter:
8787: .  nullsp - the null space object, NULL if not set

8789:    Level: developer

8791: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8792: @*/
8793: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8794: {
8799:   MatCheckPreallocated(mat,1);
8800:   *nullsp = mat->nearnullsp;
8801:   return(0);
8802: }

8804: /*@C
8805:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8807:    Collective on Mat

8809:    Input Parameters:
8810: +  mat - the matrix
8811: .  row - row/column permutation
8812: .  fill - expected fill factor >= 1.0
8813: -  level - level of fill, for ICC(k)

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

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

8823:    Level: developer


8826: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8831: @*/
8832: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8833: {

8841:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8842:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8843:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8844:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8845:   MatCheckPreallocated(mat,1);
8846:   (*mat->ops->iccfactor)(mat,row,info);
8847:   PetscObjectStateIncrease((PetscObject)mat);
8848:   return(0);
8849: }

8851: /*@
8852:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8853:          ghosted ones.

8855:    Not Collective

8857:    Input Parameters:
8858: +  mat - the matrix
8859: -  diag = the diagonal values, including ghost ones

8861:    Level: developer

8863:    Notes:
8864:     Works only for MPIAIJ and MPIBAIJ matrices

8866: .seealso: MatDiagonalScale()
8867: @*/
8868: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8869: {
8871:   PetscMPIInt    size;


8878:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8879:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8880:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8881:   if (size == 1) {
8882:     PetscInt n,m;
8883:     VecGetSize(diag,&n);
8884:     MatGetSize(mat,NULL,&m);
8885:     if (m == n) {
8886:       MatDiagonalScale(mat,NULL,diag);
8887:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8888:   } else {
8889:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8890:   }
8891:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8892:   PetscObjectStateIncrease((PetscObject)mat);
8893:   return(0);
8894: }

8896: /*@
8897:    MatGetInertia - Gets the inertia from a factored matrix

8899:    Collective on Mat

8901:    Input Parameter:
8902: .  mat - the matrix

8904:    Output Parameters:
8905: +   nneg - number of negative eigenvalues
8906: .   nzero - number of zero eigenvalues
8907: -   npos - number of positive eigenvalues

8909:    Level: advanced

8911:    Notes:
8912:     Matrix must have been factored by MatCholeskyFactor()


8915: @*/
8916: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8917: {

8923:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8924:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8925:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8926:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8927:   return(0);
8928: }

8930: /* ----------------------------------------------------------------*/
8931: /*@C
8932:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8934:    Neighbor-wise Collective on Mats

8936:    Input Parameters:
8937: +  mat - the factored matrix
8938: -  b - the right-hand-side vectors

8940:    Output Parameter:
8941: .  x - the result vectors

8943:    Notes:
8944:    The vectors b and x cannot be the same.  I.e., one cannot
8945:    call MatSolves(A,x,x).

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

8952:    Level: developer

8954: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8955: @*/
8956: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8957: {

8963:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8964:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8965:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8967:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8968:   MatCheckPreallocated(mat,1);
8969:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8970:   (*mat->ops->solves)(mat,b,x);
8971:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8972:   return(0);
8973: }

8975: /*@
8976:    MatIsSymmetric - Test whether a matrix is symmetric

8978:    Collective on Mat

8980:    Input Parameter:
8981: +  A - the matrix to test
8982: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8984:    Output Parameters:
8985: .  flg - the result

8987:    Notes:
8988:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8990:    Level: intermediate

8992: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8993: @*/
8994: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8995: {


9002:   if (!A->symmetric_set) {
9003:     if (!A->ops->issymmetric) {
9004:       MatType mattype;
9005:       MatGetType(A,&mattype);
9006:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
9007:     }
9008:     (*A->ops->issymmetric)(A,tol,flg);
9009:     if (!tol) {
9010:       MatSetOption(A,MAT_SYMMETRIC,*flg);
9011:     }
9012:   } else if (A->symmetric) {
9013:     *flg = PETSC_TRUE;
9014:   } else if (!tol) {
9015:     *flg = PETSC_FALSE;
9016:   } else {
9017:     if (!A->ops->issymmetric) {
9018:       MatType mattype;
9019:       MatGetType(A,&mattype);
9020:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
9021:     }
9022:     (*A->ops->issymmetric)(A,tol,flg);
9023:   }
9024:   return(0);
9025: }

9027: /*@
9028:    MatIsHermitian - Test whether a matrix is Hermitian

9030:    Collective on Mat

9032:    Input Parameter:
9033: +  A - the matrix to test
9034: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9036:    Output Parameters:
9037: .  flg - the result

9039:    Level: intermediate

9041: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
9042:           MatIsSymmetricKnown(), MatIsSymmetric()
9043: @*/
9044: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
9045: {


9052:   if (!A->hermitian_set) {
9053:     if (!A->ops->ishermitian) {
9054:       MatType mattype;
9055:       MatGetType(A,&mattype);
9056:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
9057:     }
9058:     (*A->ops->ishermitian)(A,tol,flg);
9059:     if (!tol) {
9060:       MatSetOption(A,MAT_HERMITIAN,*flg);
9061:     }
9062:   } else if (A->hermitian) {
9063:     *flg = PETSC_TRUE;
9064:   } else if (!tol) {
9065:     *flg = PETSC_FALSE;
9066:   } else {
9067:     if (!A->ops->ishermitian) {
9068:       MatType mattype;
9069:       MatGetType(A,&mattype);
9070:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
9071:     }
9072:     (*A->ops->ishermitian)(A,tol,flg);
9073:   }
9074:   return(0);
9075: }

9077: /*@
9078:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

9080:    Not Collective

9082:    Input Parameter:
9083: .  A - the matrix to check

9085:    Output Parameters:
9086: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
9087: -  flg - the result

9089:    Level: advanced

9091:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
9092:          if you want it explicitly checked

9094: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
9095: @*/
9096: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
9097: {
9102:   if (A->symmetric_set) {
9103:     *set = PETSC_TRUE;
9104:     *flg = A->symmetric;
9105:   } else {
9106:     *set = PETSC_FALSE;
9107:   }
9108:   return(0);
9109: }

9111: /*@
9112:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

9114:    Not Collective

9116:    Input Parameter:
9117: .  A - the matrix to check

9119:    Output Parameters:
9120: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
9121: -  flg - the result

9123:    Level: advanced

9125:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
9126:          if you want it explicitly checked

9128: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
9129: @*/
9130: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
9131: {
9136:   if (A->hermitian_set) {
9137:     *set = PETSC_TRUE;
9138:     *flg = A->hermitian;
9139:   } else {
9140:     *set = PETSC_FALSE;
9141:   }
9142:   return(0);
9143: }

9145: /*@
9146:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9148:    Collective on Mat

9150:    Input Parameter:
9151: .  A - the matrix to test

9153:    Output Parameters:
9154: .  flg - the result

9156:    Level: intermediate

9158: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
9159: @*/
9160: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
9161: {

9167:   if (!A->structurally_symmetric_set) {
9168:     if (!A->ops->isstructurallysymmetric) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type %s does not support checking for structural symmetric",((PetscObject)A)->type_name);
9169:     (*A->ops->isstructurallysymmetric)(A,flg);
9170:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
9171:   } else *flg = A->structurally_symmetric;
9172:   return(0);
9173: }

9175: /*@
9176:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9177:        to be communicated to other processors during the MatAssemblyBegin/End() process

9179:     Not collective

9181:    Input Parameter:
9182: .   vec - the vector

9184:    Output Parameters:
9185: +   nstash   - the size of the stash
9186: .   reallocs - the number of additional mallocs incurred.
9187: .   bnstash   - the size of the block stash
9188: -   breallocs - the number of additional mallocs incurred.in the block stash

9190:    Level: advanced

9192: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

9194: @*/
9195: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
9196: {

9200:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
9201:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
9202:   return(0);
9203: }

9205: /*@C
9206:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9207:      parallel layout

9209:    Collective on Mat

9211:    Input Parameter:
9212: .  mat - the matrix

9214:    Output Parameter:
9215: +   right - (optional) vector that the matrix can be multiplied against
9216: -   left - (optional) vector that the matrix vector product can be stored in

9218:    Notes:
9219:     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().

9221:   Notes:
9222:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

9224:   Level: advanced

9226: .seealso: MatCreate(), VecDestroy()
9227: @*/
9228: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
9229: {

9235:   if (mat->ops->getvecs) {
9236:     (*mat->ops->getvecs)(mat,right,left);
9237:   } else {
9238:     PetscInt rbs,cbs;
9239:     MatGetBlockSizes(mat,&rbs,&cbs);
9240:     if (right) {
9241:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
9242:       VecCreate(PetscObjectComm((PetscObject)mat),right);
9243:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
9244:       VecSetBlockSize(*right,cbs);
9245:       VecSetType(*right,mat->defaultvectype);
9246:       PetscLayoutReference(mat->cmap,&(*right)->map);
9247:     }
9248:     if (left) {
9249:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
9250:       VecCreate(PetscObjectComm((PetscObject)mat),left);
9251:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
9252:       VecSetBlockSize(*left,rbs);
9253:       VecSetType(*left,mat->defaultvectype);
9254:       PetscLayoutReference(mat->rmap,&(*left)->map);
9255:     }
9256:   }
9257:   return(0);
9258: }

9260: /*@C
9261:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
9262:      with default values.

9264:    Not Collective