Actual source code: matrix.c

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

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

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

 49:    Logically Collective on Mat

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

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

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

 66:    Level: intermediate


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


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

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

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

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

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

104:    Logically Collective on Mat

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

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

114:    Level: advanced

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

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

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

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

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

137:    Logically Collective on Mat

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

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

145:    Level: advanced

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

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

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

163:    Logically Collective on Mat

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

168:    Level: developer

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

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

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

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

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

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

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

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

243:   Level: intermediate

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

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

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

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

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

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

276:   Level: intermediate

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


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

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

305:    Not Collective

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

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

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

318:    Level: advanced

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

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

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

345:    Collective on Mat

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

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

353:    Level: advanced

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

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

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

372:    Logically Collective on Mat

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

377:    Level: advanced


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

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

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

400:    Collective on Mat

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

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

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

412:    Level: advanced

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

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


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

437:    Logically Collective on Mat

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

442:    Level: advanced


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

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

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

465:    Not Collective

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

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

474:    Level: advanced


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

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

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

499:    Not Collective

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

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

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

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

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

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

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

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


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

549:    Level: advanced

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

561:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
562:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
563:   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
564:   MatCheckPreallocated(mat,1);
565:   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);
566:   PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
567:   (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
568:   if (ncols) *ncols = incols;
569:   PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
570:   return(0);
571: }

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

576:    Logically Collective on Mat

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

581:    Level: advanced

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

592:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
593:   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);
594:   (*mat->ops->conjugate)(mat);
595: #else
597: #endif
598:   return(0);
599: }

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

604:    Not Collective

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

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

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

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

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

634:    Level: advanced

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

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

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

658:    Not Collective

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

663:    Notes:
664:    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.

666:    Level: advanced

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

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

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

688:    Not Collective

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

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


697:    Level: advanced

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

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

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

720:    Logically Collective on Mat

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

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

730:    Level: advanced

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

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

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

748:    Logically Collective on Mat

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

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

758:    Level: advanced

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

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

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

776:    Not Collective

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

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

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

788:    Level: advanced

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

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

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

805:    Collective on Mat

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

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

814:    Level: beginner

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

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


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

833:    Collective on Mat

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

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

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

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

845:    Level: beginner

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

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

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

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

881:    Collective on Mat

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

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

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

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

904:    Collective on Mat

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1098:    Collective on PetscViewer

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

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

1110:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1195:    Corresponding MatView() is not yet implemented.

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

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

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

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


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

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

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

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

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

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

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

1275:    Collective on Mat

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

1280:    Level: beginner

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

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

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

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

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

1318:    Not Collective

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

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

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

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

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

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

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

1351:    Level: beginner

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

1357: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1358:           InsertMode, INSERT_VALUES, ADD_VALUES
1359: @*/
1360: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1361: {

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

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

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

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

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


1406: /*@
1407:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1408:         values into a matrix

1410:    Not Collective

1412:    Input Parameters:
1413: +  mat - the matrix
1414: .  row - the (block) row to set
1415: -  v - a logically two-dimensional array of values

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

1420:    All the nonzeros in the row must be provided

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

1424:    The row must belong to this process

1426:    Level: intermediate

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

1440:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1441:   MatSetValuesRow(mat,globalrow,v);
1442:   return(0);
1443: }

1445: /*@
1446:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1447:         values into a matrix

1449:    Not Collective

1451:    Input Parameters:
1452: +  mat - the matrix
1453: .  row - the (block) row to set
1454: -  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

1456:    Notes:
1457:    The values, v, are column-oriented for the block version.

1459:    All the nonzeros in the row must be provided

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

1463:    The row must belong to this process

1465:    Level: advanced

1467: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1468:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1469: @*/
1470: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1471: {

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

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

1494: /*@
1495:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1496:      Using structured grid indexing

1498:    Not Collective

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

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

1514:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1515:    options cannot be mixed without intervening calls to the assembly
1516:    routines.

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

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

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

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

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

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

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

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

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

1554:    Efficiency Alert:
1555:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1556:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1558:    Level: beginner

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

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

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

1608: /*@
1609:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1610:      Using structured grid indexing

1612:    Not Collective

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

1625:    Notes:
1626:    By default the values, v, are row-oriented and unsorted.
1627:    See MatSetOption() for other options.

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

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

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

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

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

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

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

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

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

1665:    Level: beginner

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

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

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

1717: /*@
1718:    MatSetStencil - Sets the grid information for setting values into a matrix via
1719:         MatSetValuesStencil()

1721:    Not Collective

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


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

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

1737:    Level: beginner

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


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

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

1765:    Not Collective

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

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

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

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

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

1792:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1793:    options cannot be mixed without intervening calls to the assembly
1794:    routines.

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

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

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

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

1825:    Level: intermediate

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

1836:   if (!m || !n) return(0); /* no values to insert */
1840:   MatCheckPreallocated(mat,1);
1841:   if (mat->insertmode == NOT_SET_VALUES) {
1842:     mat->insertmode = addv;
1843:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1844:   if (PetscDefined(USE_DEBUG)) {
1845:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1846:     if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1847:   }

1849:   if (mat->assembled) {
1850:     mat->was_assembled = PETSC_TRUE;
1851:     mat->assembled     = PETSC_FALSE;
1852:   }
1853:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1854:   if (mat->ops->setvaluesblocked) {
1855:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1856:   } else {
1857:     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*iidxm,*iidxn;
1858:     PetscInt i,j,bs,cbs;
1859:     MatGetBlockSizes(mat,&bs,&cbs);
1860:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1861:       iidxm = buf; iidxn = buf + m*bs;
1862:     } else {
1863:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1864:       iidxm = bufr; iidxn = bufc;
1865:     }
1866:     for (i=0; i<m; i++) {
1867:       for (j=0; j<bs; j++) {
1868:         iidxm[i*bs+j] = bs*idxm[i] + j;
1869:       }
1870:     }
1871:     for (i=0; i<n; i++) {
1872:       for (j=0; j<cbs; j++) {
1873:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1874:       }
1875:     }
1876:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1877:     PetscFree2(bufr,bufc);
1878:   }
1879:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1880:   return(0);
1881: }

1883: /*@C
1884:    MatGetValues - Gets a block of values from a matrix.

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

1888:    Input Parameters:
1889: +  mat - the matrix
1890: .  v - a logically two-dimensional array for storing the values
1891: .  m, idxm - the number of rows and their global indices
1892: -  n, idxn - the number of columns and their global indices

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

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

1902:      MatGetValues() requires that the matrix has been assembled
1903:      with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1904:      MatSetValues() and MatGetValues() CANNOT be made in succession
1905:      without intermediate matrix assembly.

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

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

1914:    Level: advanced

1916: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues(), MatGetOwnershipRange(), MatGetValuesLocal()
1917: @*/
1918: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1919: {

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

1934:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1935:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1936:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1937:   return(0);
1938: }

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

1944:    Not Collective

1946:    Input Parameters:
1947: +  mat - the matrix
1948: .  nrow, irow - number of rows and their local indices
1949: -  ncol, icol - number of columns and their local indices

1951:    Output Parameter:
1952: .  y -  a logically two-dimensional array of values

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

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

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

1966:    Level: advanced

1968: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1969:            MatSetValuesLocal(), MatGetValues()
1970: @*/
1971: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1972: {

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

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

2013:   Not Collective

2015:   Input Parameters:
2016: + mat - the matrix
2017: . nb - the number of blocks
2018: . bs - the number of rows (and columns) in each block
2019: . rows - a concatenation of the rows for each block
2020: - v - a concatenation of logically two-dimensional arrays of values

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

2025:   Level: advanced

2027: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2028:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2029: @*/
2030: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2031: {

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

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

2054: /*@
2055:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2056:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2057:    using a local (per-processor) numbering.

2059:    Not Collective

2061:    Input Parameters:
2062: +  x - the matrix
2063: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2064: - cmapping - column mapping

2066:    Level: intermediate


2069: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal(), MatGetValuesLocal()
2070: @*/
2071: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2072: {


2081:   if (x->ops->setlocaltoglobalmapping) {
2082:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2083:   } else {
2084:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2085:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2086:   }
2087:   return(0);
2088: }


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

2094:    Not Collective

2096:    Input Parameters:
2097: .  A - the matrix

2099:    Output Parameters:
2100: + rmapping - row mapping
2101: - cmapping - column mapping

2103:    Level: advanced


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

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

2123:    Logically Collective on A

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

2130:    Level: advanced

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


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

2146: /*@
2147:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2149:    Not Collective

2151:    Input Parameters:
2152: .  A - the matrix

2154:    Output Parameters:
2155: + rmap - row layout
2156: - cmap - column layout

2158:    Level: advanced

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

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

2178:    Not Collective

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

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

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

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

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

2202:    Level: intermediate

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

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

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

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

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

2261:    Not Collective

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

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

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

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

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

2286:    Level: intermediate

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

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

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

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

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

2354:    Collective on Mat

2356:    Input Parameters:
2357: +  mat - the matrix
2358: -  x   - the vector to be multiplied

2360:    Output Parameters:
2361: .  y - the result

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

2367:    Level: developer

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


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

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

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

2396:    Neighbor-wise Collective on Mat

2398:    Input Parameters:
2399: +  mat - the matrix
2400: -  x   - the vector to be multiplied

2402:    Output Parameters:
2403: .  y - the result

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

2409:    Level: beginner

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

2422:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2423:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2424:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2425: #if !defined(PETSC_HAVE_CONSTRAINTS)
2426:   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);
2427:   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);
2428:   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);
2429: #endif
2430:   VecSetErrorIfLocked(y,3);
2431:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2432:   MatCheckPreallocated(mat,1);

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

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

2447:    Neighbor-wise Collective on Mat

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

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

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

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

2463:    Level: beginner

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


2477:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2478:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2479:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2480: #if !defined(PETSC_HAVE_CONSTRAINTS)
2481:   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);
2482:   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);
2483: #endif
2484:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2485:   MatCheckPreallocated(mat,1);

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

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

2504:    Neighbor-wise Collective on Mat

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

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

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

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

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

2521:    Level: beginner

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


2535:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2536:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2537:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2538: #if !defined(PETSC_HAVE_CONSTRAINTS)
2539:   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);
2540:   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);
2541: #endif
2542:   MatCheckPreallocated(mat,1);

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

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

2574:     Neighbor-wise Collective on Mat

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

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

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

2587:     Level: beginner

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


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

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

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

2625:    Neighbor-wise Collective on Mat

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

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

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

2638:    Level: beginner

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


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

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

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

2674:    Neighbor-wise Collective on Mat

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

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

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

2687:    Level: beginner

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


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

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

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

2740:    Neighbor-wise Collective on Mat

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

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

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

2753:    Level: beginner

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

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

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

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

2785:    Neighbor-wise Collective on Mat

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

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

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

2798:    Level: beginner

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

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

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

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

2826:    Not Collective

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

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

2834:    Level: intermediate

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

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

2851:    Logically Collective on Mat

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

2857:    Level: intermediate

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

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

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

2877:    Input Parameters:
2878: .  mat - the matrix

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

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

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

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

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

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

2924:     Level: intermediate

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

2929: .seealso: MatStashGetInfo()

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

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

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

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

2959: /* ----------------------------------------------------------*/

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

2964:    Collective on Mat

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

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

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

2983:    Level: developer

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

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

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

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

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

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

3022:    Collective on Mat

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

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

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

3042:    Level: developer

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

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

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

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

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

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

3077:    Collective on Mat

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


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

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

3096:    Level: developer

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

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

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

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

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

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

3140:    Collective on Mat

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

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

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

3155:    Level: developer

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

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

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

3173:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3174:   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dimensions are different %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);

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

3183:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3184:   (fact->ops->lufactornumeric)(fact,mat,info);
3185:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3186:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3187:   PetscObjectStateIncrease((PetscObject)fact);
3188:   return(0);
3189: }

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

3195:    Collective on Mat

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

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

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

3210:    Level: developer

3212: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3213:           MatGetOrdering()

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

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

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

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

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

3250:    Collective on Mat

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

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

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

3269:    Level: developer

3271: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3272:           MatGetOrdering()

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

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

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

3303:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3304:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3305:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3306:   PetscObjectStateIncrease((PetscObject)fact);
3307:   return(0);
3308: }

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

3315:    Collective on Mat

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


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

3329:    Level: developer

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

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

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

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

3356:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3357:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3358:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3359:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3360:   PetscObjectStateIncrease((PetscObject)fact);
3361:   return(0);
3362: }

3364: /* ----------------------------------------------------------------*/
3365: /*@
3366:    MatSolve - Solves A x = b, given a factored matrix.

3368:    Neighbor-wise Collective on Mat

3370:    Input Parameters:
3371: +  mat - the factored matrix
3372: -  b - the right-hand-side vector

3374:    Output Parameter:
3375: .  x - the result vector

3377:    Notes:
3378:    The vectors b and x cannot be the same.  I.e., one cannot
3379:    call MatSolve(A,x,x).

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

3386:    Level: developer

3388: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3389: @*/
3390: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3391: {

3401:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3402:   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);
3403:   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);
3404:   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);
3405:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3406:   MatCheckPreallocated(mat,1);

3408:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3409:   if (mat->factorerrortype) {
3410:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3411:     VecSetInf(x);
3412:   } else {
3413:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3414:     (*mat->ops->solve)(mat,b,x);
3415:   }
3416:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3417:   PetscObjectStateIncrease((PetscObject)x);
3418:   return(0);
3419: }

3421: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3422: {
3424:   Vec            b,x;
3425:   PetscInt       m,N,i;
3426:   PetscScalar    *bb,*xx;
3427:   PetscErrorCode (*f)(Mat,Vec,Vec);

3430:   if (A->factorerrortype) {
3431:     PetscInfo1(A,"MatFactorError %D\n",A->factorerrortype);
3432:     MatSetInf(X);
3433:     return(0);
3434:   }
3435:   f = trans ? A->ops->solvetranspose : A->ops->solve;
3436:   if (!f) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);

3438:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3439:   MatDenseGetArray(X,&xx);
3440:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3441:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3442:   MatCreateVecs(A,&x,&b);
3443:   for (i=0; i<N; i++) {
3444:     VecPlaceArray(b,bb + i*m);
3445:     VecPlaceArray(x,xx + i*m);
3446:     (*f)(A,b,x);
3447:     VecResetArray(x);
3448:     VecResetArray(b);
3449:   }
3450:   VecDestroy(&b);
3451:   VecDestroy(&x);
3452:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3453:   MatDenseRestoreArray(X,&xx);
3454:   return(0);
3455: }

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

3460:    Neighbor-wise Collective on Mat

3462:    Input Parameters:
3463: +  A - the factored matrix
3464: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3466:    Output Parameter:
3467: .  X - the result matrix (dense matrix)

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

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

3479:    Level: developer

3481: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3482: @*/
3483: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3484: {

3494:   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);
3495:   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);
3496:   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");
3497:   if (!A->rmap->N && !A->cmap->N) return(0);
3498:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3499:   MatCheckPreallocated(A,1);

3501:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3502:   if (!A->ops->matsolve) {
3503:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3504:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3505:   } else {
3506:     (*A->ops->matsolve)(A,B,X);
3507:   }
3508:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3509:   PetscObjectStateIncrease((PetscObject)X);
3510:   return(0);
3511: }

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

3516:    Neighbor-wise Collective on Mat

3518:    Input Parameters:
3519: +  A - the factored matrix
3520: -  B - the right-hand-side matrix  (dense matrix)

3522:    Output Parameter:
3523: .  X - the result matrix (dense matrix)

3525:    Notes:
3526:    The matrices B and X cannot be the same.  I.e., one cannot
3527:    call MatMatSolveTranspose(A,X,X).

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

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

3537:    Level: developer

3539: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3540: @*/
3541: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3542: {

3552:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3553:   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);
3554:   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);
3555:   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);
3556:   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");
3557:   if (!A->rmap->N && !A->cmap->N) return(0);
3558:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3559:   MatCheckPreallocated(A,1);

3561:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3562:   if (!A->ops->matsolvetranspose) {
3563:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3564:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3565:   } else {
3566:     (*A->ops->matsolvetranspose)(A,B,X);
3567:   }
3568:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3569:   PetscObjectStateIncrease((PetscObject)X);
3570:   return(0);
3571: }

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

3576:    Neighbor-wise Collective on Mat

3578:    Input Parameters:
3579: +  A - the factored matrix
3580: -  Bt - the transpose of right-hand-side matrix

3582:    Output Parameter:
3583: .  X - the result matrix (dense matrix)

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

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

3593:    Level: developer

3595: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3596: @*/
3597: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3598: {


3609:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3610:   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);
3611:   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);
3612:   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");
3613:   if (!A->rmap->N && !A->cmap->N) return(0);
3614:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3615:   MatCheckPreallocated(A,1);

3617:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3618:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3619:   (*A->ops->mattransposesolve)(A,Bt,X);
3620:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3621:   PetscObjectStateIncrease((PetscObject)X);
3622:   return(0);
3623: }

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

3629:    Neighbor-wise Collective on Mat

3631:    Input Parameters:
3632: +  mat - the factored matrix
3633: -  b - the right-hand-side vector

3635:    Output Parameter:
3636: .  x - the result vector

3638:    Notes:
3639:    MatSolve() should be used for most applications, as it performs
3640:    a forward solve followed by a backward solve.

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

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

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

3655:    Level: developer

3657: .seealso: MatSolve(), MatBackwardSolve()
3658: @*/
3659: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3660: {

3670:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3671:   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3672:   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3673:   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3674:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3675:   MatCheckPreallocated(mat,1);

3677:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3678:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3679:   (*mat->ops->forwardsolve)(mat,b,x);
3680:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3681:   PetscObjectStateIncrease((PetscObject)x);
3682:   return(0);
3683: }

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

3689:    Neighbor-wise Collective on Mat

3691:    Input Parameters:
3692: +  mat - the factored matrix
3693: -  b - the right-hand-side vector

3695:    Output Parameter:
3696: .  x - the result vector

3698:    Notes:
3699:    MatSolve() should be used for most applications, as it performs
3700:    a forward solve followed by a backward solve.

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

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

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

3715:    Level: developer

3717: .seealso: MatSolve(), MatForwardSolve()
3718: @*/
3719: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3720: {

3730:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3731:   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);
3732:   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);
3733:   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);
3734:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3735:   MatCheckPreallocated(mat,1);

3737:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3738:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3739:   (*mat->ops->backwardsolve)(mat,b,x);
3740:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3741:   PetscObjectStateIncrease((PetscObject)x);
3742:   return(0);
3743: }

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

3748:    Neighbor-wise Collective on Mat

3750:    Input Parameters:
3751: +  mat - the factored matrix
3752: .  b - the right-hand-side vector
3753: -  y - the vector to be added to

3755:    Output Parameter:
3756: .  x - the result vector

3758:    Notes:
3759:    The vectors b and x cannot be the same.  I.e., one cannot
3760:    call MatSolveAdd(A,x,y,x).

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

3766:    Level: developer

3768: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3769: @*/
3770: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3771: {
3772:   PetscScalar    one = 1.0;
3773:   Vec            tmp;

3785:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3786:   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);
3787:   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);
3788:   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);
3789:   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);
3790:   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);
3791:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3792:    MatCheckPreallocated(mat,1);

3794:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3795:   if (mat->factorerrortype) {
3796:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3797:     VecSetInf(x);
3798:   } else if (mat->ops->solveadd) {
3799:     (*mat->ops->solveadd)(mat,b,y,x);
3800:   } else {
3801:     /* do the solve then the add manually */
3802:     if (x != y) {
3803:       MatSolve(mat,b,x);
3804:       VecAXPY(x,one,y);
3805:     } else {
3806:       VecDuplicate(x,&tmp);
3807:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3808:       VecCopy(x,tmp);
3809:       MatSolve(mat,b,x);
3810:       VecAXPY(x,one,tmp);
3811:       VecDestroy(&tmp);
3812:     }
3813:   }
3814:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3815:   PetscObjectStateIncrease((PetscObject)x);
3816:   return(0);
3817: }

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

3822:    Neighbor-wise Collective on Mat

3824:    Input Parameters:
3825: +  mat - the factored matrix
3826: -  b - the right-hand-side vector

3828:    Output Parameter:
3829: .  x - the result vector

3831:    Notes:
3832:    The vectors b and x cannot be the same.  I.e., one cannot
3833:    call MatSolveTranspose(A,x,x).

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

3839:    Level: developer

3841: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3842: @*/
3843: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3844: {

3854:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3855:   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);
3856:   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);
3857:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3858:   MatCheckPreallocated(mat,1);
3859:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3860:   if (mat->factorerrortype) {
3861:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3862:     VecSetInf(x);
3863:   } else {
3864:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3865:     (*mat->ops->solvetranspose)(mat,b,x);
3866:   }
3867:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3868:   PetscObjectStateIncrease((PetscObject)x);
3869:   return(0);
3870: }

3872: /*@
3873:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3874:                       factored matrix.

3876:    Neighbor-wise Collective on Mat

3878:    Input Parameters:
3879: +  mat - the factored matrix
3880: .  b - the right-hand-side vector
3881: -  y - the vector to be added to

3883:    Output Parameter:
3884: .  x - the result vector

3886:    Notes:
3887:    The vectors b and x cannot be the same.  I.e., one cannot
3888:    call MatSolveTransposeAdd(A,x,y,x).

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

3894:    Level: developer

3896: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3897: @*/
3898: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3899: {
3900:   PetscScalar    one = 1.0;
3902:   Vec            tmp;

3913:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3914:   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);
3915:   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);
3916:   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);
3917:   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);
3918:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3919:    MatCheckPreallocated(mat,1);

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

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

3950:    Neighbor-wise Collective on Mat

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

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

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

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

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

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

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

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

3996:    Vectors x and b CANNOT be the same

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

4000:    Level: developer

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

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

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

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

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

4061: /*@
4062:    MatCopy - Copies a matrix to another matrix.

4064:    Collective on Mat

4066:    Input Parameters:
4067: +  A - the matrix
4068: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4070:    Output Parameter:
4071: .  B - where the copy is put

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

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

4081:    Level: intermediate

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

4085: @*/
4086: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4087: {
4089:   PetscInt       i;

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

4104:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4105:   if (A->ops->copy) {
4106:     (*A->ops->copy)(A,B,str);
4107:   } else { /* generic conversion */
4108:     MatCopy_Basic(A,B,str);
4109:   }

4111:   B->stencil.dim = A->stencil.dim;
4112:   B->stencil.noc = A->stencil.noc;
4113:   for (i=0; i<=A->stencil.dim; i++) {
4114:     B->stencil.dims[i]   = A->stencil.dims[i];
4115:     B->stencil.starts[i] = A->stencil.starts[i];
4116:   }

4118:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4119:   PetscObjectStateIncrease((PetscObject)B);
4120:   return(0);
4121: }

4123: /*@C
4124:    MatConvert - Converts a matrix to another matrix, either of the same
4125:    or different type.

4127:    Collective on Mat

4129:    Input Parameters:
4130: +  mat - the matrix
4131: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4132:    same type as the original matrix.
4133: -  reuse - denotes if the destination matrix is to be created or reused.
4134:    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
4135:    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).

4137:    Output Parameter:
4138: .  M - pointer to place new matrix

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

4145:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4146:    the MPI communicator of the generated matrix is always the same as the communicator
4147:    of the input matrix.

4149:    Level: intermediate

4151: .seealso: MatCopy(), MatDuplicate()
4152: @*/
4153: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4154: {
4156:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4157:   char           convname[256],mtype[256];
4158:   Mat            B;

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

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

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

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

4181:   /* Cache Mat options because some converter use MatHeaderReplace  */
4182:   issymmetric = mat->symmetric;
4183:   ishermitian = mat->hermitian;

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

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

4238:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4239:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4240:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4241:     MatSetType(B,newtype);
4242:     for (i=0; i<3; i++) {
4243:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4244:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4245:       PetscStrlcat(convname,"_",sizeof(convname));
4246:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4247:       PetscStrlcat(convname,newtype,sizeof(convname));
4248:       PetscStrlcat(convname,"_C",sizeof(convname));
4249:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4250:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4251:       if (conv) {
4252:         MatDestroy(&B);
4253:         goto foundconv;
4254:       }
4255:     }

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

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

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

4269:     /* 5) Use a really basic converter. */
4270:     PetscInfo(mat,"Using MatConvert_Basic\n");
4271:     conv = MatConvert_Basic;

4273: foundconv:
4274:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4275:     (*conv)(mat,newtype,reuse,M);
4276:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4277:       /* the block sizes must be same if the mappings are copied over */
4278:       (*M)->rmap->bs = mat->rmap->bs;
4279:       (*M)->cmap->bs = mat->cmap->bs;
4280:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4281:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4282:       (*M)->rmap->mapping = mat->rmap->mapping;
4283:       (*M)->cmap->mapping = mat->cmap->mapping;
4284:     }
4285:     (*M)->stencil.dim = mat->stencil.dim;
4286:     (*M)->stencil.noc = mat->stencil.noc;
4287:     for (i=0; i<=mat->stencil.dim; i++) {
4288:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4289:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4290:     }
4291:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4292:   }
4293:   PetscObjectStateIncrease((PetscObject)*M);

4295:   /* Copy Mat options */
4296:   if (issymmetric) {
4297:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4298:   }
4299:   if (ishermitian) {
4300:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4301:   }
4302:   return(0);
4303: }

4305: /*@C
4306:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4308:    Not Collective

4310:    Input Parameter:
4311: .  mat - the matrix, must be a factored matrix

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

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

4320:    Level: intermediate

4322: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4323: @*/
4324: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4325: {
4326:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4331:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4332:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4333:   if (!conv) {
4334:     *type = MATSOLVERPETSC;
4335:   } else {
4336:     (*conv)(mat,type);
4337:   }
4338:   return(0);
4339: }

4341: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4342: struct _MatSolverTypeForSpecifcType {
4343:   MatType                        mtype;
4344:   PetscErrorCode                 (*createfactor[4])(Mat,MatFactorType,Mat*);
4345:   MatSolverTypeForSpecifcType next;
4346: };

4348: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4349: struct _MatSolverTypeHolder {
4350:   char                        *name;
4351:   MatSolverTypeForSpecifcType handlers;
4352:   MatSolverTypeHolder         next;
4353: };

4355: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4360:    Input Parameters:
4361: +    package - name of the package, for example petsc or superlu
4362: .    mtype - the matrix type that works with this package
4363: .    ftype - the type of factorization supported by the package
4364: -    createfactor - routine that will create the factored matrix ready to be used

4366:     Level: intermediate

4368: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4369: @*/
4370: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*createfactor)(Mat,MatFactorType,Mat*))
4371: {
4372:   PetscErrorCode              ierr;
4373:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4374:   PetscBool                   flg;
4375:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4378:   MatInitializePackage();
4379:   if (!next) {
4380:     PetscNew(&MatSolverTypeHolders);
4381:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4382:     PetscNew(&MatSolverTypeHolders->handlers);
4383:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4384:     MatSolverTypeHolders->handlers->createfactor[(int)ftype-1] = createfactor;
4385:     return(0);
4386:   }
4387:   while (next) {
4388:     PetscStrcasecmp(package,next->name,&flg);
4389:     if (flg) {
4390:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4391:       inext = next->handlers;
4392:       while (inext) {
4393:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4394:         if (flg) {
4395:           inext->createfactor[(int)ftype-1] = createfactor;
4396:           return(0);
4397:         }
4398:         iprev = inext;
4399:         inext = inext->next;
4400:       }
4401:       PetscNew(&iprev->next);
4402:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4403:       iprev->next->createfactor[(int)ftype-1] = createfactor;
4404:       return(0);
4405:     }
4406:     prev = next;
4407:     next = next->next;
4408:   }
4409:   PetscNew(&prev->next);
4410:   PetscStrallocpy(package,&prev->next->name);
4411:   PetscNew(&prev->next->handlers);
4412:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4413:   prev->next->handlers->createfactor[(int)ftype-1] = createfactor;
4414:   return(0);
4415: }

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

4420:    Input Parameters:
4421: +    type - name of the package, for example petsc or superlu
4422: .    ftype - the type of factorization supported by the type
4423: -    mtype - the matrix type that works with this type

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

4430:     Level: intermediate

4432: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatSolvePackageRegister), MatGetFactor()
4433: @*/
4434: PetscErrorCode MatSolverTypeGet(MatSolverType type,MatType mtype,MatFactorType ftype,PetscBool *foundtype,PetscBool *foundmtype,PetscErrorCode (**createfactor)(Mat,MatFactorType,Mat*))
4435: {
4436:   PetscErrorCode              ierr;
4437:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4438:   PetscBool                   flg;
4439:   MatSolverTypeForSpecifcType inext;

4442:   if (foundtype) *foundtype = PETSC_FALSE;
4443:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4444:   if (createfactor) *createfactor    = NULL;

4446:   if (type) {
4447:     while (next) {
4448:       PetscStrcasecmp(type,next->name,&flg);
4449:       if (flg) {
4450:         if (foundtype) *foundtype = PETSC_TRUE;
4451:         inext = next->handlers;
4452:         while (inext) {
4453:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4454:           if (flg) {
4455:             if (foundmtype) *foundmtype = PETSC_TRUE;
4456:             if (createfactor)  *createfactor  = inext->createfactor[(int)ftype-1];
4457:             return(0);
4458:           }
4459:           inext = inext->next;
4460:         }
4461:       }
4462:       next = next->next;
4463:     }
4464:   } else {
4465:     while (next) {
4466:       inext = next->handlers;
4467:       while (inext) {
4468:         PetscStrcmp(mtype,inext->mtype,&flg);
4469:         if (flg && inext->createfactor[(int)ftype-1]) {
4470:           if (foundtype) *foundtype = PETSC_TRUE;
4471:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4472:           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4473:           return(0);
4474:         }
4475:         inext = inext->next;
4476:       }
4477:       next = next->next;
4478:     }
4479:     /* try with base classes inext->mtype */
4480:     next = MatSolverTypeHolders;
4481:     while (next) {
4482:       inext = next->handlers;
4483:       while (inext) {
4484:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4485:         if (flg && inext->createfactor[(int)ftype-1]) {
4486:           if (foundtype) *foundtype = PETSC_TRUE;
4487:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4488:           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4489:           return(0);
4490:         }
4491:         inext = inext->next;
4492:       }
4493:       next = next->next;
4494:     }
4495:   }
4496:   return(0);
4497: }

4499: PetscErrorCode MatSolverTypeDestroy(void)
4500: {
4501:   PetscErrorCode              ierr;
4502:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4503:   MatSolverTypeForSpecifcType inext,iprev;

4506:   while (next) {
4507:     PetscFree(next->name);
4508:     inext = next->handlers;
4509:     while (inext) {
4510:       PetscFree(inext->mtype);
4511:       iprev = inext;
4512:       inext = inext->next;
4513:       PetscFree(iprev);
4514:     }
4515:     prev = next;
4516:     next = next->next;
4517:     PetscFree(prev);
4518:   }
4519:   MatSolverTypeHolders = NULL;
4520:   return(0);
4521: }

4523: /*@C
4524:    MatFactorGetUseOrdering - Indicates if the factorization uses the ordering provided in MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()

4526:    Logically Collective on Mat

4528:    Input Parameters:
4529: .  mat - the matrix

4531:    Output Parameters:
4532: .  flg - PETSC_TRUE if uses the ordering

4534:    Notes:
4535:       Most internal PETSc factorizations use the ordering past to the factorization routine but external
4536:       packages do no, thus we want to skip the ordering when it is not needed.

4538:    Level: developer

4540: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4541: @*/
4542: PetscErrorCode MatFactorGetUseOrdering(Mat mat, PetscBool *flg)
4543: {
4545:   *flg = mat->useordering;
4546:   return(0);
4547: }

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

4552:    Collective on Mat

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

4559:    Output Parameters:
4560: .  f - the factor matrix used with MatXXFactorSymbolic() calls

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

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

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

4571:    Level: intermediate

4573: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetUseOrdering(), MatSolverTypeRegister()
4574: @*/
4575: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4576: {
4577:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4578:   PetscBool      foundtype,foundmtype;


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

4587:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundtype,&foundmtype,&conv);
4588:   if (!foundtype) {
4589:     if (type) {
4590:       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);
4591:     } else {
4592:       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);
4593:     }
4594:   }
4595:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4596:   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);

4598:   (*conv)(mat,ftype,f);
4599:   return(0);
4600: }

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

4605:    Not Collective

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

4612:    Output Parameter:
4613: .    flg - PETSC_TRUE if the factorization is available

4615:    Notes:
4616:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4617:      such as pastix, superlu, mumps etc.

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

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

4624:    Level: intermediate

4626: .seealso: MatCopy(), MatDuplicate(), MatGetFactor(), MatSolverTypeRegister()
4627: @*/
4628: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4629: {
4630:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4639:   *flg = PETSC_FALSE;
4640:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4641:   if (gconv) {
4642:     *flg = PETSC_TRUE;
4643:   }
4644:   return(0);
4645: }

4647: #include <petscdmtypes.h>

4649: /*@
4650:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4652:    Collective on Mat

4654:    Input Parameters:
4655: +  mat - the matrix
4656: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4657:         See the manual page for MatDuplicateOption for an explanation of these options.

4659:    Output Parameter:
4660: .  M - pointer to place new matrix

4662:    Level: intermediate

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

4668: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4669: @*/
4670: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4671: {
4673:   Mat            B;
4674:   PetscInt       i;
4675:   DM             dm;
4676:   void           (*viewf)(void);

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

4686:   *M = NULL;
4687:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4688:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4689:   (*mat->ops->duplicate)(mat,op,M);
4690:   B    = *M;

4692:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4693:   if (viewf) {
4694:     MatSetOperation(B,MATOP_VIEW,viewf);
4695:   }

4697:   B->stencil.dim = mat->stencil.dim;
4698:   B->stencil.noc = mat->stencil.noc;
4699:   for (i=0; i<=mat->stencil.dim; i++) {
4700:     B->stencil.dims[i]   = mat->stencil.dims[i];
4701:     B->stencil.starts[i] = mat->stencil.starts[i];
4702:   }

4704:   B->nooffproczerorows = mat->nooffproczerorows;
4705:   B->nooffprocentries  = mat->nooffprocentries;

4707:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4708:   if (dm) {
4709:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4710:   }
4711:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4712:   PetscObjectStateIncrease((PetscObject)B);
4713:   return(0);
4714: }

4716: /*@
4717:    MatGetDiagonal - Gets the diagonal of a matrix.

4719:    Logically Collective on Mat

4721:    Input Parameters:
4722: +  mat - the matrix
4723: -  v - the vector for storing the diagonal

4725:    Output Parameter:
4726: .  v - the diagonal of the matrix

4728:    Level: intermediate

4730:    Note:
4731:    Currently only correct in parallel for square matrices.

4733: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4734: @*/
4735: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4736: {

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

4747:   (*mat->ops->getdiagonal)(mat,v);
4748:   PetscObjectStateIncrease((PetscObject)v);
4749:   return(0);
4750: }

4752: /*@C
4753:    MatGetRowMin - Gets the minimum value (of the real part) of each
4754:         row of the matrix

4756:    Logically Collective on Mat

4758:    Input Parameters:
4759: .  mat - the matrix

4761:    Output Parameter:
4762: +  v - the vector for storing the maximums
4763: -  idx - the indices of the column found for each row (optional)

4765:    Level: intermediate

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

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

4773: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4774:           MatGetRowMax()
4775: @*/
4776: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4777: {

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

4786:   if (!mat->cmap->N) {
4787:     VecSet(v,PETSC_MAX_REAL);
4788:     if (idx) {
4789:       PetscInt i,m = mat->rmap->n;
4790:       for (i=0; i<m; i++) idx[i] = -1;
4791:     }
4792:   } else {
4793:     if (!mat->ops->getrowmin) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4794:     MatCheckPreallocated(mat,1);
4795:   }
4796:   (*mat->ops->getrowmin)(mat,v,idx);
4797:   PetscObjectStateIncrease((PetscObject)v);
4798:   return(0);
4799: }

4801: /*@C
4802:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4803:         row of the matrix

4805:    Logically Collective on Mat

4807:    Input Parameters:
4808: .  mat - the matrix

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

4814:    Level: intermediate

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

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

4822: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4823: @*/
4824: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4825: {

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

4835:   if (!mat->cmap->N) {
4836:     VecSet(v,0.0);
4837:     if (idx) {
4838:       PetscInt i,m = mat->rmap->n;
4839:       for (i=0; i<m; i++) idx[i] = -1;
4840:     }
4841:   } else {
4842:     if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4843:     MatCheckPreallocated(mat,1);
4844:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4845:     (*mat->ops->getrowminabs)(mat,v,idx);
4846:   }
4847:   PetscObjectStateIncrease((PetscObject)v);
4848:   return(0);
4849: }

4851: /*@C
4852:    MatGetRowMax - Gets the maximum value (of the real part) of each
4853:         row of the matrix

4855:    Logically Collective on Mat

4857:    Input Parameters:
4858: .  mat - the matrix

4860:    Output Parameter:
4861: +  v - the vector for storing the maximums
4862: -  idx - the indices of the column found for each row (optional)

4864:    Level: intermediate

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

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

4872: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4873: @*/
4874: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4875: {

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

4884:   if (!mat->cmap->N) {
4885:     VecSet(v,PETSC_MIN_REAL);
4886:     if (idx) {
4887:       PetscInt i,m = mat->rmap->n;
4888:       for (i=0; i<m; i++) idx[i] = -1;
4889:     }
4890:   } else {
4891:     if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4892:     MatCheckPreallocated(mat,1);
4893:     (*mat->ops->getrowmax)(mat,v,idx);
4894:   }
4895:   PetscObjectStateIncrease((PetscObject)v);
4896:   return(0);
4897: }

4899: /*@C
4900:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4901:         row of the matrix

4903:    Logically Collective on Mat

4905:    Input Parameters:
4906: .  mat - the matrix

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

4912:    Level: intermediate

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

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

4920: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4921: @*/
4922: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4923: {

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

4932:   if (!mat->cmap->N) {
4933:     VecSet(v,0.0);
4934:     if (idx) {
4935:       PetscInt i,m = mat->rmap->n;
4936:       for (i=0; i<m; i++) idx[i] = -1;
4937:     }
4938:   } else {
4939:     if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4940:     MatCheckPreallocated(mat,1);
4941:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4942:     (*mat->ops->getrowmaxabs)(mat,v,idx);
4943:   }
4944:   PetscObjectStateIncrease((PetscObject)v);
4945:   return(0);
4946: }

4948: /*@
4949:    MatGetRowSum - Gets the sum of each row of the matrix

4951:    Logically or Neighborhood Collective on Mat

4953:    Input Parameters:
4954: .  mat - the matrix

4956:    Output Parameter:
4957: .  v - the vector for storing the sum of rows

4959:    Level: intermediate

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

4964: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4965: @*/
4966: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4967: {
4968:   Vec            ones;

4975:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4976:   MatCheckPreallocated(mat,1);
4977:   MatCreateVecs(mat,&ones,NULL);
4978:   VecSet(ones,1.);
4979:   MatMult(mat,ones,v);
4980:   VecDestroy(&ones);
4981:   return(0);
4982: }

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

4987:    Collective on Mat

4989:    Input Parameter:
4990: +  mat - the matrix to transpose
4991: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4993:    Output Parameters:
4994: .  B - the transpose

4996:    Notes:
4997:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

5003:    Level: intermediate

5005: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5006: @*/
5007: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
5008: {

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

5021:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
5022:   (*mat->ops->transpose)(mat,reuse,B);
5023:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
5024:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
5025:   return(0);
5026: }

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

5032:    Collective on Mat

5034:    Input Parameter:
5035: +  A - the matrix to test
5036: -  B - the matrix to test against, this can equal the first parameter

5038:    Output Parameters:
5039: .  flg - the result

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

5046:    Level: intermediate

5048: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
5049: @*/
5050: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5051: {
5052:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5058:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
5059:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
5060:   *flg = PETSC_FALSE;
5061:   if (f && g) {
5062:     if (f == g) {
5063:       (*f)(A,B,tol,flg);
5064:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
5065:   } else {
5066:     MatType mattype;
5067:     if (!f) {
5068:       MatGetType(A,&mattype);
5069:     } else {
5070:       MatGetType(B,&mattype);
5071:     }
5072:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
5073:   }
5074:   return(0);
5075: }

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

5080:    Collective on Mat

5082:    Input Parameter:
5083: +  mat - the matrix to transpose and complex conjugate
5084: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

5086:    Output Parameters:
5087: .  B - the Hermitian

5089:    Level: intermediate

5091: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5092: @*/
5093: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5094: {

5098:   MatTranspose(mat,reuse,B);
5099: #if defined(PETSC_USE_COMPLEX)
5100:   MatConjugate(*B);
5101: #endif
5102:   return(0);
5103: }

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

5108:    Collective on Mat

5110:    Input Parameter:
5111: +  A - the matrix to test
5112: -  B - the matrix to test against, this can equal the first parameter

5114:    Output Parameters:
5115: .  flg - the result

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

5122:    Level: intermediate

5124: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5125: @*/
5126: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5127: {
5128:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5134:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5135:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5136:   if (f && g) {
5137:     if (f==g) {
5138:       (*f)(A,B,tol,flg);
5139:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5140:   }
5141:   return(0);
5142: }

5144: /*@
5145:    MatPermute - Creates a new matrix with rows and columns permuted from the
5146:    original.

5148:    Collective on Mat

5150:    Input Parameters:
5151: +  mat - the matrix to permute
5152: .  row - row permutation, each processor supplies only the permutation for its rows
5153: -  col - column permutation, each processor supplies only the permutation for its columns

5155:    Output Parameters:
5156: .  B - the permuted matrix

5158:    Level: advanced

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

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

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

5171: @*/
5172: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5173: {

5182:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5183:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5184:   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);
5185:   MatCheckPreallocated(mat,1);

5187:   if (mat->ops->permute) {
5188:     (*mat->ops->permute)(mat,row,col,B);
5189:     PetscObjectStateIncrease((PetscObject)*B);
5190:   } else {
5191:     MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B);
5192:   }
5193:   return(0);
5194: }

5196: /*@
5197:    MatEqual - Compares two matrices.

5199:    Collective on Mat

5201:    Input Parameters:
5202: +  A - the first matrix
5203: -  B - the second matrix

5205:    Output Parameter:
5206: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5208:    Level: intermediate

5210: @*/
5211: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5212: {

5222:   MatCheckPreallocated(B,2);
5223:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5224:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5225:   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);
5226:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5227:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5228:   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);
5229:   MatCheckPreallocated(A,1);

5231:   (*A->ops->equal)(A,B,flg);
5232:   return(0);
5233: }

5235: /*@
5236:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5237:    matrices that are stored as vectors.  Either of the two scaling
5238:    matrices can be NULL.

5240:    Collective on Mat

5242:    Input Parameters:
5243: +  mat - the matrix to be scaled
5244: .  l - the left scaling vector (or NULL)
5245: -  r - the right scaling vector (or NULL)

5247:    Notes:
5248:    MatDiagonalScale() computes A = LAR, where
5249:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5250:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5252:    Level: intermediate


5255: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5256: @*/
5257: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5258: {

5266:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5267:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5268:   MatCheckPreallocated(mat,1);
5269:   if (!l && !r) return(0);

5271:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5272:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5273:   (*mat->ops->diagonalscale)(mat,l,r);
5274:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5275:   PetscObjectStateIncrease((PetscObject)mat);
5276:   return(0);
5277: }

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

5282:     Logically Collective on Mat

5284:     Input Parameters:
5285: +   mat - the matrix to be scaled
5286: -   a  - the scaling value

5288:     Output Parameter:
5289: .   mat - the scaled matrix

5291:     Level: intermediate

5293: .seealso: MatDiagonalScale()
5294: @*/
5295: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5296: {

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

5308:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5309:   if (a != (PetscScalar)1.0) {
5310:     (*mat->ops->scale)(mat,a);
5311:     PetscObjectStateIncrease((PetscObject)mat);
5312:   }
5313:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5314:   return(0);
5315: }

5317: /*@
5318:    MatNorm - Calculates various norms of a matrix.

5320:    Collective on Mat

5322:    Input Parameters:
5323: +  mat - the matrix
5324: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5326:    Output Parameters:
5327: .  nrm - the resulting norm

5329:    Level: intermediate

5331: @*/
5332: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5333: {


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

5346:   (*mat->ops->norm)(mat,type,nrm);
5347:   return(0);
5348: }

5350: /*
5351:      This variable is used to prevent counting of MatAssemblyBegin() that
5352:    are called from within a MatAssemblyEnd().
5353: */
5354: static PetscInt MatAssemblyEnd_InUse = 0;
5355: /*@
5356:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5357:    be called after completing all calls to MatSetValues().

5359:    Collective on Mat

5361:    Input Parameters:
5362: +  mat - the matrix
5363: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5365:    Notes:
5366:    MatSetValues() generally caches the values.  The matrix is ready to
5367:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5368:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5369:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5370:    using the matrix.

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

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

5380:    Level: beginner

5382: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5383: @*/
5384: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5385: {

5391:   MatCheckPreallocated(mat,1);
5392:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5393:   if (mat->assembled) {
5394:     mat->was_assembled = PETSC_TRUE;
5395:     mat->assembled     = PETSC_FALSE;
5396:   }

5398:   if (!MatAssemblyEnd_InUse) {
5399:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5400:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5401:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5402:   } else if (mat->ops->assemblybegin) {
5403:     (*mat->ops->assemblybegin)(mat,type);
5404:   }
5405:   return(0);
5406: }

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

5412:    Not Collective

5414:    Input Parameter:
5415: .  mat - the matrix

5417:    Output Parameter:
5418: .  assembled - PETSC_TRUE or PETSC_FALSE

5420:    Level: advanced

5422: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5423: @*/
5424: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5425: {
5429:   *assembled = mat->assembled;
5430:   return(0);
5431: }

5433: /*@
5434:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5435:    be called after MatAssemblyBegin().

5437:    Collective on Mat

5439:    Input Parameters:
5440: +  mat - the matrix
5441: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5443:    Options Database Keys:
5444: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5445: .  -mat_view ::ascii_info_detail - Prints more detailed info
5446: .  -mat_view - Prints matrix in ASCII format
5447: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5448: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5449: .  -display <name> - Sets display name (default is host)
5450: .  -draw_pause <sec> - Sets number of seconds to pause after display
5451: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab)
5452: .  -viewer_socket_machine <machine> - Machine to use for socket
5453: .  -viewer_socket_port <port> - Port number to use for socket
5454: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5456:    Notes:
5457:    MatSetValues() generally caches the values.  The matrix is ready to
5458:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5459:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5460:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5461:    using the matrix.

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

5467:    Level: beginner

5469: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5470: @*/
5471: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5472: {
5473:   PetscErrorCode  ierr;
5474:   static PetscInt inassm = 0;
5475:   PetscBool       flg    = PETSC_FALSE;


5481:   inassm++;
5482:   MatAssemblyEnd_InUse++;
5483:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5484:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5485:     if (mat->ops->assemblyend) {
5486:       (*mat->ops->assemblyend)(mat,type);
5487:     }
5488:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5489:   } else if (mat->ops->assemblyend) {
5490:     (*mat->ops->assemblyend)(mat,type);
5491:   }

5493:   /* Flush assembly is not a true assembly */
5494:   if (type != MAT_FLUSH_ASSEMBLY) {
5495:     mat->num_ass++;
5496:     mat->assembled        = PETSC_TRUE;
5497:     mat->ass_nonzerostate = mat->nonzerostate;
5498:   }

5500:   mat->insertmode = NOT_SET_VALUES;
5501:   MatAssemblyEnd_InUse--;
5502:   PetscObjectStateIncrease((PetscObject)mat);
5503:   if (!mat->symmetric_eternal) {
5504:     mat->symmetric_set              = PETSC_FALSE;
5505:     mat->hermitian_set              = PETSC_FALSE;
5506:     mat->structurally_symmetric_set = PETSC_FALSE;
5507:   }
5508:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5509:     MatViewFromOptions(mat,NULL,"-mat_view");

5511:     if (mat->checksymmetryonassembly) {
5512:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5513:       if (flg) {
5514:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5515:       } else {
5516:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5517:       }
5518:     }
5519:     if (mat->nullsp && mat->checknullspaceonassembly) {
5520:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5521:     }
5522:   }
5523:   inassm--;
5524:   return(0);
5525: }

5527: /*@
5528:    MatSetOption - Sets a parameter option for a matrix. Some options
5529:    may be specific to certain storage formats.  Some options
5530:    determine how values will be inserted (or added). Sorted,
5531:    row-oriented input will generally assemble the fastest. The default
5532:    is row-oriented.

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

5536:    Input Parameters:
5537: +  mat - the matrix
5538: .  option - the option, one of those listed below (and possibly others),
5539: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5541:   Options Describing Matrix Structure:
5542: +    MAT_SPD - symmetric positive definite
5543: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5544: .    MAT_HERMITIAN - transpose is the complex conjugation
5545: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5546: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5547:                             you set to be kept with all future use of the matrix
5548:                             including after MatAssemblyBegin/End() which could
5549:                             potentially change the symmetry structure, i.e. you
5550:                             KNOW the matrix will ALWAYS have the property you set.
5551:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5552:                             the relevant flags must be set independently.


5555:    Options For Use with MatSetValues():
5556:    Insert a logically dense subblock, which can be
5557: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5611:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5612:    searches during matrix assembly. When this flag is set, the hash table
5613:    is created during the first Matrix Assembly. This hash table is
5614:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5615:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5616:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5617:    supported by MATMPIBAIJ format only.

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

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

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

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

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

5633:    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5634:                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5635:                      with finite difference schemes with non-periodic boundary conditions.

5637:    Level: intermediate

5639: .seealso:  MatOption, Mat

5641: @*/
5642: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5643: {

5648:   if (op > 0) {
5651:   }

5653:   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);

5655:   switch (op) {
5656:   case MAT_FORCE_DIAGONAL_ENTRIES:
5657:     mat->force_diagonals = flg;
5658:     return(0);
5659:   case MAT_NO_OFF_PROC_ENTRIES:
5660:     mat->nooffprocentries = flg;
5661:     return(0);
5662:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5663:     mat->assembly_subset = flg;
5664:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5665: #if !defined(PETSC_HAVE_MPIUNI)
5666:       MatStashScatterDestroy_BTS(&mat->stash);
5667: #endif
5668:       mat->stash.first_assembly_done = PETSC_FALSE;
5669:     }
5670:     return(0);
5671:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5672:     mat->nooffproczerorows = flg;
5673:     return(0);
5674:   case MAT_SPD:
5675:     mat->spd_set = PETSC_TRUE;
5676:     mat->spd     = flg;
5677:     if (flg) {
5678:       mat->symmetric                  = PETSC_TRUE;
5679:       mat->structurally_symmetric     = PETSC_TRUE;
5680:       mat->symmetric_set              = PETSC_TRUE;
5681:       mat->structurally_symmetric_set = PETSC_TRUE;
5682:     }
5683:     break;
5684:   case MAT_SYMMETRIC:
5685:     mat->symmetric = flg;
5686:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5687:     mat->symmetric_set              = PETSC_TRUE;
5688:     mat->structurally_symmetric_set = flg;
5689: #if !defined(PETSC_USE_COMPLEX)
5690:     mat->hermitian     = flg;
5691:     mat->hermitian_set = PETSC_TRUE;
5692: #endif
5693:     break;
5694:   case MAT_HERMITIAN:
5695:     mat->hermitian = flg;
5696:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5697:     mat->hermitian_set              = PETSC_TRUE;
5698:     mat->structurally_symmetric_set = flg;
5699: #if !defined(PETSC_USE_COMPLEX)
5700:     mat->symmetric     = flg;
5701:     mat->symmetric_set = PETSC_TRUE;
5702: #endif
5703:     break;
5704:   case MAT_STRUCTURALLY_SYMMETRIC:
5705:     mat->structurally_symmetric     = flg;
5706:     mat->structurally_symmetric_set = PETSC_TRUE;
5707:     break;
5708:   case MAT_SYMMETRY_ETERNAL:
5709:     mat->symmetric_eternal = flg;
5710:     break;
5711:   case MAT_STRUCTURE_ONLY:
5712:     mat->structure_only = flg;
5713:     break;
5714:   case MAT_SORTED_FULL:
5715:     mat->sortedfull = flg;
5716:     break;
5717:   default:
5718:     break;
5719:   }
5720:   if (mat->ops->setoption) {
5721:     (*mat->ops->setoption)(mat,op,flg);
5722:   }
5723:   return(0);
5724: }

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

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

5731:    Input Parameters:
5732: +  mat - the matrix
5733: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5741:    Level: intermediate

5743: .seealso:  MatOption, MatSetOption()

5745: @*/
5746: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5747: {

5752:   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);
5753:   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()");

5755:   switch (op) {
5756:   case MAT_NO_OFF_PROC_ENTRIES:
5757:     *flg = mat->nooffprocentries;
5758:     break;
5759:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5760:     *flg = mat->nooffproczerorows;
5761:     break;
5762:   case MAT_SYMMETRIC:
5763:     *flg = mat->symmetric;
5764:     break;
5765:   case MAT_HERMITIAN:
5766:     *flg = mat->hermitian;
5767:     break;
5768:   case MAT_STRUCTURALLY_SYMMETRIC:
5769:     *flg = mat->structurally_symmetric;
5770:     break;
5771:   case MAT_SYMMETRY_ETERNAL:
5772:     *flg = mat->symmetric_eternal;
5773:     break;
5774:   case MAT_SPD:
5775:     *flg = mat->spd;
5776:     break;
5777:   default:
5778:     break;
5779:   }
5780:   return(0);
5781: }

5783: /*@
5784:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5785:    this routine retains the old nonzero structure.

5787:    Logically Collective on Mat

5789:    Input Parameters:
5790: .  mat - the matrix

5792:    Level: intermediate

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

5798: .seealso: MatZeroRows()
5799: @*/
5800: PetscErrorCode MatZeroEntries(Mat mat)
5801: {

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

5812:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5813:   (*mat->ops->zeroentries)(mat);
5814:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5815:   PetscObjectStateIncrease((PetscObject)mat);
5816:   return(0);
5817: }

5819: /*@
5820:    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5821:    of a set of rows and columns of a matrix.

5823:    Collective on Mat

5825:    Input Parameters:
5826: +  mat - the matrix
5827: .  numRows - the number of rows to remove
5828: .  rows - the global row indices
5829: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5830: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5831: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5850:    Level: intermediate

5852: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5853:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5854: @*/
5855: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5856: {

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

5868:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5869:   MatViewFromOptions(mat,NULL,"-mat_view");
5870:   PetscObjectStateIncrease((PetscObject)mat);
5871:   return(0);
5872: }

5874: /*@
5875:    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5876:    of a set of rows and columns of a matrix.

5878:    Collective on Mat

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

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

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

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

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

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

5904:    Level: intermediate

5906: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5907:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5908: @*/
5909: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5910: {
5912:   PetscInt       numRows;
5913:   const PetscInt *rows;

5920:   ISGetLocalSize(is,&numRows);
5921:   ISGetIndices(is,&rows);
5922:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5923:   ISRestoreIndices(is,&rows);
5924:   return(0);
5925: }

5927: /*@
5928:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5929:    of a set of rows of a matrix.

5931:    Collective on Mat

5933:    Input Parameters:
5934: +  mat - the matrix
5935: .  numRows - the number of rows to remove
5936: .  rows - the global row indices
5937: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5938: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5939: -  b - optional vector of right hand side, that will be adjusted by provided solution

5941:    Notes:
5942:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5943:    but does not release memory.  For the dense and block diagonal
5944:    formats this does not alter the nonzero structure.

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

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

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

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

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

5965:    Level: intermediate

5967: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5968:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5969: @*/
5970: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5971: {

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

5983:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5984:   MatViewFromOptions(mat,NULL,"-mat_view");
5985:   PetscObjectStateIncrease((PetscObject)mat);
5986:   return(0);
5987: }

5989: /*@
5990:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5991:    of a set of rows of a matrix.

5993:    Collective on Mat

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

6002:    Notes:
6003:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6004:    but does not release memory.  For the dense and block diagonal
6005:    formats this does not alter the nonzero structure.

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

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

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

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

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

6026:    Level: intermediate

6028: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6029:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6030: @*/
6031: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6032: {
6033:   PetscInt       numRows;
6034:   const PetscInt *rows;

6041:   ISGetLocalSize(is,&numRows);
6042:   ISGetIndices(is,&rows);
6043:   MatZeroRows(mat,numRows,rows,diag,x,b);
6044:   ISRestoreIndices(is,&rows);
6045:   return(0);
6046: }

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

6052:    Collective on Mat

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

6062:    Notes:
6063:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6064:    but does not release memory.  For the dense and block diagonal
6065:    formats this does not alter the nonzero structure.

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

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

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

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

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

6085:    In Fortran idxm and idxn should be declared as
6086: $     MatStencil idxm(4,m)
6087:    and the values inserted using
6088: $    idxm(MatStencil_i,1) = i
6089: $    idxm(MatStencil_j,1) = j
6090: $    idxm(MatStencil_k,1) = k
6091: $    idxm(MatStencil_c,1) = c
6092:    etc

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

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

6102:    Level: intermediate

6104: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6105:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6106: @*/
6107: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6108: {
6109:   PetscInt       dim     = mat->stencil.dim;
6110:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6111:   PetscInt       *dims   = mat->stencil.dims+1;
6112:   PetscInt       *starts = mat->stencil.starts;
6113:   PetscInt       *dxm    = (PetscInt*) rows;
6114:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6122:   PetscMalloc1(numRows, &jdxm);
6123:   for (i = 0; i < numRows; ++i) {
6124:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6125:     for (j = 0; j < 3-sdim; ++j) dxm++;
6126:     /* Local index in X dir */
6127:     tmp = *dxm++ - starts[0];
6128:     /* Loop over remaining dimensions */
6129:     for (j = 0; j < dim-1; ++j) {
6130:       /* If nonlocal, set index to be negative */
6131:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6132:       /* Update local index */
6133:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6134:     }
6135:     /* Skip component slot if necessary */
6136:     if (mat->stencil.noc) dxm++;
6137:     /* Local row number */
6138:     if (tmp >= 0) {
6139:       jdxm[numNewRows++] = tmp;
6140:     }
6141:   }
6142:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6143:   PetscFree(jdxm);
6144:   return(0);
6145: }

6147: /*@
6148:    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6149:    of a set of rows and columns of a matrix.

6151:    Collective on Mat

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

6161:    Notes:
6162:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6163:    but does not release memory.  For the dense and block diagonal
6164:    formats this does not alter the nonzero structure.

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

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

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

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

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

6184:    In Fortran idxm and idxn should be declared as
6185: $     MatStencil idxm(4,m)
6186:    and the values inserted using
6187: $    idxm(MatStencil_i,1) = i
6188: $    idxm(MatStencil_j,1) = j
6189: $    idxm(MatStencil_k,1) = k
6190: $    idxm(MatStencil_c,1) = c
6191:    etc

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

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

6201:    Level: intermediate

6203: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6204:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6205: @*/
6206: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6207: {
6208:   PetscInt       dim     = mat->stencil.dim;
6209:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6210:   PetscInt       *dims   = mat->stencil.dims+1;
6211:   PetscInt       *starts = mat->stencil.starts;
6212:   PetscInt       *dxm    = (PetscInt*) rows;
6213:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6221:   PetscMalloc1(numRows, &jdxm);
6222:   for (i = 0; i < numRows; ++i) {
6223:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6224:     for (j = 0; j < 3-sdim; ++j) dxm++;
6225:     /* Local index in X dir */
6226:     tmp = *dxm++ - starts[0];
6227:     /* Loop over remaining dimensions */
6228:     for (j = 0; j < dim-1; ++j) {
6229:       /* If nonlocal, set index to be negative */
6230:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6231:       /* Update local index */
6232:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6233:     }
6234:     /* Skip component slot if necessary */
6235:     if (mat->stencil.noc) dxm++;
6236:     /* Local row number */
6237:     if (tmp >= 0) {
6238:       jdxm[numNewRows++] = tmp;
6239:     }
6240:   }
6241:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6242:   PetscFree(jdxm);
6243:   return(0);
6244: }

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

6250:    Collective on Mat

6252:    Input Parameters:
6253: +  mat - the matrix
6254: .  numRows - the number of rows to remove
6255: .  rows - the global row indices
6256: .  diag - value put in all diagonals of eliminated rows
6257: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6258: -  b - optional vector of right hand side, that will be adjusted by provided solution

6260:    Notes:
6261:    Before calling MatZeroRowsLocal(), the user must first set the
6262:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6264:    For the AIJ matrix formats this removes the old nonzero structure,
6265:    but does not release memory.  For the dense and block diagonal
6266:    formats this does not alter the nonzero structure.

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

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

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

6279:    Level: intermediate

6281: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6282:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6283: @*/
6284: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6285: {

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

6296:   if (mat->ops->zerorowslocal) {
6297:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6298:   } else {
6299:     IS             is, newis;
6300:     const PetscInt *newRows;

6302:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6303:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6304:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6305:     ISGetIndices(newis,&newRows);
6306:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6307:     ISRestoreIndices(newis,&newRows);
6308:     ISDestroy(&newis);
6309:     ISDestroy(&is);
6310:   }
6311:   PetscObjectStateIncrease((PetscObject)mat);
6312:   return(0);
6313: }

6315: /*@
6316:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6317:    of a set of rows of a matrix; using local numbering of rows.

6319:    Collective on Mat

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

6328:    Notes:
6329:    Before calling MatZeroRowsLocalIS(), the user must first set the
6330:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6332:    For the AIJ matrix formats this removes the old nonzero structure,
6333:    but does not release memory.  For the dense and block diagonal
6334:    formats this does not alter the nonzero structure.

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

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

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

6347:    Level: intermediate

6349: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6350:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6351: @*/
6352: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6353: {
6355:   PetscInt       numRows;
6356:   const PetscInt *rows;

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

6366:   ISGetLocalSize(is,&numRows);
6367:   ISGetIndices(is,&rows);
6368:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6369:   ISRestoreIndices(is,&rows);
6370:   return(0);
6371: }

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

6377:    Collective on Mat

6379:    Input Parameters:
6380: +  mat - the matrix
6381: .  numRows - the number of rows to remove
6382: .  rows - the global row indices
6383: .  diag - value put in all diagonals of eliminated rows
6384: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6385: -  b - optional vector of right hand side, that will be adjusted by provided solution

6387:    Notes:
6388:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6389:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6395:    Level: intermediate

6397: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6398:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6399: @*/
6400: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6401: {
6403:   IS             is, newis;
6404:   const PetscInt *newRows;

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

6414:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6415:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6416:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6417:   ISGetIndices(newis,&newRows);
6418:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6419:   ISRestoreIndices(newis,&newRows);
6420:   ISDestroy(&newis);
6421:   ISDestroy(&is);
6422:   PetscObjectStateIncrease((PetscObject)mat);
6423:   return(0);
6424: }

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

6430:    Collective on Mat

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

6439:    Notes:
6440:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6441:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6447:    Level: intermediate

6449: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6450:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6451: @*/
6452: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6453: {
6455:   PetscInt       numRows;
6456:   const PetscInt *rows;

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

6466:   ISGetLocalSize(is,&numRows);
6467:   ISGetIndices(is,&rows);
6468:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6469:   ISRestoreIndices(is,&rows);
6470:   return(0);
6471: }

6473: /*@C
6474:    MatGetSize - Returns the numbers of rows and columns in a matrix.

6476:    Not Collective

6478:    Input Parameter:
6479: .  mat - the matrix

6481:    Output Parameters:
6482: +  m - the number of global rows
6483: -  n - the number of global columns

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

6487:    Level: beginner

6489: .seealso: MatGetLocalSize()
6490: @*/
6491: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6492: {
6495:   if (m) *m = mat->rmap->N;
6496:   if (n) *n = mat->cmap->N;
6497:   return(0);
6498: }

6500: /*@C
6501:    MatGetLocalSize - Returns the number of local rows and local columns
6502:    of a matrix, that is the local size of the left and right vectors as returned by MatCreateVecs().

6504:    Not Collective

6506:    Input Parameters:
6507: .  mat - the matrix

6509:    Output Parameters:
6510: +  m - the number of local rows
6511: -  n - the number of local columns

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

6515:    Level: beginner

6517: .seealso: MatGetSize()
6518: @*/
6519: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6520: {
6525:   if (m) *m = mat->rmap->n;
6526:   if (n) *n = mat->cmap->n;
6527:   return(0);
6528: }

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

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

6536:    Input Parameters:
6537: .  mat - the matrix

6539:    Output Parameters:
6540: +  m - the global index of the first local column
6541: -  n - one more than the global index of the last local column

6543:    Notes:
6544:     both output parameters can be NULL on input.

6546:    Level: developer

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

6550: @*/
6551: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6552: {
6558:   MatCheckPreallocated(mat,1);
6559:   if (m) *m = mat->cmap->rstart;
6560:   if (n) *n = mat->cmap->rend;
6561:   return(0);
6562: }

6564: /*@C
6565:    MatGetOwnershipRange - Returns the range of matrix rows owned by
6566:    this processor, assuming that the matrix is laid out with the first
6567:    n1 rows on the first processor, the next n2 rows on the second, etc.
6568:    For certain parallel layouts this range may not be well defined.

6570:    Not Collective

6572:    Input Parameters:
6573: .  mat - the matrix

6575:    Output Parameters:
6576: +  m - the global index of the first local row
6577: -  n - one more than the global index of the last local row

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

6584:    Level: beginner

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

6588: @*/
6589: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6590: {
6596:   MatCheckPreallocated(mat,1);
6597:   if (m) *m = mat->rmap->rstart;
6598:   if (n) *n = mat->rmap->rend;
6599:   return(0);
6600: }

6602: /*@C
6603:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6604:    each process

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

6608:    Input Parameters:
6609: .  mat - the matrix

6611:    Output Parameters:
6612: .  ranges - start of each processors portion plus one more than the total length at the end

6614:    Level: beginner

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

6618: @*/
6619: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6620: {

6626:   MatCheckPreallocated(mat,1);
6627:   PetscLayoutGetRanges(mat->rmap,ranges);
6628:   return(0);
6629: }

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

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

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

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

6643:    Level: beginner

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

6647: @*/
6648: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6649: {

6655:   MatCheckPreallocated(mat,1);
6656:   PetscLayoutGetRanges(mat->cmap,ranges);
6657:   return(0);
6658: }

6660: /*@C
6661:    MatGetOwnershipIS - Get row and column ownership as index sets

6663:    Not Collective

6665:    Input Arguments:
6666: .  A - matrix of type Elemental or ScaLAPACK

6668:    Output Arguments:
6669: +  rows - rows in which this process owns elements
6670: -  cols - columns in which this process owns elements

6672:    Level: intermediate

6674: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6675: @*/
6676: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6677: {
6678:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6681:   MatCheckPreallocated(A,1);
6682:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6683:   if (f) {
6684:     (*f)(A,rows,cols);
6685:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6686:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6687:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6688:   }
6689:   return(0);
6690: }

6692: /*@C
6693:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6694:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6695:    to complete the factorization.

6697:    Collective on Mat

6699:    Input Parameters:
6700: +  mat - the matrix
6701: .  row - row permutation
6702: .  column - column permutation
6703: -  info - structure containing
6704: $      levels - number of levels of fill.
6705: $      expected fill - as ratio of original fill.
6706: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6707:                 missing diagonal entries)

6709:    Output Parameters:
6710: .  fact - new matrix that has been symbolically factored

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

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

6719:    Level: developer

6721: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6722:           MatGetOrdering(), MatFactorInfo

6724:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6729:    References:
6730:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6731: @*/
6732: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6733: {

6743:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6744:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6745:   if (!fact->ops->ilufactorsymbolic) {
6746:     MatSolverType stype;
6747:     MatFactorGetSolverType(fact,&stype);
6748:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver type %s",((PetscObject)mat)->type_name,stype);
6749:   }
6750:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6751:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6752:   MatCheckPreallocated(mat,2);

6754:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6755:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6756:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6757:   return(0);
6758: }

6760: /*@C
6761:    MatICCFactorSymbolic - Performs symbolic incomplete
6762:    Cholesky factorization for a symmetric matrix.  Use
6763:    MatCholeskyFactorNumeric() to complete the factorization.

6765:    Collective on Mat

6767:    Input Parameters:
6768: +  mat - the matrix
6769: .  perm - row and column permutation
6770: -  info - structure containing
6771: $      levels - number of levels of fill.
6772: $      expected fill - as ratio of original fill.

6774:    Output Parameter:
6775: .  fact - the factored matrix

6777:    Notes:
6778:    Most users should employ the KSP interface for linear solvers
6779:    instead of working directly with matrix algebra routines such as this.
6780:    See, e.g., KSPCreate().

6782:    Level: developer

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

6786:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6791:    References:
6792:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6793: @*/
6794: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6795: {

6804:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6805:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6806:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6807:   if (!(fact)->ops->iccfactorsymbolic) {
6808:     MatSolverType stype;
6809:     MatFactorGetSolverType(fact,&stype);
6810:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver type %s",((PetscObject)mat)->type_name,stype);
6811:   }
6812:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6813:   MatCheckPreallocated(mat,2);

6815:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6816:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6817:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6818:   return(0);
6819: }

6821: /*@C
6822:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6823:    points to an array of valid matrices, they may be reused to store the new
6824:    submatrices.

6826:    Collective on Mat

6828:    Input Parameters:
6829: +  mat - the matrix
6830: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6831: .  irow, icol - index sets of rows and columns to extract
6832: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6834:    Output Parameter:
6835: .  submat - the array of submatrices

6837:    Notes:
6838:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6839:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6840:    to extract a parallel submatrix.

6842:    Some matrix types place restrictions on the row and column
6843:    indices, such as that they be sorted or that they be equal to each other.

6845:    The index sets may not have duplicate entries.

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

6851:    When finished using the submatrices, the user should destroy
6852:    them with MatDestroySubMatrices().

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

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

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

6865:    Fortran Note:
6866:    The Fortran interface is slightly different from that given below; it
6867:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6869:    Level: advanced


6872: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6873: @*/
6874: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6875: {
6877:   PetscInt       i;
6878:   PetscBool      eq;

6883:   if (n) {
6888:   }
6890:   if (n && scall == MAT_REUSE_MATRIX) {
6893:   }
6894:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6895:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6896:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6897:   MatCheckPreallocated(mat,1);

6899:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6900:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6901:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6902:   for (i=0; i<n; i++) {
6903:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6904:     ISEqualUnsorted(irow[i],icol[i],&eq);
6905:     if (eq) {
6906:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6907:     }
6908:   }
6909:   return(0);
6910: }

6912: /*@C
6913:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6915:    Collective on Mat

6917:    Input Parameters:
6918: +  mat - the matrix
6919: .  n   - the number of submatrixes to be extracted
6920: .  irow, icol - index sets of rows and columns to extract
6921: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6923:    Output Parameter:
6924: .  submat - the array of submatrices

6926:    Level: advanced


6929: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6930: @*/
6931: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6932: {
6934:   PetscInt       i;
6935:   PetscBool      eq;

6940:   if (n) {
6945:   }
6947:   if (n && scall == MAT_REUSE_MATRIX) {
6950:   }
6951:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6952:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6953:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6954:   MatCheckPreallocated(mat,1);

6956:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6957:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6958:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6959:   for (i=0; i<n; i++) {
6960:     ISEqualUnsorted(irow[i],icol[i],&eq);
6961:     if (eq) {
6962:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6963:     }
6964:   }
6965:   return(0);
6966: }

6968: /*@C
6969:    MatDestroyMatrices - Destroys an array of matrices.

6971:    Collective on Mat

6973:    Input Parameters:
6974: +  n - the number of local matrices
6975: -  mat - the matrices (note that this is a pointer to the array of matrices)

6977:    Level: advanced

6979:     Notes:
6980:     Frees not only the matrices, but also the array that contains the matrices
6981:            In Fortran will not free the array.

6983: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6984: @*/
6985: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6986: {
6988:   PetscInt       i;

6991:   if (!*mat) return(0);
6992:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6995:   for (i=0; i<n; i++) {
6996:     MatDestroy(&(*mat)[i]);
6997:   }

6999:   /* memory is allocated even if n = 0 */
7000:   PetscFree(*mat);
7001:   return(0);
7002: }

7004: /*@C
7005:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

7007:    Collective on Mat

7009:    Input Parameters:
7010: +  n - the number of local matrices
7011: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
7012:                        sequence of MatCreateSubMatrices())

7014:    Level: advanced

7016:     Notes:
7017:     Frees not only the matrices, but also the array that contains the matrices
7018:            In Fortran will not free the array.

7020: .seealso: MatCreateSubMatrices()
7021: @*/
7022: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
7023: {
7025:   Mat            mat0;

7028:   if (!*mat) return(0);
7029:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7030:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

7033:   mat0 = (*mat)[0];
7034:   if (mat0 && mat0->ops->destroysubmatrices) {
7035:     (mat0->ops->destroysubmatrices)(n,mat);
7036:   } else {
7037:     MatDestroyMatrices(n,mat);
7038:   }
7039:   return(0);
7040: }

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

7045:    Collective on Mat

7047:    Input Parameters:
7048: .  mat - the matrix

7050:    Output Parameter:
7051: .  matstruct - the sequential matrix with the nonzero structure of mat

7053:   Level: intermediate

7055: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7056: @*/
7057: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7058: {


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

7069:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7070:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7071:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
7072:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7073:   return(0);
7074: }

7076: /*@C
7077:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

7079:    Collective on Mat

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

7085:    Level: advanced

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

7090: .seealso: MatGetSeqNonzeroStructure()
7091: @*/
7092: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7093: {

7098:   MatDestroy(mat);
7099:   return(0);
7100: }

7102: /*@
7103:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7104:    replaces the index sets by larger ones that represent submatrices with
7105:    additional overlap.

7107:    Collective on Mat

7109:    Input Parameters:
7110: +  mat - the matrix
7111: .  n   - the number of index sets
7112: .  is  - the array of index sets (these index sets will changed during the call)
7113: -  ov  - the additional overlap requested

7115:    Options Database:
7116: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7118:    Level: developer


7121: .seealso: MatCreateSubMatrices()
7122: @*/
7123: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7124: {

7130:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7131:   if (n) {
7134:   }
7135:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7136:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7137:   MatCheckPreallocated(mat,1);

7139:   if (!ov) return(0);
7140:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7141:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7142:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7143:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7144:   return(0);
7145: }


7148: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7150: /*@
7151:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7152:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7153:    additional overlap.

7155:    Collective on Mat

7157:    Input Parameters:
7158: +  mat - the matrix
7159: .  n   - the number of index sets
7160: .  is  - the array of index sets (these index sets will changed during the call)
7161: -  ov  - the additional overlap requested

7163:    Options Database:
7164: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7166:    Level: developer


7169: .seealso: MatCreateSubMatrices()
7170: @*/
7171: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7172: {
7173:   PetscInt       i;

7179:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7180:   if (n) {
7183:   }
7184:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7185:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7186:   MatCheckPreallocated(mat,1);
7187:   if (!ov) return(0);
7188:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7189:   for (i=0; i<n; i++){
7190:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7191:   }
7192:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7193:   return(0);
7194: }




7199: /*@
7200:    MatGetBlockSize - Returns the matrix block size.

7202:    Not Collective

7204:    Input Parameter:
7205: .  mat - the matrix

7207:    Output Parameter:
7208: .  bs - block size

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

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

7215:    Level: intermediate

7217: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7218: @*/
7219: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7220: {
7224:   *bs = PetscAbs(mat->rmap->bs);
7225:   return(0);
7226: }

7228: /*@
7229:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7231:    Not Collective

7233:    Input Parameter:
7234: .  mat - the matrix

7236:    Output Parameter:
7237: +  rbs - row block size
7238: -  cbs - column block size

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

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

7246:    Level: intermediate

7248: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7249: @*/
7250: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7251: {
7256:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7257:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7258:   return(0);
7259: }

7261: /*@
7262:    MatSetBlockSize - Sets the matrix block size.

7264:    Logically Collective on Mat

7266:    Input Parameters:
7267: +  mat - the matrix
7268: -  bs - block size

7270:    Notes:
7271:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7272:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7274:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7275:     is compatible with the matrix local sizes.

7277:    Level: intermediate

7279: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7280: @*/
7281: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7282: {

7288:   MatSetBlockSizes(mat,bs,bs);
7289:   return(0);
7290: }

7292: /*@
7293:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7295:    Logically Collective on Mat

7297:    Input Parameters:
7298: +  mat - the matrix
7299: .  nblocks - the number of blocks on this process
7300: -  bsizes - the block sizes

7302:    Notes:
7303:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7305:    Level: intermediate

7307: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7308: @*/
7309: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7310: {
7312:   PetscInt       i,ncnt = 0, nlocal;

7316:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7317:   MatGetLocalSize(mat,&nlocal,NULL);
7318:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7319:   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);
7320:   PetscFree(mat->bsizes);
7321:   mat->nblocks = nblocks;
7322:   PetscMalloc1(nblocks,&mat->bsizes);
7323:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7324:   return(0);
7325: }

7327: /*@C
7328:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7330:    Logically Collective on Mat

7332:    Input Parameters:
7333: .  mat - the matrix

7335:    Output Parameters:
7336: +  nblocks - the number of blocks on this process
7337: -  bsizes - the block sizes

7339:    Notes: Currently not supported from Fortran

7341:    Level: intermediate

7343: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7344: @*/
7345: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7346: {
7349:   *nblocks = mat->nblocks;
7350:   *bsizes  = mat->bsizes;
7351:   return(0);
7352: }

7354: /*@
7355:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7357:    Logically Collective on Mat

7359:    Input Parameters:
7360: +  mat - the matrix
7361: .  rbs - row block size
7362: -  cbs - column block size

7364:    Notes:
7365:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7366:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7367:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7369:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7370:     are compatible with the matrix local sizes.

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

7374:    Level: intermediate

7376: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7377: @*/
7378: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7379: {

7386:   if (mat->ops->setblocksizes) {
7387:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7388:   }
7389:   if (mat->rmap->refcnt) {
7390:     ISLocalToGlobalMapping l2g = NULL;
7391:     PetscLayout            nmap = NULL;

7393:     PetscLayoutDuplicate(mat->rmap,&nmap);
7394:     if (mat->rmap->mapping) {
7395:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7396:     }
7397:     PetscLayoutDestroy(&mat->rmap);
7398:     mat->rmap = nmap;
7399:     mat->rmap->mapping = l2g;
7400:   }
7401:   if (mat->cmap->refcnt) {
7402:     ISLocalToGlobalMapping l2g = NULL;
7403:     PetscLayout            nmap = NULL;

7405:     PetscLayoutDuplicate(mat->cmap,&nmap);
7406:     if (mat->cmap->mapping) {
7407:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7408:     }
7409:     PetscLayoutDestroy(&mat->cmap);
7410:     mat->cmap = nmap;
7411:     mat->cmap->mapping = l2g;
7412:   }
7413:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7414:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7415:   return(0);
7416: }

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

7421:    Logically Collective on Mat

7423:    Input Parameters:
7424: +  mat - the matrix
7425: .  fromRow - matrix from which to copy row block size
7426: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7428:    Level: developer

7430: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7431: @*/
7432: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7433: {

7440:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7441:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7442:   return(0);
7443: }

7445: /*@
7446:    MatResidual - Default routine to calculate the residual.

7448:    Collective on Mat

7450:    Input Parameters:
7451: +  mat - the matrix
7452: .  b   - the right-hand-side
7453: -  x   - the approximate solution

7455:    Output Parameter:
7456: .  r - location to store the residual

7458:    Level: developer

7460: .seealso: PCMGSetResidual()
7461: @*/
7462: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7463: {

7472:   MatCheckPreallocated(mat,1);
7473:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7474:   if (!mat->ops->residual) {
7475:     MatMult(mat,x,r);
7476:     VecAYPX(r,-1.0,b);
7477:   } else {
7478:     (*mat->ops->residual)(mat,b,x,r);
7479:   }
7480:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7481:   return(0);
7482: }

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

7487:    Collective on Mat

7489:     Input Parameters:
7490: +   mat - the matrix
7491: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7492: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7493: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7494:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7495:                  always used.

7497:     Output Parameters:
7498: +   n - number of rows in the (possibly compressed) matrix
7499: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7500: .   ja - the column indices
7501: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7502:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7504:     Level: developer

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

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

7511:     Fortran Notes:
7512:     In Fortran use
7513: $
7514: $      PetscInt ia(1), ja(1)
7515: $      PetscOffset iia, jja
7516: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7517: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7519:      or
7520: $
7521: $    PetscInt, pointer :: ia(:),ja(:)
7522: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7523: $    ! Access the ith and jth entries via ia(i) and ja(j)

7525: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7526: @*/
7527: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7528: {

7538:   MatCheckPreallocated(mat,1);
7539:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7540:   else {
7541:     *done = PETSC_TRUE;
7542:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7543:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7544:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7545:   }
7546:   return(0);
7547: }

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

7552:     Collective on Mat

7554:     Input Parameters:
7555: +   mat - the matrix
7556: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7557: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7558:                 symmetrized
7559: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7560:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7561:                  always used.
7562: .   n - number of columns in the (possibly compressed) matrix
7563: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7564: -   ja - the row indices

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

7569:     Level: developer

7571: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7572: @*/
7573: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7574: {

7584:   MatCheckPreallocated(mat,1);
7585:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7586:   else {
7587:     *done = PETSC_TRUE;
7588:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7589:   }
7590:   return(0);
7591: }

7593: /*@C
7594:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7595:     MatGetRowIJ().

7597:     Collective on Mat

7599:     Input Parameters:
7600: +   mat - the matrix
7601: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7602: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7603:                 symmetrized
7604: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7605:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7606:                  always used.
7607: .   n - size of (possibly compressed) matrix
7608: .   ia - the row pointers
7609: -   ja - the column indices

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

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

7619:     Level: developer

7621: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7622: @*/
7623: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7624: {

7633:   MatCheckPreallocated(mat,1);

7635:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7636:   else {
7637:     *done = PETSC_TRUE;
7638:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7639:     if (n)  *n = 0;
7640:     if (ia) *ia = NULL;
7641:     if (ja) *ja = NULL;
7642:   }
7643:   return(0);
7644: }

7646: /*@C
7647:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7648:     MatGetColumnIJ().

7650:     Collective on Mat

7652:     Input Parameters:
7653: +   mat - the matrix
7654: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7655: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7656:                 symmetrized
7657: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7658:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7659:                  always used.

7661:     Output Parameters:
7662: +   n - size of (possibly compressed) matrix
7663: .   ia - the column pointers
7664: .   ja - the row indices
7665: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7667:     Level: developer

7669: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7670: @*/
7671: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7672: {

7681:   MatCheckPreallocated(mat,1);

7683:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7684:   else {
7685:     *done = PETSC_TRUE;
7686:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7687:     if (n)  *n = 0;
7688:     if (ia) *ia = NULL;
7689:     if (ja) *ja = NULL;
7690:   }
7691:   return(0);
7692: }

7694: /*@C
7695:     MatColoringPatch -Used inside matrix coloring routines that
7696:     use MatGetRowIJ() and/or MatGetColumnIJ().

7698:     Collective on Mat

7700:     Input Parameters:
7701: +   mat - the matrix
7702: .   ncolors - max color value
7703: .   n   - number of entries in colorarray
7704: -   colorarray - array indicating color for each column

7706:     Output Parameters:
7707: .   iscoloring - coloring generated using colorarray information

7709:     Level: developer

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

7713: @*/
7714: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7715: {

7723:   MatCheckPreallocated(mat,1);

7725:   if (!mat->ops->coloringpatch) {
7726:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7727:   } else {
7728:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7729:   }
7730:   return(0);
7731: }


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

7737:    Logically Collective on Mat

7739:    Input Parameter:
7740: .  mat - the factored matrix to be reset

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

7749:    Note that one can specify in-place ILU(0) factorization by calling
7750: .vb
7751:      PCType(pc,PCILU);
7752:      PCFactorSeUseInPlace(pc);
7753: .ve
7754:    or by using the options -pc_type ilu -pc_factor_in_place

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

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

7765:    Level: developer

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

7769: @*/
7770: PetscErrorCode MatSetUnfactored(Mat mat)
7771: {

7777:   MatCheckPreallocated(mat,1);
7778:   mat->factortype = MAT_FACTOR_NONE;
7779:   if (!mat->ops->setunfactored) return(0);
7780:   (*mat->ops->setunfactored)(mat);
7781:   return(0);
7782: }

7784: /*MC
7785:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7787:     Synopsis:
7788:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7790:     Not collective

7792:     Input Parameter:
7793: .   x - matrix

7795:     Output Parameters:
7796: +   xx_v - the Fortran90 pointer to the array
7797: -   ierr - error code

7799:     Example of Usage:
7800: .vb
7801:       PetscScalar, pointer xx_v(:,:)
7802:       ....
7803:       call MatDenseGetArrayF90(x,xx_v,ierr)
7804:       a = xx_v(3)
7805:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7806: .ve

7808:     Level: advanced

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

7812: M*/

7814: /*MC
7815:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7816:     accessed with MatDenseGetArrayF90().

7818:     Synopsis:
7819:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7821:     Not collective

7823:     Input Parameters:
7824: +   x - matrix
7825: -   xx_v - the Fortran90 pointer to the array

7827:     Output Parameter:
7828: .   ierr - error code

7830:     Example of Usage:
7831: .vb
7832:        PetscScalar, pointer xx_v(:,:)
7833:        ....
7834:        call MatDenseGetArrayF90(x,xx_v,ierr)
7835:        a = xx_v(3)
7836:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7837: .ve

7839:     Level: advanced

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

7843: M*/


7846: /*MC
7847:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7849:     Synopsis:
7850:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7852:     Not collective

7854:     Input Parameter:
7855: .   x - matrix

7857:     Output Parameters:
7858: +   xx_v - the Fortran90 pointer to the array
7859: -   ierr - error code

7861:     Example of Usage:
7862: .vb
7863:       PetscScalar, pointer xx_v(:)
7864:       ....
7865:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7866:       a = xx_v(3)
7867:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7868: .ve

7870:     Level: advanced

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

7874: M*/

7876: /*MC
7877:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7878:     accessed with MatSeqAIJGetArrayF90().

7880:     Synopsis:
7881:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7883:     Not collective

7885:     Input Parameters:
7886: +   x - matrix
7887: -   xx_v - the Fortran90 pointer to the array

7889:     Output Parameter:
7890: .   ierr - error code

7892:     Example of Usage:
7893: .vb
7894:        PetscScalar, pointer xx_v(:)
7895:        ....
7896:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7897:        a = xx_v(3)
7898:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7899: .ve

7901:     Level: advanced

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

7905: M*/


7908: /*@
7909:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7910:                       as the original matrix.

7912:     Collective on Mat

7914:     Input Parameters:
7915: +   mat - the original matrix
7916: .   isrow - parallel IS containing the rows this processor should obtain
7917: .   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.
7918: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7920:     Output Parameter:
7921: .   newmat - the new submatrix, of the same type as the old

7923:     Level: advanced

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

7928:     Some matrix types place restrictions on the row and column indices, such
7929:     as that they be sorted or that they be equal to each other.

7931:     The index sets may not have duplicate entries.

7933:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7934:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7935:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7936:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7937:    you are finished using it.

7939:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7940:     the input matrix.

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

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

7950: .vb
7951:             1  2  0  |  0  3  0  |  0  4
7952:     Proc0   0  5  6  |  7  0  0  |  8  0
7953:             9  0 10  | 11  0  0  | 12  0
7954:     -------------------------------------
7955:            13  0 14  | 15 16 17  |  0  0
7956:     Proc1   0 18  0  | 19 20 21  |  0  0
7957:             0  0  0  | 22 23  0  | 24  0
7958:     -------------------------------------
7959:     Proc2  25 26 27  |  0  0 28  | 29  0
7960:            30  0  0  | 31 32 33  |  0 34
7961: .ve

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

7965: .vb
7966:             2  0  |  0  3  0  |  0
7967:     Proc0   5  6  |  7  0  0  |  8
7968:     -------------------------------
7969:     Proc1  18  0  | 19 20 21  |  0
7970:     -------------------------------
7971:     Proc2  26 27  |  0  0 28  | 29
7972:             0  0  | 31 32 33  |  0
7973: .ve


7976: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7977: @*/
7978: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7979: {
7981:   PetscMPIInt    size;
7982:   Mat            *local;
7983:   IS             iscoltmp;
7984:   PetscBool      flg;

7993:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7994:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7996:   MatCheckPreallocated(mat,1);
7997:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7999:   if (!iscol || isrow == iscol) {
8000:     PetscBool   stride;
8001:     PetscMPIInt grabentirematrix = 0,grab;
8002:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
8003:     if (stride) {
8004:       PetscInt first,step,n,rstart,rend;
8005:       ISStrideGetInfo(isrow,&first,&step);
8006:       if (step == 1) {
8007:         MatGetOwnershipRange(mat,&rstart,&rend);
8008:         if (rstart == first) {
8009:           ISGetLocalSize(isrow,&n);
8010:           if (n == rend-rstart) {
8011:             grabentirematrix = 1;
8012:           }
8013:         }
8014:       }
8015:     }
8016:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
8017:     if (grab) {
8018:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
8019:       if (cll == MAT_INITIAL_MATRIX) {
8020:         *newmat = mat;
8021:         PetscObjectReference((PetscObject)mat);
8022:       }
8023:       return(0);
8024:     }
8025:   }

8027:   if (!iscol) {
8028:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
8029:   } else {
8030:     iscoltmp = iscol;
8031:   }

8033:   /* if original matrix is on just one processor then use submatrix generated */
8034:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8035:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
8036:     goto setproperties;
8037:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8038:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
8039:     *newmat = *local;
8040:     PetscFree(local);
8041:     goto setproperties;
8042:   } else if (!mat->ops->createsubmatrix) {
8043:     /* Create a new matrix type that implements the operation using the full matrix */
8044:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8045:     switch (cll) {
8046:     case MAT_INITIAL_MATRIX:
8047:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
8048:       break;
8049:     case MAT_REUSE_MATRIX:
8050:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
8051:       break;
8052:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8053:     }
8054:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8055:     goto setproperties;
8056:   }

8058:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8059:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8060:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
8061:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

8063: setproperties:
8064:   ISEqualUnsorted(isrow,iscoltmp,&flg);
8065:   if (flg) {
8066:     MatPropagateSymmetryOptions(mat,*newmat);
8067:   }
8068:   if (!iscol) {ISDestroy(&iscoltmp);}
8069:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
8070:   return(0);
8071: }

8073: /*@
8074:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8076:    Not Collective

8078:    Input Parameters:
8079: +  A - the matrix we wish to propagate options from
8080: -  B - the matrix we wish to propagate options to

8082:    Level: beginner

8084:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

8086: .seealso: MatSetOption()
8087: @*/
8088: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8089: {

8095:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
8096:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
8097:   }
8098:   if (A->structurally_symmetric_set) {
8099:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
8100:   }
8101:   if (A->hermitian_set) {
8102:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
8103:   }
8104:   if (A->spd_set) {
8105:     MatSetOption(B,MAT_SPD,A->spd);
8106:   }
8107:   if (A->symmetric_set) {
8108:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
8109:   }
8110:   return(0);
8111: }

8113: /*@
8114:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8115:    used during the assembly process to store values that belong to
8116:    other processors.

8118:    Not Collective

8120:    Input Parameters:
8121: +  mat   - the matrix
8122: .  size  - the initial size of the stash.
8123: -  bsize - the initial size of the block-stash(if used).

8125:    Options Database Keys:
8126: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8127: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

8129:    Level: intermediate

8131:    Notes:
8132:      The block-stash is used for values set with MatSetValuesBlocked() while
8133:      the stash is used for values set with MatSetValues()

8135:      Run with the option -info and look for output of the form
8136:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8137:      to determine the appropriate value, MM, to use for size and
8138:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8139:      to determine the value, BMM to use for bsize


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

8144: @*/
8145: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8146: {

8152:   MatStashSetInitialSize_Private(&mat->stash,size);
8153:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8154:   return(0);
8155: }

8157: /*@
8158:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8159:      the matrix

8161:    Neighbor-wise Collective on Mat

8163:    Input Parameters:
8164: +  mat   - the matrix
8165: .  x,y - the vectors
8166: -  w - where the result is stored

8168:    Level: intermediate

8170:    Notes:
8171:     w may be the same vector as y.

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

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

8178: @*/
8179: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8180: {
8182:   PetscInt       M,N,Ny;

8190:   MatCheckPreallocated(A,1);
8191:   MatGetSize(A,&M,&N);
8192:   VecGetSize(y,&Ny);
8193:   if (M == Ny) {
8194:     MatMultAdd(A,x,y,w);
8195:   } else {
8196:     MatMultTransposeAdd(A,x,y,w);
8197:   }
8198:   return(0);
8199: }

8201: /*@
8202:    MatInterpolate - y = A*x or A'*x depending on the shape of
8203:      the matrix

8205:    Neighbor-wise Collective on Mat

8207:    Input Parameters:
8208: +  mat   - the matrix
8209: -  x,y - the vectors

8211:    Level: intermediate

8213:    Notes:
8214:     This allows one to use either the restriction or interpolation (its transpose)
8215:     matrix to do the interpolation

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

8219: @*/
8220: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8221: {
8223:   PetscInt       M,N,Ny;

8230:   MatCheckPreallocated(A,1);
8231:   MatGetSize(A,&M,&N);
8232:   VecGetSize(y,&Ny);
8233:   if (M == Ny) {
8234:     MatMult(A,x,y);
8235:   } else {
8236:     MatMultTranspose(A,x,y);
8237:   }
8238:   return(0);
8239: }

8241: /*@
8242:    MatRestrict - y = A*x or A'*x

8244:    Neighbor-wise Collective on Mat

8246:    Input Parameters:
8247: +  mat   - the matrix
8248: -  x,y - the vectors

8250:    Level: intermediate

8252:    Notes:
8253:     This allows one to use either the restriction or interpolation (its transpose)
8254:     matrix to do the restriction

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

8258: @*/
8259: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8260: {
8262:   PetscInt       M,N,Ny;

8269:   MatCheckPreallocated(A,1);

8271:   MatGetSize(A,&M,&N);
8272:   VecGetSize(y,&Ny);
8273:   if (M == Ny) {
8274:     MatMult(A,x,y);
8275:   } else {
8276:     MatMultTranspose(A,x,y);
8277:   }
8278:   return(0);
8279: }

8281: /*@
8282:    MatGetNullSpace - retrieves the null space of a matrix.

8284:    Logically Collective on Mat

8286:    Input Parameters:
8287: +  mat - the matrix
8288: -  nullsp - the null space object

8290:    Level: developer

8292: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8293: @*/
8294: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8295: {
8299:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8300:   return(0);
8301: }

8303: /*@
8304:    MatSetNullSpace - attaches a null space to a matrix.

8306:    Logically Collective on Mat

8308:    Input Parameters:
8309: +  mat - the matrix
8310: -  nullsp - the null space object

8312:    Level: advanced

8314:    Notes:
8315:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8317:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8318:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8320:       You can remove the null space by calling this routine with an nullsp of NULL


8323:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8324:    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).
8325:    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
8326:    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
8327:    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).

8329:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8331:     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
8332:     routine also automatically calls MatSetTransposeNullSpace().

8334: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8335: @*/
8336: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8337: {

8343:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8344:   MatNullSpaceDestroy(&mat->nullsp);
8345:   mat->nullsp = nullsp;
8346:   if (mat->symmetric_set && mat->symmetric) {
8347:     MatSetTransposeNullSpace(mat,nullsp);
8348:   }
8349:   return(0);
8350: }

8352: /*@
8353:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8355:    Logically Collective on Mat

8357:    Input Parameters:
8358: +  mat - the matrix
8359: -  nullsp - the null space object

8361:    Level: developer

8363: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8364: @*/
8365: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8366: {
8371:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8372:   return(0);
8373: }

8375: /*@
8376:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8378:    Logically Collective on Mat

8380:    Input Parameters:
8381: +  mat - the matrix
8382: -  nullsp - the null space object

8384:    Level: advanced

8386:    Notes:
8387:       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.
8388:       You must also call MatSetNullSpace()


8391:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8392:    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).
8393:    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
8394:    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
8395:    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).

8397:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8399: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8400: @*/
8401: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8402: {

8408:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8409:   MatNullSpaceDestroy(&mat->transnullsp);
8410:   mat->transnullsp = nullsp;
8411:   return(0);
8412: }

8414: /*@
8415:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8416:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8418:    Logically Collective on Mat

8420:    Input Parameters:
8421: +  mat - the matrix
8422: -  nullsp - the null space object

8424:    Level: advanced

8426:    Notes:
8427:       Overwrites any previous near null space that may have been attached

8429:       You can remove the null space by calling this routine with an nullsp of NULL

8431: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8432: @*/
8433: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8434: {

8441:   MatCheckPreallocated(mat,1);
8442:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8443:   MatNullSpaceDestroy(&mat->nearnullsp);
8444:   mat->nearnullsp = nullsp;
8445:   return(0);
8446: }

8448: /*@
8449:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8451:    Not Collective

8453:    Input Parameter:
8454: .  mat - the matrix

8456:    Output Parameter:
8457: .  nullsp - the null space object, NULL if not set

8459:    Level: developer

8461: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8462: @*/
8463: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8464: {
8469:   MatCheckPreallocated(mat,1);
8470:   *nullsp = mat->nearnullsp;
8471:   return(0);
8472: }

8474: /*@C
8475:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8477:    Collective on Mat

8479:    Input Parameters:
8480: +  mat - the matrix
8481: .  row - row/column permutation
8482: .  fill - expected fill factor >= 1.0
8483: -  level - level of fill, for ICC(k)

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

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

8493:    Level: developer


8496: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8501: @*/
8502: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8503: {

8511:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8512:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8513:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8514:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8515:   MatCheckPreallocated(mat,1);
8516:   (*mat->ops->iccfactor)(mat,row,info);
8517:   PetscObjectStateIncrease((PetscObject)mat);
8518:   return(0);
8519: }

8521: /*@
8522:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8523:          ghosted ones.

8525:    Not Collective

8527:    Input Parameters:
8528: +  mat - the matrix
8529: -  diag = the diagonal values, including ghost ones

8531:    Level: developer

8533:    Notes:
8534:     Works only for MPIAIJ and MPIBAIJ matrices

8536: .seealso: MatDiagonalScale()
8537: @*/
8538: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8539: {
8541:   PetscMPIInt    size;


8548:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8549:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8550:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8551:   if (size == 1) {
8552:     PetscInt n,m;
8553:     VecGetSize(diag,&n);
8554:     MatGetSize(mat,NULL,&m);
8555:     if (m == n) {
8556:       MatDiagonalScale(mat,NULL,diag);
8557:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8558:   } else {
8559:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8560:   }
8561:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8562:   PetscObjectStateIncrease((PetscObject)mat);
8563:   return(0);
8564: }

8566: /*@
8567:    MatGetInertia - Gets the inertia from a factored matrix

8569:    Collective on Mat

8571:    Input Parameter:
8572: .  mat - the matrix

8574:    Output Parameters:
8575: +   nneg - number of negative eigenvalues
8576: .   nzero - number of zero eigenvalues
8577: -   npos - number of positive eigenvalues

8579:    Level: advanced

8581:    Notes:
8582:     Matrix must have been factored by MatCholeskyFactor()


8585: @*/
8586: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8587: {

8593:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8594:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8595:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8596:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8597:   return(0);
8598: }

8600: /* ----------------------------------------------------------------*/
8601: /*@C
8602:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8604:    Neighbor-wise Collective on Mats

8606:    Input Parameters:
8607: +  mat - the factored matrix
8608: -  b - the right-hand-side vectors

8610:    Output Parameter:
8611: .  x - the result vectors

8613:    Notes:
8614:    The vectors b and x cannot be the same.  I.e., one cannot
8615:    call MatSolves(A,x,x).

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

8622:    Level: developer

8624: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8625: @*/
8626: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8627: {

8633:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8634:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8635:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8637:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8638:   MatCheckPreallocated(mat,1);
8639:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8640:   (*mat->ops->solves)(mat,b,x);
8641:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8642:   return(0);
8643: }

8645: /*@
8646:    MatIsSymmetric - Test whether a matrix is symmetric

8648:    Collective on Mat

8650:    Input Parameter:
8651: +  A - the matrix to test
8652: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8654:    Output Parameters:
8655: .  flg - the result

8657:    Notes:
8658:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8660:    Level: intermediate

8662: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8663: @*/
8664: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8665: {


8672:   if (!A->symmetric_set) {
8673:     if (!A->ops->issymmetric) {
8674:       MatType mattype;
8675:       MatGetType(A,&mattype);
8676:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8677:     }
8678:     (*A->ops->issymmetric)(A,tol,flg);
8679:     if (!tol) {
8680:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8681:     }
8682:   } else if (A->symmetric) {
8683:     *flg = PETSC_TRUE;
8684:   } else if (!tol) {
8685:     *flg = PETSC_FALSE;
8686:   } else {
8687:     if (!A->ops->issymmetric) {
8688:       MatType mattype;
8689:       MatGetType(A,&mattype);
8690:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8691:     }
8692:     (*A->ops->issymmetric)(A,tol,flg);
8693:   }
8694:   return(0);
8695: }

8697: /*@
8698:    MatIsHermitian - Test whether a matrix is Hermitian

8700:    Collective on Mat

8702:    Input Parameter:
8703: +  A - the matrix to test
8704: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8706:    Output Parameters:
8707: .  flg - the result

8709:    Level: intermediate

8711: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8712:           MatIsSymmetricKnown(), MatIsSymmetric()
8713: @*/
8714: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8715: {


8722:   if (!A->hermitian_set) {
8723:     if (!A->ops->ishermitian) {
8724:       MatType mattype;
8725:       MatGetType(A,&mattype);
8726:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8727:     }
8728:     (*A->ops->ishermitian)(A,tol,flg);
8729:     if (!tol) {
8730:       MatSetOption(A,MAT_HERMITIAN,*flg);
8731:     }
8732:   } else if (A->hermitian) {
8733:     *flg = PETSC_TRUE;
8734:   } else if (!tol) {
8735:     *flg = PETSC_FALSE;
8736:   } else {
8737:     if (!A->ops->ishermitian) {
8738:       MatType mattype;
8739:       MatGetType(A,&mattype);
8740:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8741:     }
8742:     (*A->ops->ishermitian)(A,tol,flg);
8743:   }
8744:   return(0);
8745: }

8747: /*@
8748:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8750:    Not Collective

8752:    Input Parameter:
8753: .  A - the matrix to check

8755:    Output Parameters:
8756: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8757: -  flg - the result

8759:    Level: advanced

8761:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8762:          if you want it explicitly checked

8764: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8765: @*/
8766: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8767: {
8772:   if (A->symmetric_set) {
8773:     *set = PETSC_TRUE;
8774:     *flg = A->symmetric;
8775:   } else {
8776:     *set = PETSC_FALSE;
8777:   }
8778:   return(0);
8779: }

8781: /*@
8782:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8784:    Not Collective

8786:    Input Parameter:
8787: .  A - the matrix to check

8789:    Output Parameters:
8790: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8791: -  flg - the result

8793:    Level: advanced

8795:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8796:          if you want it explicitly checked

8798: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8799: @*/
8800: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8801: {
8806:   if (A->hermitian_set) {
8807:     *set = PETSC_TRUE;
8808:     *flg = A->hermitian;
8809:   } else {
8810:     *set = PETSC_FALSE;
8811:   }
8812:   return(0);
8813: }

8815: /*@
8816:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8818:    Collective on Mat

8820:    Input Parameter:
8821: .  A - the matrix to test

8823:    Output Parameters:
8824: .  flg - the result

8826:    Level: intermediate

8828: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8829: @*/
8830: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8831: {

8837:   if (!A->structurally_symmetric_set) {
8838:     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);
8839:     (*A->ops->isstructurallysymmetric)(A,flg);
8840:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8841:   } else *flg = A->structurally_symmetric;
8842:   return(0);
8843: }

8845: /*@
8846:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8847:        to be communicated to other processors during the MatAssemblyBegin/End() process

8849:     Not collective

8851:    Input Parameter:
8852: .   vec - the vector

8854:    Output Parameters:
8855: +   nstash   - the size of the stash
8856: .   reallocs - the number of additional mallocs incurred.
8857: .   bnstash   - the size of the block stash
8858: -   breallocs - the number of additional mallocs incurred.in the block stash

8860:    Level: advanced

8862: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8864: @*/
8865: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8866: {

8870:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8871:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8872:   return(0);
8873: }

8875: /*@C
8876:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8877:      parallel layout

8879:    Collective on Mat

8881:    Input Parameter:
8882: .  mat - the matrix

8884:    Output Parameter:
8885: +   right - (optional) vector that the matrix can be multiplied against
8886: -   left - (optional) vector that the matrix vector product can be stored in

8888:    Notes:
8889:     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().

8891:   Notes:
8892:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8894:   Level: advanced

8896: .seealso: MatCreate(), VecDestroy()
8897: @*/
8898: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8899: {

8905:   if (mat->ops->getvecs) {
8906:     (*mat->ops->getvecs)(mat,right,left);
8907:   } else {
8908:     PetscInt rbs,cbs;
8909:     MatGetBlockSizes(mat,&rbs,&cbs);
8910:     if (right) {
8911:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8912:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8913:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8914:       VecSetBlockSize(*right,cbs);
8915:       VecSetType(*right,mat->defaultvectype);
8916:       PetscLayoutReference(mat->cmap,&(*right)->map);
8917:     }
8918:     if (left) {
8919:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8920:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8921:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8922:       VecSetBlockSize(*left,rbs);
8923:       VecSetType(*left,mat->defaultvectype);
8924:       PetscLayoutReference(mat->rmap,&(*left)->map);
8925:     }
8926:   }
8927:   return(0);
8928: }

8930: /*@C
8931:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8932:      with default values.

8934:    Not Collective

8936:    Input Parameters:
8937: .    info - the MatFactorInfo data structure


8940:    Notes:
8941:     The solvers are generally used through the KSP and PC objects, for example
8942:           PCLU, PCILU, PCCHOLESKY, PCICC

8944:    Level: developer

8946: .seealso: MatFactorInfo

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

8951: @*/

8953: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8954: {

8958:   PetscMemzero(info,sizeof(MatFactorInfo));
8959:   return(0);
8960: }

8962: /*@
8963:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8965:    Collective on Mat

8967:    Input Parameters:
8968: +  mat - the factored matrix
8969: -  is - the index set defining the Schur indices (0-based)

8971:    Notes:
8972:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8974:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8976:    Level: developer

8978: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8979:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8981: @*/
8982: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8983: {
8984:   PetscErrorCode ierr,(*f)(Mat,IS);

8992:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8993:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8994:   if (!f) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
8995:   MatDestroy(&mat->schur);
8996:   (*f)(mat,is);
8997:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8998:   return(0);
8999: }

9001: /*@
9002:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

9004:    Logically Collective on Mat

9006:    Input Parameters:
9007: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
9008: .  S - location where to return the Schur complement, can be NULL
9009: -  status - the status of the Schur complement matrix, can be NULL

9011:    Notes:
9012:    You must call MatFactorSetSchurIS() before calling this routine.

9014:    The routine provides a copy of the Schur matrix stored within the solver data structures.
9015:    The caller must destroy the object when it is no longer needed.
9016:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

9018:    Use MatFactorGetSchurComplement() to get access to the Schur complement matrix inside the factored matrix instead of making a copy of it (which this function does)

9020:    Developer Notes:
9021:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9022:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

9024:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

9026:    Level: advanced

9028:    References:

9030: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
9031: @*/
9032: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9033: {

9040:   if (S) {
9041:     PetscErrorCode (*f)(Mat,Mat*);

9043:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
9044:     if (f) {
9045:       (*f)(F,S);
9046:     } else {
9047:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
9048:     }
9049:   }
9050:   if (status) *status = F->schur_status;
9051:   return(0);
9052: }

9054: /*@
9055:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

9057:    Logically Collective on Mat

9059:    Input Parameters:
9060: +  F - the factored matrix obtained by calling MatGetFactor()
9061: .  *S - location where to return the Schur complement, can be NULL
9062: -  status - the status of the Schur complement matrix, can be NULL

9064:    Notes:
9065:    You must call MatFactorSetSchurIS() before calling this routine.

9067:    Schur complement mode is currently implemented for sequential matrices.
9068:    The routine returns a the Schur Complement stored within the data strutures of the solver.
9069:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
9070:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

9072:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

9074:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

9076:    Level: advanced

9078:    References:

9080: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9081: @*/
9082: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9083: {
9088:   if (S) *S = F->schur;
9089:   if (status) *status = F->schur_status;
9090:   return(0);
9091: }

9093: /*@
9094:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

9096:    Logically Collective on Mat

9098:    Input Parameters:
9099: +  F - the factored matrix obtained by calling MatGetFactor()
9100: .  *S - location where the Schur complement is stored
9101: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

9103:    Notes:

9105:    Level: advanced

9107:    References:

9109: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9110: @*/
9111: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9112: {

9117:   if (S) {
9119:     *S = NULL;
9120:   }
9121:   F->schur_status = status;
9122:   MatFactorUpdateSchurStatus_Private(F);
9123:   return(0);
9124: }

9126: /*@
9127:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9129:    Logically Collective on Mat

9131:    Input Parameters:
9132: +  F - the factored matrix obtained by calling MatGetFactor()
9133: .  rhs - location where the right hand side of the Schur complement system is stored
9134: -  sol - location where the solution of the Schur complement system has to be returned

9136:    Notes:
9137:    The sizes of the vectors should match the size of the Schur complement

9139:    Must be called after MatFactorSetSchurIS()

9141:    Level: advanced

9143:    References:

9145: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9146: @*/
9147: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9148: {

9160:   MatFactorFactorizeSchurComplement(F);
9161:   switch (F->schur_status) {
9162:   case MAT_FACTOR_SCHUR_FACTORED:
9163:     MatSolveTranspose(F->schur,rhs,sol);
9164:     break;
9165:   case MAT_FACTOR_SCHUR_INVERTED:
9166:     MatMultTranspose(F->schur,rhs,sol);
9167:     break;
9168:   default:
9169:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9170:   }
9171:   return(0);
9172: }

9174: /*@
9175:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9177:    Logically Collective on Mat

9179:    Input Parameters:
9180: +  F - the factored matrix obtained by calling MatGetFactor()
9181: .  rhs - location where the right hand side of the Schur complement system is stored
9182: -  sol - location where the solution of the Schur complement system has to be returned

9184:    Notes:
9185:    The sizes of the vectors should match the size of the Schur complement

9187:    Must be called after MatFactorSetSchurIS()

9189:    Level: advanced

9191:    References:

9193: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9194: @*/
9195: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9196: {

9208:   MatFactorFactorizeSchurComplement(F);
9209:   switch (F->schur_status) {
9210:   case MAT_FACTOR_SCHUR_FACTORED:
9211:     MatSolve(F->schur,rhs,sol);
9212:     break;
9213:   case MAT_FACTOR_SCHUR_INVERTED:
9214:     MatMult(F->schur,rhs,sol);
9215:     break;
9216:   default:
9217:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9218:   }
9219:   return(0);
9220: }

9222: /*@
9223:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9225:    Logically Collective on Mat

9227:    Input Parameters:
9228: .  F - the factored matrix obtained by calling MatGetFactor()

9230:    Notes:
9231:     Must be called after MatFactorSetSchurIS().

9233:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9235:    Level: advanced

9237:    References:

9239: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9240: @*/
9241: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9242: {

9248:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9249:   MatFactorFactorizeSchurComplement(F);
9250:   MatFactorInvertSchurComplement_Private(F);
9251:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9252:   return(0);
9253: }

9255: /*@
9256:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9258:    Logically Collective on Mat

9260:    Input Parameters:
9261: .  F - the factored matrix obtained by calling MatGetFactor()

9263:    Notes:
9264:     Must be called after MatFactorSetSchurIS().

9266:    Level: advanced

9268:    References:

9270: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9271: @*/
9272: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9273: {

9279:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9280:   MatFactorFactorizeSchurComplement_Private(F);
9281:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9282:   return(0);
9283: }

9285: /*@
9286:    MatPtAP - Creates the matrix product C = P^T * A * P

9288:    Neighbor-wise Collective on Mat

9290:    Input Parameters:
9291: +  A - the matrix
9292: .  P - the projection matrix
9293: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9294: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9295:           if the result is a dense matrix this is irrelevent

9297:    Output Parameters:
9298: .  C - the product matrix

9300:    Notes:
9301:    C will be created and must be destroyed by the user with MatDestroy().

9303:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9305:    Level: intermediate

9307: .seealso: MatMatMult(),