Actual source code: matrix.c
petsc-3.15.0 2021-03-30
Report Typos and Errors

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

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

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

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

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

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

     50:    Logically Collective on Mat

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

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

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

     67:    Level: intermediate

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

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

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

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

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

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

    105:    Logically Collective on Mat

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

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

    115:    Level: advanced

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

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

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

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

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

    138:    Logically Collective on Mat

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

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

    146:    Level: advanced

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

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

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

    164:    Logically Collective on Mat

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

    169:    Level: developer

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

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

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

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

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

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

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

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

    244:   Level: intermediate

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

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

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

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

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

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

    277:   Level: intermediate

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

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

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

    306:    Not Collective

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

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

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

    319:    Level: advanced

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

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

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

    346:    Collective on Mat

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

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

    354:    Level: advanced

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

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

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

    373:    Logically Collective on Mat

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

    378:    Level: advanced

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

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

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

    401:    Collective on Mat

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

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

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

    413:    Level: advanced

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

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

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

    438:    Logically Collective on Mat

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

    443:    Level: advanced

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

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

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

    466:    Not Collective

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

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

    475:    Level: advanced

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

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

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

    500:    Not Collective

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

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

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

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

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

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

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

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

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

    550:    Level: advanced

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

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

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

    577:    Logically Collective on Mat

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

    582:    Level: advanced

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

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

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

    605:    Not Collective

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

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

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

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

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

    635:    Level: advanced

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

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

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

    659:    Not Collective

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

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

    667:    Level: advanced

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

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

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

    689:    Not Collective

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

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

    698:    Level: advanced

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

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

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

    721:    Logically Collective on Mat

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

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

    731:    Level: advanced

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

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

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

    749:    Logically Collective on Mat

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

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

    759:    Level: advanced

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

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

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

    777:    Not Collective

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

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

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

    789:    Level: advanced

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

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

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

    806:    Collective on Mat

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

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

    815:    Level: beginner

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

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

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

    834:    Collective on Mat

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

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

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

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

    846:    Level: beginner

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

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

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

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

    882:    Collective on Mat

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

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

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

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

    905:    Collective on Mat

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1099:    Collective on PetscViewer

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

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

    1111:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    1196:    Corresponding MatView() is not yet implemented.

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

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

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

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

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

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

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

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

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

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

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

    1276:    Collective on Mat

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

    1281:    Level: beginner

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

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

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

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

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

    1319:    Not Collective

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

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

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

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

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

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

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

    1352:    Level: beginner

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

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

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

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

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

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

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

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

    1411:    Not Collective

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

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

    1421:    All the nonzeros in the row must be provided

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

    1425:    The row must belong to this process

    1427:    Level: intermediate

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

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

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

    1450:    Not Collective

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

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

    1460:    All the nonzeros in the row must be provided

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

    1464:    The row must belong to this process

    1466:    Level: advanced

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

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

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

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

    1499:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

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

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

    1559:    Level: beginner

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

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

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

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

    1613:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

    1666:    Level: beginner

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

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

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

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

    1722:    Not Collective

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

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

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

    1738:    Level: beginner

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

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

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

    1766:    Not Collective

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

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

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

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

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

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

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

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

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

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

    1826:    Level: intermediate

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

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

    1894: /*@C
    1895:    MatGetValues - Gets a block of values from a matrix.

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

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

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

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

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

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

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

    1925:    Level: advanced

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

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

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

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

    1955:    Not Collective

    1957:    Input Parameters:
    1958: +  mat - the matrix
    1959: .  nrow, irow - number of rows and their local indices
    1960: -  ncol, icol - number of columns and their local indices

    1962:    Output Parameter:
    1963: .  y -  a logically two-dimensional array of values

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

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

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

    1977:    Level: advanced

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

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

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

    2024:   Not Collective

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

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

    2036:   Level: advanced

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

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

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

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

    2070:    Not Collective

    2072:    Input Parameters:
    2073: +  x - the matrix
    2074: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
    2075: - cmapping - column mapping

    2077:    Level: intermediate

    2080: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal(), MatGetValuesLocal()
    2081: @*/
    2082: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
    2083: {

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

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

    2105:    Not Collective

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

    2110:    Output Parameters:
    2111: + rmapping - row mapping
    2112: - cmapping - column mapping

    2114:    Level: advanced

    2117: .seealso:  MatSetValuesLocal()
    2118: @*/
    2119: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
    2120: {
    2126:   if (rmapping) *rmapping = A->rmap->mapping;
    2127:   if (cmapping) *cmapping = A->cmap->mapping;
    2128:   return(0);
    2129: }

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

    2134:    Logically Collective on A

    2136:    Input Parameters:
    2137: +  A - the matrix
    2138: . rmap - row layout
    2139: - cmap - column layout

    2141:    Level: advanced

    2143: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatGetLayouts()
    2144: @*/
    2145: PetscErrorCode MatSetLayouts(Mat A,PetscLayout rmap,PetscLayout cmap)
    2146: {

    2152:   PetscLayoutReference(rmap,&A->rmap);
    2153:   PetscLayoutReference(cmap,&A->cmap);
    2154:   return(0);
    2155: }

    2157: /*@
    2158:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

    2160:    Not Collective

    2162:    Input Parameters:
    2163: .  A - the matrix

    2165:    Output Parameters:
    2166: + rmap - row layout
    2167: - cmap - column layout

    2169:    Level: advanced

    2171: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatSetLayouts()
    2172: @*/
    2173: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
    2174: {
    2180:   if (rmap) *rmap = A->rmap;
    2181:   if (cmap) *cmap = A->cmap;
    2182:   return(0);
    2183: }

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

    2189:    Not Collective

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

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

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

    2206:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
    2207:    options cannot be mixed without intervening calls to the assembly
    2208:    routines.

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

    2213:    Level: intermediate

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

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

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

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

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

    2272:    Not Collective

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

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

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

    2290:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
    2291:    options cannot be mixed without intervening calls to the assembly
    2292:    routines.

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

    2297:    Level: intermediate

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

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

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

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

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

    2365:    Collective on Mat

    2367:    Input Parameters:
    2368: +  mat - the matrix
    2369: -  x   - the vector to be multiplied

    2371:    Output Parameters:
    2372: .  y - the result

    2374:    Notes:
    2375:    The vectors x and y cannot be the same.  I.e., one cannot
    2376:    call MatMult(A,y,y).

    2378:    Level: developer

    2380: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2381: @*/
    2382: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
    2383: {

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

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

    2403: /* --------------------------------------------------------*/
    2404: /*@
    2405:    MatMult - Computes the matrix-vector product, y = Ax.

    2407:    Neighbor-wise Collective on Mat

    2409:    Input Parameters:
    2410: +  mat - the matrix
    2411: -  x   - the vector to be multiplied

    2413:    Output Parameters:
    2414: .  y - the result

    2416:    Notes:
    2417:    The vectors x and y cannot be the same.  I.e., one cannot
    2418:    call MatMult(A,y,y).

    2420:    Level: beginner

    2422: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2423: @*/
    2424: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
    2425: {

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

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

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

    2458:    Neighbor-wise Collective on Mat

    2460:    Input Parameters:
    2461: +  mat - the matrix
    2462: -  x   - the vector to be multiplied

    2464:    Output Parameters:
    2465: .  y - the result

    2467:    Notes:
    2468:    The vectors x and y cannot be the same.  I.e., one cannot
    2469:    call MatMultTranspose(A,y,y).

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

    2474:    Level: beginner

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

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

    2498:   if (!mat->ops->multtranspose) {
    2499:     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
    2500:     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);
    2501:   } else op = mat->ops->multtranspose;
    2502:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
    2503:   VecLockReadPush(x);
    2504:   (*op)(mat,x,y);
    2505:   VecLockReadPop(x);
    2506:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
    2507:   PetscObjectStateIncrease((PetscObject)y);
    2508:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
    2509:   return(0);
    2510: }

    2512: /*@
    2513:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

    2515:    Neighbor-wise Collective on Mat

    2517:    Input Parameters:
    2518: +  mat - the matrix
    2519: -  x   - the vector to be multilplied

    2521:    Output Parameters:
    2522: .  y - the result

    2524:    Notes:
    2525:    The vectors x and y cannot be the same.  I.e., one cannot
    2526:    call MatMultHermitianTranspose(A,y,y).

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

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

    2532:    Level: beginner

    2534: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
    2535: @*/
    2536: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
    2537: {

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

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

    2582: /*@
    2583:     MatMultAdd -  Computes v3 = v2 + A * v1.

    2585:     Neighbor-wise Collective on Mat

    2587:     Input Parameters:
    2588: +   mat - the matrix
    2589: -   v1, v2 - the vectors

    2591:     Output Parameters:
    2592: .   v3 - the result

    2594:     Notes:
    2595:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
    2596:     call MatMultAdd(A,v1,v2,v1).

    2598:     Level: beginner

    2600: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
    2601: @*/
    2602: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
    2603: {

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

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

    2633: /*@
    2634:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

    2636:    Neighbor-wise Collective on Mat

    2638:    Input Parameters:
    2639: +  mat - the matrix
    2640: -  v1, v2 - the vectors

    2642:    Output Parameters:
    2643: .  v3 - the result

    2645:    Notes:
    2646:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
    2647:    call MatMultTransposeAdd(A,v1,v2,v1).

    2649:    Level: beginner

    2651: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
    2652: @*/
    2653: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
    2654: {

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

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

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

    2685:    Neighbor-wise Collective on Mat

    2687:    Input Parameters:
    2688: +  mat - the matrix
    2689: -  v1, v2 - the vectors

    2691:    Output Parameters:
    2692: .  v3 - the result

    2694:    Notes:
    2695:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
    2696:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

    2698:    Level: beginner

    2700: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
    2701: @*/
    2702: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
    2703: {

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

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

    2747: /*@
    2748:    MatMultConstrained - The inner multiplication routine for a
    2749:    constrained matrix P^T A P.

    2751:    Neighbor-wise Collective on Mat

    2753:    Input Parameters:
    2754: +  mat - the matrix
    2755: -  x   - the vector to be multilplied

    2757:    Output Parameters:
    2758: .  y - the result

    2760:    Notes:
    2761:    The vectors x and y cannot be the same.  I.e., one cannot
    2762:    call MatMult(A,y,y).

    2764:    Level: beginner

    2766: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2767: @*/
    2768: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
    2769: {

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

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

    2792: /*@
    2793:    MatMultTransposeConstrained - The inner multiplication routine for a
    2794:    constrained matrix P^T A^T P.

    2796:    Neighbor-wise Collective on Mat

    2798:    Input Parameters:
    2799: +  mat - the matrix
    2800: -  x   - the vector to be multilplied

    2802:    Output Parameters:
    2803: .  y - the result

    2805:    Notes:
    2806:    The vectors x and y cannot be the same.  I.e., one cannot
    2807:    call MatMult(A,y,y).

    2809:    Level: beginner

    2811: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2812: @*/
    2813: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
    2814: {

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

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

    2834: /*@C
    2835:    MatGetFactorType - gets the type of factorization it is

    2837:    Not Collective

    2839:    Input Parameters:
    2840: .  mat - the matrix

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

    2845:    Level: intermediate

    2847: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
    2848: @*/
    2849: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
    2850: {
    2855:   *t = mat->factortype;
    2856:   return(0);
    2857: }

    2859: /*@C
    2860:    MatSetFactorType - sets the type of factorization it is

    2862:    Logically Collective on Mat

    2864:    Input Parameters:
    2865: +  mat - the matrix
    2866: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

    2868:    Level: intermediate

    2870: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
    2871: @*/
    2872: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
    2873: {
    2877:   mat->factortype = t;
    2878:   return(0);
    2879: }

    2881: /* ------------------------------------------------------------*/
    2882: /*@C
    2883:    MatGetInfo - Returns information about matrix storage (number of
    2884:    nonzeros, memory, etc.).

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

    2888:    Input Parameters:
    2889: .  mat - the matrix

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

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

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

    2914:       MatGetInfo(A,MAT_LOCAL,&info);
    2915:       mal  = info.mallocs;
    2916:       nz_a = info.nz_allocated;
    2917: .ve

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

    2930:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
    2931:       mal = info(MAT_INFO_MALLOCS)
    2932:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
    2933: .ve

    2935:     Level: intermediate

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

    2940: .seealso: MatStashGetInfo()

    2942: @*/
    2943: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
    2944: {

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

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

    2966:   PetscMemzero(info,sizeof(MatInfo));
    2967:   return(0);
    2968: }

    2970: /* ----------------------------------------------------------*/

    2972: /*@C
    2973:    MatLUFactor - Performs in-place LU factorization of matrix.

    2975:    Collective on Mat

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

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

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

    2994:    Level: developer

    2996: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
    2997:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

    3002: @*/
    3003: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
    3004: {
    3006:   MatFactorInfo  tinfo;

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

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

    3030: /*@C
    3031:    MatILUFactor - Performs in-place ILU factorization of matrix.

    3033:    Collective on Mat

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

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

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

    3053:    Level: developer

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

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

    3060: @*/
    3061: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
    3062: {

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

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

    3084: /*@C
    3085:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
    3086:    Call this routine before calling MatLUFactorNumeric().

    3088:    Collective on Mat

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

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

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

    3107:    Level: developer

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

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

    3114: @*/
    3115: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
    3116: {
    3118:   MatFactorInfo  tinfo;

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

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

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

    3151:    Collective on Mat

    3153:    Input Parameters:
    3154: +  fact - the factor matrix obtained with MatGetFactor()
    3155: .  mat - the matrix
    3156: -  info - options for factorization

    3158:    Notes:
    3159:    See MatLUFactor() for in-place factorization.  See
    3160:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

    3166:    Level: developer

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

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

    3173: @*/
    3174: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
    3175: {
    3176:   MatFactorInfo  tinfo;

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

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

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

    3202: /*@C
    3203:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
    3204:    symmetric matrix.

    3206:    Collective on Mat

    3208:    Input Parameters:
    3209: +  mat - the matrix
    3210: .  perm - row and column permutations
    3211: -  f - expected fill as ratio of original fill

    3213:    Notes:
    3214:    See MatLUFactor() for the nonsymmetric case.  See also
    3215:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

    3221:    Level: developer

    3223: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
    3224:           MatGetOrdering()

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

    3229: @*/
    3230: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
    3231: {
    3233:   MatFactorInfo  tinfo;

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

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

    3257: /*@C
    3258:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
    3259:    of a symmetric matrix.

    3261:    Collective on Mat

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

    3272:    Notes:
    3273:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
    3274:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

    3280:    Level: developer

    3282: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
    3283:           MatGetOrdering()

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

    3288: @*/
    3289: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
    3290: {
    3292:   MatFactorInfo  tinfo;

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

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

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

    3326:    Collective on Mat

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

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

    3340:    Level: developer

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

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

    3347: @*/
    3348: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
    3349: {
    3350:   MatFactorInfo  tinfo;

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

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

    3375: /*@C
    3376:    MatQRFactor - Performs in-place QR factorization of matrix.

    3378:    Collective on Mat

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

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

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

    3396:    Level: developer

    3398: .seealso: MatQRFactorSymbolic(), MatQRFactorNumeric(), MatLUFactor(),
    3399:           MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

    3404: @*/
    3405: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
    3406: {

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

    3424: /*@C
    3425:    MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
    3426:    Call this routine before calling MatQRFactorNumeric().

    3428:    Collective on Mat

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

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

    3443:    Level: developer

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

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

    3450: @*/
    3451: PetscErrorCode MatQRFactorSymbolic(Mat fact,Mat mat,IS col,const MatFactorInfo *info)
    3452: {
    3454:   MatFactorInfo  tinfo;

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

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

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

    3481:    Collective on Mat

    3483:    Input Parameters:
    3484: +  fact - the factor matrix obtained with MatGetFactor()
    3485: .  mat - the matrix
    3486: -  info - options for factorization

    3488:    Notes:
    3489:    See MatQRFactor() for in-place factorization.

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

    3495:    Level: developer

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

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

    3502: @*/
    3503: PetscErrorCode MatQRFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
    3504: {
    3505:   MatFactorInfo  tinfo;

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

    3516:   MatCheckPreallocated(mat,2);
    3517:   if (!info) {
    3518:     MatFactorInfoInitialize(&tinfo);
    3519:     info = &tinfo;
    3520:   }

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

    3530: /* ----------------------------------------------------------------*/
    3531: /*@
    3532:    MatSolve - Solves A x = b, given a factored matrix.

    3534:    Neighbor-wise Collective on Mat

    3536:    Input Parameters:
    3537: +  mat - the factored matrix
    3538: -  b - the right-hand-side vector

    3540:    Output Parameter:
    3541: .  x - the result vector

    3543:    Notes:
    3544:    The vectors b and x cannot be the same.  I.e., one cannot
    3545:    call MatSolve(A,x,x).

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

    3552:    Level: developer

    3554: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
    3555: @*/
    3556: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
    3557: {

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

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

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

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

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

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

    3626:    Neighbor-wise Collective on Mat

    3628:    Input Parameters:
    3629: +  A - the factored matrix
    3630: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

    3632:    Output Parameter:
    3633: .  X - the result matrix (dense matrix)

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

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

    3645:    Level: developer

    3647: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
    3648: @*/
    3649: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
    3650: {

    3660:   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);
    3661:   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);
    3662:   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");
    3663:   if (!A->rmap->N && !A->cmap->N) return(0);
    3664:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    3665:   MatCheckPreallocated(A,1);

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

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

    3682:    Neighbor-wise Collective on Mat

    3684:    Input Parameters:
    3685: +  A - the factored matrix
    3686: -  B - the right-hand-side matrix  (dense matrix)

    3688:    Output Parameter:
    3689: .  X - the result matrix (dense matrix)

    3691:    Notes:
    3692:    The matrices B and X cannot be the same.  I.e., one cannot
    3693:    call MatMatSolveTranspose(A,X,X).

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

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

    3703:    Level: developer

    3705: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
    3706: @*/
    3707: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
    3708: {

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

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

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

    3742:    Neighbor-wise Collective on Mat

    3744:    Input Parameters:
    3745: +  A - the factored matrix
    3746: -  Bt - the transpose of right-hand-side matrix

    3748:    Output Parameter:
    3749: .  X - the result matrix (dense matrix)

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

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

    3759:    Level: developer

    3761: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
    3762: @*/
    3763: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
    3764: {

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

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

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

    3795:    Neighbor-wise Collective on Mat

    3797:    Input Parameters:
    3798: +  mat - the factored matrix
    3799: -  b - the right-hand-side vector

    3801:    Output Parameter:
    3802: .  x - the result vector

    3804:    Notes:
    3805:    MatSolve() should be used for most applications, as it performs
    3806:    a forward solve followed by a backward solve.

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

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

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

    3821:    Level: developer

    3823: .seealso: MatSolve(), MatBackwardSolve()
    3824: @*/
    3825: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
    3826: {

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

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

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

    3855:    Neighbor-wise Collective on Mat

    3857:    Input Parameters:
    3858: +  mat - the factored matrix
    3859: -  b - the right-hand-side vector

    3861:    Output Parameter:
    3862: .  x - the result vector

    3864:    Notes:
    3865:    MatSolve() should be used for most applications, as it performs
    3866:    a forward solve followed by a backward solve.

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

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

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

    3881:    Level: developer

    3883: .seealso: MatSolve(), MatForwardSolve()
    3884: @*/
    3885: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
    3886: {

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

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

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

    3914:    Neighbor-wise Collective on Mat

    3916:    Input Parameters:
    3917: +  mat - the factored matrix
    3918: .  b - the right-hand-side vector
    3919: -  y - the vector to be added to

    3921:    Output Parameter:
    3922: .  x - the result vector

    3924:    Notes:
    3925:    The vectors b and x cannot be the same.  I.e., one cannot
    3926:    call MatSolveAdd(A,x,y,x).

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

    3932:    Level: developer

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

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

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

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

    3988:    Neighbor-wise Collective on Mat

    3990:    Input Parameters:
    3991: +  mat - the factored matrix
    3992: -  b - the right-hand-side vector

    3994:    Output Parameter:
    3995: .  x - the result vector

    3997:    Notes:
    3998:    The vectors b and x cannot be the same.  I.e., one cannot
    3999:    call MatSolveTranspose(A,x,x).

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

    4005:    Level: developer

    4007: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
    4008: @*/
    4009: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
    4010: {

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

    4038: /*@
    4039:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
    4040:                       factored matrix.

    4042:    Neighbor-wise Collective on Mat

    4044:    Input Parameters:
    4045: +  mat - the factored matrix
    4046: .  b - the right-hand-side vector
    4047: -  y - the vector to be added to

    4049:    Output Parameter:
    4050: .  x - the result vector

    4052:    Notes:
    4053:    The vectors b and x cannot be the same.  I.e., one cannot
    4054:    call MatSolveTransposeAdd(A,x,y,x).

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

    4060:    Level: developer

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

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

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

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

    4116:    Neighbor-wise Collective on Mat

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

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

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

    4142:    Notes:
    4143:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
    4144:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
    4145:    on each processor.

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

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

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

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

    4162:    Vectors x and b CANNOT be the same

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

    4166:    Level: developer

    4168: @*/
    4169: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
    4170: {

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

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

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

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

    4227: /*@
    4228:    MatCopy - Copies a matrix to another matrix.

    4230:    Collective on Mat

    4232:    Input Parameters:
    4233: +  A - the matrix
    4234: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

    4236:    Output Parameter:
    4237: .  B - where the copy is put

    4239:    Notes:
    4240:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
    4241:    same nonzero pattern or the routine will crash.

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

    4247:    Level: intermediate

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

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

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

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

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

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

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

    4293:    Collective on Mat

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

    4303:    Output Parameter:
    4304: .  M - pointer to place new matrix

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

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

    4315:    Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    4471: /*@C
    4472:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

    4474:    Not Collective

    4476:    Input Parameter:
    4477: .  mat - the matrix, must be a factored matrix

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

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

    4486:    Level: intermediate

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

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

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

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

    4521: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

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

    4532:     Level: intermediate

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

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

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

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

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

    4596:     Level: intermediate

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

    4608:   if (foundtype) *foundtype = PETSC_FALSE;
    4609:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
    4610:   if (createfactor) *createfactor    = NULL;

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

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

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

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

    4692:    Logically Collective on Mat

    4694:    Input Parameters:
    4695: .  mat - the matrix

    4697:    Output Parameters:
    4698: .  flg - PETSC_TRUE if uses the ordering

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

    4704:    Level: developer

    4706: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
    4707: @*/
    4708: PetscErrorCode MatFactorGetUseOrdering(Mat mat, PetscBool *flg)
    4709: {
    4711:   *flg = mat->useordering;
    4712:   return(0);
    4713: }

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

    4718:    Collective on Mat

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

    4725:    Output Parameters:
    4726: .  f - the factor matrix used with MatXXFactorSymbolic() calls

    4728:    Notes:
    4729:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
    4730:      such as pastix, superlu, mumps etc.

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

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

    4737:    Level: intermediate

    4739: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetUseOrdering(), MatSolverTypeRegister()
    4740: @*/
    4741: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
    4742: {
    4743:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
    4744:   PetscBool      foundtype,foundmtype;

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

    4753:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundtype,&foundmtype,&conv);
    4754:   if (!foundtype) {
    4755:     if (type) {
    4756:       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);
    4757:     } else {
    4758:       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);
    4759:     }
    4760:   }
    4761:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
    4762:   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);

    4764:   (*conv)(mat,ftype,f);
    4765:   return(0);
    4766: }

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

    4771:    Not Collective

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

    4778:    Output Parameter:
    4779: .    flg - PETSC_TRUE if the factorization is available

    4781:    Notes:
    4782:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
    4783:      such as pastix, superlu, mumps etc.

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

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

    4790:    Level: intermediate

    4792: .seealso: MatCopy(), MatDuplicate(), MatGetFactor(), MatSolverTypeRegister()
    4793: @*/
    4794: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
    4795: {
    4796:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);

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

    4805:   *flg = PETSC_FALSE;
    4806:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
    4807:   if (gconv) {
    4808:     *flg = PETSC_TRUE;
    4809:   }
    4810:   return(0);
    4811: }

    4813: #include <petscdmtypes.h>

    4815: /*@
    4816:    MatDuplicate - Duplicates a matrix including the non-zero structure.

    4818:    Collective on Mat

    4820:    Input Parameters:
    4821: +  mat - the matrix
    4822: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
    4823:         See the manual page for MatDuplicateOption for an explanation of these options.

    4825:    Output Parameter:
    4826: .  M - pointer to place new matrix

    4828:    Level: intermediate

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

    4834: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
    4835: @*/
    4836: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
    4837: {
    4839:   Mat            B;
    4840:   PetscInt       i;
    4841:   DM             dm;
    4842:   void           (*viewf)(void);

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

    4852:   *M = NULL;
    4853:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
    4854:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
    4855:   (*mat->ops->duplicate)(mat,op,M);
    4856:   B    = *M;

    4858:   MatGetOperation(mat,MATOP_VIEW,&viewf);
    4859:   if (viewf) {
    4860:     MatSetOperation(B,MATOP_VIEW,viewf);
    4861:   }

    4863:   B->stencil.dim = mat->stencil.dim;
    4864:   B->stencil.noc = mat->stencil.noc;
    4865:   for (i=0; i<=mat->stencil.dim; i++) {
    4866:     B->stencil.dims[i]   = mat->stencil.dims[i];
    4867:     B->stencil.starts[i] = mat->stencil.starts[i];
    4868:   }

    4870:   B->nooffproczerorows = mat->nooffproczerorows;
    4871:   B->nooffprocentries  = mat->nooffprocentries;

    4873:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
    4874:   if (dm) {
    4875:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
    4876:   }
    4877:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
    4878:   PetscObjectStateIncrease((PetscObject)B);
    4879:   return(0);
    4880: }

    4882: /*@
    4883:    MatGetDiagonal - Gets the diagonal of a matrix.

    4885:    Logically Collective on Mat

    4887:    Input Parameters:
    4888: +  mat - the matrix
    4889: -  v - the vector for storing the diagonal

    4891:    Output Parameter:
    4892: .  v - the diagonal of the matrix

    4894:    Level: intermediate

    4896:    Note:
    4897:    Currently only correct in parallel for square matrices.

    4899: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
    4900: @*/
    4901: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
    4902: {

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

    4913:   (*mat->ops->getdiagonal)(mat,v);
    4914:   PetscObjectStateIncrease((PetscObject)v);
    4915:   return(0);
    4916: }

    4918: /*@C
    4919:    MatGetRowMin - Gets the minimum value (of the real part) of each
    4920:         row of the matrix

    4922:    Logically Collective on Mat

    4924:    Input Parameters:
    4925: .  mat - the matrix

    4927:    Output Parameter:
    4928: +  v - the vector for storing the maximums
    4929: -  idx - the indices of the column found for each row (optional)

    4931:    Level: intermediate

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

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

    4939: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
    4940:           MatGetRowMax()
    4941: @*/
    4942: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
    4943: {

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

    4952:   if (!mat->cmap->N) {
    4953:     VecSet(v,PETSC_MAX_REAL);
    4954:     if (idx) {
    4955:       PetscInt i,m = mat->rmap->n;
    4956:       for (i=0; i<m; i++) idx[i] = -1;
    4957:     }
    4958:   } else {
    4959:     if (!mat->ops->getrowmin) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    4960:     MatCheckPreallocated(mat,1);
    4961:   }
    4962:   (*mat->ops->getrowmin)(mat,v,idx);
    4963:   PetscObjectStateIncrease((PetscObject)v);
    4964:   return(0);
    4965: }

    4967: /*@C
    4968:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
    4969:         row of the matrix

    4971:    Logically Collective on Mat

    4973:    Input Parameters:
    4974: .  mat - the matrix

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

    4980:    Level: intermediate

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

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

    4988: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
    4989: @*/
    4990: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
    4991: {

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

    5001:   if (!mat->cmap->N) {
    5002:     VecSet(v,0.0);
    5003:     if (idx) {
    5004:       PetscInt i,m = mat->rmap->n;
    5005:       for (i=0; i<m; i++) idx[i] = -1;
    5006:     }
    5007:   } else {
    5008:     if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    5009:     MatCheckPreallocated(mat,1);
    5010:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
    5011:     (*mat->ops->getrowminabs)(mat,v,idx);
    5012:   }
    5013:   PetscObjectStateIncrease((PetscObject)v);
    5014:   return(0);
    5015: }

    5017: /*@C
    5018:    MatGetRowMax - Gets the maximum value (of the real part) of each
    5019:         row of the matrix

    5021:    Logically Collective on Mat

    5023:    Input Parameters:
    5024: .  mat - the matrix

    5026:    Output Parameter:
    5027: +  v - the vector for storing the maximums
    5028: -  idx - the indices of the column found for each row (optional)

    5030:    Level: intermediate

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

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

    5038: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
    5039: @*/
    5040: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
    5041: {

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

    5050:   if (!mat->cmap->N) {
    5051:     VecSet(v,PETSC_MIN_REAL);
    5052:     if (idx) {
    5053:       PetscInt i,m = mat->rmap->n;
    5054:       for (i=0; i<m; i++) idx[i] = -1;
    5055:     }
    5056:   } else {
    5057:     if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    5058:     MatCheckPreallocated(mat,1);
    5059:     (*mat->ops->getrowmax)(mat,v,idx);
    5060:   }
    5061:   PetscObjectStateIncrease((PetscObject)v);
    5062:   return(0);
    5063: }

    5065: /*@C
    5066:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
    5067:         row of the matrix

    5069:    Logically Collective on Mat

    5071:    Input Parameters:
    5072: .  mat - the matrix

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

    5078:    Level: intermediate

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

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

    5086: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
    5087: @*/
    5088: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
    5089: {

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

    5098:   if (!mat->cmap->N) {
    5099:     VecSet(v,0.0);
    5100:     if (idx) {
    5101:       PetscInt i,m = mat->rmap->n;
    5102:       for (i=0; i<m; i++) idx[i] = -1;
    5103:     }
    5104:   } else {
    5105:     if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    5106:     MatCheckPreallocated(mat,1);
    5107:     if (idx) {PetscArrayzero(idx,mat->rmap->n);}
    5108:     (*mat->ops->getrowmaxabs)(mat,v,idx);
    5109:   }
    5110:   PetscObjectStateIncrease((PetscObject)v);
    5111:   return(0);
    5112: }

    5114: /*@
    5115:    MatGetRowSum - Gets the sum of each row of the matrix

    5117:    Logically or Neighborhood Collective on Mat

    5119:    Input Parameters:
    5120: .  mat - the matrix

    5122:    Output Parameter:
    5123: .  v - the vector for storing the sum of rows

    5125:    Level: intermediate

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

    5130: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
    5131: @*/
    5132: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
    5133: {
    5134:   Vec            ones;

    5141:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    5142:   MatCheckPreallocated(mat,1);
    5143:   MatCreateVecs(mat,&ones,NULL);
    5144:   VecSet(ones,1.);
    5145:   MatMult(mat,ones,v);
    5146:   VecDestroy(&ones);
    5147:   return(0);
    5148: }

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

    5153:    Collective on Mat

    5155:    Input Parameter:
    5156: +  mat - the matrix to transpose
    5157: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

    5159:    Output Parameters:
    5160: .  B - the transpose

    5162:    Notes:
    5163:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

    5169:    Level: intermediate

    5171: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
    5172: @*/
    5173: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
    5174: {

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

    5187:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
    5188:   (*mat->ops->transpose)(mat,reuse,B);
    5189:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
    5190:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
    5191:   return(0);
    5192: }

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

    5198:    Collective on Mat

    5200:    Input Parameter:
    5201: +  A - the matrix to test
    5202: -  B - the matrix to test against, this can equal the first parameter

    5204:    Output Parameters:
    5205: .  flg - the result

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

    5212:    Level: intermediate

    5214: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
    5215: @*/
    5216: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
    5217: {
    5218:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

    5224:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
    5225:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
    5226:   *flg = PETSC_FALSE;
    5227:   if (f && g) {
    5228:     if (f == g) {
    5229:       (*f)(A,B,tol,flg);
    5230:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
    5231:   } else {
    5232:     MatType mattype;
    5233:     if (!f) {
    5234:       MatGetType(A,&mattype);
    5235:     } else {
    5236:       MatGetType(B,&mattype);
    5237:     }
    5238:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
    5239:   }
    5240:   return(0);
    5241: }

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

    5246:    Collective on Mat

    5248:    Input Parameter:
    5249: +  mat - the matrix to transpose and complex conjugate
    5250: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

    5252:    Output Parameters:
    5253: .  B - the Hermitian

    5255:    Level: intermediate

    5257: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
    5258: @*/
    5259: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
    5260: {

    5264:   MatTranspose(mat,reuse,B);
    5265: #if defined(PETSC_USE_COMPLEX)
    5266:   MatConjugate(*B);
    5267: #endif
    5268:   return(0);
    5269: }

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

    5274:    Collective on Mat

    5276:    Input Parameter:
    5277: +  A - the matrix to test
    5278: -  B - the matrix to test against, this can equal the first parameter

    5280:    Output Parameters:
    5281: .  flg - the result

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

    5288:    Level: intermediate

    5290: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
    5291: @*/
    5292: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
    5293: {
    5294:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

    5300:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
    5301:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
    5302:   if (f && g) {
    5303:     if (f==g) {
    5304:       (*f)(A,B,tol,flg);
    5305:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
    5306:   }
    5307:   return(0);
    5308: }

    5310: /*@
    5311:    MatPermute - Creates a new matrix with rows and columns permuted from the
    5312:    original.

    5314:    Collective on Mat

    5316:    Input Parameters:
    5317: +  mat - the matrix to permute
    5318: .  row - row permutation, each processor supplies only the permutation for its rows
    5319: -  col - column permutation, each processor supplies only the permutation for its columns

    5321:    Output Parameters:
    5322: .  B - the permuted matrix

    5324:    Level: advanced

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

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

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

    5337: @*/
    5338: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
    5339: {

    5350:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    5351:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    5352:   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);
    5353:   MatCheckPreallocated(mat,1);

    5355:   if (mat->ops->permute) {
    5356:     (*mat->ops->permute)(mat,row,col,B);
    5357:     PetscObjectStateIncrease((PetscObject)*B);
    5358:   } else {
    5359:     MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B);
    5360:   }
    5361:   return(0);
    5362: }

    5364: /*@
    5365:    MatEqual - Compares two matrices.

    5367:    Collective on Mat

    5369:    Input Parameters:
    5370: +  A - the first matrix
    5371: -  B - the second matrix

    5373:    Output Parameter:
    5374: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

    5376:    Level: intermediate

    5378: @*/
    5379: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
    5380: {

    5390:   MatCheckPreallocated(B,2);
    5391:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    5392:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    5393:   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);
    5394:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
    5395:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
    5396:   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);
    5397:   MatCheckPreallocated(A,1);

    5399:   (*A->ops->equal)(A,B,flg);
    5400:   return(0);
    5401: }

    5403: /*@
    5404:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
    5405:    matrices that are stored as vectors.  Either of the two scaling
    5406:    matrices can be NULL.

    5408:    Collective on Mat

    5410:    Input Parameters:
    5411: +  mat - the matrix to be scaled
    5412: .  l - the left scaling vector (or NULL)
    5413: -  r - the right scaling vector (or NULL)

    5415:    Notes:
    5416:    MatDiagonalScale() computes A = LAR, where
    5417:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
    5418:    The L scales the rows of the matrix, the R scales the columns of the matrix.

    5420:    Level: intermediate

    5423: .seealso: MatScale(), MatShift(), MatDiagonalSet()
    5424: @*/
    5425: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
    5426: {

    5434:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    5435:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    5436:   MatCheckPreallocated(mat,1);
    5437:   if (!l && !r) return(0);

    5439:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    5440:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
    5441:   (*mat->ops->diagonalscale)(mat,l,r);
    5442:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
    5443:   PetscObjectStateIncrease((PetscObject)mat);
    5444:   return(0);
    5445: }

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

    5450:     Logically Collective on Mat

    5452:     Input Parameters:
    5453: +   mat - the matrix to be scaled
    5454: -   a  - the scaling value

    5456:     Output Parameter:
    5457: .   mat - the scaled matrix

    5459:     Level: intermediate

    5461: .seealso: MatDiagonalScale()
    5462: @*/
    5463: PetscErrorCode MatScale(Mat mat,PetscScalar a)
    5464: {

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

    5476:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
    5477:   if (a != (PetscScalar)1.0) {
    5478:     (*mat->ops->scale)(mat,a);
    5479:     PetscObjectStateIncrease((PetscObject)mat);
    5480:   }
    5481:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
    5482:   return(0);
    5483: }

    5485: /*@
    5486:    MatNorm - Calculates various norms of a matrix.

    5488:    Collective on Mat

    5490:    Input Parameters:
    5491: +  mat - the matrix
    5492: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

    5494:    Output Parameters:
    5495: .  nrm - the resulting norm

    5497:    Level: intermediate

    5499: @*/
    5500: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
    5501: {

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

    5514:   (*mat->ops->norm)(mat,type,nrm);
    5515:   return(0);
    5516: }

    5518: /*
    5519:      This variable is used to prevent counting of MatAssemblyBegin() that
    5520:    are called from within a MatAssemblyEnd().
    5521: */
    5522: static PetscInt MatAssemblyEnd_InUse = 0;
    5523: /*@
    5524:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
    5525:    be called after completing all calls to MatSetValues().

    5527:    Collective on Mat

    5529:    Input Parameters:
    5530: +  mat - the matrix
    5531: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

    5533:    Notes:
    5534:    MatSetValues() generally caches the values.  The matrix is ready to
    5535:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
    5536:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
    5537:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
    5538:    using the matrix.

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

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

    5548:    Level: beginner

    5550: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
    5551: @*/
    5552: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
    5553: {

    5559:   MatCheckPreallocated(mat,1);
    5560:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
    5561:   if (mat->assembled) {
    5562:     mat->was_assembled = PETSC_TRUE;
    5563:     mat->assembled     = PETSC_FALSE;
    5564:   }

    5566:   if (!MatAssemblyEnd_InUse) {
    5567:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
    5568:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
    5569:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
    5570:   } else if (mat->ops->assemblybegin) {
    5571:     (*mat->ops->assemblybegin)(mat,type);
    5572:   }
    5573:   return(0);
    5574: }

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

    5580:    Not Collective

    5582:    Input Parameter:
    5583: .  mat - the matrix

    5585:    Output Parameter:
    5586: .  assembled - PETSC_TRUE or PETSC_FALSE

    5588:    Level: advanced

    5590: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
    5591: @*/
    5592: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
    5593: {
    5597:   *assembled = mat->assembled;
    5598:   return(0);
    5599: }

    5601: /*@
    5602:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
    5603:    be called after MatAssemblyBegin().

    5605:    Collective on Mat

    5607:    Input Parameters:
    5608: +  mat - the matrix
    5609: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

    5611:    Options Database Keys:
    5612: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
    5613: .  -mat_view ::ascii_info_detail - Prints more detailed info
    5614: .  -mat_view - Prints matrix in ASCII format
    5615: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
    5616: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
    5617: .  -display <name> - Sets display name (default is host)
    5618: .  -draw_pause <sec> - Sets number of seconds to pause after display
    5619: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab)
    5620: .  -viewer_socket_machine <machine> - Machine to use for socket
    5621: .  -viewer_socket_port <port> - Port number to use for socket
    5622: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

    5624:    Notes:
    5625:    MatSetValues() generally caches the values.  The matrix is ready to
    5626:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
    5627:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
    5628:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
    5629:    using the matrix.

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

    5635:    Level: beginner

    5637: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
    5638: @*/
    5639: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
    5640: {
    5641:   PetscErrorCode  ierr;
    5642:   static PetscInt inassm = 0;
    5643:   PetscBool       flg    = PETSC_FALSE;

    5649:   inassm++;
    5650:   MatAssemblyEnd_InUse++;
    5651:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
    5652:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
    5653:     if (mat->ops->assemblyend) {
    5654:       (*mat->ops->assemblyend)(mat,type);
    5655:     }
    5656:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
    5657:   } else if (mat->ops->assemblyend) {
    5658:     (*mat->ops->assemblyend)(mat,type);
    5659:   }

    5661:   /* Flush assembly is not a true assembly */
    5662:   if (type != MAT_FLUSH_ASSEMBLY) {
    5663:     mat->num_ass++;
    5664:     mat->assembled        = PETSC_TRUE;
    5665:     mat->ass_nonzerostate = mat->nonzerostate;
    5666:   }

    5668:   mat->insertmode = NOT_SET_VALUES;
    5669:   MatAssemblyEnd_InUse--;
    5670:   PetscObjectStateIncrease((PetscObject)mat);
    5671:   if (!mat->symmetric_eternal) {
    5672:     mat->symmetric_set              = PETSC_FALSE;
    5673:     mat->hermitian_set              = PETSC_FALSE;
    5674:     mat->structurally_symmetric_set = PETSC_FALSE;
    5675:   }
    5676:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
    5677:     MatViewFromOptions(mat,NULL,"-mat_view");

    5679:     if (mat->checksymmetryonassembly) {
    5680:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
    5681:       if (flg) {
    5682:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
    5683:       } else {
    5684:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
    5685:       }
    5686:     }
    5687:     if (mat->nullsp && mat->checknullspaceonassembly) {
    5688:       MatNullSpaceTest(mat->nullsp,mat,NULL);
    5689:     }
    5690:   }
    5691:   inassm--;
    5692:   return(0);
    5693: }

    5695: /*@
    5696:    MatSetOption - Sets a parameter option for a matrix. Some options
    5697:    may be specific to certain storage formats.  Some options
    5698:    determine how values will be inserted (or added). Sorted,
    5699:    row-oriented input will generally assemble the fastest. The default
    5700:    is row-oriented.

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

    5704:    Input Parameters:
    5705: +  mat - the matrix
    5706: .  option - the option, one of those listed below (and possibly others),
    5707: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

    5709:   Options Describing Matrix Structure:
    5710: +    MAT_SPD - symmetric positive definite
    5711: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
    5712: .    MAT_HERMITIAN - transpose is the complex conjugation
    5713: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
    5714: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
    5715:                             you set to be kept with all future use of the matrix
    5716:                             including after MatAssemblyBegin/End() which could
    5717:                             potentially change the symmetry structure, i.e. you
    5718:                             KNOW the matrix will ALWAYS have the property you set.
    5719:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
    5720:                             the relevant flags must be set independently.

    5723:    Options For Use with MatSetValues():
    5724:    Insert a logically dense subblock, which can be
    5725: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

    5763:    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
    5764:    that would generate a new entry in the nonzero structure instead produces
    5765:    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

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

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

    5779:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
    5780:    searches during matrix assembly. When this flag is set, the hash table
    5781:    is created during the first Matrix Assembly. This hash table is
    5782:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
    5783:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
    5784:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
    5785:    supported by MATMPIBAIJ format only.

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

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

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

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

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

    5801:    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
    5802:                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
    5803:                      with finite difference schemes with non-periodic boundary conditions.

    5805:    Level: intermediate

    5807: .seealso:  MatOption, Mat

    5809: @*/
    5810: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
    5811: {

    5816:   if (op > 0) {
    5819:   }

    5821:   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);

    5823:   switch (op) {
    5824:   case MAT_FORCE_DIAGONAL_ENTRIES:
    5825:     mat->force_diagonals = flg;
    5826:     return(0);
    5827:   case MAT_NO_OFF_PROC_ENTRIES:
    5828:     mat->nooffprocentries = flg;
    5829:     return(0);
    5830:   case MAT_SUBSET_OFF_PROC_ENTRIES:
    5831:     mat->assembly_subset = flg;
    5832:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
    5833: #if !defined(PETSC_HAVE_MPIUNI)
    5834:       MatStashScatterDestroy_BTS(&mat->stash);
    5835: #endif
    5836:       mat->stash.first_assembly_done = PETSC_FALSE;
    5837:     }
    5838:     return(0);
    5839:   case MAT_NO_OFF_PROC_ZERO_ROWS:
    5840:     mat->nooffproczerorows = flg;
    5841:     return(0);
    5842:   case MAT_SPD:
    5843:     mat->spd_set = PETSC_TRUE;
    5844:     mat->spd     = flg;
    5845:     if (flg) {
    5846:       mat->symmetric                  = PETSC_TRUE;
    5847:       mat->structurally_symmetric     = PETSC_TRUE;
    5848:       mat->symmetric_set              = PETSC_TRUE;
    5849:       mat->structurally_symmetric_set = PETSC_TRUE;
    5850:     }
    5851:     break;
    5852:   case MAT_SYMMETRIC:
    5853:     mat->symmetric = flg;
    5854:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
    5855:     mat->symmetric_set              = PETSC_TRUE;
    5856:     mat->structurally_symmetric_set = flg;
    5857: #if !defined(PETSC_USE_COMPLEX)
    5858:     mat->hermitian     = flg;
    5859:     mat->hermitian_set = PETSC_TRUE;
    5860: #endif
    5861:     break;
    5862:   case MAT_HERMITIAN:
    5863:     mat->hermitian = flg;
    5864:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
    5865:     mat->hermitian_set              = PETSC_TRUE;
    5866:     mat->structurally_symmetric_set = flg;
    5867: #if !defined(PETSC_USE_COMPLEX)
    5868:     mat->symmetric     = flg;
    5869:     mat->symmetric_set = PETSC_TRUE;
    5870: #endif
    5871:     break;
    5872:   case MAT_STRUCTURALLY_SYMMETRIC:
    5873:     mat->structurally_symmetric     = flg;
    5874:     mat->structurally_symmetric_set = PETSC_TRUE;
    5875:     break;
    5876:   case MAT_SYMMETRY_ETERNAL:
    5877:     mat->symmetric_eternal = flg;
    5878:     break;
    5879:   case MAT_STRUCTURE_ONLY:
    5880:     mat->structure_only = flg;
    5881:     break;
    5882:   case MAT_SORTED_FULL:
    5883:     mat->sortedfull = flg;
    5884:     break;
    5885:   default:
    5886:     break;
    5887:   }
    5888:   if (mat->ops->setoption) {
    5889:     (*mat->ops->setoption)(mat,op,flg);
    5890:   }
    5891:   return(0);
    5892: }

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

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

    5899:    Input Parameters:
    5900: +  mat - the matrix
    5901: -  option - the option, this only responds to certain options, check the code for which ones

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

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

    5909:    Level: intermediate

    5911: .seealso:  MatOption, MatSetOption()

    5913: @*/
    5914: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
    5915: {

    5920:   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);
    5921:   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()");

    5923:   switch (op) {
    5924:   case MAT_NO_OFF_PROC_ENTRIES:
    5925:     *flg = mat->nooffprocentries;
    5926:     break;
    5927:   case MAT_NO_OFF_PROC_ZERO_ROWS:
    5928:     *flg = mat->nooffproczerorows;
    5929:     break;
    5930:   case MAT_SYMMETRIC:
    5931:     *flg = mat->symmetric;
    5932:     break;
    5933:   case MAT_HERMITIAN:
    5934:     *flg = mat->hermitian;
    5935:     break;
    5936:   case MAT_STRUCTURALLY_SYMMETRIC:
    5937:     *flg = mat->structurally_symmetric;
    5938:     break;
    5939:   case MAT_SYMMETRY_ETERNAL:
    5940:     *flg = mat->symmetric_eternal;
    5941:     break;
    5942:   case MAT_SPD:
    5943:     *flg = mat->spd;
    5944:     break;
    5945:   default:
    5946:     break;
    5947:   }
    5948:   return(0);
    5949: }

    5951: /*@
    5952:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
    5953:    this routine retains the old nonzero structure.

    5955:    Logically Collective on Mat

    5957:    Input Parameters:
    5958: .  mat - the matrix

    5960:    Level: intermediate

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

    5966: .seealso: MatZeroRows()
    5967: @*/
    5968: PetscErrorCode MatZeroEntries(Mat mat)
    5969: {

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

    5980:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
    5981:   (*mat->ops->zeroentries)(mat);
    5982:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
    5983:   PetscObjectStateIncrease((PetscObject)mat);
    5984:   return(0);
    5985: }

    5987: /*@
    5988:    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
    5989:    of a set of rows and columns of a matrix.

    5991:    Collective on Mat

    5993:    Input Parameters:
    5994: +  mat - the matrix
    5995: .  numRows - the number of rows to remove
    5996: .  rows - the global row indices
    5997: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
    5998: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    5999: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

    6018:    Level: intermediate

    6020: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6021:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6022: @*/
    6023: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    6024: {

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

    6036:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
    6037:   MatViewFromOptions(mat,NULL,"-mat_view");
    6038:   PetscObjectStateIncrease((PetscObject)mat);
    6039:   return(0);
    6040: }

    6042: /*@
    6043:    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
    6044:    of a set of rows and columns of a matrix.

    6046:    Collective on Mat

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

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

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

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

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

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

    6072:    Level: intermediate

    6074: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6075:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
    6076: @*/
    6077: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    6078: {
    6080:   PetscInt       numRows;
    6081:   const PetscInt *rows;

    6088:   ISGetLocalSize(is,&numRows);
    6089:   ISGetIndices(is,&rows);
    6090:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
    6091:   ISRestoreIndices(is,&rows);
    6092:   return(0);
    6093: }

    6095: /*@
    6096:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
    6097:    of a set of rows of a matrix.

    6099:    Collective on Mat

    6101:    Input Parameters:
    6102: +  mat - the matrix
    6103: .  numRows - the number of rows to remove
    6104: .  rows - the global row indices
    6105: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
    6106: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    6107: -  b - optional vector of right hand side, that will be adjusted by provided solution

    6109:    Notes:
    6110:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    6111:    but does not release memory.  For the dense and block diagonal
    6112:    formats this does not alter the nonzero structure.

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

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

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

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

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

    6133:    Level: intermediate

    6135: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6136:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6137: @*/
    6138: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    6139: {

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

    6151:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
    6152:   MatViewFromOptions(mat,NULL,"-mat_view");
    6153:   PetscObjectStateIncrease((PetscObject)mat);
    6154:   return(0);
    6155: }

    6157: /*@
    6158:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
    6159:    of a set of rows of a matrix.

    6161:    Collective on Mat

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

    6170:    Notes:
    6171:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    6172:    but does not release memory.  For the dense and block diagonal
    6173:    formats this does not alter the nonzero structure.

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

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

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

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

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

    6194:    Level: intermediate

    6196: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6197:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6198: @*/
    6199: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    6200: {
    6201:   PetscInt       numRows;
    6202:   const PetscInt *rows;

    6209:   ISGetLocalSize(is,&numRows);
    6210:   ISGetIndices(is,&rows);
    6211:   MatZeroRows(mat,numRows,rows,diag,x,b);
    6212:   ISRestoreIndices(is,&rows);
    6213:   return(0);
    6214: }

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

    6220:    Collective on Mat

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

    6230:    Notes:
    6231:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    6232:    but does not release memory.  For the dense and block diagonal
    6233:    formats this does not alter the nonzero structure.

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

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

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

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

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

    6253:    In Fortran idxm and idxn should be declared as
    6254: $     MatStencil idxm(4,m)
    6255:    and the values inserted using
    6256: $    idxm(MatStencil_i,1) = i
    6257: $    idxm(MatStencil_j,1) = j
    6258: $    idxm(MatStencil_k,1) = k
    6259: $    idxm(MatStencil_c,1) = c
    6260:    etc

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

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

    6270:    Level: intermediate

    6272: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6273:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6274: @*/
    6275: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
    6276: {
    6277:   PetscInt       dim     = mat->stencil.dim;
    6278:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
    6279:   PetscInt       *dims   = mat->stencil.dims+1;
    6280:   PetscInt       *starts = mat->stencil.starts;
    6281:   PetscInt       *dxm    = (PetscInt*) rows;
    6282:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;

    6290:   PetscMalloc1(numRows, &jdxm);
    6291:   for (i = 0; i < numRows; ++i) {
    6292:     /* Skip unused dimensions (they are ordered k, j, i, c) */
    6293:     for (j = 0; j < 3-sdim; ++j) dxm++;
    6294:     /* Local index in X dir */
    6295:     tmp = *dxm++ - starts[0];
    6296:     /* Loop over remaining dimensions */
    6297:     for (j = 0; j < dim-1; ++j) {
    6298:       /* If nonlocal, set index to be negative */
    6299:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
    6300:       /* Update local index */
    6301:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
    6302:     }
    6303:     /* Skip component slot if necessary */
    6304:     if (mat->stencil.noc) dxm++;
    6305:     /* Local row number */
    6306:     if (tmp >= 0) {
    6307:       jdxm[numNewRows++] = tmp;
    6308:     }
    6309:   }
    6310:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
    6311:   PetscFree(jdxm);
    6312:   return(0);
    6313: }

    6315: /*@
    6316:    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
    6317:    of a set of rows and columns of a matrix.

    6319:    Collective on Mat

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

    6329:    Notes:
    6330:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    6331:    but does not release memory.  For the dense and block diagonal
    6332:    formats this does not alter the nonzero structure.

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

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

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

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

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

    6352:    In Fortran idxm and idxn should be declared as
    6353: $     MatStencil idxm(4,m)
    6354:    and the values inserted using
    6355: $    idxm(MatStencil_i,1) = i
    6356: $    idxm(MatStencil_j,1) = j
    6357: $    idxm(MatStencil_k,1) = k
    6358: $    idxm(MatStencil_c,1) = c
    6359:    etc

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

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

    6369:    Level: intermediate

    6371: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6372:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
    6373: @*/
    6374: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
    6375: {
    6376:   PetscInt       dim     = mat->stencil.dim;
    6377:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
    6378:   PetscInt       *dims   = mat->stencil.dims+1;
    6379:   PetscInt       *starts = mat->stencil.starts;
    6380:   PetscInt       *dxm    = (PetscInt*) rows;
    6381:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;

    6389:   PetscMalloc1(numRows, &jdxm);
    6390:   for (i = 0; i < numRows; ++i) {
    6391:     /* Skip unused dimensions (they are ordered k, j, i, c) */
    6392:     for (j = 0; j < 3-sdim; ++j) dxm++;
    6393:     /* Local index in X dir */
    6394:     tmp = *dxm++ - starts[0];
    6395:     /* Loop over remaining dimensions */
    6396:     for (j = 0; j < dim-1; ++j) {
    6397:       /* If nonlocal, set index to be negative */
    6398:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
    6399:       /* Update local index */
    6400:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
    6401:     }
    6402:     /* Skip component slot if necessary */
    6403:     if (mat->stencil.noc) dxm++;
    6404:     /* Local row number */
    6405:     if (tmp >= 0) {
    6406:       jdxm[numNewRows++] = tmp;
    6407:     }
    6408:   }
    6409:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
    6410:   PetscFree(jdxm);
    6411:   return(0);
    6412: }

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

    6418:    Collective on Mat

    6420:    Input Parameters:
    6421: +  mat - the matrix
    6422: .  numRows - the number of rows to remove
    6423: .  rows - the global row indices
    6424: .  diag - value put in all diagonals of eliminated rows
    6425: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    6426: -  b - optional vector of right hand side, that will be adjusted by provided solution

    6428:    Notes:
    6429:    Before calling MatZeroRowsLocal(), the user must first set the
    6430:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

    6432:    For the AIJ matrix formats this removes the old nonzero structure,
    6433:    but does not release memory.  For the dense and block diagonal
    6434:    formats this does not alter the nonzero structure.

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

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

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

    6447:    Level: intermediate

    6449: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
    6450:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6451: @*/
    6452: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    6453: {

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

    6464:   if (mat->ops->zerorowslocal) {
    6465:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
    6466:   } else {
    6467:     IS             is, newis;
    6468:     const PetscInt *newRows;

    6470:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
    6471:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
    6472:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
    6473:     ISGetIndices(newis,&newRows);
    6474:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
    6475:     ISRestoreIndices(newis,&newRows);
    6476:     ISDestroy(&newis);
    6477:     ISDestroy(&is);
    6478:   }
    6479:   PetscObjectStateIncrease((PetscObject)mat);
    6480:   return(0);
    6481: }

    6483: /*@
    6484:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
    6485:    of a set of rows of a matrix; using local numbering of rows.

    6487:    Collective on Mat

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

    6496:    Notes:
    6497:    Before calling MatZeroRowsLocalIS(), the user must first set the
    6498:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

    6500:    For the AIJ matrix formats this removes the old nonzero structure,
    6501:    but does not release memory.  For the dense and block diagonal
    6502:    formats this does not alter the nonzero structure.

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

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

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

    6515:    Level: intermediate

    6517: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6518:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6519: @*/
    6520: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    6521: {
    6523:   PetscInt       numRows;
    6524:   const PetscInt *rows;

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

    6534:   ISGetLocalSize(is,&numRows);
    6535:   ISGetIndices(is,&rows);
    6536:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
    6537:   ISRestoreIndices(is,&rows);
    6538:   return(0);
    6539: }

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

    6545:    Collective on Mat

    6547:    Input Parameters:
    6548: +  mat - the matrix
    6549: .  numRows - the number of rows to remove
    6550: .  rows - the global row indices
    6551: .  diag - value put in all diagonals of eliminated rows
    6552: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    6553: -  b - optional vector of right hand side, that will be adjusted by provided solution

    6555:    Notes:
    6556:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
    6557:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

    6563:    Level: intermediate

    6565: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6566:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6567: @*/
    6568: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    6569: {
    6571:   IS             is, newis;
    6572:   const PetscInt *newRows;

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

    6582:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
    6583:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
    6584:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
    6585:   ISGetIndices(newis,&newRows);
    6586:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
    6587:   ISRestoreIndices(newis,&newRows);
    6588:   ISDestroy(&newis);
    6589:   ISDestroy(&is);
    6590:   PetscObjectStateIncrease((PetscObject)mat);
    6591:   return(0);
    6592: }

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

    6598:    Collective on Mat

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

    6607:    Notes:
    6608:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
    6609:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

    6615:    Level: intermediate

    6617: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6618:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6619: @*/
    6620: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    6621: {
    6623:   PetscInt       numRows;
    6624:   const PetscInt *rows;

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

    6634:   ISGetLocalSize(is,&numRows);
    6635:   ISGetIndices(is,&rows);
    6636:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
    6637:   ISRestoreIndices(is,&rows);
    6638:   return(0);
    6639: }

    6641: /*@C
    6642:    MatGetSize - Returns the numbers of rows and columns in a matrix.

    6644:    Not Collective

    6646:    Input Parameter:
    6647: .  mat - the matrix

    6649:    Output Parameters:
    6650: +  m - the number of global rows
    6651: -  n - the number of global columns

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

    6655:    Level: beginner

    6657: .seealso: MatGetLocalSize()
    6658: @*/
    6659: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
    6660: {
    6663:   if (m) *m = mat->rmap->N;
    6664:   if (n) *n = mat->cmap->N;
    6665:   return(0);
    6666: }

    6668: /*@C
    6669:    MatGetLocalSize - Returns the number of local rows and local columns
    6670:    of a matrix, that is the local size of the left and right vectors as returned by MatCreateVecs().

    6672:    Not Collective

    6674:    Input Parameters:
    6675: .  mat - the matrix

    6677:    Output Parameters:
    6678: +  m - the number of local rows
    6679: -  n - the number of local columns

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

    6683:    Level: beginner

    6685: .seealso: MatGetSize()
    6686: @*/
    6687: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
    6688: {
    6693:   if (m) *m = mat->rmap->n;
    6694:   if (n) *n = mat->cmap->n;
    6695:   return(0);
    6696: }

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

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

    6704:    Input Parameters:
    6705: .  mat - the matrix

    6707:    Output Parameters:
    6708: +  m - the global index of the first local column
    6709: -  n - one more than the global index of the last local column

    6711:    Notes:
    6712:     both output parameters can be NULL on input.

    6714:    Level: developer

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

    6718: @*/
    6719: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
    6720: {
    6726:   MatCheckPreallocated(mat,1);
    6727:   if (m) *m = mat->cmap->rstart;
    6728:   if (n) *n = mat->cmap->rend;
    6729:   return(0);
    6730: }

    6732: /*@C
    6733:    MatGetOwnershipRange - Returns the range of matrix rows owned by
    6734:    this processor, assuming that the matrix is laid out with the first
    6735:    n1 rows on the first processor, the next n2 rows on the second, etc.
    6736:    For certain parallel layouts this range may not be well defined.

    6738:    Not Collective

    6740:    Input Parameters:
    6741: .  mat - the matrix

    6743:    Output Parameters:
    6744: +  m - the global index of the first local row
    6745: -  n - one more than the global index of the last local row

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

    6752:    Level: beginner

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

    6756: @*/
    6757: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
    6758: {
    6764:   MatCheckPreallocated(mat,1);
    6765:   if (m) *m = mat->rmap->rstart;
    6766:   if (n) *n = mat->rmap->rend;
    6767:   return(0);
    6768: }

    6770: /*@C
    6771:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
    6772:    each process

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

    6776:    Input Parameters:
    6777: .  mat - the matrix

    6779:    Output Parameters:
    6780: .  ranges - start of each processors portion plus one more than the total length at the end

    6782:    Level: beginner

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

    6786: @*/
    6787: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
    6788: {

    6794:   MatCheckPreallocated(mat,1);
    6795:   PetscLayoutGetRanges(mat->rmap,ranges);
    6796:   return(0);
    6797: }

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

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

    6805:    Input Parameters:
    6806: .  mat - the matrix

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

    6811:    Level: beginner

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

    6815: @*/
    6816: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
    6817: {

    6823:   MatCheckPreallocated(mat,1);
    6824:   PetscLayoutGetRanges(mat->cmap,ranges);
    6825:   return(0);
    6826: }

    6828: /*@C
    6829:    MatGetOwnershipIS - Get row and column ownership as index sets

    6831:    Not Collective

    6833:    Input Arguments:
    6834: .  A - matrix of type Elemental or ScaLAPACK

    6836:    Output Arguments:
    6837: +  rows - rows in which this process owns elements
    6838: -  cols - columns in which this process owns elements

    6840:    Level: intermediate

    6842: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
    6843: @*/
    6844: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
    6845: {
    6846:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

    6849:   MatCheckPreallocated(A,1);
    6850:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
    6851:   if (f) {
    6852:     (*f)(A,rows,cols);
    6853:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
    6854:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
    6855:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
    6856:   }
    6857:   return(0);
    6858: }

    6860: /*@C
    6861:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
    6862:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
    6863:    to complete the factorization.

    6865:    Collective on Mat

    6867:    Input Parameters:
    6868: +  mat - the matrix
    6869: .  row - row permutation
    6870: .  column - column permutation
    6871: -  info - structure containing
    6872: $      levels - number of levels of fill.
    6873: $      expected fill - as ratio of original fill.
    6874: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
    6875:                 missing diagonal entries)

    6877:    Output Parameters:
    6878: .  fact - new matrix that has been symbolically factored

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

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

    6887:    Level: developer

    6889: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
    6890:           MatGetOrdering(), MatFactorInfo

    6892:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

    6897:    References:
    6898:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
    6899: @*/
    6900: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
    6901: {

    6911:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
    6912:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
    6913:   if (!fact->ops->ilufactorsymbolic) {
    6914:     MatSolverType stype;
    6915:     MatFactorGetSolverType(fact,&stype);
    6916:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver type %s",((PetscObject)mat)->type_name,stype);
    6917:   }
    6918:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    6919:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    6920:   MatCheckPreallocated(mat,2);

    6922:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
    6923:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
    6924:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
    6925:   return(0);
    6926: }

    6928: /*@C
    6929:    MatICCFactorSymbolic - Performs symbolic incomplete
    6930:    Cholesky factorization for a symmetric matrix.  Use
    6931:    MatCholeskyFactorNumeric() to complete the factorization.

    6933:    Collective on Mat

    6935:    Input Parameters:
    6936: +  mat - the matrix
    6937: .  perm - row and column permutation
    6938: -  info - structure containing
    6939: $      levels - number of levels of fill.
    6940: $      expected fill - as ratio of original fill.

    6942:    Output Parameter:
    6943: .  fact - the factored matrix

    6945:    Notes:
    6946:    Most users should employ the KSP interface for linear solvers
    6947:    instead of working directly with matrix algebra routines such as this.
    6948:    See, e.g., KSPCreate().

    6950:    Level: developer

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

    6954:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

    6959:    References:
    6960:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
    6961: @*/
    6962: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
    6963: {

    6972:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    6973:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
    6974:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
    6975:   if (!(fact)->ops->iccfactorsymbolic) {
    6976:     MatSolverType stype;
    6977:     MatFactorGetSolverType(fact,&stype);
    6978:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver type %s",((PetscObject)mat)->type_name,stype);
    6979:   }
    6980:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    6981:   MatCheckPreallocated(mat,2);

    6983:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
    6984:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
    6985:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
    6986:   return(0);
    6987: }

    6989: /*@C
    6990:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
    6991:    points to an array of valid matrices, they may be reused to store the new
    6992:    submatrices.

    6994:    Collective on Mat

    6996:    Input Parameters:
    6997: +  mat - the matrix
    6998: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
    6999: .  irow, icol - index sets of rows and columns to extract
    7000: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    7002:    Output Parameter:
    7003: .  submat - the array of submatrices

    7005:    Notes:
    7006:    MatCreateSubMatrices() can extract ONLY sequential submatrices
    7007:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
    7008:    to extract a parallel submatrix.

    7010:    Some matrix types place restrictions on the row and column
    7011:    indices, such as that they be sorted or that they be equal to each other.

    7013:    The index sets may not have duplicate entries.

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

    7019:    When finished using the submatrices, the user should destroy
    7020:    them with MatDestroySubMatrices().

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

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

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

    7033:    Fortran Note:
    7034:    The Fortran interface is slightly different from that given below; it
    7035:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

    7037:    Level: advanced

    7040: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
    7041: @*/
    7042: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
    7043: {
    7045:   PetscInt       i;
    7046:   PetscBool      eq;

    7051:   if (n) {
    7056:   }
    7058:   if (n && scall == MAT_REUSE_MATRIX) {
    7061:   }
    7062:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    7063:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    7064:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    7065:   MatCheckPreallocated(mat,1);

    7067:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
    7068:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
    7069:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
    7070:   for (i=0; i<n; i++) {
    7071:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
    7072:     ISEqualUnsorted(irow[i],icol[i],&eq);
    7073:     if (eq) {
    7074:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
    7075:     }
    7076:   }
    7077:   return(0);
    7078: }

    7080: /*@C
    7081:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

    7083:    Collective on Mat

    7085:    Input Parameters:
    7086: +  mat - the matrix
    7087: .  n   - the number of submatrixes to be extracted
    7088: .  irow, icol - index sets of rows and columns to extract
    7089: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    7091:    Output Parameter:
    7092: .  submat - the array of submatrices

    7094:    Level: advanced

    7097: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
    7098: @*/
    7099: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
    7100: {
    7102:   PetscInt       i;
    7103:   PetscBool      eq;

    7108:   if (n) {
    7113:   }
    7115:   if (n && scall == MAT_REUSE_MATRIX) {
    7118:   }
    7119:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    7120:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    7121:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    7122:   MatCheckPreallocated(mat,1);

    7124:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
    7125:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
    7126:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
    7127:   for (i=0; i<n; i++) {
    7128:     ISEqualUnsorted(irow[i],icol[i],&eq);
    7129:     if (eq) {
    7130:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
    7131:     }
    7132:   }
    7133:   return(0);
    7134: }

    7136: /*@C
    7137:    MatDestroyMatrices - Destroys an array of matrices.

    7139:    Collective on Mat

    7141:    Input Parameters:
    7142: +  n - the number of local matrices
    7143: -  mat - the matrices (note that this is a pointer to the array of matrices)

    7145:    Level: advanced

    7147:     Notes:
    7148:     Frees not only the matrices, but also the array that contains the matrices
    7149:            In Fortran will not free the array.

    7151: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
    7152: @*/
    7153: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
    7154: {
    7156:   PetscInt       i;

    7159:   if (!*mat) return(0);
    7160:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

    7163:   for (i=0; i<n; i++) {
    7164:     MatDestroy(&(*mat)[i]);
    7165:   }

    7167:   /* memory is allocated even if n = 0 */
    7168:   PetscFree(*mat);
    7169:   return(0);
    7170: }

    7172: /*@C
    7173:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

    7175:    Collective on Mat

    7177:    Input Parameters:
    7178: +  n - the number of local matrices
    7179: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
    7180:                        sequence of MatCreateSubMatrices())

    7182:    Level: advanced

    7184:     Notes:
    7185:     Frees not only the matrices, but also the array that contains the matrices
    7186:            In Fortran will not free the array.

    7188: .seealso: MatCreateSubMatrices()
    7189: @*/
    7190: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
    7191: {
    7193:   Mat            mat0;

    7196:   if (!*mat) return(0);
    7197:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
    7198:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

    7201:   mat0 = (*mat)[0];
    7202:   if (mat0 && mat0->ops->destroysubmatrices) {
    7203:     (mat0->ops->destroysubmatrices)(n,mat);
    7204:   } else {
    7205:     MatDestroyMatrices(n,mat);
    7206:   }
    7207:   return(0);
    7208: }

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

    7213:    Collective on Mat

    7215:    Input Parameters:
    7216: .  mat - the matrix

    7218:    Output Parameter:
    7219: .  matstruct - the sequential matrix with the nonzero structure of mat

    7221:   Level: intermediate

    7223: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
    7224: @*/
    7225: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
    7226: {

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

    7237:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
    7238:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
    7239:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
    7240:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
    7241:   return(0);
    7242: }

    7244: /*@C
    7245:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

    7247:    Collective on Mat

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

    7253:    Level: advanced

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

    7258: .seealso: MatGetSeqNonzeroStructure()
    7259: @*/
    7260: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
    7261: {

    7266:   MatDestroy(mat);
    7267:   return(0);
    7268: }

    7270: /*@
    7271:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
    7272:    replaces the index sets by larger ones that represent submatrices with
    7273:    additional overlap.

    7275:    Collective on Mat

    7277:    Input Parameters:
    7278: +  mat - the matrix
    7279: .  n   - the number of index sets
    7280: .  is  - the array of index sets (these index sets will changed during the call)
    7281: -  ov  - the additional overlap requested

    7283:    Options Database:
    7284: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

    7286:    Level: developer

    7289: .seealso: MatCreateSubMatrices()
    7290: @*/
    7291: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
    7292: {

    7298:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
    7299:   if (n) {
    7302:   }
    7303:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    7304:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    7305:   MatCheckPreallocated(mat,1);

    7307:   if (!ov) return(0);
    7308:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    7309:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
    7310:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
    7311:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
    7312:   return(0);
    7313: }

    7316: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

    7318: /*@
    7319:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
    7320:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
    7321:    additional overlap.

    7323:    Collective on Mat

    7325:    Input Parameters:
    7326: +  mat - the matrix
    7327: .  n   - the number of index sets
    7328: .  is  - the array of index sets (these index sets will changed during the call)
    7329: -  ov  - the additional overlap requested

    7331:    Options Database:
    7332: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

    7334:    Level: developer

    7337: .seealso: MatCreateSubMatrices()
    7338: @*/
    7339: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
    7340: {
    7341:   PetscInt       i;

    7347:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
    7348:   if (n) {
    7351:   }
    7352:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    7353:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    7354:   MatCheckPreallocated(mat,1);
    7355:   if (!ov) return(0);
    7356:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
    7357:   for (i=0; i<n; i++){
    7358:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
    7359:   }
    7360:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
    7361:   return(0);
    7362: }

    7367: /*@
    7368:    MatGetBlockSize - Returns the matrix block size.

    7370:    Not Collective

    7372:    Input Parameter:
    7373: .  mat - the matrix

    7375:    Output Parameter:
    7376: .  bs - block size

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

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

    7383:    Level: intermediate

    7385: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
    7386: @*/
    7387: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
    7388: {
    7392:   *bs = PetscAbs(mat->rmap->bs);
    7393:   return(0);
    7394: }

    7396: /*@
    7397:    MatGetBlockSizes - Returns the matrix block row and column sizes.

    7399:    Not Collective

    7401:    Input Parameter:
    7402: .  mat - the matrix

    7404:    Output Parameter:
    7405: +  rbs - row block size
    7406: -  cbs - column block size

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

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

    7414:    Level: intermediate

    7416: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
    7417: @*/
    7418: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
    7419: {
    7424:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
    7425:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
    7426:   return(0);
    7427: }

    7429: /*@
    7430:    MatSetBlockSize - Sets the matrix block size.

    7432:    Logically Collective on Mat

    7434:    Input Parameters:
    7435: +  mat - the matrix
    7436: -  bs - block size

    7438:    Notes:
    7439:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
    7440:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

    7442:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
    7443:     is compatible with the matrix local sizes.

    7445:    Level: intermediate

    7447: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
    7448: @*/
    7449: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
    7450: {

    7456:   MatSetBlockSizes(mat,bs,bs);
    7457:   return(0);
    7458: }

    7460: /*@
    7461:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

    7463:    Logically Collective on Mat

    7465:    Input Parameters:
    7466: +  mat - the matrix
    7467: .  nblocks - the number of blocks on this process
    7468: -  bsizes - the block sizes

    7470:    Notes:
    7471:     Currently used by PCVPBJACOBI for SeqAIJ matrices

    7473:    Level: intermediate

    7475: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
    7476: @*/
    7477: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
    7478: {
    7480:   PetscInt       i,ncnt = 0, nlocal;

    7484:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
    7485:   MatGetLocalSize(mat,&nlocal,NULL);
    7486:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
    7487:   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);
    7488:   PetscFree(mat->bsizes);
    7489:   mat->nblocks = nblocks;
    7490:   PetscMalloc1(nblocks,&mat->bsizes);
    7491:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
    7492:   return(0);
    7493: }

    7495: /*@C
    7496:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

    7498:    Logically Collective on Mat

    7500:    Input Parameters:
    7501: .  mat - the matrix

    7503:    Output Parameters:
    7504: +  nblocks - the number of blocks on this process
    7505: -  bsizes - the block sizes

    7507:    Notes: Currently not supported from Fortran

    7509:    Level: intermediate

    7511: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
    7512: @*/
    7513: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
    7514: {
    7517:   *nblocks = mat->nblocks;
    7518:   *bsizes  = mat->bsizes;
    7519:   return(0);
    7520: }

    7522: /*@
    7523:    MatSetBlockSizes - Sets the matrix block row and column sizes.

    7525:    Logically Collective on Mat

    7527:    Input Parameters:
    7528: +  mat - the matrix
    7529: .  rbs - row block size
    7530: -  cbs - column block size

    7532:    Notes:
    7533:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
    7534:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
    7535:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

    7537:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
    7538:     are compatible with the matrix local sizes.

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

    7542:    Level: intermediate

    7544: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
    7545: @*/
    7546: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
    7547: {

    7554:   if (mat->ops->setblocksizes) {
    7555:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
    7556:   }
    7557:   if (mat->rmap->refcnt) {
    7558:     ISLocalToGlobalMapping l2g = NULL;
    7559:     PetscLayout            nmap = NULL;

    7561:     PetscLayoutDuplicate(mat->rmap,&nmap);
    7562:     if (mat->rmap->mapping) {
    7563:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
    7564:     }
    7565:     PetscLayoutDestroy(&mat->rmap);
    7566:     mat->rmap = nmap;
    7567:     mat->rmap->mapping = l2g;
    7568:   }
    7569:   if (mat->cmap->refcnt) {
    7570:     ISLocalToGlobalMapping l2g = NULL;
    7571:     PetscLayout            nmap = NULL;

    7573:     PetscLayoutDuplicate(mat->cmap,&nmap);
    7574:     if (mat->cmap->mapping) {
    7575:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
    7576:     }
    7577:     PetscLayoutDestroy(&mat->cmap);
    7578:     mat->cmap = nmap;
    7579:     mat->cmap->mapping = l2g;
    7580:   }
    7581:   PetscLayoutSetBlockSize(mat->rmap,rbs);
    7582:   PetscLayoutSetBlockSize(mat->cmap,cbs);
    7583:   return(0);
    7584: }

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

    7589:    Logically Collective on Mat

    7591:    Input Parameters:
    7592: +  mat - the matrix
    7593: .  fromRow - matrix from which to copy row block size
    7594: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

    7596:    Level: developer

    7598: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
    7599: @*/
    7600: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
    7601: {

    7608:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
    7609:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
    7610:   return(0);
    7611: }

    7613: /*@
    7614:    MatResidual - Default routine to calculate the residual.

    7616:    Collective on Mat

    7618:    Input Parameters:
    7619: +  mat - the matrix
    7620: .  b   - the right-hand-side
    7621: -  x   - the approximate solution

    7623:    Output Parameter:
    7624: .  r - location to store the residual

    7626:    Level: developer

    7628: .seealso: PCMGSetResidual()
    7629: @*/
    7630: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
    7631: {

    7640:   MatCheckPreallocated(mat,1);
    7641:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
    7642:   if (!mat->ops->residual) {
    7643:     MatMult(mat,x,r);
    7644:     VecAYPX(r,-1.0,b);
    7645:   } else {
    7646:     (*mat->ops->residual)(mat,b,x,r);
    7647:   }
    7648:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
    7649:   return(0);
    7650: }

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

    7655:    Collective on Mat

    7657:     Input Parameters:
    7658: +   mat - the matrix
    7659: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
    7660: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
    7661: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
    7662:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7663:                  always used.

    7665:     Output Parameters:
    7666: +   n - number of rows in the (possibly compressed) matrix
    7667: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
    7668: .   ja - the column indices
    7669: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
    7670:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

    7672:     Level: developer

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

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

    7679:     Fortran Notes:
    7680:     In Fortran use
    7681: $
    7682: $      PetscInt ia(1), ja(1)
    7683: $      PetscOffset iia, jja
    7684: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
    7685: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

    7687:      or
    7688: $
    7689: $    PetscInt, pointer :: ia(:),ja(:)
    7690: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
    7691: $    ! Access the ith and jth entries via ia(i) and ja(j)

    7693: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
    7694: @*/
    7695: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7696: {

    7706:   MatCheckPreallocated(mat,1);
    7707:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
    7708:   else {
    7709:     *done = PETSC_TRUE;
    7710:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
    7711:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7712:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
    7713:   }
    7714:   return(0);
    7715: }

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

    7720:     Collective on Mat

    7722:     Input Parameters:
    7723: +   mat - the matrix
    7724: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
    7725: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
    7726:                 symmetrized
    7727: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
    7728:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7729:                  always used.
    7730: .   n - number of columns in the (possibly compressed) matrix
    7731: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
    7732: -   ja - the row indices

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

    7737:     Level: developer

    7739: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
    7740: @*/
    7741: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7742: {

    7752:   MatCheckPreallocated(mat,1);
    7753:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
    7754:   else {
    7755:     *done = PETSC_TRUE;
    7756:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7757:   }
    7758:   return(0);
    7759: }

    7761: /*@C
    7762:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
    7763:     MatGetRowIJ().

    7765:     Collective on Mat

    7767:     Input Parameters:
    7768: +   mat - the matrix
    7769: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
    7770: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
    7771:                 symmetrized
    7772: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
    7773:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7774:                  always used.
    7775: .   n - size of (possibly compressed) matrix
    7776: .   ia - the row pointers
    7777: -   ja - the column indices

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

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

    7787:     Level: developer

    7789: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
    7790: @*/
    7791: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7792: {

    7801:   MatCheckPreallocated(mat,1);

    7803:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
    7804:   else {
    7805:     *done = PETSC_TRUE;
    7806:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7807:     if (n)  *n = 0;
    7808:     if (ia) *ia = NULL;
    7809:     if (ja) *ja = NULL;
    7810:   }
    7811:   return(0);
    7812: }

    7814: /*@C
    7815:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
    7816:     MatGetColumnIJ().

    7818:     Collective on Mat

    7820:     Input Parameters:
    7821: +   mat - the matrix
    7822: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
    7823: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
    7824:                 symmetrized
    7825: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
    7826:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7827:                  always used.

    7829:     Output Parameters:
    7830: +   n - size of (possibly compressed) matrix
    7831: .   ia - the column pointers
    7832: .   ja - the row indices
    7833: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

    7835:     Level: developer

    7837: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
    7838: @*/
    7839: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7840: {

    7849:   MatCheckPreallocated(mat,1);

    7851:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
    7852:   else {
    7853:     *done = PETSC_TRUE;
    7854:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7855:     if (n)  *n = 0;
    7856:     if (ia) *ia = NULL;
    7857:     if (ja) *ja = NULL;
    7858:   }
    7859:   return(0);
    7860: }

    7862: /*@C
    7863:     MatColoringPatch -Used inside matrix coloring routines that
    7864:     use MatGetRowIJ() and/or MatGetColumnIJ().

    7866:     Collective on Mat

    7868:     Input Parameters:
    7869: +   mat - the matrix
    7870: .   ncolors - max color value
    7871: .   n   - number of entries in colorarray
    7872: -   colorarray - array indicating color for each column

    7874:     Output Parameters:
    7875: .   iscoloring - coloring generated using colorarray information

    7877:     Level: developer

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

    7881: @*/
    7882: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
    7883: {

    7891:   MatCheckPreallocated(mat,1);

    7893:   if (!mat->ops->coloringpatch) {
    7894:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
    7895:   } else {
    7896:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
    7897:   }
    7898:   return(0);
    7899: }

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

    7905:    Logically Collective on Mat

    7907:    Input Parameter:
    7908: .  mat - the factored matrix to be reset

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

    7917:    Note that one can specify in-place ILU(0) factorization by calling
    7918: .vb
    7919:      PCType(pc,PCILU);
    7920:      PCFactorSeUseInPlace(pc);
    7921: .ve
    7922:    or by using the options -pc_type ilu -pc_factor_in_place

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

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

    7933:    Level: developer

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

    7937: @*/
    7938: PetscErrorCode MatSetUnfactored(Mat mat)
    7939: {

    7945:   MatCheckPreallocated(mat,1);
    7946:   mat->factortype = MAT_FACTOR_NONE;
    7947:   if (!mat->ops->setunfactored) return(0);
    7948:   (*mat->ops->setunfactored)(mat);
    7949:   return(0);
    7950: }

    7952: /*MC
    7953:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

    7955:     Synopsis:
    7956:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

    7958:     Not collective

    7960:     Input Parameter:
    7961: .   x - matrix

    7963:     Output Parameters:
    7964: +   xx_v - the Fortran90 pointer to the array
    7965: -   ierr - error code

    7967:     Example of Usage:
    7968: .vb
    7969:       PetscScalar, pointer xx_v(:,:)
    7970:       ....
    7971:       call MatDenseGetArrayF90(x,xx_v,ierr)
    7972:       a = xx_v(3)
    7973:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
    7974: .ve

    7976:     Level: advanced

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

    7980: M*/

    7982: /*MC
    7983:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
    7984:     accessed with MatDenseGetArrayF90().

    7986:     Synopsis:
    7987:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

    7989:     Not collective

    7991:     Input Parameters:
    7992: +   x - matrix
    7993: -   xx_v - the Fortran90 pointer to the array

    7995:     Output Parameter:
    7996: .   ierr - error code

    7998:     Example of Usage:
    7999: .vb
    8000:        PetscScalar, pointer xx_v(:,:)
    8001:        ....
    8002:        call MatDenseGetArrayF90(x,xx_v,ierr)
    8003:        a = xx_v(3)
    8004:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
    8005: .ve

    8007:     Level: advanced

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

    8011: M*/

    8014: /*MC
    8015:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

    8017:     Synopsis:
    8018:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

    8020:     Not collective

    8022:     Input Parameter:
    8023: .   x - matrix

    8025:     Output Parameters:
    8026: +   xx_v - the Fortran90 pointer to the array
    8027: -   ierr - error code

    8029:     Example of Usage:
    8030: .vb
    8031:       PetscScalar, pointer xx_v(:)
    8032:       ....
    8033:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
    8034:       a = xx_v(3)
    8035:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
    8036: .ve

    8038:     Level: advanced

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

    8042: M*/

    8044: /*MC
    8045:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
    8046:     accessed with MatSeqAIJGetArrayF90().

    8048:     Synopsis:
    8049:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

    8051:     Not collective

    8053:     Input Parameters:
    8054: +   x - matrix
    8055: -   xx_v - the Fortran90 pointer to the array

    8057:     Output Parameter:
    8058: .   ierr - error code

    8060:     Example of Usage:
    8061: .vb
    8062:        PetscScalar, pointer xx_v(:)
    8063:        ....
    8064:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
    8065:        a = xx_v(3)
    8066:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
    8067: .ve

    8069:     Level: advanced

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

    8073: M*/

    8076: /*@
    8077:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
    8078:                       as the original matrix.

    8080:     Collective on Mat

    8082:     Input Parameters:
    8083: +   mat - the original matrix
    8084: .   isrow - parallel IS containing the rows this processor should obtain
    8085: .   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.
    8086: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    8088:     Output Parameter:
    8089: .   newmat - the new submatrix, of the same type as the old

    8091:     Level: advanced

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

    8096:     Some matrix types place restrictions on the row and column indices, such
    8097:     as that they be sorted or that they be equal to each other.

    8099:     The index sets may not have duplicate entries.

    8101:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
    8102:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
    8103:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
    8104:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
    8105:    you are finished using it.

    8107:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
    8108:     the input matrix.

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

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

    8118: .vb
    8119:             1  2  0  |  0  3  0  |  0  4
    8120:     Proc0   0  5  6  |  7  0  0  |  8  0
    8121:             9  0 10  | 11  0  0  | 12  0
    8122:     -------------------------------------
    8123:            13  0 14  | 15 16 17  |  0  0
    8124:     Proc1   0 18  0  | 19 20 21  |  0  0
    8125:             0  0  0  | 22 23  0  | 24  0
    8126:     -------------------------------------
    8127:     Proc2  25 26 27  |  0  0 28  | 29  0
    8128:            30  0  0  | 31 32 33  |  0 34
    8129: .ve

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

    8133: .vb
    8134:             2  0  |  0  3  0  |  0
    8135:     Proc0   5  6  |  7  0  0  |  8
    8136:     -------------------------------
    8137:     Proc1  18  0  | 19 20 21  |  0
    8138:     -------------------------------
    8139:     Proc2  26 27  |  0  0 28  | 29
    8140:             0  0  | 31 32 33  |  0
    8141: .ve

    8144: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
    8145: @*/
    8146: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
    8147: {
    8149:   PetscMPIInt    size;
    8150:   Mat            *local;
    8151:   IS             iscoltmp;
    8152:   PetscBool      flg;

    8161:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    8162:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

    8164:   MatCheckPreallocated(mat,1);
    8165:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

    8167:   if (!iscol || isrow == iscol) {
    8168:     PetscBool   stride;
    8169:     PetscMPIInt grabentirematrix = 0,grab;
    8170:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
    8171:     if (stride) {
    8172:       PetscInt first,step,n,rstart,rend;
    8173:       ISStrideGetInfo(isrow,&first,&step);
    8174:       if (step == 1) {
    8175:         MatGetOwnershipRange(mat,&rstart,&rend);
    8176:         if (rstart == first) {
    8177:           ISGetLocalSize(isrow,&n);
    8178:           if (n == rend-rstart) {
    8179:             grabentirematrix = 1;
    8180:           }
    8181:         }
    8182:       }
    8183:     }
    8184:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
    8185:     if (grab) {
    8186:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
    8187:       if (cll == MAT_INITIAL_MATRIX) {
    8188:         *newmat = mat;
    8189:         PetscObjectReference((PetscObject)mat);
    8190:       }
    8191:       return(0);
    8192:     }
    8193:   }

    8195:   if (!iscol) {
    8196:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
    8197:   } else {
    8198:     iscoltmp = iscol;
    8199:   }

    8201:   /* if original matrix is on just one processor then use submatrix generated */
    8202:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
    8203:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
    8204:     goto setproperties;
    8205:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
    8206:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
    8207:     *newmat = *local;
    8208:     PetscFree(local);
    8209:     goto setproperties;
    8210:   } else if (!mat->ops->createsubmatrix) {
    8211:     /* Create a new matrix type that implements the operation using the full matrix */
    8212:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
    8213:     switch (cll) {
    8214:     case MAT_INITIAL_MATRIX:
    8215:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
    8216:       break;
    8217:     case MAT_REUSE_MATRIX:
    8218:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
    8219:       break;
    8220:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
    8221:     }
    8222:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
    8223:     goto setproperties;
    8224:   }

    8226:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    8227:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
    8228:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
    8229:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

    8231: setproperties:
    8232:   ISEqualUnsorted(isrow,iscoltmp,&flg);
    8233:   if (flg) {
    8234:     MatPropagateSymmetryOptions(mat,*newmat);
    8235:   }
    8236:   if (!iscol) {ISDestroy(&iscoltmp);}
    8237:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
    8238:   return(0);
    8239: }

    8241: /*@
    8242:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

    8244:    Not Collective

    8246:    Input Parameters:
    8247: +  A - the matrix we wish to propagate options from
    8248: -  B - the matrix we wish to propagate options to

    8250:    Level: beginner

    8252:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

    8254: .seealso: MatSetOption()
    8255: @*/
    8256: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
    8257: {

    8263:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
    8264:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
    8265:   }
    8266:   if (A->structurally_symmetric_set) {
    8267:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
    8268:   }
    8269:   if (A->hermitian_set) {
    8270:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
    8271:   }
    8272:   if (A->spd_set) {
    8273:     MatSetOption(B,MAT_SPD,A->spd);
    8274:   }
    8275:   if (A->symmetric_set) {
    8276:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
    8277:   }
    8278:   return(0);
    8279: }

    8281: /*@
    8282:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
    8283:    used during the assembly process to store values that belong to
    8284:    other processors.

    8286:    Not Collective

    8288:    Input Parameters:
    8289: +  mat   - the matrix
    8290: .  size  - the initial size of the stash.
    8291: -  bsize - the initial size of the block-stash(if used).

    8293:    Options Database Keys:
    8294: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
    8295: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

    8297:    Level: intermediate

    8299:    Notes:
    8300:      The block-stash is used for values set with MatSetValuesBlocked() while
    8301:      the stash is used for values set with MatSetValues()

    8303:      Run with the option -info and look for output of the form
    8304:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
    8305:      to determine the appropriate value, MM, to use for size and
    8306:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
    8307:      to determine the value, BMM to use for bsize

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

    8312: @*/
    8313: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
    8314: {

    8320:   MatStashSetInitialSize_Private(&mat->stash,size);
    8321:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
    8322:   return(0);
    8323: }

    8325: /*@
    8326:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
    8327:      the matrix

    8329:    Neighbor-wise Collective on Mat

    8331:    Input Parameters:
    8332: +  mat   - the matrix
    8333: .  x,y - the vectors
    8334: -  w - where the result is stored

    8336:    Level: intermediate

    8338:    Notes:
    8339:     w may be the same vector as y.

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

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

    8346: @*/
    8347: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
    8348: {
    8350:   PetscInt       M,N,Ny;

    8357:   MatGetSize(A,&M,&N);
    8358:   VecGetSize(y,&Ny);
    8359:   if (M == Ny) {
    8360:     MatMultAdd(A,x,y,w);
    8361:   } else {
    8362:     MatMultTransposeAdd(A,x,y,w);
    8363:   }
    8364:   return(0);
    8365: }

    8367: /*@
    8368:    MatInterpolate - y = A*x or A'*x depending on the shape of
    8369:      the matrix

    8371:    Neighbor-wise Collective on Mat

    8373:    Input Parameters:
    8374: +  mat   - the matrix
    8375: -  x,y - the vectors

    8377:    Level: intermediate

    8379:    Notes:
    8380:     This allows one to use either the restriction or interpolation (its transpose)
    8381:     matrix to do the interpolation

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

    8385: @*/
    8386: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
    8387: {
    8389:   PetscInt       M,N,Ny;

    8395:   MatGetSize(A,&M,&N);
    8396:   VecGetSize(y,&Ny);
    8397:   if (M == Ny) {
    8398:     MatMult(A,x,y);
    8399:   } else {
    8400:     MatMultTranspose(A,x,y);
    8401:   }
    8402:   return(0);
    8403: }

    8405: /*@
    8406:    MatRestrict - y = A*x or A'*x

    8408:    Neighbor-wise Collective on Mat

    8410:    Input Parameters:
    8411: +  mat   - the matrix
    8412: -  x,y - the vectors

    8414:    Level: intermediate

    8416:    Notes:
    8417:     This allows one to use either the restriction or interpolation (its transpose)
    8418:     matrix to do the restriction

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

    8422: @*/
    8423: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
    8424: {
    8426:   PetscInt       M,N,Ny;

    8432:   MatGetSize(A,&M,&N);
    8433:   VecGetSize(y,&Ny);
    8434:   if (M == Ny) {
    8435:     MatMult(A,x,y);
    8436:   } else {
    8437:     MatMultTranspose(A,x,y);
    8438:   }
    8439:   return(0);
    8440: }

    8442: /*@
    8443:    MatMatInterpolateAdd - Y = W + A*X or W + A'*X

    8445:    Neighbor-wise Collective on Mat

    8447:    Input Parameters:
    8448: +  mat   - the matrix
    8449: -  w, x - the input dense matrices

    8451:    Output Parameters:
    8452: .  y - the output dense matrix

    8454:    Level: intermediate

    8456:    Notes:
    8457:     This allows one to use either the restriction or interpolation (its transpose)
    8458:     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
    8459:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

    8461: .seealso: MatInterpolateAdd(), MatMatInterpolate(), MatMatRestrict()

    8463: @*/
    8464: PetscErrorCode MatMatInterpolateAdd(Mat A,Mat x,Mat w,Mat *y)
    8465: {
    8467:   PetscInt       M,N,Mx,Nx,Mo,My = 0,Ny = 0;
    8468:   PetscBool      trans = PETSC_TRUE;
    8469:   MatReuse       reuse = MAT_INITIAL_MATRIX;

    8477:   MatGetSize(A,&M,&N);
    8478:   MatGetSize(x,&Mx,&Nx);
    8479:   if (N == Mx) trans = PETSC_FALSE;
    8480:   else if (M != Mx) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Size mismatch: A %Dx%D, X %Dx%D",M,N,Mx,Nx);
    8481:   Mo = trans ? N : M;
    8482:   if (*y) {
    8483:     MatGetSize(*y,&My,&Ny);
    8484:     if (Mo == My && Nx == Ny) { reuse = MAT_REUSE_MATRIX; }
    8485:     else {
    8486:       if (w && *y == w) SETERRQ6(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Cannot reuse y and w, size mismatch: A %Dx%D, X %Dx%D, Y %Dx%D",M,N,Mx,Nx,My,Ny);
    8487:       MatDestroy(y);
    8488:     }
    8489:   }

    8491:   if (w && *y == w) { /* this is to minimize changes in PCMG */
    8492:     PetscBool flg;

    8494:     PetscObjectQuery((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject*)&w);
    8495:     if (w) {
    8496:       PetscInt My,Ny,Mw,Nw;

    8498:       PetscObjectTypeCompare((PetscObject)*y,((PetscObject)w)->type_name,&flg);
    8499:       MatGetSize(*y,&My,&Ny);
    8500:       MatGetSize(w,&Mw,&Nw);
    8501:       if (!flg || My != Mw || Ny != Nw) w = NULL;
    8502:     }
    8503:     if (!w) {
    8504:       MatDuplicate(*y,MAT_COPY_VALUES,&w);
    8505:       PetscObjectCompose((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject)w);
    8506:       PetscLogObjectParent((PetscObject)*y,(PetscObject)w);
    8507:       PetscObjectDereference((PetscObject)w);
    8508:     } else {
    8509:       MatCopy(*y,w,UNKNOWN_NONZERO_PATTERN);
    8510:     }
    8511:   }
    8512:   if (!trans) {
    8513:     MatMatMult(A,x,reuse,PETSC_DEFAULT,y);
    8514:   } else {
    8515:     MatTransposeMatMult(A,x,reuse,PETSC_DEFAULT,y);
    8516:   }
    8517:   if (w) {
    8518:     MatAXPY(*y,1.0,w,UNKNOWN_NONZERO_PATTERN);
    8519:   }
    8520:   return(0);
    8521: }

    8523: /*@
    8524:    MatMatInterpolate - Y = A*X or A'*X

    8526:    Neighbor-wise Collective on Mat

    8528:    Input Parameters:
    8529: +  mat   - the matrix
    8530: -  x - the input dense matrix

    8532:    Output Parameters:
    8533: .  y - the output dense matrix

    8536:    Level: intermediate

    8538:    Notes:
    8539:     This allows one to use either the restriction or interpolation (its transpose)
    8540:     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
    8541:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

    8543: .seealso: MatInterpolate(), MatRestrict(), MatMatRestrict()

    8545: @*/
    8546: PetscErrorCode MatMatInterpolate(Mat A,Mat x,Mat *y)
    8547: {

    8551:   MatMatInterpolateAdd(A,x,NULL,y);
    8552:   return(0);
    8553: }

    8555: /*@
    8556:    MatMatRestrict - Y = A*X or A'*X

    8558:    Neighbor-wise Collective on Mat

    8560:    Input Parameters:
    8561: +  mat   - the matrix
    8562: -  x - the input dense matrix

    8564:    Output Parameters:
    8565: .  y - the output dense matrix

    8568:    Level: intermediate

    8570:    Notes:
    8571:     This allows one to use either the restriction or interpolation (its transpose)
    8572:     matrix to do the restriction. y matrix can be reused if already created with the proper sizes,
    8573:     otherwise it will be recreated. y must be initialized to NULL if not supplied.

    8575: .seealso: MatRestrict(), MatInterpolate(), MatMatInterpolate()
    8576: @*/
    8577: PetscErrorCode MatMatRestrict(Mat A,Mat x,Mat *y)
    8578: {

    8582:   MatMatInterpolateAdd(A,x,NULL,y);
    8583:   return(0);
    8584: }

    8586: /*@
    8587:    MatGetNullSpace - retrieves the null space of a matrix.

    8589:    Logically Collective on Mat

    8591:    Input Parameters:
    8592: +  mat - the matrix
    8593: -  nullsp - the null space object

    8595:    Level: developer

    8597: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
    8598: @*/
    8599: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
    8600: {
    8604:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
    8605:   return(0);
    8606: }

    8608: /*@
    8609:    MatSetNullSpace - attaches a null space to a matrix.

    8611:    Logically Collective on Mat

    8613:    Input Parameters:
    8614: +  mat - the matrix
    8615: -  nullsp - the null space object

    8617:    Level: advanced

    8619:    Notes:
    8620:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

    8622:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
    8623:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

    8625:       You can remove the null space by calling this routine with an nullsp of NULL

    8628:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
    8629:    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).
    8630:    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
    8631:    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
    8632:    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).

    8634:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

    8636:     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
    8637:     routine also automatically calls MatSetTransposeNullSpace().

    8639: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
    8640: @*/
    8641: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
    8642: {

    8648:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
    8649:   MatNullSpaceDestroy(&mat->nullsp);
    8650:   mat->nullsp = nullsp;
    8651:   if (mat->symmetric_set && mat->symmetric) {
    8652:     MatSetTransposeNullSpace(mat,nullsp);
    8653:   }
    8654:   return(0);
    8655: }

    8657: /*@
    8658:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

    8660:    Logically Collective on Mat

    8662:    Input Parameters:
    8663: +  mat - the matrix
    8664: -  nullsp - the null space object

    8666:    Level: developer

    8668: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
    8669: @*/
    8670: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
    8671: {
    8676:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
    8677:   return(0);
    8678: }

    8680: /*@
    8681:    MatSetTransposeNullSpace - attaches a null space to a matrix.

    8683:    Logically Collective on Mat

    8685:    Input Parameters:
    8686: +  mat - the matrix
    8687: -  nullsp - the null space object

    8689:    Level: advanced

    8691:    Notes:
    8692:       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.
    8693:       You must also call MatSetNullSpace()

    8696:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
    8697:    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).
    8698:    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
    8699:    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
    8700:    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).

    8702:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

    8704: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
    8705: @*/
    8706: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
    8707: {

    8713:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
    8714:   MatNullSpaceDestroy(&mat->transnullsp);
    8715:   mat->transnullsp = nullsp;
    8716:   return(0);
    8717: }

    8719: /*@
    8720:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
    8721:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

    8723:    Logically Collective on Mat

    8725:    Input Parameters:
    8726: +  mat - the matrix
    8727: -  nullsp - the null space object

    8729:    Level: advanced

    8731:    Notes:
    8732:       Overwrites any previous near null space that may have been attached

    8734:       You can remove the null space by calling this routine with an nullsp of NULL

    8736: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
    8737: @*/
    8738: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
    8739: {

    8746:   MatCheckPreallocated(mat,1);
    8747:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
    8748:   MatNullSpaceDestroy(&mat->nearnullsp);
    8749:   mat->nearnullsp = nullsp;
    8750:   return(0);
    8751: }

    8753: /*@
    8754:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

    8756:    Not Collective

    8758:    Input Parameter:
    8759: .  mat - the matrix

    8761:    Output Parameter:
    8762: .  nullsp - the null space object, NULL if not set

    8764:    Level: developer

    8766: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
    8767: @*/
    8768: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
    8769: {
    8774:   MatCheckPreallocated(mat,1);
    8775:   *nullsp = mat->nearnullsp;
    8776:   return(0);
    8777: }

    8779: /*@C
    8780:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

    8782:    Collective on Mat

    8784:    Input Parameters:
    8785: +  mat - the matrix
    8786: .  row - row/column permutation
    8787: .  fill - expected fill factor >= 1.0
    8788: -  level - level of fill, for ICC(k)

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

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

    8798:    Level: developer

    8801: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

    8806: @*/
    8807: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
    8808: {

    8816:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
    8817:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    8818:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    8819:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    8820:   MatCheckPreallocated(mat,1);
    8821:   (*mat->ops->iccfactor)(mat,row,info);
    8822:   PetscObjectStateIncrease((PetscObject)mat);
    8823:   return(0);
    8824: }

    8826: /*@
    8827:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
    8828:          ghosted ones.

    8830:    Not Collective

    8832:    Input Parameters:
    8833: +  mat - the matrix
    8834: -  diag = the diagonal values, including ghost ones

    8836:    Level: developer

    8838:    Notes:
    8839:     Works only for MPIAIJ and MPIBAIJ matrices

    8841: .seealso: MatDiagonalScale()
    8842: @*/
    8843: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
    8844: {
    8846:   PetscMPIInt    size;

    8853:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
    8854:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
    8855:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    8856:   if (size == 1) {
    8857:     PetscInt n,m;
    8858:     VecGetSize(diag,&n);
    8859:     MatGetSize(mat,NULL,&m);
    8860:     if (m == n) {
    8861:       MatDiagonalScale(mat,NULL,diag);
    8862:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
    8863:   } else {
    8864:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
    8865:   }
    8866:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
    8867:   PetscObjectStateIncrease((PetscObject)mat);
    8868:   return(0);
    8869: }

    8871: /*@
    8872:    MatGetInertia - Gets the inertia from a factored matrix

    8874:    Collective on Mat

    8876:    Input Parameter:
    8877: .  mat - the matrix

    8879:    Output Parameters:
    8880: +   nneg - number of negative eigenvalues
    8881: .   nzero - number of zero eigenvalues
    8882: -   npos - number of positive eigenvalues

    8884:    Level: advanced

    8886:    Notes:
    8887:     Matrix must have been factored by MatCholeskyFactor()

    8890: @*/
    8891: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
    8892: {

    8898:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    8899:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
    8900:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    8901:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
    8902:   return(0);
    8903: }

    8905: /* ----------------------------------------------------------------*/
    8906: /*@C
    8907:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

    8909:    Neighbor-wise Collective on Mats

    8911:    Input Parameters:
    8912: +  mat - the factored matrix
    8913: -  b - the right-hand-side vectors

    8915:    Output Parameter:
    8916: .  x - the result vectors

    8918:    Notes:
    8919:    The vectors b and x cannot be the same.  I.e., one cannot
    8920:    call MatSolves(A,x,x).

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

    8927:    Level: developer

    8929: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
    8930: @*/
    8931: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
    8932: {

    8938:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    8939:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    8940:   if (!mat->rmap->N && !mat->cmap->N) return(0);

    8942:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    8943:   MatCheckPreallocated(mat,1);
    8944:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
    8945:   (*mat->ops->solves)(mat,b,x);
    8946:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
    8947:   return(0);
    8948: }

    8950: /*@
    8951:    MatIsSymmetric - Test whether a matrix is symmetric

    8953:    Collective on Mat

    8955:    Input Parameter:
    8956: +  A - the matrix to test
    8957: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

    8959:    Output Parameters:
    8960: .  flg - the result

    8962:    Notes:
    8963:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

    8965:    Level: intermediate

    8967: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
    8968: @*/
    8969: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
    8970: {

    8977:   if (!A->symmetric_set) {
    8978:     if (!A->ops->issymmetric) {
    8979:       MatType mattype;
    8980:       MatGetType(A,&mattype);
    8981:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
    8982:     }
    8983:     (*A->ops->issymmetric)(A,tol,flg);
    8984:     if (!tol) {
    8985:       MatSetOption(A,MAT_SYMMETRIC,*flg);
    8986:     }
    8987:   } else if (A->symmetric) {
    8988:     *flg = PETSC_TRUE;
    8989:   } else if (!tol) {
    8990:     *flg = PETSC_FALSE;
    8991:   } else {
    8992:     if (!A->ops->issymmetric) {
    8993:       MatType mattype;
    8994:       MatGetType(A,&mattype);
    8995:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
    8996:     }
    8997:     (*A->ops->issymmetric)(A,tol,flg);
    8998:   }
    8999:   return(0);
    9000: }

    9002: /*@
    9003:    MatIsHermitian - Test whether a matrix is Hermitian

    9005:    Collective on Mat

    9007:    Input Parameter:
    9008: +  A - the matrix to test
    9009: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

    9011:    Output Parameters:
    9012: .  flg - the result

    9014:    Level: intermediate

    9016: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
    9017:           MatIsSymmetricKnown(), MatIsSymmetric()
    9018: @*/
    9019: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
    9020: {

    9027:   if (!A->hermitian_set) {
    9028:     if (!A->ops->ishermitian) {
    9029:       MatType mattype;
    9030:       MatGetType(A,&mattype);
    9031:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
    9032:     }
    9033:     (*A->ops->ishermitian)(A,tol,flg);
    9034:     if (!tol) {
    9035:       MatSetOption(A,MAT_HERMITIAN,*flg);
    9036:     }
    9037:   } else if (A->hermitian) {
    9038:     *flg = PETSC_TRUE;
    9039:   } else if (!tol) {
    9040:     *flg = PETSC_FALSE;
    9041:   } else {
    9042:     if (!A->ops->ishermitian) {
    9043:       MatType mattype;
    9044:       MatGetType(A,&mattype);
    9045:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
    9046:     }
    9047:     (*A->ops->ishermitian)(A,tol,flg);
    9048:   }
    9049:   return(0);
    9050: }

    9052: /*@
    9053:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

    9055:    Not Collective

    9057:    Input Parameter:
    9058: .  A - the matrix to check

    9060:    Output Parameters:
    9061: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
    9062: -  flg - the result

    9064:    Level: advanced

    9066:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
    9067:          if you want it explicitly checked

    9069: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
    9070: @*/
    9071: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
    9072: {
    9077:   if (A->symmetric_set) {
    9078:     *set = PETSC_TRUE;
    9079:     *flg = A->symmetric;
    9080:   } else {
    9081:     *set = PETSC_FALSE;
    9082:   }
    9083:   return(0);
    9084: }

    9086: /*@
    9087:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

    9089:    Not Collective

    9091:    Input Parameter:
    9092: .  A - the matrix to check

    9094:    Output Parameters:
    9095: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
    9096: -  flg - the result

    9098:    Level: advanced

    9100:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
    9101:          if you want it explicitly checked

    9103: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
    9104: @*/
    9105: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
    9106: {
    9111:   if (A->hermitian_set) {
    9112:     *set = PETSC_TRUE;
    9113:     *flg = A->hermitian;
    9114:   } else {
    9115:     *set = PETSC_FALSE;
    9116:   }
    9117:   return(0);
    9118: }

    9120: /*@
    9121:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

    9123:    Collective on Mat

    9125:    Input Parameter:
    9126: .  A - the matrix to test

    9128:    Output Parameters:
    9129: .  flg - the result

    9131:    Level: intermediate

    9133: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
    9134: @*/
    9135: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
    9136: {

    9142:   if (!A->structurally_symmetric_set) {
    9143:     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);
    9144:     (*A->ops->isstructurallysymmetric)(A,flg);
    9145:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
    9146:   } else *flg = A->structurally_symmetric;
    9147:   return(0);
    9148: }

    9150: /*@
    9151:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
    9152:        to be communicated to other processors during the MatAssemblyBegin/End() process

    9154:     Not collective

    9156:    Input Parameter:
    9157: .   vec - the vector

    9159:    Output Parameters:
    9160: +   nstash   - the size of the stash
    9161: .   reallocs - the number of additional mallocs incurred.
    9162: .   bnstash   - the size of the block stash
    9163: -   breallocs - the number of additional mallocs incurred.in the block stash

    9165:    Level: advanced

    9167: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

    9169: @*/
    9170: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
    9171: {

    9175:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
    9176:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
    9177:   return(0);
    9178: }

    9180: /*@C
    9181:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
    9182:      parallel layout

    9184:    Collective on Mat

    9186:    Input Parameter:
    9187: .  mat - the matrix

    9189:    Output Parameter:
    9190: +   right - (optional) vector that the matrix can be multiplied against
    9191: -   left - (optional) vector that the matrix vector product can be stored in

    9193:    Notes:
    9194:     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().

    9196:   Notes:
    9197:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

    9199:   Level: advanced

    9201: .seealso: MatCreate(), VecDestroy()
    9202: @*/
    9203: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
    9204: {

    9210:   if (mat->ops->getvecs) {
    9211:     (*mat->ops->getvecs)(mat,right,left);
    9212:   } else {
    9213:     PetscInt rbs,cbs;
    9214:     MatGetBlockSizes(mat,&rbs,&cbs);
    9215:     if (right) {
    9216:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
    9217:       VecCreate(PetscObjectComm((PetscObject)mat),right);
    9218:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
    9219:       VecSetBlockSize(*right,cbs);
    9220:       VecSetType(*right,mat->defaultvectype);
    9221:       PetscLayoutReference(mat->cmap,&(*right)->map);
    9222:     }
    9223:     if (left) {
    9224:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
    9225:       VecCreate(PetscObjectComm((PetscObject)mat),left);
    9226:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
    9227:       VecSetBlockSize(*left,rbs);
    9228:       VecSetType(*left,mat->defaultvectype);
    9229:       PetscLayoutReference(mat->rmap,&(*left)->map);
    9230:     }
    9231:   }
    9232:   return(0);
    9233: }

    9235: /*@C
    9236:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
    9237:      with default values.

    9239:    Not Collective

    9241:    Input Parameters:
    9242: .    info - the MatFactorInfo data structure

    9245:    Notes:
    9246:     The solvers are generally used through the KSP and PC objects, for example
    9247:           PCLU, PCILU, PCCHOLESKY, PCICC

    9249:    Level: developer

    9251: .seealso: MatFactorInfo

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

    9256: @*/

    9258: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
    9259: {

    9263:   PetscMemzero(info,sizeof(MatFactorInfo));
    9264:   return(0);
    9265: }

    9267: /*@
    9268:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

    9270:    Collective on Mat

    9272:    Input Parameters:
    9273: +  mat - the factored matrix
    9274: -  is - the index set defining the Schur indices (0-based)

    9276:    Notes:
    9277:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

    9279:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

    9281:    Level: developer

    9283: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
    9284:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

    9286: @*/
    9287: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
    9288: {
    9289:   PetscErrorCode ierr,(*f)(Mat,IS);

    9297:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
    9298:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
    9299:   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");
    9300:   MatDestroy(&mat->schur);
    9301:   (*f)(mat,is);
    9302:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
    9303:   return(0);
    9304: }

    9306: /*@
    9307:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

    9309:    Logically Collective on Mat

    9311:    Input Parameters:
    9312: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
    9313: .  S - location where to return the Schur complement, can be NULL
    9314: -  status - the status of the Schur complement matrix, can be NULL

    9316:    Notes:
    9317:    You must call MatFactorSetSchurIS() before calling this routine.

    9319:    The routine provides a copy of the Schur matrix stored within the solver data structures.
    9320:    The caller must destroy the object when it is no longer needed.
    9321:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

    9323:    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)

    9325:    Developer Notes:
    9326:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
    9327:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

    9329:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

    9331:    Level: advanced

    9333:    References:

    9335: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
    9336: @*/
    9337: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
    9338: {

    9345:   if (S) {
    9346:     PetscErrorCode (*f)(Mat,Mat*);

    9348:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
    9349:     if (f) {
    9350:       (*f)(F,S);
    9351:     } else {
    9352:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
    9353:     }
    9354:   }
    9355:   if (status) *status = F->schur_status;
    9356:   return(0);
    9357: }

    9359: /*@
    9360:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

    9362:    Logically Collective on Mat

    9364:    Input Parameters:
    9365: +  F - the factored matrix obtained by calling MatGetFactor()
    9366: .  *S - location where to return the Schur complement, can be NULL
    9367: -  status - the status of the Schur complement matrix, can be NULL

    9369:    Notes:
    9370:    You must call MatFactorSetSchurIS() before calling this routine.

    9372:    Schur complement mode is currently implemented for sequential matrices.
    9373:    The routine returns a the Schur Complement stored within the data strutures of the solver.
    9374:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
    9375:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

    9377:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

    9379:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

    9381:    Level: advanced

    9383:    References:

    9385: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
    9386: @*/
    9387: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
    9388: {
    9393:   if (S) *S = F->schur;
    9394:   if (status) *status = F->schur_status;
    9395:   return(0);
    9396: }

    9398: /*@
    9399:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

    9401:    Logically Collective on Mat

    9403:    Input Parameters:
    9404: +  F - the factored matrix obtained by calling MatGetFactor()
    9405: .  *S - location where the Schur complement is stored
    9406: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

    9408:    Notes:

    9410:    Level: advanced

    9412:    References:

    9414: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
    9415: @*/
    9416: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
    9417: {

    9422:   if (S) {
    9424:     *S = NULL;
    9425:   }
    9426:   F->schur_status = status;
    9427:   MatFactorUpdateSchurStatus_Private(F);
    9428:   return(0);
    9429: }

    9431: /*@
    9432:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

    9434:    Logically Collective on Mat

    9436:    Input Parameters:
    9437: +  F - the factored matrix obtained by calling MatGetFactor()
    9438: .  rhs - location where the right hand side of the Schur complement system is stored
    9439: -  sol - location where the solution of the Schur complement system has to be returned

    9441:    Notes:
    9442:    The sizes of the vectors should match the size of the Schur complement

    9444:    Must be called after MatFactorSetSchurIS()

    9446:    Level: advanced

    9448:    References:

    9450: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
    9451: @*/
    9452: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
    9453: {

    9465:   MatFactorFactorizeSchurComplement(F);
    9466:   switch (F->schur_status) {
    9467:   case MAT_FACTOR_SCHUR_FACTORED:
    9468:     MatSolveTranspose(F->schur,rhs,sol);
    9469:     break;
    9470:   case MAT_FACTOR_SCHUR_INVERTED:
    9471:     MatMultTranspose(F->schur,rhs,sol);
    9472:     break;
    9473:   default:
    9474:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
    9475:   }
    9476:   return(0);
    9477: }

    9479: /*@
    9480:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

    9482:    Logically Collective on Mat

    9484:    Input Parameters:
    9485: +  F - the factored matrix obtained by calling MatGetFactor()
    9486: .  rhs - location where the right hand side of the Schur complement system is stored
    9487: -  sol - location where the solution of the Schur complement system has to be returned

    9489:    Notes:
    9490:    The sizes of the vectors should match the size of the Schur complement

    9492:    Must be called after MatFactorSetSchurIS()

    9494:    Level: advanced

    9496:    References:

    9498: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
    9499: @*/
    9500: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
    9501: {

    9513:   MatFactorFactorizeSchurComplement(F);
    9514:   switch (F->schur_status) {
    9515:   case MAT_FACTOR_SCHUR_FACTORED:
    9516:     MatSolve(F->schur,rhs,sol);
    9517:     break;
    9518:   case MAT_FACTOR_SCHUR_INVERTED:
    9519:     MatMult(F->schur,rhs,sol);
    9520:     break;
    9521:   default:
    9522:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
    9523:   }
    9524:   return(0);
    9525: }

    9527: /*@
    9528:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

    9530:    Logically Collective on Mat

    9532:    Input Parameters:
    9533: .  F - the factored matrix obtained by calling MatGetFactor()

    9535:    Notes:
    9536:     Must be called after MatFactorSetSchurIS().

    9538:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

    9540:    Level: advanced

    9542:    References:

    9544: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
    9545: @*/
    9546: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
    9547: {

    9553:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
    9554:   MatFactorFactorizeSchurComplement(F);
    9555:   MatFactorInvertSchurComplement_Private(F);
    9556:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
    9557:   return(0);
    9558: }

    9560: /*@
    9561:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

    9563:    Logically Collective on Mat

    9565:    Input Parameters:
    9566: .  F - the factored matrix obtained by calling MatGetFactor()

    9568:    Notes:
    9569:     Must be called after MatFactorSetSchurIS().

    9571:    Level: advanced

    9573:    References:

    9575: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
    9576: @*/
    9577: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
    9578: {

    9584:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
    9585:   MatFactorFactorizeSchurComplement_Private(F);
    9586:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
    9587:   return(0);
    9588: }

    9590: /*@
    9591:    MatPtAP - Creates the matrix product C = P^T * A * P

    9593:    Neighbor-wise Collective on Mat

    9595:    Input Parameters:
    9596: +  A - the matrix
    9597: .  P - the projection matrix
    9598: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9599: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
    9600:           if the result is a dense matrix this is irrelevent

    9602:    Output Parameters:
    9603: .  C - the product matrix

    9605:    Notes:
    9606:    C will be created and must be destroyed by the user with MatDestroy().

    9608:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

    9610:    Level: intermediate

    9612: .seealso: MatMatMult(), MatRARt()
    9613: @*/
    9614: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
    9615: {

    9619:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
    9620:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9622:   if (scall == MAT_INITIAL_MATRIX) {
    9623:     MatProductCreate(A,P,NULL,C);
    9624:     MatProductSetType(*C,MATPRODUCT_PtAP);
    9625:     MatProductSetAlgorithm(*C,"default");
    9626:     MatProductSetFill(*C,fill);

    9628:     (*C)->product->api_user = PETSC_TRUE;
    9629:     MatProductSetFromOptions(*C);
    9630:     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and P %s",MatProductTypes[MATPRODUCT_PtAP],((PetscObject)A)->type_name,((PetscObject)P)->type_name);
    9631:     MatProductSymbolic(*C);
    9632:   } else { /* scall == MAT_REUSE_MATRIX */
    9633:     MatProductReplaceMats(A,P,NULL,*C);
    9634:   }

    9636:   MatProductNumeric(*C);
    9637:   if (A->symmetric_set && A->symmetric) {
    9638:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
    9639:   }
    9640:   return(0);
    9641: }

    9643: /*@
    9644:    MatRARt - Creates the matrix product C = R * A * R^T

    9646:    Neighbor-wise Collective on Mat

    9648:    Input Parameters:
    9649: +  A - the matrix
    9650: .  R - the projection matrix
    9651: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9652: -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
    9653:           if the result is a dense matrix this is irrelevent

    9655:    Output Parameters:
    9656: .  C - the product matrix

    9658:    Notes:
    9659:    C will be created and must be destroyed by the user with MatDestroy().

    9661:    This routine is currently only implemented for pairs of AIJ matrices and classes
    9662:    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
    9663:    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
    9664:    We recommend using MatPtAP().

    9666:    Level: intermediate

    9668: .seealso: MatMatMult(), MatPtAP()
    9669: @*/
    9670: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
    9671: {

    9675:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
    9676:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9678:   if (scall == MAT_INITIAL_MATRIX) {
    9679:     MatProductCreate(A,R,NULL,C);
    9680:     MatProductSetType(*C,MATPRODUCT_RARt);
    9681:     MatProductSetAlgorithm(*C,"default");
    9682:     MatProductSetFill(*C,fill);

    9684:     (*C)->product->api_user = PETSC_TRUE;
    9685:     MatProductSetFromOptions(*C);
    9686:     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and R %s",MatProductTypes[MATPRODUCT_RARt],((PetscObject)A)->type_name,((PetscObject)R)->type_name);
    9687:     MatProductSymbolic(*C);
    9688:   } else { /* scall == MAT_REUSE_MATRIX */
    9689:     MatProductReplaceMats(A,R,NULL,*C);
    9690:   }

    9692:   MatProductNumeric(*C);
    9693:   if (A->symmetric_set && A->symmetric) {
    9694:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
    9695:   }
    9696:   return(0);
    9697: }

    9700: static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
    9701: {

    9705:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9707:   if (scall == MAT_INITIAL_MATRIX) {
    9708:     PetscInfo1(A,"Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n",MatProductTypes[ptype]);
    9709:     MatProductCreate(A,B,NULL,C);
    9710:     MatProductSetType(*C,ptype);
    9711:     MatProductSetAlgorithm(*C,MATPRODUCTALGORITHM_DEFAULT);
    9712:     MatProductSetFill(*C,fill);

    9714:     (*C)->product->api_user = PETSC_TRUE;
    9715:     MatProductSetFromOptions(*C);
    9716:     MatProductSymbolic(*C);
    9717:   } else { /* scall == MAT_REUSE_MATRIX */
    9718:     Mat_Product *product = (*C)->product;

    9720:     PetscInfo2(A,"Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n",product ? "with" : "without",MatProductTypes[ptype]);
    9721:     if (!product) {
    9722:       /* user provide the dense matrix *C without calling MatProductCreate() */
    9723:       PetscBool isdense;

    9725:       PetscObjectBaseTypeCompareAny((PetscObject)(*C),&isdense,MATSEQDENSE,MATMPIDENSE,"");
    9726:       if (isdense) {
    9727:         /* user wants to reuse an assembled dense matrix */
    9728:         /* Create product -- see MatCreateProduct() */
    9729:         MatProductCreate_Private(A,B,NULL,*C);
    9730:         product = (*C)->product;
    9731:         product->fill     = fill;
    9732:         product->api_user = PETSC_TRUE;
    9733:         product->clear    = PETSC_TRUE;

    9735:         MatProductSetType(*C,ptype);
    9736:         MatProductSetFromOptions(*C);
    9737:         if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for %s and %s",MatProductTypes[ptype],((PetscObject)A)->type_name,((PetscObject)B)->type_name);
    9738:         MatProductSymbolic(*C);
    9739:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
    9740:     } else { /* user may change input matrices A or B when REUSE */
    9741:       MatProductReplaceMats(A,B,NULL,*C);
    9742:     }
    9743:   }
    9744:   MatProductNumeric(*C);
    9745:   return(0);
    9746: }

    9748: /*@
    9749:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

    9751:    Neighbor-wise Collective on Mat

    9753:    Input Parameters:
    9754: +  A - the left matrix
    9755: .  B - the right matrix
    9756: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9757: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
    9758:           if the result is a dense matrix this is irrelevent

    9760:    Output Parameters:
    9761: .  C - the product matrix

    9763:    Notes:
    9764:    Unless scall is MAT_REUSE_MATRIX C will be created.

    9766:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call and C was obtained from a previous
    9767:    call to this function with MAT_INITIAL_MATRIX.

    9769:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.

    9771:    If you have many matrices with the same non-zero structure to multiply, you should use MatProductCreate()/MatProductSymbolic(C)/ReplaceMats(), and call MatProductNumeric() repeatedly.

    9773:    In the special case where matrix B (and hence C) are dense you can create the correctly sized matrix C yourself and then call this routine with MAT_REUSE_MATRIX, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.

    9775:    Level: intermediate

    9777: .seealso: MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
    9778: @*/
    9779: PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
    9780: {

    9784:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_AB,C);
    9785:   return(0);
    9786: }

    9788: /*@
    9789:    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.

    9791:    Neighbor-wise Collective on Mat

    9793:    Input Parameters:
    9794: +  A - the left matrix
    9795: .  B - the right matrix
    9796: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9797: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

    9799:    Output Parameters:
    9800: .  C - the product matrix

    9802:    Notes:
    9803:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

    9805:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

    9807:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
    9808:    actually needed.

    9810:    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
    9811:    and for pairs of MPIDense matrices.

    9813:    Options Database Keys:
    9814: .  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
    9815:                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
    9816:                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.

    9818:    Level: intermediate

    9820: .seealso: MatMatMult(), MatTransposeMatMult() MatPtAP()
    9821: @*/
    9822: PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
    9823: {

    9827:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_ABt,C);
    9828:   return(0);
    9829: }

    9831: /*@
    9832:    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.

    9834:    Neighbor-wise Collective on Mat

    9836:    Input Parameters:
    9837: +  A - the left matrix
    9838: .  B - the right matrix
    9839: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9840: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

    9842:    Output Parameters:
    9843: .  C - the product matrix

    9845:    Notes:
    9846:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

    9848:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call.

    9850:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
    9851:    actually needed.

    9853:    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
    9854:    which inherit from SeqAIJ.  C will be of same type as the input matrices.

    9856:    Level: intermediate

    9858: .seealso: MatMatMult(), MatMatTransposeMult(), MatPtAP()
    9859: @*/
    9860: PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
    9861: {

    9865:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_AtB,C);
    9866:   return(0);
    9867: }

    9869: /*@
    9870:    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.

    9872:    Neighbor-wise Collective on Mat

    9874:    Input Parameters:
    9875: +  A - the left matrix
    9876: .  B - the middle matrix
    9877: .  C - the right matrix
    9878: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9879: -  fill - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use PETSC_DEFAULT if you do not have a good estimate
    9880:           if the result is a dense matrix this is irrelevent

    9882:    Output Parameters:
    9883: .  D - the product matrix

    9885:    Notes:
    9886:    Unless scall is MAT_REUSE_MATRIX D will be created.

    9888:    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call

    9890:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
    9891:    actually needed.

    9893:    If you have many matrices with the same non-zero structure to multiply, you
    9894:    should use MAT_REUSE_MATRIX in all calls but the first or

    9896:    Level: intermediate

    9898: .seealso: MatMatMult, MatPtAP()
    9899: @*/
    9900: PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
    9901: {

    9905:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D,6);
    9906:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9908:   if (scall == MAT_INITIAL_MATRIX) {
    9909:     MatProductCreate(A,B,C,D);
    9910:     MatProductSetType(*D,MATPRODUCT_ABC);
    9911:     MatProductSetAlgorithm(*D,"default");
    9912:     MatProductSetFill(*D,fill);

    9914:     (*D)->product->api_user = PETSC_TRUE;
    9915:     MatProductSetFromOptions(*D);
    9916:     if (!(*D)->ops->productsymbolic) SETERRQ4(PetscObjectComm((PetscObject)(*D)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s, B %s and C %s",MatProductTypes[MATPRODUCT_ABC],((PetscObject)A)->type_name,((PetscObject)B)->type_name,((PetscObject)C)->type_name);
    9917:     MatProductSymbolic(*D);
    9918:   } else { /* user may change input matrices when REUSE */
    9919:     MatProductReplaceMats(A,B,C,*D);
    9920:   }
    9921:   MatProductNumeric(*D);
    9922:   return(0);
    9923: }

    9925: /*@
    9926:    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

    9928:    Collective on Mat

    9930:    Input Parameters:
    9931: +  mat - the matrix
    9932: .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
    9933: .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
    9934: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    9936:    Output Parameter:
    9937: .  matredundant - redundant matrix

    9939:    Notes:
    9940:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
    9941:    original matrix has not changed from that last call to MatCreateRedundantMatrix().

    9943:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
    9944:    calling it.

    9946:    Level: advanced

    9949: .seealso: MatDestroy()
    9950: @*/
    9951: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
    9952: {
    9954:   MPI_Comm       comm;
    9955:   PetscMPIInt    size;
    9956:   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
    9957:   Mat_Redundant  *redund=NULL;
    9958:   PetscSubcomm   psubcomm=NULL;
    9959:   MPI_Comm       subcomm_in=subcomm;
    9960:   Mat            *matseq;
    9961:   IS             isrow,iscol;
    9962:   PetscBool      newsubcomm=PETSC_FALSE;

    9966:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
    9969:   }

    9971:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    9972:   if (size == 1 || nsubcomm == 1) {
    9973:     if (reuse == MAT_INITIAL_MATRIX) {
    9974:       MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
    9975:     } else {
    9976:       if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
    9977:       MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
    9978:     }
    9979:     return(0);
    9980:   }

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

    9986:   PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
    9987:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
    9988:     /* create psubcomm, then get subcomm */
    9989:     PetscObjectGetComm((PetscObject)mat,&comm);
    9990:     MPI_Comm_size(comm,&size);
    9991:     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);

    9993:     PetscSubcommCreate(comm,&psubcomm);
    9994:     PetscSubcommSetNumber(psubcomm,nsubcomm);
    9995:     PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
    9996:     PetscSubcommSetFromOptions(psubcomm);
    9997:     PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
    9998:     newsubcomm = PETSC_TRUE;
    9999:     PetscSubcommDestroy(&psubcomm);
    10000:   }

    10002:   /* get isrow, iscol and a local sequential matrix matseq[0] */
    10003:   if (reuse == MAT_INITIAL_MATRIX) {
    10004:     mloc_sub = PETSC_DECIDE;
    10005:     nloc_sub = PETSC_DECIDE;
    10006:     if (bs < 1) {
    10007:       PetscSplitOwnership(subcomm,&mloc_sub,&M);
    10008:       PetscSplitOwnership(subcomm,&nloc_sub,&N);
    10009:     } else {
    10010:       PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
    10011:       PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);
    10012:     }
    10013:     MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
    10014:     rstart = rend - mloc_sub;
    10015:     ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
    10016:     ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
    10017:   } else { /* reuse == MAT_REUSE_MATRIX */
    10018:     if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
    10019:     /* retrieve subcomm */
    10020:     PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
    10021:     redund = (*matredundant)->redundant;
    10022:     isrow  = redund->isrow;
    10023:     iscol  = redund->iscol;
    10024:     matseq = redund->matseq;
    10025:   }
    10026:   MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);

    10028:   /* get matredundant over subcomm */
    10029:   if (reuse == MAT_INITIAL_MATRIX) {
    10030:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);

    10032:     /* create a supporting struct and attach it to C for reuse */
    10033:     PetscNewLog(*matredundant,&redund);
    10034:     (*matredundant)->redundant = redund;
    10035:     redund->isrow              = isrow;
    10036:     redund->iscol              = iscol;
    10037:     redund->matseq             = matseq;
    10038:     if (newsubcomm) {
    10039:       redund->subcomm          = subcomm;
    10040:     } else {
    10041:       redund->subcomm          = MPI_COMM_NULL;
    10042:     }
    10043:   } else {
    10044:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
    10045:   }
    10046:   PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
    10047:   return(0);
    10048: }

    10050: /*@C
    10051:    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
    10052:    a given 'mat' object. Each submatrix can span multiple procs.

    10054:    Collective on Mat

    10056:    Input Parameters:
    10057: +  mat - the matrix
    10058: .  subcomm - the subcommunicator obtained by com_split(comm)
    10059: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    10061:    Output Parameter:
    10062: .  subMat - 'parallel submatrices each spans a given subcomm

    10064:   Notes:
    10065:   The submatrix partition across processors is dictated by 'subComm' a
    10066:   communicator obtained by com_split(comm). The comm_split
    10067:   is not restriced to be grouped with consecutive original ranks.

    10069:   Due the comm_split() usage, the parallel layout of the submatrices
    10070:   map directly to the layout of the original matrix [wrt the local
    10071:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
    10072:   into the 'DiagonalMat' of the subMat, hence it is used directly from
    10073:   the subMat. However the offDiagMat looses some columns - and this is
    10074:   reconstructed with MatSetValues()

    10076:   Level: advanced

    10079: .seealso: MatCreateSubMatrices()
    10080: @*/
    10081: PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
    10082: {
    10084:   PetscMPIInt    commsize,subCommSize;

    10087:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
    10088:   MPI_Comm_size(subComm,&subCommSize);
    10089:   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);

    10091:   if (scall == MAT_REUSE_MATRIX && *subMat == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
    10092:   PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
    10093:   (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
    10094:   PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
    10095:   return(0);
    10096: }

    10098: /*@
    10099:    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

    10101:    Not Collective

    10103:    Input Arguments:
    10104: +  mat - matrix to extract local submatrix from
    10105: .  isrow - local row indices for submatrix
    10106: -  iscol - local column indices for submatrix

    10108:    Output Arguments:
    10109: .  submat - the submatrix

    10111:    Level: intermediate

    10113:    Notes:
    10114:    The submat should be returned with MatRestoreLocalSubMatrix().

    10116:    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
    10117:    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.

    10119:    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
    10120:    MatSetValuesBlockedLocal() will also be implemented.

    10122:    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
    10123:    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.

    10125: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
    10126: @*/
    10127: PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
    10128: {

    10137:   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");

    10139:   if (mat->ops->getlocalsubmatrix) {
    10140:     (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
    10141:   } else {
    10142:     MatCreateLocalRef(mat,isrow,iscol,submat);
    10143:   }
    10144:   return(0);
    10145: }

    10147: /*@
    10148:    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering

    10150:    Not Collective

    10152:    Input Arguments:
    10153:    mat - matrix to extract local submatrix from
    10154:    isrow - local row indices for submatrix
    10155:    iscol - local column indices for submatrix
    10156:    submat - the submatrix

    10158:    Level: intermediate

    10160: .seealso: MatGetLocalSubMatrix()
    10161: @*/
    10162: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
    10163: {

    10172:   if (*submat) {
    10174:   }

    10176:   if (mat->ops->restorelocalsubmatrix) {
    10177:     (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
    10178:   } else {
    10179:     MatDestroy(submat);
    10180:   }
    10181:   *submat = NULL;
    10182:   return(0);
    10183: }

    10185: /* --------------------------------------------------------*/
    10186: /*@
    10187:    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

    10189:    Collective on Mat

    10191:    Input Parameter:
    10192: .  mat - the matrix

    10194:    Output Parameter:
    10195: .  is - if any rows have zero diagonals this contains the list of them

    10197:    Level: developer

    10199: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    10200: @*/
    10201: PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
    10202: {

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

    10211:   if (!mat->ops->findzerodiagonals) {
    10212:     Vec                diag;
    10213:     const PetscScalar *a;
    10214:     PetscInt          *rows;
    10215:     PetscInt           rStart, rEnd, r, nrow = 0;

    10217:     MatCreateVecs(mat, &diag, NULL);
    10218:     MatGetDiagonal(mat, diag);
    10219:     MatGetOwnershipRange(mat, &rStart, &rEnd);
    10220:     VecGetArrayRead(diag, &a);
    10221:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
    10222:     PetscMalloc1(nrow, &rows);
    10223:     nrow = 0;
    10224:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
    10225:     VecRestoreArrayRead(diag, &a);
    10226:     VecDestroy(&diag);
    10227:     ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);
    10228:   } else {
    10229:     (*mat->ops->findzerodiagonals)(mat, is);
    10230:   }
    10231:   return(0);
    10232: }

    10234: /*@
    10235:    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

    10237:    Collective on Mat

    10239:    Input Parameter:
    10240: .  mat - the matrix

    10242:    Output Parameter:
    10243: .  is - contains the list of rows with off block diagonal entries

    10245:    Level: developer

    10247: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    10248: @*/
    10249: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
    10250: {

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

    10259:   if (!mat->ops->findoffblockdiagonalentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a find off block diagonal entries defined",((PetscObject)mat)->type_name);
    10260:   (*mat->ops->findoffblockdiagonalentries)(mat,is);
    10261:   return(0);
    10262: }

    10264: /*@C
    10265:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

    10267:   Collective on Mat

    10269:   Input Parameters:
    10270: . mat - the matrix

    10272:   Output Parameters:
    10273: . values - the block inverses in column major order (FORTRAN-like)

    10275:    Note:
    10276:    This routine is not available from Fortran.

    10278:   Level: advanced

    10280: .seealso: MatInvertBockDiagonalMat
    10281: @*/
    10282: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
    10283: {

    10288:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    10289:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    10290:   if (!mat->ops->invertblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type %s",((PetscObject)mat)->type_name);
    10291:   (*mat->ops->invertblockdiagonal)(mat,values);
    10292:   return(0);
    10293: }

    10295: /*@C
    10296:   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.

    10298:   Collective on Mat

    10300:   Input Parameters:
    10301: + mat - the matrix
    10302: . nblocks - the number of blocks
    10303: - bsizes - the size of each block

    10305:   Output Parameters:
    10306: . values - the block inverses in column major order (FORTRAN-like)

    10308:    Note:
    10309:    This routine is not available from Fortran.

    10311:   Level: advanced

    10313: .seealso: MatInvertBockDiagonal()
    10314: @*/
    10315: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
    10316: {

    10321:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    10322:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    10323:   if (!mat->ops->invertvariableblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type",((PetscObject)mat)->type_name);
    10324:   (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);
    10325:   return(0);
    10326: }

    10328: /*@
    10329:   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A

    10331:   Collective on Mat

    10333:   Input Parameters:
    10334: . A - the matrix

    10336:   Output Parameters:
    10337: . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.

    10339:   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C

    10341:   Level: advanced

    10343: .seealso: MatInvertBockDiagonal()
    10344: @*/
    10345: PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
    10346: {
    10347:   PetscErrorCode     ierr;
    10348:   const PetscScalar *vals;
    10349:   PetscInt          *dnnz;
    10350:   PetscInt           M,N,m,n,rstart,rend,bs,i,j;

    10353:   MatInvertBlockDiagonal(A,&vals);
    10354:   MatGetBlockSize(A,&bs);
    10355:   MatGetSize(A,&M,&N);
    10356:   MatGetLocalSize(A,&m,&n);
    10357:   MatSetSizes(C,m,n,M,N);
    10358:   MatSetBlockSize(C,bs);
    10359:   PetscMalloc1(m/bs,&dnnz);
    10360:   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
    10361:   MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);
    10362:   PetscFree(dnnz);
    10363:   MatGetOwnershipRange(C,&rstart,&rend);
    10364:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);
    10365:   for (i = rstart/bs; i < rend/bs; i++) {
    10366:     MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);
    10367:   }
    10368:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
    10369:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
    10370:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);
    10371:   return(0);
    10372: }

    10374: /*@C
    10375:     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
    10376:     via MatTransposeColoringCreate().

    10378:     Collective on MatTransposeColoring

    10380:     Input Parameter:
    10381: .   c - coloring context

    10383:     Level: intermediate

    10385: .seealso: MatTransposeColoringCreate()
    10386: @*/
    10387: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
    10388: {
    10389:   PetscErrorCode       ierr;
    10390:   MatTransposeColoring matcolor=*c;

    10393:   if (!matcolor) return(0);
    10394:   if (--((PetscObject)matcolor)->refct > 0) {matcolor = NULL; return(0);}

    10396:   PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
    10397:   PetscFree(matcolor->rows);
    10398:   PetscFree(matcolor->den2sp);
    10399:   PetscFree(matcolor->colorforcol);
    10400:   PetscFree(matcolor->columns);
    10401:   if (matcolor->brows>0) {
    10402:     PetscFree(matcolor->lstart);
    10403:   }
    10404:   PetscHeaderDestroy(c);
    10405:   return(0);
    10406: }

    10408: /*@C
    10409:     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
    10410:     a MatTransposeColoring context has been created, computes a dense B^T by Apply
    10411:     MatTransposeColoring to sparse B.

    10413:     Collective on MatTransposeColoring

    10415:     Input Parameters:
    10416: +   B - sparse matrix B
    10417: .   Btdense - symbolic dense matrix B^T
    10418: -   coloring - coloring context created with MatTransposeColoringCreate()

    10420:     Output Parameter:
    10421: .   Btdense - dense matrix B^T

    10423:     Level: advanced

    10425:      Notes:
    10426:     These are used internally for some implementations of MatRARt()

    10428: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()

    10430: @*/
    10431: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
    10432: {

    10440:   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
    10441:   (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
    10442:   return(0);
    10443: }

    10445: /*@C
    10446:     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
    10447:     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
    10448:     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
    10449:     Csp from Cden.

    10451:     Collective on MatTransposeColoring

    10453:     Input Parameters:
    10454: +   coloring - coloring context created with MatTransposeColoringCreate()
    10455: -   Cden - matrix product of a sparse matrix and a dense matrix Btdense

    10457:     Output Parameter:
    10458: .   Csp - sparse matrix

    10460:     Level: advanced

    10462:      Notes:
    10463:     These are used internally for some implementations of MatRARt()

    10465: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()

    10467: @*/
    10468: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
    10469: {

    10477:   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
    10478:   (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
    10479:   MatAssemblyBegin(Csp,MAT_FINAL_ASSEMBLY);
    10480:   MatAssemblyEnd(Csp,MAT_FINAL_ASSEMBLY);
    10481:   return(0);
    10482: }

    10484: /*@C
    10485:    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.

    10487:    Collective on Mat

    10489:    Input Parameters:
    10490: +  mat - the matrix product C
    10491: -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()

    10493:     Output Parameter:
    10494: .   color - the new coloring context

    10496:     Level: intermediate

    10498: .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
    10499:            MatTransColoringApplyDenToSp()
    10500: @*/
    10501: PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
    10502: {
    10503:   MatTransposeColoring c;
    10504:   MPI_Comm             comm;
    10505:   PetscErrorCode       ierr;

    10508:   PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
    10509:   PetscObjectGetComm((PetscObject)mat,&comm);
    10510:   PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);

    10512:   c->ctype = iscoloring->ctype;
    10513:   if (mat->ops->transposecoloringcreate) {
    10514:     (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
    10515:   } else SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for matrix type %s",((PetscObject)mat)->type_name);

    10517:   *color = c;
    10518:   PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
    10519:   return(0);
    10520: }

    10522: /*@
    10523:       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
    10524:         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
    10525:         same, otherwise it will be larger

    10527:      Not Collective

    10529:   Input Parameter:
    10530: .    A  - the matrix

    10532:   Output Parameter:
    10533: .    state - the current state

    10535:   Notes:
    10536:     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
    10537:          different matrices

    10539:   Level: intermediate

    10541: @*/
    10542: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
    10543: {
    10546:   *state = mat->nonzerostate;
    10547:   return(0);
    10548: }

    10550: /*@
    10551:       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
    10552:                  matrices from each processor

    10554:     Collective

    10556:    Input Parameters:
    10557: +    comm - the communicators the parallel matrix will live on
    10558: .    seqmat - the input sequential matrices
    10559: .    n - number of local columns (or PETSC_DECIDE)
    10560: -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    10562:    Output Parameter:
    10563: .    mpimat - the parallel matrix generated

    10565:     Level: advanced

    10567:    Notes:
    10568:     The number of columns of the matrix in EACH processor MUST be the same.

    10570: @*/
    10571: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
    10572: {

    10576:   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
    10577:   if (reuse == MAT_REUSE_MATRIX && seqmat == *mpimat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");

    10579:   PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
    10580:   (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
    10581:   PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
    10582:   return(0);
    10583: }

    10585: /*@
    10586:      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
    10587:                  ranks' ownership ranges.

    10589:     Collective on A

    10591:    Input Parameters:
    10592: +    A   - the matrix to create subdomains from
    10593: -    N   - requested number of subdomains

    10596:    Output Parameters:
    10597: +    n   - number of subdomains resulting on this rank
    10598: -    iss - IS list with indices of subdomains on this rank

    10600:     Level: advanced

    10602:     Notes:
    10603:     number of subdomains must be smaller than the communicator size
    10604: @*/
    10605: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
    10606: {
    10607:   MPI_Comm        comm,subcomm;
    10608:   PetscMPIInt     size,rank,color;
    10609:   PetscInt        rstart,rend,k;
    10610:   PetscErrorCode  ierr;

    10613:   PetscObjectGetComm((PetscObject)A,&comm);
    10614:   MPI_Comm_size(comm,&size);
    10615:   MPI_Comm_rank(comm,&rank);
    10616:   if (N < 1 || N >= (PetscInt)size) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"number of subdomains must be > 0 and < %D, got N = %D",size,N);
    10617:   *n = 1;
    10618:   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
    10619:   color = rank/k;
    10620:   MPI_Comm_split(comm,color,rank,&subcomm);
    10621:   PetscMalloc1(1,iss);
    10622:   MatGetOwnershipRange(A,&rstart,&rend);
    10623:   ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);
    10624:   MPI_Comm_free(&subcomm);
    10625:   return(0);
    10626: }

    10628: /*@
    10629:    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.

    10631:    If the interpolation and restriction operators are the same, uses MatPtAP.
    10632:    If they are not the same, use MatMatMatMult.

    10634:    Once the coarse grid problem is constructed, correct for interpolation operators
    10635:    that are not of full rank, which can legitimately happen in the case of non-nested
    10636:    geometric multigrid.

    10638:    Input Parameters:
    10639: +  restrct - restriction operator
    10640: .  dA - fine grid matrix
    10641: .  interpolate - interpolation operator
    10642: .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    10643: -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate

    10645:    Output Parameters:
    10646: .  A - the Galerkin coarse matrix

    10648:    Options Database Key:
    10649: .  -pc_mg_galerkin <both,pmat,mat,none>

    10651:    Level: developer

    10653: .seealso: MatPtAP(), MatMatMatMult()
    10654: @*/
    10655: PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
    10656: {
    10658:   IS             zerorows;
    10659:   Vec            diag;

    10662:   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
    10663:   /* Construct the coarse grid matrix */
    10664:   if (interpolate == restrct) {
    10665:     MatPtAP(dA,interpolate,reuse,fill,A);
    10666:   } else {
    10667:     MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);
    10668:   }

    10670:   /* If the interpolation matrix is not of full rank, A will have zero rows.
    10671:      This can legitimately happen in the case of non-nested geometric multigrid.
    10672:      In that event, we set the rows of the matrix to the rows of the identity,
    10673:      ignoring the equations (as the RHS will also be zero). */

    10675:   MatFindZeroRows(*A, &zerorows);

    10677:   if (zerorows != NULL) { /* if there are any zero rows */
    10678:     MatCreateVecs(*A, &diag, NULL);
    10679:     MatGetDiagonal(*A, diag);
    10680:     VecISSet(diag, zerorows, 1.0);
    10681:     MatDiagonalSet(*A, diag, INSERT_VALUES);
    10682:     VecDestroy(&diag);
    10683:     ISDestroy(&zerorows);
    10684:   }
    10685:   return(0);
    10686: }

    10688: /*@C
    10689:     MatSetOperation - Allows user to set a matrix operation for any matrix type

    10691:    Logically Collective on Mat

    10693:     Input Parameters:
    10694: +   mat - the matrix
    10695: .   op - the name of the operation
    10696: -   f - the function that provides the operation

    10698:    Level: developer

    10700:     Usage:
    10701: $      extern PetscErrorCode usermult(Mat,Vec,Vec);
    10702: $      MatCreateXXX(comm,...&A);
    10703: $      MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);

    10705:     Notes:
    10706:     See the file include/petscmat.h for a complete list of matrix
    10707:     operations, which all have the form MATOP_<OPERATION>, where
    10708:     <OPERATION> is the name (in all capital letters) of the
    10709:     user interface routine (e.g., MatMult() -> MATOP_MULT).

    10711:     All user-provided functions (except for MATOP_DESTROY) should have the same calling
    10712:     sequence as the usual matrix interface routines, since they
    10713:     are intended to be accessed via the usual matrix interface
    10714:     routines, e.g.,
    10715: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

    10717:     In particular each function MUST return an error code of 0 on success and
    10718:     nonzero on failure.

    10720:     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.

    10722: .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
    10723: @*/
    10724: PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
    10725: {
    10728:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
    10729:     mat->ops->viewnative = mat->ops->view;
    10730:   }
    10731:   (((void(**)(void))mat->ops)[op]) = f;
    10732:   return(0);
    10733: }

    10735: /*@C
    10736:     MatGetOperation - Gets a matrix operation for any matrix type.

    10738:     Not Collective

    10740:     Input Parameters:
    10741: +   mat - the matrix
    10742: -   op - the name of the operation

    10744:     Output Parameter:
    10745: .   f - the function that provides the operation

    10747:     Level: developer

    10749:     Usage:
    10750: $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
    10751: $      MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);

    10753:     Notes:
    10754:     See the file include/petscmat.h for a complete list of matrix
    10755:     operations, which all have the form MATOP_<OPERATION>, where
    10756:     <OPERATION> is the name (in all capital letters) of the
    10757:     user interface routine (e.g., MatMult() -> MATOP_MULT).

    10759:     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.

    10761: .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
    10762: @*/
    10763: PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
    10764: {
    10767:   *f = (((void (**)(void))mat->ops)[op]);
    10768:   return(0);
    10769: }

    10771: /*@
    10772:     MatHasOperation - Determines whether the given matrix supports the particular
    10773:     operation.

    10775:    Not Collective

    10777:    Input Parameters:
    10778: +  mat - the matrix
    10779: -  op - the operation, for example, MATOP_GET_DIAGONAL

    10781:    Output Parameter:
    10782: .  has - either PETSC_TRUE or PETSC_FALSE

    10784:    Level: advanced

    10786:    Notes:
    10787:    See the file include/petscmat.h for a complete list of matrix
    10788:    operations, which all have the form MATOP_<OPERATION>, where
    10789:    <OPERATION> is the name (in all capital letters) of the
    10790:    user-level routine.  E.g., MatNorm() -> MATOP_NORM.

    10792: .seealso: MatCreateShell()
    10793: @*/
    10794: PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
    10795: {

    10800:   /* symbolic product can be set before matrix type */
    10803:   if (mat->ops->hasoperation) {
    10804:     (*mat->ops->hasoperation)(mat,op,has);
    10805:   } else {
    10806:     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
    10807:     else {
    10808:       *has = PETSC_FALSE;
    10809:       if (op == MATOP_CREATE_SUBMATRIX) {
    10810:         PetscMPIInt size;

    10812:         MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    10813:         if (size == 1) {
    10814:           MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);
    10815:         }
    10816:       }
    10817:     }
    10818:   }
    10819:   return(0);
    10820: }

    10822: /*@
    10823:     MatHasCongruentLayouts - Determines whether the rows and columns layouts
    10824:     of the matrix are congruent

    10826:    Collective on mat

    10828:    Input Parameters:
    10829: .  mat - the matrix

    10831:    Output Parameter:
    10832: .  cong - either PETSC_TRUE or PETSC_FALSE

    10834:    Level: beginner

    10836:    Notes:

    10838: .seealso: MatCreate(), MatSetSizes()
    10839: @*/
    10840: PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
    10841: {

    10848:   if (!mat->rmap || !mat->cmap) {
    10849:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
    10850:     return(0);
    10851:   }
    10852:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
    10853:     PetscLayoutCompare(mat->rmap,mat->cmap,cong);
    10854:     if (*cong) mat->congruentlayouts = 1;
    10855:     else       mat->congruentlayouts = 0;
    10856:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
    10857:   return(0);
    10858: }

    10860: PetscErrorCode MatSetInf(Mat A)
    10861: {

    10865:   if (!A->ops->setinf) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"No support for this operation for this matrix type");
    10866:   (*A->ops->setinf)(A);
    10867:   return(0);
    10868: }