Actual source code: matrix.c
petsc-3.13.6 2020-09-29
Report Typos and Errors

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

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

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

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

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

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

     47:    Logically Collective on Mat

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

     54:    Output Parameter:
     55: .  x  - the matrix

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

     64:    Level: intermediate

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

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

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

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

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

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

    102:    Logically Collective on Mat

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

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

    112:    Level: advanced

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

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

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

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

    134:    Logically Collective on Mat

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

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

    142:    Level: advanced

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

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

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

    160:    Logically Collective on Mat

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

    165:    Level: developer

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

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

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

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

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

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

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

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

    240:   Level: intermediate

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

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

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

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

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

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

    273:   Level: intermediate

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

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

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

    302:    Not Collective

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

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

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

    315:    Level: advanced

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

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

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

    342:    Collective on Mat

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

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

    350:    Level: advanced

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

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

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

    369:    Logically Collective on Mat

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

    374:    Level: advanced

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

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

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

    397:    Collective on Mat

    399:    Input Parameter:
    400: .  mat - the matrix

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

    406:    Notes:
    407:     the nghosts and ghosts are suitable to pass into VecCreateGhost()

    409:    Level: advanced

    411: @*/
    412: PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
    413: {

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

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

    434:    Logically Collective on Mat

    436:    Input Parameters:
    437: .  mat - the matrix

    439:    Level: advanced

    442: .seealso: MatRealPart()
    443: @*/
    444: PetscErrorCode MatImaginaryPart(Mat mat)
    445: {

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

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

    462:    Not Collective

    464:    Input Parameter:
    465: .  mat - the matrix

    467:    Output Parameters:
    468: +  missing - is any diagonal missing
    469: -  dd - first diagonal entry that is missing (optional) on this process

    471:    Level: advanced

    474: .seealso: MatRealPart()
    475: @*/
    476: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
    477: {

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

    491: /*@C
    492:    MatGetRow - Gets a row of a matrix.  You MUST call MatRestoreRow()
    493:    for each row that you get to ensure that your Section 1.5 Writing Application Codes with PETSc does
    494:    not bleed memory.

    496:    Not Collective

    498:    Input Parameters:
    499: +  mat - the matrix
    500: -  row - the row to get

    502:    Output Parameters:
    503: +  ncols -  if not NULL, the number of nonzeros in the row
    504: .  cols - if not NULL, the column numbers
    505: -  vals - if not NULL, the values

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

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

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

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

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

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

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

    546:    Level: advanced

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

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

    569: /*@
    570:    MatConjugate - replaces the matrix values with their complex conjugates

    572:    Logically Collective on Mat

    574:    Input Parameters:
    575: .  mat - the matrix

    577:    Level: advanced

    579: .seealso:  VecConjugate()
    580: @*/
    581: PetscErrorCode MatConjugate(Mat mat)
    582: {
    583: #if defined(PETSC_USE_COMPLEX)

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

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

    600:    Not Collective

    602:    Input Parameters:
    603: +  mat - the matrix
    604: .  row - the row to get
    605: .  ncols, cols - the number of nonzeros and their columns
    606: -  vals - if nonzero the column values

    608:    Notes:
    609:    This routine should be called after you have finished examining the entries.

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

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

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

    630:    Level: advanced

    632: .seealso:  MatGetRow()
    633: @*/
    634: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
    635: {

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

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

    654:    Not Collective

    656:    Input Parameters:
    657: .  mat - the matrix

    659:    Notes:
    660:    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.

    662:    Level: advanced

    664: .seealso: MatRestoreRowUpperTriangular()
    665: @*/
    666: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
    667: {

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

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

    684:    Not Collective

    686:    Input Parameters:
    687: .  mat - the matrix

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

    693:    Level: advanced

    695: .seealso:  MatGetRowUpperTriangular()
    696: @*/
    697: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
    698: {

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

    712: /*@C
    713:    MatSetOptionsPrefix - Sets the prefix used for searching for all
    714:    Mat options in the database.

    716:    Logically Collective on Mat

    718:    Input Parameter:
    719: +  A - the Mat context
    720: -  prefix - the prefix to prepend to all option names

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

    726:    Level: advanced

    728: .seealso: MatSetFromOptions()
    729: @*/
    730: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
    731: {

    736:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
    737:   return(0);
    738: }

    740: /*@C
    741:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
    742:    Mat options in the database.

    744:    Logically Collective on Mat

    746:    Input Parameters:
    747: +  A - the Mat context
    748: -  prefix - the prefix to prepend to all option names

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

    754:    Level: advanced

    756: .seealso: MatGetOptionsPrefix()
    757: @*/
    758: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
    759: {

    764:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
    765:   return(0);
    766: }

    768: /*@C
    769:    MatGetOptionsPrefix - Gets the prefix used for searching for all
    770:    Mat options in the database.

    772:    Not Collective

    774:    Input Parameter:
    775: .  A - the Mat context

    777:    Output Parameter:
    778: .  prefix - pointer to the prefix string used

    780:    Notes:
    781:     On the fortran side, the user should pass in a string 'prefix' of
    782:    sufficient length to hold the prefix.

    784:    Level: advanced

    786: .seealso: MatAppendOptionsPrefix()
    787: @*/
    788: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
    789: {

    794:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
    795:   return(0);
    796: }

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

    801:    Collective on Mat

    803:    Input Parameters:
    804: .  A - the Mat context

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

    810:    Level: beginner

    812: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
    813: @*/
    814: PetscErrorCode MatResetPreallocation(Mat A)
    815: {

    821:   PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
    822:   return(0);
    823: }

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

    829:    Collective on Mat

    831:    Input Parameters:
    832: .  A - the Mat context

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

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

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

    841:    Level: beginner

    843: .seealso: MatCreate(), MatDestroy()
    844: @*/
    845: PetscErrorCode MatSetUp(Mat A)
    846: {
    847:   PetscMPIInt    size;

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

    870: #if defined(PETSC_HAVE_SAWS)
    871:  #include <petscviewersaws.h>
    872: #endif

    874: /*@C
    875:    MatViewFromOptions - View from Options

    877:    Collective on Mat

    879:    Input Parameters:
    880: +  A - the Mat context
    881: .  obj - Optional object
    882: -  name - command line option

    884:    Level: intermediate
    885: .seealso:  Mat, MatView, PetscObjectViewFromOptions(), MatCreate()
    886: @*/
    887: PetscErrorCode  MatViewFromOptions(Mat A,PetscObject obj,const char name[])
    888: {

    893:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
    894:   return(0);
    895: }

    897: /*@C
    898:    MatView - Visualizes a matrix object.

    900:    Collective on Mat

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

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

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

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

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

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

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

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

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

    969: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
    970:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
    971: @*/
    972: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
    973: {
    974:   PetscErrorCode    ierr;
    975:   PetscInt          rows,cols,rbs,cbs;
    976:   PetscBool         isascii,isstring,issaws;
    977:   PetscViewerFormat format;
    978:   PetscMPIInt       size;

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

    988:   PetscViewerGetFormat(viewer,&format);
    989:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    990:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);

    992:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
    993:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);
    994:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
    995:   if ((!isascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
    996:     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detail");
    997:   }

    999:   PetscLogEventBegin(MAT_View,mat,viewer,0,0);
    1000:   if (isascii) {
    1001:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
    1002:     PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
    1003:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
    1004:       MatNullSpace nullsp,transnullsp;

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

    1037:     PetscObjectName((PetscObject)mat);
    1038:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
    1039:     if (!((PetscObject)mat)->amsmem && !rank) {
    1040:       PetscObjectViewSAWs((PetscObject)mat,viewer);
    1041:     }
    1042: #endif
    1043:   } else if (isstring) {
    1044:     const char *type;
    1045:     MatGetType(mat,&type);
    1046:     PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);
    1047:     if (mat->ops->view) {(*mat->ops->view)(mat,viewer);}
    1048:   }
    1049:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
    1050:     PetscViewerASCIIPushTab(viewer);
    1051:     (*mat->ops->viewnative)(mat,viewer);
    1052:     PetscViewerASCIIPopTab(viewer);
    1053:   } else if (mat->ops->view) {
    1054:     PetscViewerASCIIPushTab(viewer);
    1055:     (*mat->ops->view)(mat,viewer);
    1056:     PetscViewerASCIIPopTab(viewer);
    1057:   }
    1058:   if (isascii) {
    1059:     PetscViewerGetFormat(viewer,&format);
    1060:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
    1061:       PetscViewerASCIIPopTab(viewer);
    1062:     }
    1063:   }
    1064:   PetscLogEventEnd(MAT_View,mat,viewer,0,0);
    1065:   return(0);
    1066: }

    1068: #if defined(PETSC_USE_DEBUG)
    1069:  #include <../src/sys/totalview/tv_data_display.h>
    1070: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
    1071: {
    1072:   TV_add_row("Local rows", "int", &mat->rmap->n);
    1073:   TV_add_row("Local columns", "int", &mat->cmap->n);
    1074:   TV_add_row("Global rows", "int", &mat->rmap->N);
    1075:   TV_add_row("Global columns", "int", &mat->cmap->N);
    1076:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
    1077:   return TV_format_OK;
    1078: }
    1079: #endif

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

    1087:    Collective on PetscViewer

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

    1094:    Options Database Keys:
    1095:    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
    1096:    block size
    1097: .    -matload_block_size <bs>

    1099:    Level: beginner

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

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

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

    1114:    In parallel, each processor can load a subset of rows (or the
    1115:    entire matrix).  This routine is especially useful when a large
    1116:    matrix is stored on disk and only part of it is desired on each
    1117:    processor.  For example, a parallel solver may access only some of
    1118:    the rows from each processor.  The algorithm used here reads
    1119:    relatively small blocks of data rather than reading the entire
    1120:    matrix and then subsetting it.

    1122:    Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
    1123:    Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
    1124:    or the sequence like
    1125: $    PetscViewer v;
    1126: $    PetscViewerCreate(PETSC_COMM_WORLD,&v);
    1127: $    PetscViewerSetType(v,PETSCVIEWERBINARY);
    1128: $    PetscViewerSetFromOptions(v);
    1129: $    PetscViewerFileSetMode(v,FILE_MODE_READ);
    1130: $    PetscViewerFileSetName(v,"datafile");
    1131:    The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
    1132: $ -viewer_type {binary,hdf5}

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

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

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

    1148: $    PetscInt    MAT_FILE_CLASSID
    1149: $    PetscInt    number of rows
    1150: $    PetscInt    number of columns
    1151: $    PetscInt    total number of nonzeros
    1152: $    PetscInt    *number nonzeros in each row
    1153: $    PetscInt    *column indices of all nonzeros (starting index is zero)
    1154: $    PetscScalar *values of all nonzeros

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

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

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

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

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

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

    1184:    Corresponding MatView() is not yet implemented.

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

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

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

    1197:  @*/
    1198: PetscErrorCode MatLoad(Mat mat,PetscViewer viewer)
    1199: {
    1201:   PetscBool      flg;

    1207:   if (!((PetscObject)mat)->type_name) {
    1208:     MatSetType(mat,MATAIJ);
    1209:   }

    1211:   flg  = PETSC_FALSE;
    1212:   PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_symmetric",&flg,NULL);
    1213:   if (flg) {
    1214:     MatSetOption(mat,MAT_SYMMETRIC,PETSC_TRUE);
    1215:     MatSetOption(mat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
    1216:   }
    1217:   flg  = PETSC_FALSE;
    1218:   PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_spd",&flg,NULL);
    1219:   if (flg) {
    1220:     MatSetOption(mat,MAT_SPD,PETSC_TRUE);
    1221:   }

    1223:   if (!mat->ops->load) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type %s",((PetscObject)mat)->type_name);
    1224:   PetscLogEventBegin(MAT_Load,mat,viewer,0,0);
    1225:   (*mat->ops->load)(mat,viewer);
    1226:   PetscLogEventEnd(MAT_Load,mat,viewer,0,0);
    1227:   return(0);
    1228: }

    1230: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
    1231: {
    1233:   Mat_Redundant  *redund = *redundant;
    1234:   PetscInt       i;

    1237:   if (redund){
    1238:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
    1239:       ISDestroy(&redund->isrow);
    1240:       ISDestroy(&redund->iscol);
    1241:       MatDestroySubMatrices(1,&redund->matseq);
    1242:     } else {
    1243:       PetscFree2(redund->send_rank,redund->recv_rank);
    1244:       PetscFree(redund->sbuf_j);
    1245:       PetscFree(redund->sbuf_a);
    1246:       for (i=0; i<redund->nrecvs; i++) {
    1247:         PetscFree(redund->rbuf_j[i]);
    1248:         PetscFree(redund->rbuf_a[i]);
    1249:       }
    1250:       PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
    1251:     }

    1253:     if (redund->subcomm) {
    1254:       PetscCommDestroy(&redund->subcomm);
    1255:     }
    1256:     PetscFree(redund);
    1257:   }
    1258:   return(0);
    1259: }

    1261: /*@
    1262:    MatDestroy - Frees space taken by a matrix.

    1264:    Collective on Mat

    1266:    Input Parameter:
    1267: .  A - the matrix

    1269:    Level: beginner

    1271: @*/
    1272: PetscErrorCode MatDestroy(Mat *A)
    1273: {

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

    1281:   /* if memory was published with SAWs then destroy it */
    1282:   PetscObjectSAWsViewOff((PetscObject)*A);
    1283:   if ((*A)->ops->destroy) {
    1284:     (*(*A)->ops->destroy)(*A);
    1285:   }

    1287:   PetscFree((*A)->defaultvectype);
    1288:   PetscFree((*A)->bsizes);
    1289:   PetscFree((*A)->solvertype);
    1290:   MatDestroy_Redundant(&(*A)->redundant);
    1291:   MatProductClear(*A);

    1293:   MatNullSpaceDestroy(&(*A)->nullsp);
    1294:   MatNullSpaceDestroy(&(*A)->transnullsp);
    1295:   MatNullSpaceDestroy(&(*A)->nearnullsp);
    1296:   MatDestroy(&(*A)->schur);
    1297:   PetscLayoutDestroy(&(*A)->rmap);
    1298:   PetscLayoutDestroy(&(*A)->cmap);
    1299:   PetscHeaderDestroy(A);
    1300:   return(0);
    1301: }

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

    1308:    Not Collective

    1310:    Input Parameters:
    1311: +  mat - the matrix
    1312: .  v - a logically two-dimensional array of values
    1313: .  m, idxm - the number of rows and their global indices
    1314: .  n, idxn - the number of columns and their global indices
    1315: -  addv - either ADD_VALUES or INSERT_VALUES, where
    1316:    ADD_VALUES adds values to any existing entries, and
    1317:    INSERT_VALUES replaces existing entries with new values

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

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

    1325:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
    1326:    options cannot be mixed without intervening calls to the assembly
    1327:    routines.

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

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

    1337:    Efficiency Alert:
    1338:    The routine MatSetValuesBlocked() may offer much better efficiency
    1339:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

    1341:    Level: beginner

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

    1347: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
    1348:           InsertMode, INSERT_VALUES, ADD_VALUES
    1349: @*/
    1350: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
    1351: {
    1353: #if defined(PETSC_USE_DEBUG)
    1354:   PetscInt       i,j;
    1355: #endif

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

    1365:   if (mat->insertmode == NOT_SET_VALUES) {
    1366:     mat->insertmode = addv;
    1367:   }
    1368: #if defined(PETSC_USE_DEBUG)
    1369:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
    1370:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    1371:   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

    1373:   for (i=0; i<m; i++) {
    1374:     for (j=0; j<n; j++) {
    1375:       if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
    1376: #if defined(PETSC_USE_COMPLEX)
    1377:         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]);
    1378: #else
    1379:         SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
    1380: #endif
    1381:     }
    1382:   }
    1383: #endif

    1385:   if (mat->assembled) {
    1386:     mat->was_assembled = PETSC_TRUE;
    1387:     mat->assembled     = PETSC_FALSE;
    1388:   }
    1389:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
    1390:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
    1391:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
    1392:   return(0);
    1393: }

    1396: /*@
    1397:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
    1398:         values into a matrix

    1400:    Not Collective

    1402:    Input Parameters:
    1403: +  mat - the matrix
    1404: .  row - the (block) row to set
    1405: -  v - a logically two-dimensional array of values

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

    1410:    All the nonzeros in the row must be provided

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

    1414:    The row must belong to this process

    1416:    Level: intermediate

    1418: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
    1419:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
    1420: @*/
    1421: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
    1422: {
    1424:   PetscInt       globalrow;

    1430:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
    1431:   MatSetValuesRow(mat,globalrow,v);
    1432:   return(0);
    1433: }

    1435: /*@
    1436:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
    1437:         values into a matrix

    1439:    Not Collective

    1441:    Input Parameters:
    1442: +  mat - the matrix
    1443: .  row - the (block) row to set
    1444: -  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

    1446:    Notes:
    1447:    The values, v, are column-oriented for the block version.

    1449:    All the nonzeros in the row must be provided

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

    1453:    The row must belong to this process

    1455:    Level: advanced

    1457: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
    1458:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
    1459: @*/
    1460: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
    1461: {

    1467:   MatCheckPreallocated(mat,1);
    1469: #if defined(PETSC_USE_DEBUG)
    1470:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
    1471:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    1472: #endif
    1473:   mat->insertmode = INSERT_VALUES;

    1475:   if (mat->assembled) {
    1476:     mat->was_assembled = PETSC_TRUE;
    1477:     mat->assembled     = PETSC_FALSE;
    1478:   }
    1479:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
    1480:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    1481:   (*mat->ops->setvaluesrow)(mat,row,v);
    1482:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
    1483:   return(0);
    1484: }

    1486: /*@
    1487:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
    1488:      Using structured grid indexing

    1490:    Not Collective

    1492:    Input Parameters:
    1493: +  mat - the matrix
    1494: .  m - number of rows being entered
    1495: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
    1496: .  n - number of columns being entered
    1497: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
    1498: .  v - a logically two-dimensional array of values
    1499: -  addv - either ADD_VALUES or INSERT_VALUES, where
    1500:    ADD_VALUES adds values to any existing entries, and
    1501:    INSERT_VALUES replaces existing entries with new values

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

    1506:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
    1507:    options cannot be mixed without intervening calls to the assembly
    1508:    routines.

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

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

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

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

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

    1526:    In Fortran idxm and idxn should be declared as
    1527: $     MatStencil idxm(4,m),idxn(4,n)
    1528:    and the values inserted using
    1529: $    idxm(MatStencil_i,1) = i
    1530: $    idxm(MatStencil_j,1) = j
    1531: $    idxm(MatStencil_k,1) = k
    1532: $    idxm(MatStencil_c,1) = c
    1533:    etc

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

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

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

    1546:    Efficiency Alert:
    1547:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
    1548:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

    1550:    Level: beginner

    1552: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
    1553:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
    1554: @*/
    1555: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
    1556: {
    1558:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
    1559:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
    1560:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

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

    1600: /*@
    1601:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
    1602:      Using structured grid indexing

    1604:    Not Collective

    1606:    Input Parameters:
    1607: +  mat - the matrix
    1608: .  m - number of rows being entered
    1609: .  idxm - grid coordinates for matrix rows being entered
    1610: .  n - number of columns being entered
    1611: .  idxn - grid coordinates for matrix columns being entered
    1612: .  v - a logically two-dimensional array of values
    1613: -  addv - either ADD_VALUES or INSERT_VALUES, where
    1614:    ADD_VALUES adds values to any existing entries, and
    1615:    INSERT_VALUES replaces existing entries with new values

    1617:    Notes:
    1618:    By default the values, v, are row-oriented and unsorted.
    1619:    See MatSetOption() for other options.

    1621:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
    1622:    options cannot be mixed without intervening calls to the assembly
    1623:    routines.

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

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

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

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

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

    1641:    In Fortran idxm and idxn should be declared as
    1642: $     MatStencil idxm(4,m),idxn(4,n)
    1643:    and the values inserted using
    1644: $    idxm(MatStencil_i,1) = i
    1645: $    idxm(MatStencil_j,1) = j
    1646: $    idxm(MatStencil_k,1) = k
    1647:    etc

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

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

    1657:    Level: beginner

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

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

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

    1709: /*@
    1710:    MatSetStencil - Sets the grid information for setting values into a matrix via
    1711:         MatSetValuesStencil()

    1713:    Not Collective

    1715:    Input Parameters:
    1716: +  mat - the matrix
    1717: .  dim - dimension of the grid 1, 2, or 3
    1718: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
    1719: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
    1720: -  dof - number of degrees of freedom per node

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

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

    1729:    Level: beginner

    1731: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
    1732:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
    1733: @*/
    1734: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
    1735: {
    1736:   PetscInt i;

    1743:   mat->stencil.dim = dim + (dof > 1);
    1744:   for (i=0; i<dim; i++) {
    1745:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
    1746:     mat->stencil.starts[i] = starts[dim-i-1];
    1747:   }
    1748:   mat->stencil.dims[dim]   = dof;
    1749:   mat->stencil.starts[dim] = 0;
    1750:   mat->stencil.noc         = (PetscBool)(dof == 1);
    1751:   return(0);
    1752: }

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

    1757:    Not Collective

    1759:    Input Parameters:
    1760: +  mat - the matrix
    1761: .  v - a logically two-dimensional array of values
    1762: .  m, idxm - the number of block rows and their global block indices
    1763: .  n, idxn - the number of block columns and their global block indices
    1764: -  addv - either ADD_VALUES or INSERT_VALUES, where
    1765:    ADD_VALUES adds values to any existing entries, and
    1766:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

    1784:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
    1785:    options cannot be mixed without intervening calls to the assembly
    1786:    routines.

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

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

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

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

    1817:    Level: intermediate

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

    1828:   if (!m || !n) return(0); /* no values to insert */
    1832:   MatCheckPreallocated(mat,1);
    1833:   if (mat->insertmode == NOT_SET_VALUES) {
    1834:     mat->insertmode = addv;
    1835:   }
    1836: #if defined(PETSC_USE_DEBUG)
    1837:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
    1838:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    1839:   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    1840: #endif

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

    1876: /*@C
    1877:    MatGetValues - Gets a block of values from a matrix.

    1879:    Not Collective; currently only returns a local block

    1881:    Input Parameters:
    1882: +  mat - the matrix
    1883: .  v - a logically two-dimensional array for storing the values
    1884: .  m, idxm - the number of rows and their global indices
    1885: -  n, idxn - the number of columns and their global indices

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

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

    1895:    MatGetValues() requires that the matrix has been assembled
    1896:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
    1897:    MatSetValues() and MatGetValues() CANNOT be made in succession
    1898:    without intermediate matrix assembly.

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

    1903:    Level: advanced

    1905: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
    1906: @*/
    1907: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
    1908: {

    1914:   if (!m || !n) return(0);
    1918:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    1919:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    1920:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    1921:   MatCheckPreallocated(mat,1);

    1923:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
    1924:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
    1925:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
    1926:   return(0);
    1927: }

    1929: /*@C
    1930:    MatGetValuesLocal - retrieves values into certain locations of a matrix,
    1931:    using a local numbering of the nodes.

    1933:    Not Collective

    1935:    Input Parameters:
    1936: +  mat - the matrix
    1937: .  nrow, irow - number of rows and their local indices
    1938: -  ncol, icol - number of columns and their local indices

    1940:    Output Parameter:
    1941: .  y -  a logically two-dimensional array of values

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

    1946:    Level: advanced

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

    1952: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
    1953:            MatSetValuesLocal()
    1954: @*/
    1955: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
    1956: {

    1962:   MatCheckPreallocated(mat,1);
    1963:   if (!nrow || !ncol) return(0); /* no values to retrieve */
    1966: #if defined(PETSC_USE_DEBUG)
    1967:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    1968:   if (!mat->ops->getvalueslocal && !mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    1969: #endif
    1970:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    1971:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
    1972:   if (mat->ops->getvalueslocal) {
    1973:     (*mat->ops->getvalueslocal)(mat,nrow,irow,ncol,icol,y);
    1974:   } else {
    1975:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
    1976:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
    1977:       irowm = buf; icolm = buf+nrow;
    1978:     } else {
    1979:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
    1980:       irowm = bufr; icolm = bufc;
    1981:     }
    1982:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
    1983:     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
    1984:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
    1985:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
    1986:     MatGetValues(mat,nrow,irowm,ncol,icolm,y);
    1987:     PetscFree2(bufr,bufc);
    1988:   }
    1989:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
    1990:   return(0);
    1991: }

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

    1997:   Not Collective

    1999:   Input Parameters:
    2000: + mat - the matrix
    2001: . nb - the number of blocks
    2002: . bs - the number of rows (and columns) in each block
    2003: . rows - a concatenation of the rows for each block
    2004: - v - a concatenation of logically two-dimensional arrays of values

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

    2009:   Level: advanced

    2011: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
    2012:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
    2013: @*/
    2014: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
    2015: {

    2023: #if defined(PETSC_USE_DEBUG)
    2024:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    2025: #endif

    2027:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
    2028:   if (mat->ops->setvaluesbatch) {
    2029:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
    2030:   } else {
    2031:     PetscInt b;
    2032:     for (b = 0; b < nb; ++b) {
    2033:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
    2034:     }
    2035:   }
    2036:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
    2037:   return(0);
    2038: }

    2040: /*@
    2041:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
    2042:    the routine MatSetValuesLocal() to allow users to insert matrix entries
    2043:    using a local (per-processor) numbering.

    2045:    Not Collective

    2047:    Input Parameters:
    2048: +  x - the matrix
    2049: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
    2050: - cmapping - column mapping

    2052:    Level: intermediate

    2055: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
    2056: @*/
    2057: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
    2058: {

    2067:   if (x->ops->setlocaltoglobalmapping) {
    2068:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
    2069:   } else {
    2070:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
    2071:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
    2072:   }
    2073:   return(0);
    2074: }

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

    2080:    Not Collective

    2082:    Input Parameters:
    2083: .  A - the matrix

    2085:    Output Parameters:
    2086: + rmapping - row mapping
    2087: - cmapping - column mapping

    2089:    Level: advanced

    2092: .seealso:  MatSetValuesLocal()
    2093: @*/
    2094: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
    2095: {
    2101:   if (rmapping) *rmapping = A->rmap->mapping;
    2102:   if (cmapping) *cmapping = A->cmap->mapping;
    2103:   return(0);
    2104: }

    2106: /*@
    2107:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

    2109:    Not Collective

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

    2114:    Output Parameters:
    2115: + rmap - row layout
    2116: - cmap - column layout

    2118:    Level: advanced

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

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

    2138:    Not Collective

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

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

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

    2155:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
    2156:    options cannot be mixed without intervening calls to the assembly
    2157:    routines.

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

    2162:    Level: intermediate

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

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

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

    2191:   if (mat->assembled) {
    2192:     mat->was_assembled = PETSC_TRUE;
    2193:     mat->assembled     = PETSC_FALSE;
    2194:   }
    2195:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
    2196:   if (mat->ops->setvalueslocal) {
    2197:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
    2198:   } else {
    2199:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
    2200:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
    2201:       irowm = buf; icolm = buf+nrow;
    2202:     } else {
    2203:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
    2204:       irowm = bufr; icolm = bufc;
    2205:     }
    2206:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
    2207:     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
    2208:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
    2209:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
    2210:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
    2211:     PetscFree2(bufr,bufc);
    2212:   }
    2213:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
    2214:   return(0);
    2215: }

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

    2221:    Not Collective

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

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

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

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

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

    2246:    Level: intermediate

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

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

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

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

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

    2318:    Collective on Mat

    2320:    Input Parameters:
    2321: +  mat - the matrix
    2322: -  x   - the vector to be multiplied

    2324:    Output Parameters:
    2325: .  y - the result

    2327:    Notes:
    2328:    The vectors x and y cannot be the same.  I.e., one cannot
    2329:    call MatMult(A,y,y).

    2331:    Level: developer

    2333: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2334: @*/
    2335: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
    2336: {

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

    2350:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
    2351:   (*mat->ops->multdiagonalblock)(mat,x,y);
    2352:   PetscObjectStateIncrease((PetscObject)y);
    2353:   return(0);
    2354: }

    2356: /* --------------------------------------------------------*/
    2357: /*@
    2358:    MatMult - Computes the matrix-vector product, y = Ax.

    2360:    Neighbor-wise Collective on Mat

    2362:    Input Parameters:
    2363: +  mat - the matrix
    2364: -  x   - the vector to be multiplied

    2366:    Output Parameters:
    2367: .  y - the result

    2369:    Notes:
    2370:    The vectors x and y cannot be the same.  I.e., one cannot
    2371:    call MatMult(A,y,y).

    2373:    Level: beginner

    2375: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2376: @*/
    2377: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
    2378: {

    2386:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    2387:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    2388:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
    2389: #if !defined(PETSC_HAVE_CONSTRAINTS)
    2390:   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);
    2391:   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);
    2392:   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);
    2393: #endif
    2394:   VecSetErrorIfLocked(y,3);
    2395:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
    2396:   MatCheckPreallocated(mat,1);

    2398:   VecLockReadPush(x);
    2399:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
    2400:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
    2401:   (*mat->ops->mult)(mat,x,y);
    2402:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
    2403:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
    2404:   VecLockReadPop(x);
    2405:   return(0);
    2406: }

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

    2411:    Neighbor-wise Collective on Mat

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

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

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

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

    2427:    Level: beginner

    2429: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
    2430: @*/
    2431: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
    2432: {
    2433:   PetscErrorCode (*op)(Mat,Vec,Vec)=NULL,ierr;

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

    2451:   if (!mat->ops->multtranspose) {
    2452:     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
    2453:     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);
    2454:   } else op = mat->ops->multtranspose;
    2455:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
    2456:   VecLockReadPush(x);
    2457:   (*op)(mat,x,y);
    2458:   VecLockReadPop(x);
    2459:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
    2460:   PetscObjectStateIncrease((PetscObject)y);
    2461:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
    2462:   return(0);
    2463: }

    2465: /*@
    2466:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

    2468:    Neighbor-wise Collective on Mat

    2470:    Input Parameters:
    2471: +  mat - the matrix
    2472: -  x   - the vector to be multilplied

    2474:    Output Parameters:
    2475: .  y - the result

    2477:    Notes:
    2478:    The vectors x and y cannot be the same.  I.e., one cannot
    2479:    call MatMultHermitianTranspose(A,y,y).

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

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

    2485:    Level: beginner

    2487: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
    2488: @*/
    2489: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
    2490: {
    2492:   Vec            w;

    2500:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    2501:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    2502:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
    2503: #if !defined(PETSC_HAVE_CONSTRAINTS)
    2504:   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);
    2505:   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);
    2506: #endif
    2507:   MatCheckPreallocated(mat,1);

    2509:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
    2510:   if (mat->ops->multhermitiantranspose || (mat->hermitian && mat->ops->mult)) {
    2511:     VecLockReadPush(x);
    2512:     if (mat->ops->multhermitiantranspose) {
    2513:       (*mat->ops->multhermitiantranspose)(mat,x,y);
    2514:     } else {
    2515:       (*mat->ops->mult)(mat,x,y);
    2516:     }
    2517:     VecLockReadPop(x);
    2518:   } else {
    2519:     VecDuplicate(x,&w);
    2520:     VecCopy(x,w);
    2521:     VecConjugate(w);
    2522:     MatMultTranspose(mat,w,y);
    2523:     VecDestroy(&w);
    2524:     VecConjugate(y);
    2525:   }
    2526:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
    2527:   PetscObjectStateIncrease((PetscObject)y);
    2528:   return(0);
    2529: }

    2531: /*@
    2532:     MatMultAdd -  Computes v3 = v2 + A * v1.

    2534:     Neighbor-wise Collective on Mat

    2536:     Input Parameters:
    2537: +   mat - the matrix
    2538: -   v1, v2 - the vectors

    2540:     Output Parameters:
    2541: .   v3 - the result

    2543:     Notes:
    2544:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
    2545:     call MatMultAdd(A,v1,v2,v1).

    2547:     Level: beginner

    2549: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
    2550: @*/
    2551: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
    2552: {

    2562:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    2563:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    2564:   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);
    2565:   /* 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);
    2566:      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); */
    2567:   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);
    2568:   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);
    2569:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
    2570:   MatCheckPreallocated(mat,1);

    2572:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
    2573:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
    2574:   VecLockReadPush(v1);
    2575:   (*mat->ops->multadd)(mat,v1,v2,v3);
    2576:   VecLockReadPop(v1);
    2577:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
    2578:   PetscObjectStateIncrease((PetscObject)v3);
    2579:   return(0);
    2580: }

    2582: /*@
    2583:    MatMultTransposeAdd - 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 MatMultTransposeAdd(A,v1,v2,v1).

    2598:    Level: beginner

    2600: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
    2601: @*/
    2602: PetscErrorCode MatMultTransposeAdd(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->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    2616:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
    2617:   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);
    2618:   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);
    2619:   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);
    2620:   MatCheckPreallocated(mat,1);

    2622:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
    2623:   VecLockReadPush(v1);
    2624:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
    2625:   VecLockReadPop(v1);
    2626:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
    2627:   PetscObjectStateIncrease((PetscObject)v3);
    2628:   return(0);
    2629: }

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

    2634:    Neighbor-wise Collective on Mat

    2636:    Input Parameters:
    2637: +  mat - the matrix
    2638: -  v1, v2 - the vectors

    2640:    Output Parameters:
    2641: .  v3 - the result

    2643:    Notes:
    2644:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
    2645:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

    2647:    Level: beginner

    2649: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
    2650: @*/
    2651: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
    2652: {

    2662:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    2663:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    2664:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
    2665:   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);
    2666:   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);
    2667:   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);
    2668:   MatCheckPreallocated(mat,1);

    2670:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
    2671:   VecLockReadPush(v1);
    2672:   if (mat->ops->multhermitiantransposeadd) {
    2673:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
    2674:   } else {
    2675:     Vec w,z;
    2676:     VecDuplicate(v1,&w);
    2677:     VecCopy(v1,w);
    2678:     VecConjugate(w);
    2679:     VecDuplicate(v3,&z);
    2680:     MatMultTranspose(mat,w,z);
    2681:     VecDestroy(&w);
    2682:     VecConjugate(z);
    2683:     if (v2 != v3) {
    2684:       VecWAXPY(v3,1.0,v2,z);
    2685:     } else {
    2686:       VecAXPY(v3,1.0,z);
    2687:     }
    2688:     VecDestroy(&z);
    2689:   }
    2690:   VecLockReadPop(v1);
    2691:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
    2692:   PetscObjectStateIncrease((PetscObject)v3);
    2693:   return(0);
    2694: }

    2696: /*@
    2697:    MatMultConstrained - The inner multiplication routine for a
    2698:    constrained matrix P^T A P.

    2700:    Neighbor-wise Collective on Mat

    2702:    Input Parameters:
    2703: +  mat - the matrix
    2704: -  x   - the vector to be multilplied

    2706:    Output Parameters:
    2707: .  y - the result

    2709:    Notes:
    2710:    The vectors x and y cannot be the same.  I.e., one cannot
    2711:    call MatMult(A,y,y).

    2713:    Level: beginner

    2715: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2716: @*/
    2717: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
    2718: {

    2725:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    2726:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    2727:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
    2728:   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);
    2729:   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);
    2730:   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);

    2732:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
    2733:   VecLockReadPush(x);
    2734:   (*mat->ops->multconstrained)(mat,x,y);
    2735:   VecLockReadPop(x);
    2736:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
    2737:   PetscObjectStateIncrease((PetscObject)y);
    2738:   return(0);
    2739: }

    2741: /*@
    2742:    MatMultTransposeConstrained - The inner multiplication routine for a
    2743:    constrained matrix P^T A^T P.

    2745:    Neighbor-wise Collective on Mat

    2747:    Input Parameters:
    2748: +  mat - the matrix
    2749: -  x   - the vector to be multilplied

    2751:    Output Parameters:
    2752: .  y - the result

    2754:    Notes:
    2755:    The vectors x and y cannot be the same.  I.e., one cannot
    2756:    call MatMult(A,y,y).

    2758:    Level: beginner

    2760: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    2761: @*/
    2762: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
    2763: {

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

    2776:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
    2777:   (*mat->ops->multtransposeconstrained)(mat,x,y);
    2778:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
    2779:   PetscObjectStateIncrease((PetscObject)y);
    2780:   return(0);
    2781: }

    2783: /*@C
    2784:    MatGetFactorType - gets the type of factorization it is

    2786:    Not Collective

    2788:    Input Parameters:
    2789: .  mat - the matrix

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

    2794:    Level: intermediate

    2796: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
    2797: @*/
    2798: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
    2799: {
    2804:   *t = mat->factortype;
    2805:   return(0);
    2806: }

    2808: /*@C
    2809:    MatSetFactorType - sets the type of factorization it is

    2811:    Logically Collective on Mat

    2813:    Input Parameters:
    2814: +  mat - the matrix
    2815: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

    2817:    Level: intermediate

    2819: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
    2820: @*/
    2821: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
    2822: {
    2826:   mat->factortype = t;
    2827:   return(0);
    2828: }

    2830: /* ------------------------------------------------------------*/
    2831: /*@C
    2832:    MatGetInfo - Returns information about matrix storage (number of
    2833:    nonzeros, memory, etc.).

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

    2837:    Input Parameters:
    2838: .  mat - the matrix

    2840:    Output Parameters:
    2841: +  flag - flag indicating the type of parameters to be returned
    2842:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
    2843:    MAT_GLOBAL_SUM - sum over all processors)
    2844: -  info - matrix information context

    2846:    Notes:
    2847:    The MatInfo context contains a variety of matrix data, including
    2848:    number of nonzeros allocated and used, number of mallocs during
    2849:    matrix assembly, etc.  Additional information for factored matrices
    2850:    is provided (such as the fill ratio, number of mallocs during
    2851:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
    2852:    when using the runtime options
    2853: $       -info -mat_view ::ascii_info

    2855:    Example for C/C++ Users:
    2856:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
    2857:    data within the MatInfo context.  For example,
    2858: .vb
    2859:       MatInfo info;
    2860:       Mat     A;
    2861:       double  mal, nz_a, nz_u;

    2863:       MatGetInfo(A,MAT_LOCAL,&info);
    2864:       mal  = info.mallocs;
    2865:       nz_a = info.nz_allocated;
    2866: .ve

    2868:    Example for Fortran Users:
    2869:    Fortran users should declare info as a double precision
    2870:    array of dimension MAT_INFO_SIZE, and then extract the parameters
    2871:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
    2872:    a complete list of parameter names.
    2873: .vb
    2874:       double  precision info(MAT_INFO_SIZE)
    2875:       double  precision mal, nz_a
    2876:       Mat     A
    2877:       integer ierr

    2879:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
    2880:       mal = info(MAT_INFO_MALLOCS)
    2881:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
    2882: .ve

    2884:     Level: intermediate

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

    2889: .seealso: MatStashGetInfo()

    2891: @*/
    2892: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
    2893: {

    2900:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    2901:   MatCheckPreallocated(mat,1);
    2902:   (*mat->ops->getinfo)(mat,flag,info);
    2903:   return(0);
    2904: }

    2906: /*
    2907:    This is used by external packages where it is not easy to get the info from the actual
    2908:    matrix factorization.
    2909: */
    2910: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
    2911: {

    2915:   PetscMemzero(info,sizeof(MatInfo));
    2916:   return(0);
    2917: }

    2919: /* ----------------------------------------------------------*/

    2921: /*@C
    2922:    MatLUFactor - Performs in-place LU factorization of matrix.

    2924:    Collective on Mat

    2926:    Input Parameters:
    2927: +  mat - the matrix
    2928: .  row - row permutation
    2929: .  col - column permutation
    2930: -  info - options for factorization, includes
    2931: $          fill - expected fill as ratio of original fill.
    2932: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
    2933: $                   Run with the option -info to determine an optimal value to use

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

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

    2943:    Level: developer

    2945: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
    2946:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

    2951: @*/
    2952: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
    2953: {
    2955:   MatFactorInfo  tinfo;

    2963:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    2964:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    2965:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    2966:   MatCheckPreallocated(mat,1);
    2967:   if (!info) {
    2968:     MatFactorInfoInitialize(&tinfo);
    2969:     info = &tinfo;
    2970:   }

    2972:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
    2973:   (*mat->ops->lufactor)(mat,row,col,info);
    2974:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
    2975:   PetscObjectStateIncrease((PetscObject)mat);
    2976:   return(0);
    2977: }

    2979: /*@C
    2980:    MatILUFactor - Performs in-place ILU factorization of matrix.

    2982:    Collective on Mat

    2984:    Input Parameters:
    2985: +  mat - the matrix
    2986: .  row - row permutation
    2987: .  col - column permutation
    2988: -  info - structure containing
    2989: $      levels - number of levels of fill.
    2990: $      expected fill - as ratio of original fill.
    2991: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
    2992:                 missing diagonal entries)

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

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

    3002:    Level: developer

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

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

    3009: @*/
    3010: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
    3011: {

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

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

    3033: /*@C
    3034:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
    3035:    Call this routine before calling MatLUFactorNumeric().

    3037:    Collective on Mat

    3039:    Input Parameters:
    3040: +  fact - the factor matrix obtained with MatGetFactor()
    3041: .  mat - the matrix
    3042: .  row, col - row and column permutations
    3043: -  info - options for factorization, includes
    3044: $          fill - expected fill as ratio of original fill.
    3045: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
    3046: $                   Run with the option -info to determine an optimal value to use

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

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

    3056:    Level: developer

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

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

    3063: @*/
    3064: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
    3065: {
    3067:   MatFactorInfo  tinfo;

    3076:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    3077:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    3078:   if (!(fact)->ops->lufactorsymbolic) {
    3079:     MatSolverType spackage;
    3080:     MatFactorGetSolverType(fact,&spackage);
    3081:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
    3082:   }
    3083:   MatCheckPreallocated(mat,2);
    3084:   if (!info) {
    3085:     MatFactorInfoInitialize(&tinfo);
    3086:     info = &tinfo;
    3087:   }

    3089:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
    3090:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
    3091:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
    3092:   PetscObjectStateIncrease((PetscObject)fact);
    3093:   return(0);
    3094: }

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

    3100:    Collective on Mat

    3102:    Input Parameters:
    3103: +  fact - the factor matrix obtained with MatGetFactor()
    3104: .  mat - the matrix
    3105: -  info - options for factorization

    3107:    Notes:
    3108:    See MatLUFactor() for in-place factorization.  See
    3109:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

    3115:    Level: developer

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

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

    3122: @*/
    3123: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
    3124: {
    3125:   MatFactorInfo  tinfo;

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

    3136:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
    3137:   MatCheckPreallocated(mat,2);
    3138:   if (!info) {
    3139:     MatFactorInfoInitialize(&tinfo);
    3140:     info = &tinfo;
    3141:   }

    3143:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
    3144:   (fact->ops->lufactornumeric)(fact,mat,info);
    3145:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
    3146:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
    3147:   PetscObjectStateIncrease((PetscObject)fact);
    3148:   return(0);
    3149: }

    3151: /*@C
    3152:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
    3153:    symmetric matrix.

    3155:    Collective on Mat

    3157:    Input Parameters:
    3158: +  mat - the matrix
    3159: .  perm - row and column permutations
    3160: -  f - expected fill as ratio of original fill

    3162:    Notes:
    3163:    See MatLUFactor() for the nonsymmetric case.  See also
    3164:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

    3170:    Level: developer

    3172: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
    3173:           MatGetOrdering()

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

    3178: @*/
    3179: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
    3180: {
    3182:   MatFactorInfo  tinfo;

    3189:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
    3190:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    3191:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    3192:   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);
    3193:   MatCheckPreallocated(mat,1);
    3194:   if (!info) {
    3195:     MatFactorInfoInitialize(&tinfo);
    3196:     info = &tinfo;
    3197:   }

    3199:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
    3200:   (*mat->ops->choleskyfactor)(mat,perm,info);
    3201:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
    3202:   PetscObjectStateIncrease((PetscObject)mat);
    3203:   return(0);
    3204: }

    3206: /*@C
    3207:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
    3208:    of a symmetric matrix.

    3210:    Collective on Mat

    3212:    Input Parameters:
    3213: +  fact - the factor matrix obtained with MatGetFactor()
    3214: .  mat - the matrix
    3215: .  perm - row and column permutations
    3216: -  info - options for factorization, includes
    3217: $          fill - expected fill as ratio of original fill.
    3218: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
    3219: $                   Run with the option -info to determine an optimal value to use

    3221:    Notes:
    3222:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
    3223:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

    3229:    Level: developer

    3231: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
    3232:           MatGetOrdering()

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

    3237: @*/
    3238: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
    3239: {
    3241:   MatFactorInfo  tinfo;

    3249:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
    3250:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    3251:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    3252:   if (!(fact)->ops->choleskyfactorsymbolic) {
    3253:     MatSolverType spackage;
    3254:     MatFactorGetSolverType(fact,&spackage);
    3255:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
    3256:   }
    3257:   MatCheckPreallocated(mat,2);
    3258:   if (!info) {
    3259:     MatFactorInfoInitialize(&tinfo);
    3260:     info = &tinfo;
    3261:   }

    3263:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
    3264:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
    3265:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
    3266:   PetscObjectStateIncrease((PetscObject)fact);
    3267:   return(0);
    3268: }

    3270: /*@C
    3271:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
    3272:    of a symmetric matrix. Call this routine after first calling
    3273:    MatCholeskyFactorSymbolic().

    3275:    Collective on Mat

    3277:    Input Parameters:
    3278: +  fact - the factor matrix obtained with MatGetFactor()
    3279: .  mat - the initial matrix
    3280: .  info - options for factorization
    3281: -  fact - the symbolic factor of mat

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

    3289:    Level: developer

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

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

    3296: @*/
    3297: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
    3298: {
    3299:   MatFactorInfo  tinfo;

    3307:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    3308:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
    3309:   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);
    3310:   MatCheckPreallocated(mat,2);
    3311:   if (!info) {
    3312:     MatFactorInfoInitialize(&tinfo);
    3313:     info = &tinfo;
    3314:   }

    3316:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
    3317:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
    3318:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
    3319:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
    3320:   PetscObjectStateIncrease((PetscObject)fact);
    3321:   return(0);
    3322: }

    3324: /* ----------------------------------------------------------------*/
    3325: /*@
    3326:    MatSolve - Solves A x = b, given a factored matrix.

    3328:    Neighbor-wise Collective on Mat

    3330:    Input Parameters:
    3331: +  mat - the factored matrix
    3332: -  b - the right-hand-side vector

    3334:    Output Parameter:
    3335: .  x - the result vector

    3337:    Notes:
    3338:    The vectors b and x cannot be the same.  I.e., one cannot
    3339:    call MatSolve(A,x,x).

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

    3346:    Level: developer

    3348: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
    3349: @*/
    3350: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
    3351: {

    3361:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    3362:   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);
    3363:   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);
    3364:   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);
    3365:   if (!mat->rmap->N && !mat->cmap->N) return(0);
    3366:   MatCheckPreallocated(mat,1);

    3368:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
    3369:   if (mat->factorerrortype) {
    3370:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
    3371:     VecSetInf(x);
    3372:   } else {
    3373:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    3374:     (*mat->ops->solve)(mat,b,x);
    3375:   }
    3376:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
    3377:   PetscObjectStateIncrease((PetscObject)x);
    3378:   return(0);
    3379: }

    3381: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
    3382: {
    3384:   Vec            b,x;
    3385:   PetscInt       m,N,i;
    3386:   PetscScalar    *bb,*xx;

    3389:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
    3390:   MatDenseGetArray(X,&xx);
    3391:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
    3392:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
    3393:   MatCreateVecs(A,&x,&b);
    3394:   for (i=0; i<N; i++) {
    3395:     VecPlaceArray(b,bb + i*m);
    3396:     VecPlaceArray(x,xx + i*m);
    3397:     if (trans) {
    3398:       MatSolveTranspose(A,b,x);
    3399:     } else {
    3400:       MatSolve(A,b,x);
    3401:     }
    3402:     VecResetArray(x);
    3403:     VecResetArray(b);
    3404:   }
    3405:   VecDestroy(&b);
    3406:   VecDestroy(&x);
    3407:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
    3408:   MatDenseRestoreArray(X,&xx);
    3409:   return(0);
    3410: }

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

    3415:    Neighbor-wise Collective on Mat

    3417:    Input Parameters:
    3418: +  A - the factored matrix
    3419: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

    3421:    Output Parameter:
    3422: .  X - the result matrix (dense matrix)

    3424:    Notes:
    3425:    If B is a MATDENSE matrix then one can call MatMatSolve(A,B,B);
    3426:    otherwise, B and X cannot be the same.

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

    3434:    Level: developer

    3436: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
    3437: @*/
    3438: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
    3439: {

    3449:   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);
    3450:   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);
    3451:   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");
    3452:   if (!A->rmap->N && !A->cmap->N) return(0);
    3453:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    3454:   MatCheckPreallocated(A,1);

    3456:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
    3457:   if (!A->ops->matsolve) {
    3458:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
    3459:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
    3460:   } else {
    3461:     (*A->ops->matsolve)(A,B,X);
    3462:   }
    3463:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
    3464:   PetscObjectStateIncrease((PetscObject)X);
    3465:   return(0);
    3466: }

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

    3471:    Neighbor-wise Collective on Mat

    3473:    Input Parameters:
    3474: +  A - the factored matrix
    3475: -  B - the right-hand-side matrix  (dense matrix)

    3477:    Output Parameter:
    3478: .  X - the result matrix (dense matrix)

    3480:    Notes:
    3481:    The matrices B and X cannot be the same.  I.e., one cannot
    3482:    call MatMatSolveTranspose(A,X,X).

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

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

    3492:    Level: developer

    3494: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
    3495: @*/
    3496: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
    3497: {

    3507:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
    3508:   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);
    3509:   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);
    3510:   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);
    3511:   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");
    3512:   if (!A->rmap->N && !A->cmap->N) return(0);
    3513:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    3514:   MatCheckPreallocated(A,1);

    3516:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
    3517:   if (!A->ops->matsolvetranspose) {
    3518:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
    3519:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
    3520:   } else {
    3521:     (*A->ops->matsolvetranspose)(A,B,X);
    3522:   }
    3523:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
    3524:   PetscObjectStateIncrease((PetscObject)X);
    3525:   return(0);
    3526: }

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

    3531:    Neighbor-wise Collective on Mat

    3533:    Input Parameters:
    3534: +  A - the factored matrix
    3535: -  Bt - the transpose of right-hand-side matrix

    3537:    Output Parameter:
    3538: .  X - the result matrix (dense matrix)

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

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

    3548:    Level: developer

    3550: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
    3551: @*/
    3552: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
    3553: {

    3564:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
    3565:   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);
    3566:   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);
    3567:   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");
    3568:   if (!A->rmap->N && !A->cmap->N) return(0);
    3569:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    3570:   MatCheckPreallocated(A,1);

    3572:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
    3573:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
    3574:   (*A->ops->mattransposesolve)(A,Bt,X);
    3575:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
    3576:   PetscObjectStateIncrease((PetscObject)X);
    3577:   return(0);
    3578: }

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

    3584:    Neighbor-wise Collective on Mat

    3586:    Input Parameters:
    3587: +  mat - the factored matrix
    3588: -  b - the right-hand-side vector

    3590:    Output Parameter:
    3591: .  x - the result vector

    3593:    Notes:
    3594:    MatSolve() should be used for most applications, as it performs
    3595:    a forward solve followed by a backward solve.

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

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

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

    3610:    Level: developer

    3612: .seealso: MatSolve(), MatBackwardSolve()
    3613: @*/
    3614: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
    3615: {

    3625:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    3626:   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);
    3627:   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);
    3628:   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);
    3629:   if (!mat->rmap->N && !mat->cmap->N) return(0);
    3630:   MatCheckPreallocated(mat,1);

    3632:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    3633:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
    3634:   (*mat->ops->forwardsolve)(mat,b,x);
    3635:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
    3636:   PetscObjectStateIncrease((PetscObject)x);
    3637:   return(0);
    3638: }

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

    3644:    Neighbor-wise Collective on Mat

    3646:    Input Parameters:
    3647: +  mat - the factored matrix
    3648: -  b - the right-hand-side vector

    3650:    Output Parameter:
    3651: .  x - the result vector

    3653:    Notes:
    3654:    MatSolve() should be used for most applications, as it performs
    3655:    a forward solve followed by a backward solve.

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

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

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

    3670:    Level: developer

    3672: .seealso: MatSolve(), MatForwardSolve()
    3673: @*/
    3674: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
    3675: {

    3685:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    3686:   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);
    3687:   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);
    3688:   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);
    3689:   if (!mat->rmap->N && !mat->cmap->N) return(0);
    3690:   MatCheckPreallocated(mat,1);

    3692:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    3693:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
    3694:   (*mat->ops->backwardsolve)(mat,b,x);
    3695:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
    3696:   PetscObjectStateIncrease((PetscObject)x);
    3697:   return(0);
    3698: }

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

    3703:    Neighbor-wise Collective on Mat

    3705:    Input Parameters:
    3706: +  mat - the factored matrix
    3707: .  b - the right-hand-side vector
    3708: -  y - the vector to be added to

    3710:    Output Parameter:
    3711: .  x - the result vector

    3713:    Notes:
    3714:    The vectors b and x cannot be the same.  I.e., one cannot
    3715:    call MatSolveAdd(A,x,y,x).

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

    3721:    Level: developer

    3723: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
    3724: @*/
    3725: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
    3726: {
    3727:   PetscScalar    one = 1.0;
    3728:   Vec            tmp;

    3740:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    3741:   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);
    3742:   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);
    3743:   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);
    3744:   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);
    3745:   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);
    3746:   if (!mat->rmap->N && !mat->cmap->N) return(0);
    3747:    MatCheckPreallocated(mat,1);

    3749:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
    3750:   if (mat->factorerrortype) {
    3751:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
    3752:     VecSetInf(x);
    3753:   } else if (mat->ops->solveadd) {
    3754:     (*mat->ops->solveadd)(mat,b,y,x);
    3755:   } else {
    3756:     /* do the solve then the add manually */
    3757:     if (x != y) {
    3758:       MatSolve(mat,b,x);
    3759:       VecAXPY(x,one,y);
    3760:     } else {
    3761:       VecDuplicate(x,&tmp);
    3762:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
    3763:       VecCopy(x,tmp);
    3764:       MatSolve(mat,b,x);
    3765:       VecAXPY(x,one,tmp);
    3766:       VecDestroy(&tmp);
    3767:     }
    3768:   }
    3769:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
    3770:   PetscObjectStateIncrease((PetscObject)x);
    3771:   return(0);
    3772: }

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

    3777:    Neighbor-wise Collective on Mat

    3779:    Input Parameters:
    3780: +  mat - the factored matrix
    3781: -  b - the right-hand-side vector

    3783:    Output Parameter:
    3784: .  x - the result vector

    3786:    Notes:
    3787:    The vectors b and x cannot be the same.  I.e., one cannot
    3788:    call MatSolveTranspose(A,x,x).

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

    3794:    Level: developer

    3796: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
    3797: @*/
    3798: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
    3799: {

    3809:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    3810:   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);
    3811:   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);
    3812:   if (!mat->rmap->N && !mat->cmap->N) return(0);
    3813:   MatCheckPreallocated(mat,1);
    3814:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
    3815:   if (mat->factorerrortype) {
    3816:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
    3817:     VecSetInf(x);
    3818:   } else {
    3819:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
    3820:     (*mat->ops->solvetranspose)(mat,b,x);
    3821:   }
    3822:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
    3823:   PetscObjectStateIncrease((PetscObject)x);
    3824:   return(0);
    3825: }

    3827: /*@
    3828:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
    3829:                       factored matrix.

    3831:    Neighbor-wise Collective on Mat

    3833:    Input Parameters:
    3834: +  mat - the factored matrix
    3835: .  b - the right-hand-side vector
    3836: -  y - the vector to be added to

    3838:    Output Parameter:
    3839: .  x - the result vector

    3841:    Notes:
    3842:    The vectors b and x cannot be the same.  I.e., one cannot
    3843:    call MatSolveTransposeAdd(A,x,y,x).

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

    3849:    Level: developer

    3851: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
    3852: @*/
    3853: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
    3854: {
    3855:   PetscScalar    one = 1.0;
    3857:   Vec            tmp;

    3868:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    3869:   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);
    3870:   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);
    3871:   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);
    3872:   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);
    3873:   if (!mat->rmap->N && !mat->cmap->N) return(0);
    3874:    MatCheckPreallocated(mat,1);

    3876:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
    3877:   if (mat->factorerrortype) {
    3878:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
    3879:     VecSetInf(x);
    3880:   } else if (mat->ops->solvetransposeadd){
    3881:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
    3882:   } else {
    3883:     /* do the solve then the add manually */
    3884:     if (x != y) {
    3885:       MatSolveTranspose(mat,b,x);
    3886:       VecAXPY(x,one,y);
    3887:     } else {
    3888:       VecDuplicate(x,&tmp);
    3889:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
    3890:       VecCopy(x,tmp);
    3891:       MatSolveTranspose(mat,b,x);
    3892:       VecAXPY(x,one,tmp);
    3893:       VecDestroy(&tmp);
    3894:     }
    3895:   }
    3896:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
    3897:   PetscObjectStateIncrease((PetscObject)x);
    3898:   return(0);
    3899: }
    3900: /* ----------------------------------------------------------------*/

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

    3905:    Neighbor-wise Collective on Mat

    3907:    Input Parameters:
    3908: +  mat - the matrix
    3909: .  b - the right hand side
    3910: .  omega - the relaxation factor
    3911: .  flag - flag indicating the type of SOR (see below)
    3912: .  shift -  diagonal shift
    3913: .  its - the number of iterations
    3914: -  lits - the number of local iterations

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

    3919:    SOR Flags:
    3920: +     SOR_FORWARD_SWEEP - forward SOR
    3921: .     SOR_BACKWARD_SWEEP - backward SOR
    3922: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
    3923: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
    3924: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
    3925: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
    3926: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
    3927:          upper/lower triangular part of matrix to
    3928:          vector (with omega)
    3929: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

    3931:    Notes:
    3932:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
    3933:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
    3934:    on each processor.

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

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

    3942:    Notes for Advanced Users:
    3943:    The flags are implemented as bitwise inclusive or operations.
    3944:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
    3945:    to specify a zero initial guess for SSOR.

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

    3951:    Vectors x and b CANNOT be the same

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

    3955:    Level: developer

    3957: @*/
    3958: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
    3959: {

    3969:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    3970:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    3971:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    3972:   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);
    3973:   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);
    3974:   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);
    3975:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
    3976:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
    3977:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

    3979:   MatCheckPreallocated(mat,1);
    3980:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
    3981:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
    3982:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
    3983:   PetscObjectStateIncrease((PetscObject)x);
    3984:   return(0);
    3985: }

    3987: /*
    3988:       Default matrix copy routine.
    3989: */
    3990: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
    3991: {
    3992:   PetscErrorCode    ierr;
    3993:   PetscInt          i,rstart = 0,rend = 0,nz;
    3994:   const PetscInt    *cwork;
    3995:   const PetscScalar *vwork;

    3998:   if (B->assembled) {
    3999:     MatZeroEntries(B);
    4000:   }
    4001:   if (str == SAME_NONZERO_PATTERN) {
    4002:     MatGetOwnershipRange(A,&rstart,&rend);
    4003:     for (i=rstart; i<rend; i++) {
    4004:       MatGetRow(A,i,&nz,&cwork,&vwork);
    4005:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
    4006:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
    4007:     }
    4008:   } else {
    4009:     MatAYPX(B,0.0,A,str);
    4010:   }
    4011:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
    4012:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
    4013:   return(0);
    4014: }

    4016: /*@
    4017:    MatCopy - Copies a matrix to another matrix.

    4019:    Collective on Mat

    4021:    Input Parameters:
    4022: +  A - the matrix
    4023: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

    4025:    Output Parameter:
    4026: .  B - where the copy is put

    4028:    Notes:
    4029:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
    4030:    same nonzero pattern or the routine will crash.

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

    4036:    Level: intermediate

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

    4040: @*/
    4041: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
    4042: {
    4044:   PetscInt       i;

    4052:   MatCheckPreallocated(B,2);
    4053:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    4054:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    4055:   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);
    4056:   MatCheckPreallocated(A,1);
    4057:   if (A == B) return(0);

    4059:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
    4060:   if (A->ops->copy) {
    4061:     (*A->ops->copy)(A,B,str);
    4062:   } else { /* generic conversion */
    4063:     MatCopy_Basic(A,B,str);
    4064:   }

    4066:   B->stencil.dim = A->stencil.dim;
    4067:   B->stencil.noc = A->stencil.noc;
    4068:   for (i=0; i<=A->stencil.dim; i++) {
    4069:     B->stencil.dims[i]   = A->stencil.dims[i];
    4070:     B->stencil.starts[i] = A->stencil.starts[i];
    4071:   }

    4073:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
    4074:   PetscObjectStateIncrease((PetscObject)B);
    4075:   return(0);
    4076: }

    4078: /*@C
    4079:    MatConvert - Converts a matrix to another matrix, either of the same
    4080:    or different type.

    4082:    Collective on Mat

    4084:    Input Parameters:
    4085: +  mat - the matrix
    4086: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
    4087:    same type as the original matrix.
    4088: -  reuse - denotes if the destination matrix is to be created or reused.
    4089:    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
    4090:    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).

    4092:    Output Parameter:
    4093: .  M - pointer to place new matrix

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

    4100:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
    4101:    the MPI communicator of the generated matrix is always the same as the communicator
    4102:    of the input matrix.

    4104:    Level: intermediate

    4106: .seealso: MatCopy(), MatDuplicate()
    4107: @*/
    4108: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
    4109: {
    4111:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
    4112:   char           convname[256],mtype[256];
    4113:   Mat            B;

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

    4123:   PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
    4124:   if (flg) newtype = mtype;

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

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

    4136:   /* Cache Mat options because some converter use MatHeaderReplace  */
    4137:   issymmetric = mat->symmetric;
    4138:   ishermitian = mat->hermitian;

    4140:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
    4141:     PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
    4142:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
    4143:   } else {
    4144:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
    4145:     const char     *prefix[3] = {"seq","mpi",""};
    4146:     PetscInt       i;
    4147:     /*
    4148:        Order of precedence:
    4149:        0) See if newtype is a superclass of the current matrix.
    4150:        1) See if a specialized converter is known to the current matrix.
    4151:        2) See if a specialized converter is known to the desired matrix class.
    4152:        3) See if a good general converter is registered for the desired class
    4153:           (as of 6/27/03 only MATMPIADJ falls into this category).
    4154:        4) See if a good general converter is known for the current matrix.
    4155:        5) Use a really basic converter.
    4156:     */

    4158:     /* 0) See if newtype is a superclass of the current matrix.
    4159:           i.e mat is mpiaij and newtype is aij */
    4160:     for (i=0; i<2; i++) {
    4161:       PetscStrncpy(convname,prefix[i],sizeof(convname));
    4162:       PetscStrlcat(convname,newtype,sizeof(convname));
    4163:       PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
    4164:       PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
    4165:       if (flg) {
    4166:         if (reuse == MAT_INPLACE_MATRIX) {
    4167:           return(0);
    4168:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
    4169:           (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
    4170:           return(0);
    4171:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
    4172:           MatCopy(mat,*M,SAME_NONZERO_PATTERN);
    4173:           return(0);
    4174:         }
    4175:       }
    4176:     }
    4177:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
    4178:     for (i=0; i<3; i++) {
    4179:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
    4180:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
    4181:       PetscStrlcat(convname,"_",sizeof(convname));
    4182:       PetscStrlcat(convname,prefix[i],sizeof(convname));
    4183:       PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
    4184:       PetscStrlcat(convname,"_C",sizeof(convname));
    4185:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
    4186:       PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
    4187:       if (conv) goto foundconv;
    4188:     }

    4190:     /* 2)  See if a specialized converter is known to the desired matrix class. */
    4191:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
    4192:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
    4193:     MatSetType(B,newtype);
    4194:     for (i=0; i<3; i++) {
    4195:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
    4196:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
    4197:       PetscStrlcat(convname,"_",sizeof(convname));
    4198:       PetscStrlcat(convname,prefix[i],sizeof(convname));
    4199:       PetscStrlcat(convname,newtype,sizeof(convname));
    4200:       PetscStrlcat(convname,"_C",sizeof(convname));
    4201:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
    4202:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
    4203:       if (conv) {
    4204:         MatDestroy(&B);
    4205:         goto foundconv;
    4206:       }
    4207:     }

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

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

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

    4221:     /* 5) Use a really basic converter. */
    4222:     PetscInfo(mat,"Using MatConvert_Basic\n");
    4223:     conv = MatConvert_Basic;

    4225: foundconv:
    4226:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
    4227:     (*conv)(mat,newtype,reuse,M);
    4228:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
    4229:       /* the block sizes must be same if the mappings are copied over */
    4230:       (*M)->rmap->bs = mat->rmap->bs;
    4231:       (*M)->cmap->bs = mat->cmap->bs;
    4232:       PetscObjectReference((PetscObject)mat->rmap->mapping);
    4233:       PetscObjectReference((PetscObject)mat->cmap->mapping);
    4234:       (*M)->rmap->mapping = mat->rmap->mapping;
    4235:       (*M)->cmap->mapping = mat->cmap->mapping;
    4236:     }
    4237:     (*M)->stencil.dim = mat->stencil.dim;
    4238:     (*M)->stencil.noc = mat->stencil.noc;
    4239:     for (i=0; i<=mat->stencil.dim; i++) {
    4240:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
    4241:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
    4242:     }
    4243:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
    4244:   }
    4245:   PetscObjectStateIncrease((PetscObject)*M);

    4247:   /* Copy Mat options */
    4248:   if (issymmetric) {
    4249:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
    4250:   }
    4251:   if (ishermitian) {
    4252:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
    4253:   }
    4254:   return(0);
    4255: }

    4257: /*@C
    4258:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

    4260:    Not Collective

    4262:    Input Parameter:
    4263: .  mat - the matrix, must be a factored matrix

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

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

    4272:    Level: intermediate

    4274: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
    4275: @*/
    4276: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
    4277: {
    4278:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

    4283:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
    4284:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
    4285:   if (!conv) {
    4286:     *type = MATSOLVERPETSC;
    4287:   } else {
    4288:     (*conv)(mat,type);
    4289:   }
    4290:   return(0);
    4291: }

    4293: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
    4294: struct _MatSolverTypeForSpecifcType {
    4295:   MatType                        mtype;
    4296:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
    4297:   MatSolverTypeForSpecifcType next;
    4298: };

    4300: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
    4301: struct _MatSolverTypeHolder {
    4302:   char                           *name;
    4303:   MatSolverTypeForSpecifcType handlers;
    4304:   MatSolverTypeHolder         next;
    4305: };

    4307: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

    4312:    Input Parameters:
    4313: +    package - name of the package, for example petsc or superlu
    4314: .    mtype - the matrix type that works with this package
    4315: .    ftype - the type of factorization supported by the package
    4316: -    getfactor - routine that will create the factored matrix ready to be used

    4318:     Level: intermediate

    4320: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
    4321: @*/
    4322: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
    4323: {
    4324:   PetscErrorCode              ierr;
    4325:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
    4326:   PetscBool                   flg;
    4327:   MatSolverTypeForSpecifcType inext,iprev = NULL;

    4330:   MatInitializePackage();
    4331:   if (!next) {
    4332:     PetscNew(&MatSolverTypeHolders);
    4333:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
    4334:     PetscNew(&MatSolverTypeHolders->handlers);
    4335:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
    4336:     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
    4337:     return(0);
    4338:   }
    4339:   while (next) {
    4340:     PetscStrcasecmp(package,next->name,&flg);
    4341:     if (flg) {
    4342:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
    4343:       inext = next->handlers;
    4344:       while (inext) {
    4345:         PetscStrcasecmp(mtype,inext->mtype,&flg);
    4346:         if (flg) {
    4347:           inext->getfactor[(int)ftype-1] = getfactor;
    4348:           return(0);
    4349:         }
    4350:         iprev = inext;
    4351:         inext = inext->next;
    4352:       }
    4353:       PetscNew(&iprev->next);
    4354:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
    4355:       iprev->next->getfactor[(int)ftype-1] = getfactor;
    4356:       return(0);
    4357:     }
    4358:     prev = next;
    4359:     next = next->next;
    4360:   }
    4361:   PetscNew(&prev->next);
    4362:   PetscStrallocpy(package,&prev->next->name);
    4363:   PetscNew(&prev->next->handlers);
    4364:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
    4365:   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
    4366:   return(0);
    4367: }

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

    4372:    Input Parameters:
    4373: +    package - name of the package, for example petsc or superlu
    4374: .    ftype - the type of factorization supported by the package
    4375: -    mtype - the matrix type that works with this package

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

    4382:     Level: intermediate

    4384: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
    4385: @*/
    4386: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
    4387: {
    4388:   PetscErrorCode              ierr;
    4389:   MatSolverTypeHolder         next = MatSolverTypeHolders;
    4390:   PetscBool                   flg;
    4391:   MatSolverTypeForSpecifcType inext;

    4394:   if (foundpackage) *foundpackage = PETSC_FALSE;
    4395:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
    4396:   if (getfactor)    *getfactor    = NULL;

    4398:   if (package) {
    4399:     while (next) {
    4400:       PetscStrcasecmp(package,next->name,&flg);
    4401:       if (flg) {
    4402:         if (foundpackage) *foundpackage = PETSC_TRUE;
    4403:         inext = next->handlers;
    4404:         while (inext) {
    4405:           PetscStrbeginswith(mtype,inext->mtype,&flg);
    4406:           if (flg) {
    4407:             if (foundmtype) *foundmtype = PETSC_TRUE;
    4408:             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
    4409:             return(0);
    4410:           }
    4411:           inext = inext->next;
    4412:         }
    4413:       }
    4414:       next = next->next;
    4415:     }
    4416:   } else {
    4417:     while (next) {
    4418:       inext = next->handlers;
    4419:       while (inext) {
    4420:         PetscStrbeginswith(mtype,inext->mtype,&flg);
    4421:         if (flg && inext->getfactor[(int)ftype-1]) {
    4422:           if (foundpackage) *foundpackage = PETSC_TRUE;
    4423:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
    4424:           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
    4425:           return(0);
    4426:         }
    4427:         inext = inext->next;
    4428:       }
    4429:       next = next->next;
    4430:     }
    4431:   }
    4432:   return(0);
    4433: }

    4435: PetscErrorCode MatSolverTypeDestroy(void)
    4436: {
    4437:   PetscErrorCode              ierr;
    4438:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
    4439:   MatSolverTypeForSpecifcType inext,iprev;

    4442:   while (next) {
    4443:     PetscFree(next->name);
    4444:     inext = next->handlers;
    4445:     while (inext) {
    4446:       PetscFree(inext->mtype);
    4447:       iprev = inext;
    4448:       inext = inext->next;
    4449:       PetscFree(iprev);
    4450:     }
    4451:     prev = next;
    4452:     next = next->next;
    4453:     PetscFree(prev);
    4454:   }
    4455:   MatSolverTypeHolders = NULL;
    4456:   return(0);
    4457: }

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

    4462:    Collective on Mat

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

    4469:    Output Parameters:
    4470: .  f - the factor matrix used with MatXXFactorSymbolic() calls

    4472:    Notes:
    4473:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
    4474:      such as pastix, superlu, mumps etc.

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

    4478:    Level: intermediate

    4480: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
    4481: @*/
    4482: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
    4483: {
    4484:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
    4485:   PetscBool      foundpackage,foundmtype;

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

    4494:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
    4495:   if (!foundpackage) {
    4496:     if (type) {
    4497:       SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s for factorization type %s and matrix type %s. Perhaps you must ./configure with --download-%s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name,type);
    4498:     } else {
    4499:       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package for factorization type %s and matrix type %s.",MatFactorTypes[ftype],((PetscObject)mat)->type_name);
    4500:     }
    4501:   }
    4502:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
    4503:   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);

    4505:   (*conv)(mat,ftype,f);
    4506:   return(0);
    4507: }

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

    4512:    Not Collective

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

    4519:    Output Parameter:
    4520: .    flg - PETSC_TRUE if the factorization is available

    4522:    Notes:
    4523:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
    4524:      such as pastix, superlu, mumps etc.

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

    4528:    Level: intermediate

    4530: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
    4531: @*/
    4532: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
    4533: {
    4534:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);

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

    4543:   *flg = PETSC_FALSE;
    4544:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
    4545:   if (gconv) {
    4546:     *flg = PETSC_TRUE;
    4547:   }
    4548:   return(0);
    4549: }

    4551:  #include <petscdmtypes.h>

    4553: /*@
    4554:    MatDuplicate - Duplicates a matrix including the non-zero structure.

    4556:    Collective on Mat

    4558:    Input Parameters:
    4559: +  mat - the matrix
    4560: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
    4561:         See the manual page for MatDuplicateOption for an explanation of these options.

    4563:    Output Parameter:
    4564: .  M - pointer to place new matrix

    4566:    Level: intermediate

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

    4572: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
    4573: @*/
    4574: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
    4575: {
    4577:   Mat            B;
    4578:   PetscInt       i;
    4579:   DM             dm;
    4580:   void           (*viewf)(void);

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

    4590:   *M = 0;
    4591:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
    4592:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
    4593:   (*mat->ops->duplicate)(mat,op,M);
    4594:   B    = *M;

    4596:   MatGetOperation(mat,MATOP_VIEW,&viewf);
    4597:   if (viewf) {
    4598:     MatSetOperation(B,MATOP_VIEW,viewf);
    4599:   }

    4601:   B->stencil.dim = mat->stencil.dim;
    4602:   B->stencil.noc = mat->stencil.noc;
    4603:   for (i=0; i<=mat->stencil.dim; i++) {
    4604:     B->stencil.dims[i]   = mat->stencil.dims[i];
    4605:     B->stencil.starts[i] = mat->stencil.starts[i];
    4606:   }

    4608:   B->nooffproczerorows = mat->nooffproczerorows;
    4609:   B->nooffprocentries  = mat->nooffprocentries;

    4611:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
    4612:   if (dm) {
    4613:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
    4614:   }
    4615:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
    4616:   PetscObjectStateIncrease((PetscObject)B);
    4617:   return(0);
    4618: }

    4620: /*@
    4621:    MatGetDiagonal - Gets the diagonal of a matrix.

    4623:    Logically Collective on Mat

    4625:    Input Parameters:
    4626: +  mat - the matrix
    4627: -  v - the vector for storing the diagonal

    4629:    Output Parameter:
    4630: .  v - the diagonal of the matrix

    4632:    Level: intermediate

    4634:    Note:
    4635:    Currently only correct in parallel for square matrices.

    4637: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
    4638: @*/
    4639: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
    4640: {

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

    4651:   (*mat->ops->getdiagonal)(mat,v);
    4652:   PetscObjectStateIncrease((PetscObject)v);
    4653:   return(0);
    4654: }

    4656: /*@C
    4657:    MatGetRowMin - Gets the minimum value (of the real part) of each
    4658:         row of the matrix

    4660:    Logically Collective on Mat

    4662:    Input Parameters:
    4663: .  mat - the matrix

    4665:    Output Parameter:
    4666: +  v - the vector for storing the maximums
    4667: -  idx - the indices of the column found for each row (optional)

    4669:    Level: intermediate

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

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

    4677: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
    4678:           MatGetRowMax()
    4679: @*/
    4680: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
    4681: {

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

    4692:   (*mat->ops->getrowmin)(mat,v,idx);
    4693:   PetscObjectStateIncrease((PetscObject)v);
    4694:   return(0);
    4695: }

    4697: /*@C
    4698:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
    4699:         row of the matrix

    4701:    Logically Collective on Mat

    4703:    Input Parameters:
    4704: .  mat - the matrix

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

    4710:    Level: intermediate

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

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

    4718: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
    4719: @*/
    4720: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
    4721: {

    4728:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    4729:   if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    4730:   MatCheckPreallocated(mat,1);
    4731:   if (idx) {PetscArrayzero(idx,mat->rmap->n);}

    4733:   (*mat->ops->getrowminabs)(mat,v,idx);
    4734:   PetscObjectStateIncrease((PetscObject)v);
    4735:   return(0);
    4736: }

    4738: /*@C
    4739:    MatGetRowMax - Gets the maximum value (of the real part) of each
    4740:         row of the matrix

    4742:    Logically Collective on Mat

    4744:    Input Parameters:
    4745: .  mat - the matrix

    4747:    Output Parameter:
    4748: +  v - the vector for storing the maximums
    4749: -  idx - the indices of the column found for each row (optional)

    4751:    Level: intermediate

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

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

    4759: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
    4760: @*/
    4761: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
    4762: {

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

    4773:   (*mat->ops->getrowmax)(mat,v,idx);
    4774:   PetscObjectStateIncrease((PetscObject)v);
    4775:   return(0);
    4776: }

    4778: /*@C
    4779:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
    4780:         row of the matrix

    4782:    Logically Collective on Mat

    4784:    Input Parameters:
    4785: .  mat - the matrix

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

    4791:    Level: intermediate

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

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

    4799: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
    4800: @*/
    4801: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
    4802: {

    4809:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    4810:   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    4811:   MatCheckPreallocated(mat,1);
    4812:   if (idx) {PetscArrayzero(idx,mat->rmap->n);}

    4814:   (*mat->ops->getrowmaxabs)(mat,v,idx);
    4815:   PetscObjectStateIncrease((PetscObject)v);
    4816:   return(0);
    4817: }

    4819: /*@
    4820:    MatGetRowSum - Gets the sum of each row of the matrix

    4822:    Logically or Neighborhood Collective on Mat

    4824:    Input Parameters:
    4825: .  mat - the matrix

    4827:    Output Parameter:
    4828: .  v - the vector for storing the sum of rows

    4830:    Level: intermediate

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

    4835: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
    4836: @*/
    4837: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
    4838: {
    4839:   Vec            ones;

    4846:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    4847:   MatCheckPreallocated(mat,1);
    4848:   MatCreateVecs(mat,&ones,NULL);
    4849:   VecSet(ones,1.);
    4850:   MatMult(mat,ones,v);
    4851:   VecDestroy(&ones);
    4852:   return(0);
    4853: }

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

    4858:    Collective on Mat

    4860:    Input Parameter:
    4861: +  mat - the matrix to transpose
    4862: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

    4864:    Output Parameters:
    4865: .  B - the transpose

    4867:    Notes:
    4868:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

    4874:    Level: intermediate

    4876: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
    4877: @*/
    4878: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
    4879: {

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

    4892:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
    4893:   (*mat->ops->transpose)(mat,reuse,B);
    4894:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
    4895:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
    4896:   return(0);
    4897: }

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

    4903:    Collective on Mat

    4905:    Input Parameter:
    4906: +  A - the matrix to test
    4907: -  B - the matrix to test against, this can equal the first parameter

    4909:    Output Parameters:
    4910: .  flg - the result

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

    4917:    Level: intermediate

    4919: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
    4920: @*/
    4921: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
    4922: {
    4923:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

    4929:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
    4930:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
    4931:   *flg = PETSC_FALSE;
    4932:   if (f && g) {
    4933:     if (f == g) {
    4934:       (*f)(A,B,tol,flg);
    4935:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
    4936:   } else {
    4937:     MatType mattype;
    4938:     if (!f) {
    4939:       MatGetType(A,&mattype);
    4940:     } else {
    4941:       MatGetType(B,&mattype);
    4942:     }
    4943:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
    4944:   }
    4945:   return(0);
    4946: }

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

    4951:    Collective on Mat

    4953:    Input Parameter:
    4954: +  mat - the matrix to transpose and complex conjugate
    4955: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

    4957:    Output Parameters:
    4958: .  B - the Hermitian

    4960:    Level: intermediate

    4962: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
    4963: @*/
    4964: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
    4965: {

    4969:   MatTranspose(mat,reuse,B);
    4970: #if defined(PETSC_USE_COMPLEX)
    4971:   MatConjugate(*B);
    4972: #endif
    4973:   return(0);
    4974: }

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

    4979:    Collective on Mat

    4981:    Input Parameter:
    4982: +  A - the matrix to test
    4983: -  B - the matrix to test against, this can equal the first parameter

    4985:    Output Parameters:
    4986: .  flg - the result

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

    4993:    Level: intermediate

    4995: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
    4996: @*/
    4997: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
    4998: {
    4999:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

    5005:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
    5006:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
    5007:   if (f && g) {
    5008:     if (f==g) {
    5009:       (*f)(A,B,tol,flg);
    5010:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
    5011:   }
    5012:   return(0);
    5013: }

    5015: /*@
    5016:    MatPermute - Creates a new matrix with rows and columns permuted from the
    5017:    original.

    5019:    Collective on Mat

    5021:    Input Parameters:
    5022: +  mat - the matrix to permute
    5023: .  row - row permutation, each processor supplies only the permutation for its rows
    5024: -  col - column permutation, each processor supplies only the permutation for its columns

    5026:    Output Parameters:
    5027: .  B - the permuted matrix

    5029:    Level: advanced

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

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

    5037: @*/
    5038: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
    5039: {

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

    5053:   (*mat->ops->permute)(mat,row,col,B);
    5054:   PetscObjectStateIncrease((PetscObject)*B);
    5055:   return(0);
    5056: }

    5058: /*@
    5059:    MatEqual - Compares two matrices.

    5061:    Collective on Mat

    5063:    Input Parameters:
    5064: +  A - the first matrix
    5065: -  B - the second matrix

    5067:    Output Parameter:
    5068: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

    5070:    Level: intermediate

    5072: @*/
    5073: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
    5074: {

    5084:   MatCheckPreallocated(B,2);
    5085:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    5086:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    5087:   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);
    5088:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
    5089:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
    5090:   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);
    5091:   MatCheckPreallocated(A,1);

    5093:   (*A->ops->equal)(A,B,flg);
    5094:   return(0);
    5095: }

    5097: /*@
    5098:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
    5099:    matrices that are stored as vectors.  Either of the two scaling
    5100:    matrices can be NULL.

    5102:    Collective on Mat

    5104:    Input Parameters:
    5105: +  mat - the matrix to be scaled
    5106: .  l - the left scaling vector (or NULL)
    5107: -  r - the right scaling vector (or NULL)

    5109:    Notes:
    5110:    MatDiagonalScale() computes A = LAR, where
    5111:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
    5112:    The L scales the rows of the matrix, the R scales the columns of the matrix.

    5114:    Level: intermediate

    5117: .seealso: MatScale(), MatShift(), MatDiagonalSet()
    5118: @*/
    5119: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
    5120: {

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

    5133:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
    5134:   (*mat->ops->diagonalscale)(mat,l,r);
    5135:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
    5136:   PetscObjectStateIncrease((PetscObject)mat);
    5137:   return(0);
    5138: }

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

    5143:     Logically Collective on Mat

    5145:     Input Parameters:
    5146: +   mat - the matrix to be scaled
    5147: -   a  - the scaling value

    5149:     Output Parameter:
    5150: .   mat - the scaled matrix

    5152:     Level: intermediate

    5154: .seealso: MatDiagonalScale()
    5155: @*/
    5156: PetscErrorCode MatScale(Mat mat,PetscScalar a)
    5157: {

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

    5169:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
    5170:   if (a != (PetscScalar)1.0) {
    5171:     (*mat->ops->scale)(mat,a);
    5172:     PetscObjectStateIncrease((PetscObject)mat);
    5173:   }
    5174:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
    5175:   return(0);
    5176: }

    5178: /*@
    5179:    MatNorm - Calculates various norms of a matrix.

    5181:    Collective on Mat

    5183:    Input Parameters:
    5184: +  mat - the matrix
    5185: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

    5187:    Output Parameters:
    5188: .  nrm - the resulting norm

    5190:    Level: intermediate

    5192: @*/
    5193: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
    5194: {

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

    5207:   (*mat->ops->norm)(mat,type,nrm);
    5208:   return(0);
    5209: }

    5211: /*
    5212:      This variable is used to prevent counting of MatAssemblyBegin() that
    5213:    are called from within a MatAssemblyEnd().
    5214: */
    5215: static PetscInt MatAssemblyEnd_InUse = 0;
    5216: /*@
    5217:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
    5218:    be called after completing all calls to MatSetValues().

    5220:    Collective on Mat

    5222:    Input Parameters:
    5223: +  mat - the matrix
    5224: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

    5226:    Notes:
    5227:    MatSetValues() generally caches the values.  The matrix is ready to
    5228:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
    5229:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
    5230:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
    5231:    using the matrix.

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

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

    5241:    Level: beginner

    5243: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
    5244: @*/
    5245: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
    5246: {

    5252:   MatCheckPreallocated(mat,1);
    5253:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
    5254:   if (mat->assembled) {
    5255:     mat->was_assembled = PETSC_TRUE;
    5256:     mat->assembled     = PETSC_FALSE;
    5257:   }

    5259:   if (!MatAssemblyEnd_InUse) {
    5260:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
    5261:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
    5262:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
    5263:   } else if (mat->ops->assemblybegin) {
    5264:     (*mat->ops->assemblybegin)(mat,type);
    5265:   }
    5266:   return(0);
    5267: }

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

    5273:    Not Collective

    5275:    Input Parameter:
    5276: .  mat - the matrix

    5278:    Output Parameter:
    5279: .  assembled - PETSC_TRUE or PETSC_FALSE

    5281:    Level: advanced

    5283: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
    5284: @*/
    5285: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
    5286: {
    5290:   *assembled = mat->assembled;
    5291:   return(0);
    5292: }

    5294: /*@
    5295:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
    5296:    be called after MatAssemblyBegin().

    5298:    Collective on Mat

    5300:    Input Parameters:
    5301: +  mat - the matrix
    5302: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

    5304:    Options Database Keys:
    5305: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
    5306: .  -mat_view ::ascii_info_detail - Prints more detailed info
    5307: .  -mat_view - Prints matrix in ASCII format
    5308: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
    5309: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
    5310: .  -display <name> - Sets display name (default is host)
    5311: .  -draw_pause <sec> - Sets number of seconds to pause after display
    5312: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
    5313: .  -viewer_socket_machine <machine> - Machine to use for socket
    5314: .  -viewer_socket_port <port> - Port number to use for socket
    5315: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

    5317:    Notes:
    5318:    MatSetValues() generally caches the values.  The matrix is ready to
    5319:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
    5320:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
    5321:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
    5322:    using the matrix.

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

    5328:    Level: beginner

    5330: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
    5331: @*/
    5332: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
    5333: {
    5334:   PetscErrorCode  ierr;
    5335:   static PetscInt inassm = 0;
    5336:   PetscBool       flg    = PETSC_FALSE;

    5342:   inassm++;
    5343:   MatAssemblyEnd_InUse++;
    5344:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
    5345:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
    5346:     if (mat->ops->assemblyend) {
    5347:       (*mat->ops->assemblyend)(mat,type);
    5348:     }
    5349:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
    5350:   } else if (mat->ops->assemblyend) {
    5351:     (*mat->ops->assemblyend)(mat,type);
    5352:   }

    5354:   /* Flush assembly is not a true assembly */
    5355:   if (type != MAT_FLUSH_ASSEMBLY) {
    5356:     mat->num_ass++;
    5357:     mat->assembled        = PETSC_TRUE;
    5358:     mat->ass_nonzerostate = mat->nonzerostate;
    5359:   }

    5361:   mat->insertmode = NOT_SET_VALUES;
    5362:   MatAssemblyEnd_InUse--;
    5363:   PetscObjectStateIncrease((PetscObject)mat);
    5364:   if (!mat->symmetric_eternal) {
    5365:     mat->symmetric_set              = PETSC_FALSE;
    5366:     mat->hermitian_set              = PETSC_FALSE;
    5367:     mat->structurally_symmetric_set = PETSC_FALSE;
    5368:   }
    5369:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
    5370:     MatViewFromOptions(mat,NULL,"-mat_view");

    5372:     if (mat->checksymmetryonassembly) {
    5373:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
    5374:       if (flg) {
    5375:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
    5376:       } else {
    5377:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
    5378:       }
    5379:     }
    5380:     if (mat->nullsp && mat->checknullspaceonassembly) {
    5381:       MatNullSpaceTest(mat->nullsp,mat,NULL);
    5382:     }
    5383:   }
    5384:   inassm--;
    5385:   return(0);
    5386: }

    5388: /*@
    5389:    MatSetOption - Sets a parameter option for a matrix. Some options
    5390:    may be specific to certain storage formats.  Some options
    5391:    determine how values will be inserted (or added). Sorted,
    5392:    row-oriented input will generally assemble the fastest. The default
    5393:    is row-oriented.

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

    5397:    Input Parameters:
    5398: +  mat - the matrix
    5399: .  option - the option, one of those listed below (and possibly others),
    5400: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

    5402:   Options Describing Matrix Structure:
    5403: +    MAT_SPD - symmetric positive definite
    5404: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
    5405: .    MAT_HERMITIAN - transpose is the complex conjugation
    5406: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
    5407: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
    5408:                             you set to be kept with all future use of the matrix
    5409:                             including after MatAssemblyBegin/End() which could
    5410:                             potentially change the symmetry structure, i.e. you
    5411:                             KNOW the matrix will ALWAYS have the property you set.
    5412:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
    5413:                             the relevant flags must be set independently.

    5416:    Options For Use with MatSetValues():
    5417:    Insert a logically dense subblock, which can be
    5418: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

    5456:    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
    5457:    that would generate a new entry in the nonzero structure instead produces
    5458:    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

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

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

    5472:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
    5473:    searches during matrix assembly. When this flag is set, the hash table
    5474:    is created during the first Matrix Assembly. This hash table is
    5475:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
    5476:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
    5477:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
    5478:    supported by MATMPIBAIJ format only.

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

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

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

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

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

    5494:    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
    5495:                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
    5496:                      with finite difference schemes with non-periodic boundary conditions.
    5497:    Notes:
    5498:     Can only be called after MatSetSizes() and MatSetType() have been set.

    5500:    Level: intermediate

    5502: .seealso:  MatOption, Mat

    5504: @*/
    5505: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
    5506: {

    5512:   if (op > 0) {
    5515:   }

    5517:   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);
    5518:   if (!((PetscObject)mat)->type_name) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_TYPENOTSET,"Cannot set options until type and size have been set, see MatSetType() and MatSetSizes()");

    5520:   switch (op) {
    5521:   case MAT_NO_OFF_PROC_ENTRIES:
    5522:     mat->nooffprocentries = flg;
    5523:     return(0);
    5524:     break;
    5525:   case MAT_SUBSET_OFF_PROC_ENTRIES:
    5526:     mat->assembly_subset = flg;
    5527:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
    5528: #if !defined(PETSC_HAVE_MPIUNI)
    5529:       MatStashScatterDestroy_BTS(&mat->stash);
    5530: #endif
    5531:       mat->stash.first_assembly_done = PETSC_FALSE;
    5532:     }
    5533:     return(0);
    5534:   case MAT_NO_OFF_PROC_ZERO_ROWS:
    5535:     mat->nooffproczerorows = flg;
    5536:     return(0);
    5537:     break;
    5538:   case MAT_SPD:
    5539:     mat->spd_set = PETSC_TRUE;
    5540:     mat->spd     = flg;
    5541:     if (flg) {
    5542:       mat->symmetric                  = PETSC_TRUE;
    5543:       mat->structurally_symmetric     = PETSC_TRUE;
    5544:       mat->symmetric_set              = PETSC_TRUE;
    5545:       mat->structurally_symmetric_set = PETSC_TRUE;
    5546:     }
    5547:     break;
    5548:   case MAT_SYMMETRIC:
    5549:     mat->symmetric = flg;
    5550:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
    5551:     mat->symmetric_set              = PETSC_TRUE;
    5552:     mat->structurally_symmetric_set = flg;
    5553: #if !defined(PETSC_USE_COMPLEX)
    5554:     mat->hermitian     = flg;
    5555:     mat->hermitian_set = PETSC_TRUE;
    5556: #endif
    5557:     break;
    5558:   case MAT_HERMITIAN:
    5559:     mat->hermitian = flg;
    5560:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
    5561:     mat->hermitian_set              = PETSC_TRUE;
    5562:     mat->structurally_symmetric_set = flg;
    5563: #if !defined(PETSC_USE_COMPLEX)
    5564:     mat->symmetric     = flg;
    5565:     mat->symmetric_set = PETSC_TRUE;
    5566: #endif
    5567:     break;
    5568:   case MAT_STRUCTURALLY_SYMMETRIC:
    5569:     mat->structurally_symmetric     = flg;
    5570:     mat->structurally_symmetric_set = PETSC_TRUE;
    5571:     break;
    5572:   case MAT_SYMMETRY_ETERNAL:
    5573:     mat->symmetric_eternal = flg;
    5574:     break;
    5575:   case MAT_STRUCTURE_ONLY:
    5576:     mat->structure_only = flg;
    5577:     break;
    5578:   case MAT_SORTED_FULL:
    5579:     mat->sortedfull = flg;
    5580:     break;
    5581:   default:
    5582:     break;
    5583:   }
    5584:   if (mat->ops->setoption) {
    5585:     (*mat->ops->setoption)(mat,op,flg);
    5586:   }
    5587:   return(0);
    5588: }

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

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

    5595:    Input Parameters:
    5596: +  mat - the matrix
    5597: -  option - the option, this only responds to certain options, check the code for which ones

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

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

    5605:    Level: intermediate

    5607: .seealso:  MatOption, MatSetOption()

    5609: @*/
    5610: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
    5611: {

    5616:   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);
    5617:   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()");

    5619:   switch (op) {
    5620:   case MAT_NO_OFF_PROC_ENTRIES:
    5621:     *flg = mat->nooffprocentries;
    5622:     break;
    5623:   case MAT_NO_OFF_PROC_ZERO_ROWS:
    5624:     *flg = mat->nooffproczerorows;
    5625:     break;
    5626:   case MAT_SYMMETRIC:
    5627:     *flg = mat->symmetric;
    5628:     break;
    5629:   case MAT_HERMITIAN:
    5630:     *flg = mat->hermitian;
    5631:     break;
    5632:   case MAT_STRUCTURALLY_SYMMETRIC:
    5633:     *flg = mat->structurally_symmetric;
    5634:     break;
    5635:   case MAT_SYMMETRY_ETERNAL:
    5636:     *flg = mat->symmetric_eternal;
    5637:     break;
    5638:   case MAT_SPD:
    5639:     *flg = mat->spd;
    5640:     break;
    5641:   default:
    5642:     break;
    5643:   }
    5644:   return(0);
    5645: }

    5647: /*@
    5648:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
    5649:    this routine retains the old nonzero structure.

    5651:    Logically Collective on Mat

    5653:    Input Parameters:
    5654: .  mat - the matrix

    5656:    Level: intermediate

    5658:    Notes:
    5659:     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.
    5660:    See the Performance chapter of the users manual for information on preallocating matrices.

    5662: .seealso: MatZeroRows()
    5663: @*/
    5664: PetscErrorCode MatZeroEntries(Mat mat)
    5665: {

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

    5676:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
    5677:   (*mat->ops->zeroentries)(mat);
    5678:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
    5679:   PetscObjectStateIncrease((PetscObject)mat);
    5680:   return(0);
    5681: }

    5683: /*@
    5684:    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
    5685:    of a set of rows and columns of a matrix.

    5687:    Collective on Mat

    5689:    Input Parameters:
    5690: +  mat - the matrix
    5691: .  numRows - the number of rows to remove
    5692: .  rows - the global row indices
    5693: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
    5694: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    5695: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

    5714:    Level: intermediate

    5716: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    5717:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    5718: @*/
    5719: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    5720: {

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

    5732:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
    5733:   MatViewFromOptions(mat,NULL,"-mat_view");
    5734:   PetscObjectStateIncrease((PetscObject)mat);
    5735:   return(0);
    5736: }

    5738: /*@
    5739:    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
    5740:    of a set of rows and columns of a matrix.

    5742:    Collective on Mat

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

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

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

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

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

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

    5768:    Level: intermediate

    5770: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    5771:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
    5772: @*/
    5773: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    5774: {
    5776:   PetscInt       numRows;
    5777:   const PetscInt *rows;

    5784:   ISGetLocalSize(is,&numRows);
    5785:   ISGetIndices(is,&rows);
    5786:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
    5787:   ISRestoreIndices(is,&rows);
    5788:   return(0);
    5789: }

    5791: /*@
    5792:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
    5793:    of a set of rows of a matrix.

    5795:    Collective on Mat

    5797:    Input Parameters:
    5798: +  mat - the matrix
    5799: .  numRows - the number of rows to remove
    5800: .  rows - the global row indices
    5801: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
    5802: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    5803: -  b - optional vector of right hand side, that will be adjusted by provided solution

    5805:    Notes:
    5806:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    5807:    but does not release memory.  For the dense and block diagonal
    5808:    formats this does not alter the nonzero structure.

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

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

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

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

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

    5829:    Level: intermediate

    5831: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    5832:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    5833: @*/
    5834: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    5835: {

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

    5847:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
    5848:   MatViewFromOptions(mat,NULL,"-mat_view");
    5849:   PetscObjectStateIncrease((PetscObject)mat);
    5850:   return(0);
    5851: }

    5853: /*@
    5854:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
    5855:    of a set of rows of a matrix.

    5857:    Collective on Mat

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

    5866:    Notes:
    5867:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    5868:    but does not release memory.  For the dense and block diagonal
    5869:    formats this does not alter the nonzero structure.

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

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

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

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

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

    5890:    Level: intermediate

    5892: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    5893:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    5894: @*/
    5895: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    5896: {
    5897:   PetscInt       numRows;
    5898:   const PetscInt *rows;

    5905:   ISGetLocalSize(is,&numRows);
    5906:   ISGetIndices(is,&rows);
    5907:   MatZeroRows(mat,numRows,rows,diag,x,b);
    5908:   ISRestoreIndices(is,&rows);
    5909:   return(0);
    5910: }

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

    5916:    Collective on Mat

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

    5926:    Notes:
    5927:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    5928:    but does not release memory.  For the dense and block diagonal
    5929:    formats this does not alter the nonzero structure.

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

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

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

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

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

    5949:    In Fortran idxm and idxn should be declared as
    5950: $     MatStencil idxm(4,m)
    5951:    and the values inserted using
    5952: $    idxm(MatStencil_i,1) = i
    5953: $    idxm(MatStencil_j,1) = j
    5954: $    idxm(MatStencil_k,1) = k
    5955: $    idxm(MatStencil_c,1) = c
    5956:    etc

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

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

    5966:    Level: intermediate

    5968: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    5969:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    5970: @*/
    5971: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
    5972: {
    5973:   PetscInt       dim     = mat->stencil.dim;
    5974:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
    5975:   PetscInt       *dims   = mat->stencil.dims+1;
    5976:   PetscInt       *starts = mat->stencil.starts;
    5977:   PetscInt       *dxm    = (PetscInt*) rows;
    5978:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;

    5986:   PetscMalloc1(numRows, &jdxm);
    5987:   for (i = 0; i < numRows; ++i) {
    5988:     /* Skip unused dimensions (they are ordered k, j, i, c) */
    5989:     for (j = 0; j < 3-sdim; ++j) dxm++;
    5990:     /* Local index in X dir */
    5991:     tmp = *dxm++ - starts[0];
    5992:     /* Loop over remaining dimensions */
    5993:     for (j = 0; j < dim-1; ++j) {
    5994:       /* If nonlocal, set index to be negative */
    5995:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
    5996:       /* Update local index */
    5997:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
    5998:     }
    5999:     /* Skip component slot if necessary */
    6000:     if (mat->stencil.noc) dxm++;
    6001:     /* Local row number */
    6002:     if (tmp >= 0) {
    6003:       jdxm[numNewRows++] = tmp;
    6004:     }
    6005:   }
    6006:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
    6007:   PetscFree(jdxm);
    6008:   return(0);
    6009: }

    6011: /*@
    6012:    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
    6013:    of a set of rows and columns of a matrix.

    6015:    Collective on Mat

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

    6025:    Notes:
    6026:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
    6027:    but does not release memory.  For the dense and block diagonal
    6028:    formats this does not alter the nonzero structure.

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

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

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

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

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

    6048:    In Fortran idxm and idxn should be declared as
    6049: $     MatStencil idxm(4,m)
    6050:    and the values inserted using
    6051: $    idxm(MatStencil_i,1) = i
    6052: $    idxm(MatStencil_j,1) = j
    6053: $    idxm(MatStencil_k,1) = k
    6054: $    idxm(MatStencil_c,1) = c
    6055:    etc

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

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

    6065:    Level: intermediate

    6067: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6068:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
    6069: @*/
    6070: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
    6071: {
    6072:   PetscInt       dim     = mat->stencil.dim;
    6073:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
    6074:   PetscInt       *dims   = mat->stencil.dims+1;
    6075:   PetscInt       *starts = mat->stencil.starts;
    6076:   PetscInt       *dxm    = (PetscInt*) rows;
    6077:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;

    6085:   PetscMalloc1(numRows, &jdxm);
    6086:   for (i = 0; i < numRows; ++i) {
    6087:     /* Skip unused dimensions (they are ordered k, j, i, c) */
    6088:     for (j = 0; j < 3-sdim; ++j) dxm++;
    6089:     /* Local index in X dir */
    6090:     tmp = *dxm++ - starts[0];
    6091:     /* Loop over remaining dimensions */
    6092:     for (j = 0; j < dim-1; ++j) {
    6093:       /* If nonlocal, set index to be negative */
    6094:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
    6095:       /* Update local index */
    6096:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
    6097:     }
    6098:     /* Skip component slot if necessary */
    6099:     if (mat->stencil.noc) dxm++;
    6100:     /* Local row number */
    6101:     if (tmp >= 0) {
    6102:       jdxm[numNewRows++] = tmp;
    6103:     }
    6104:   }
    6105:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
    6106:   PetscFree(jdxm);
    6107:   return(0);
    6108: }

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

    6114:    Collective on Mat

    6116:    Input Parameters:
    6117: +  mat - the matrix
    6118: .  numRows - the number of rows to remove
    6119: .  rows - the global row indices
    6120: .  diag - value put in all diagonals of eliminated rows
    6121: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    6122: -  b - optional vector of right hand side, that will be adjusted by provided solution

    6124:    Notes:
    6125:    Before calling MatZeroRowsLocal(), the user must first set the
    6126:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

    6128:    For the AIJ matrix formats this removes the old nonzero structure,
    6129:    but does not release memory.  For the dense and block diagonal
    6130:    formats this does not alter the nonzero structure.

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

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

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

    6143:    Level: intermediate

    6145: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
    6146:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6147: @*/
    6148: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    6149: {

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

    6160:   if (mat->ops->zerorowslocal) {
    6161:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
    6162:   } else {
    6163:     IS             is, newis;
    6164:     const PetscInt *newRows;

    6166:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
    6167:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
    6168:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
    6169:     ISGetIndices(newis,&newRows);
    6170:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
    6171:     ISRestoreIndices(newis,&newRows);
    6172:     ISDestroy(&newis);
    6173:     ISDestroy(&is);
    6174:   }
    6175:   PetscObjectStateIncrease((PetscObject)mat);
    6176:   return(0);
    6177: }

    6179: /*@
    6180:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
    6181:    of a set of rows of a matrix; using local numbering of rows.

    6183:    Collective on Mat

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

    6192:    Notes:
    6193:    Before calling MatZeroRowsLocalIS(), the user must first set the
    6194:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

    6196:    For the AIJ matrix formats this removes the old nonzero structure,
    6197:    but does not release memory.  For the dense and block diagonal
    6198:    formats this does not alter the nonzero structure.

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

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

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

    6211:    Level: intermediate

    6213: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6214:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6215: @*/
    6216: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    6217: {
    6219:   PetscInt       numRows;
    6220:   const PetscInt *rows;

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

    6230:   ISGetLocalSize(is,&numRows);
    6231:   ISGetIndices(is,&rows);
    6232:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
    6233:   ISRestoreIndices(is,&rows);
    6234:   return(0);
    6235: }

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

    6241:    Collective on Mat

    6243:    Input Parameters:
    6244: +  mat - the matrix
    6245: .  numRows - the number of rows to remove
    6246: .  rows - the global row indices
    6247: .  diag - value put in all diagonals of eliminated rows
    6248: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
    6249: -  b - optional vector of right hand side, that will be adjusted by provided solution

    6251:    Notes:
    6252:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
    6253:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

    6259:    Level: intermediate

    6261: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6262:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6263: @*/
    6264: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
    6265: {
    6267:   IS             is, newis;
    6268:   const PetscInt *newRows;

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

    6278:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
    6279:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
    6280:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
    6281:   ISGetIndices(newis,&newRows);
    6282:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
    6283:   ISRestoreIndices(newis,&newRows);
    6284:   ISDestroy(&newis);
    6285:   ISDestroy(&is);
    6286:   PetscObjectStateIncrease((PetscObject)mat);
    6287:   return(0);
    6288: }

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

    6294:    Collective on Mat

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

    6303:    Notes:
    6304:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
    6305:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

    6311:    Level: intermediate

    6313: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
    6314:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
    6315: @*/
    6316: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
    6317: {
    6319:   PetscInt       numRows;
    6320:   const PetscInt *rows;

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

    6330:   ISGetLocalSize(is,&numRows);
    6331:   ISGetIndices(is,&rows);
    6332:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
    6333:   ISRestoreIndices(is,&rows);
    6334:   return(0);
    6335: }

    6337: /*@C
    6338:    MatGetSize - Returns the numbers of rows and columns in a matrix.

    6340:    Not Collective

    6342:    Input Parameter:
    6343: .  mat - the matrix

    6345:    Output Parameters:
    6346: +  m - the number of global rows
    6347: -  n - the number of global columns

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

    6351:    Level: beginner

    6353: .seealso: MatGetLocalSize()
    6354: @*/
    6355: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
    6356: {
    6359:   if (m) *m = mat->rmap->N;
    6360:   if (n) *n = mat->cmap->N;
    6361:   return(0);
    6362: }

    6364: /*@C
    6365:    MatGetLocalSize - Returns the number of local rows and local columns
    6366:    of a matrix, that is the local size of the left and right vectors as returned by MatCreateVecs().

    6368:    Not Collective

    6370:    Input Parameters:
    6371: .  mat - the matrix

    6373:    Output Parameters:
    6374: +  m - the number of local rows
    6375: -  n - the number of local columns

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

    6379:    Level: beginner

    6381: .seealso: MatGetSize()
    6382: @*/
    6383: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
    6384: {
    6389:   if (m) *m = mat->rmap->n;
    6390:   if (n) *n = mat->cmap->n;
    6391:   return(0);
    6392: }

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

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

    6400:    Input Parameters:
    6401: .  mat - the matrix

    6403:    Output Parameters:
    6404: +  m - the global index of the first local column
    6405: -  n - one more than the global index of the last local column

    6407:    Notes:
    6408:     both output parameters can be NULL on input.

    6410:    Level: developer

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

    6414: @*/
    6415: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
    6416: {
    6422:   MatCheckPreallocated(mat,1);
    6423:   if (m) *m = mat->cmap->rstart;
    6424:   if (n) *n = mat->cmap->rend;
    6425:   return(0);
    6426: }

    6428: /*@C
    6429:    MatGetOwnershipRange - Returns the range of matrix rows owned by
    6430:    this processor, assuming that the matrix is laid out with the first
    6431:    n1 rows on the first processor, the next n2 rows on the second, etc.
    6432:    For certain parallel layouts this range may not be well defined.

    6434:    Not Collective

    6436:    Input Parameters:
    6437: .  mat - the matrix

    6439:    Output Parameters:
    6440: +  m - the global index of the first local row
    6441: -  n - one more than the global index of the last local row

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

    6448:    Level: beginner

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

    6452: @*/
    6453: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
    6454: {
    6460:   MatCheckPreallocated(mat,1);
    6461:   if (m) *m = mat->rmap->rstart;
    6462:   if (n) *n = mat->rmap->rend;
    6463:   return(0);
    6464: }

    6466: /*@C
    6467:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
    6468:    each process

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

    6472:    Input Parameters:
    6473: .  mat - the matrix

    6475:    Output Parameters:
    6476: .  ranges - start of each processors portion plus one more than the total length at the end

    6478:    Level: beginner

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

    6482: @*/
    6483: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
    6484: {

    6490:   MatCheckPreallocated(mat,1);
    6491:   PetscLayoutGetRanges(mat->rmap,ranges);
    6492:   return(0);
    6493: }

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

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

    6501:    Input Parameters:
    6502: .  mat - the matrix

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

    6507:    Level: beginner

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

    6511: @*/
    6512: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
    6513: {

    6519:   MatCheckPreallocated(mat,1);
    6520:   PetscLayoutGetRanges(mat->cmap,ranges);
    6521:   return(0);
    6522: }

    6524: /*@C
    6525:    MatGetOwnershipIS - Get row and column ownership as index sets

    6527:    Not Collective

    6529:    Input Arguments:
    6530: .  A - matrix of type Elemental

    6532:    Output Arguments:
    6533: +  rows - rows in which this process owns elements
    6534: -  cols - columns in which this process owns elements

    6536:    Level: intermediate

    6538: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
    6539: @*/
    6540: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
    6541: {
    6542:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

    6545:   MatCheckPreallocated(A,1);
    6546:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
    6547:   if (f) {
    6548:     (*f)(A,rows,cols);
    6549:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
    6550:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
    6551:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
    6552:   }
    6553:   return(0);
    6554: }

    6556: /*@C
    6557:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
    6558:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
    6559:    to complete the factorization.

    6561:    Collective on Mat

    6563:    Input Parameters:
    6564: +  mat - the matrix
    6565: .  row - row permutation
    6566: .  column - column permutation
    6567: -  info - structure containing
    6568: $      levels - number of levels of fill.
    6569: $      expected fill - as ratio of original fill.
    6570: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
    6571:                 missing diagonal entries)

    6573:    Output Parameters:
    6574: .  fact - new matrix that has been symbolically factored

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

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

    6583:    Level: developer

    6585: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
    6586:           MatGetOrdering(), MatFactorInfo

    6588:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

    6593:    References:
    6594:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
    6595: @*/
    6596: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
    6597: {

    6607:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
    6608:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
    6609:   if (!(fact)->ops->ilufactorsymbolic) {
    6610:     MatSolverType spackage;
    6611:     MatFactorGetSolverType(fact,&spackage);
    6612:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
    6613:   }
    6614:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    6615:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    6616:   MatCheckPreallocated(mat,2);

    6618:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
    6619:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
    6620:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
    6621:   return(0);
    6622: }

    6624: /*@C
    6625:    MatICCFactorSymbolic - Performs symbolic incomplete
    6626:    Cholesky factorization for a symmetric matrix.  Use
    6627:    MatCholeskyFactorNumeric() to complete the factorization.

    6629:    Collective on Mat

    6631:    Input Parameters:
    6632: +  mat - the matrix
    6633: .  perm - row and column permutation
    6634: -  info - structure containing
    6635: $      levels - number of levels of fill.
    6636: $      expected fill - as ratio of original fill.

    6638:    Output Parameter:
    6639: .  fact - the factored matrix

    6641:    Notes:
    6642:    Most users should employ the KSP interface for linear solvers
    6643:    instead of working directly with matrix algebra routines such as this.
    6644:    See, e.g., KSPCreate().

    6646:    Level: developer

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

    6650:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

    6655:    References:
    6656:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
    6657: @*/
    6658: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
    6659: {

    6668:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    6669:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
    6670:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
    6671:   if (!(fact)->ops->iccfactorsymbolic) {
    6672:     MatSolverType spackage;
    6673:     MatFactorGetSolverType(fact,&spackage);
    6674:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
    6675:   }
    6676:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    6677:   MatCheckPreallocated(mat,2);

    6679:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
    6680:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
    6681:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
    6682:   return(0);
    6683: }

    6685: /*@C
    6686:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
    6687:    points to an array of valid matrices, they may be reused to store the new
    6688:    submatrices.

    6690:    Collective on Mat

    6692:    Input Parameters:
    6693: +  mat - the matrix
    6694: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
    6695: .  irow, icol - index sets of rows and columns to extract
    6696: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    6698:    Output Parameter:
    6699: .  submat - the array of submatrices

    6701:    Notes:
    6702:    MatCreateSubMatrices() can extract ONLY sequential submatrices
    6703:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
    6704:    to extract a parallel submatrix.

    6706:    Some matrix types place restrictions on the row and column
    6707:    indices, such as that they be sorted or that they be equal to each other.

    6709:    The index sets may not have duplicate entries.

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

    6715:    When finished using the submatrices, the user should destroy
    6716:    them with MatDestroySubMatrices().

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

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

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

    6729:    Fortran Note:
    6730:    The Fortran interface is slightly different from that given below; it
    6731:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

    6733:    Level: advanced

    6736: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
    6737: @*/
    6738: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
    6739: {
    6741:   PetscInt       i;
    6742:   PetscBool      eq;

    6747:   if (n) {
    6752:   }
    6754:   if (n && scall == MAT_REUSE_MATRIX) {
    6757:   }
    6758:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    6759:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    6760:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    6761:   MatCheckPreallocated(mat,1);

    6763:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
    6764:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
    6765:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
    6766:   for (i=0; i<n; i++) {
    6767:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
    6768:     ISEqualUnsorted(irow[i],icol[i],&eq);
    6769:     if (eq) {
    6770:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
    6771:     }
    6772:   }
    6773:   return(0);
    6774: }

    6776: /*@C
    6777:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

    6779:    Collective on Mat

    6781:    Input Parameters:
    6782: +  mat - the matrix
    6783: .  n   - the number of submatrixes to be extracted
    6784: .  irow, icol - index sets of rows and columns to extract
    6785: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    6787:    Output Parameter:
    6788: .  submat - the array of submatrices

    6790:    Level: advanced

    6793: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
    6794: @*/
    6795: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
    6796: {
    6798:   PetscInt       i;
    6799:   PetscBool      eq;

    6804:   if (n) {
    6809:   }
    6811:   if (n && scall == MAT_REUSE_MATRIX) {
    6814:   }
    6815:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    6816:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    6817:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    6818:   MatCheckPreallocated(mat,1);

    6820:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
    6821:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
    6822:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
    6823:   for (i=0; i<n; i++) {
    6824:     ISEqualUnsorted(irow[i],icol[i],&eq);
    6825:     if (eq) {
    6826:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
    6827:     }
    6828:   }
    6829:   return(0);
    6830: }

    6832: /*@C
    6833:    MatDestroyMatrices - Destroys an array of matrices.

    6835:    Collective on Mat

    6837:    Input Parameters:
    6838: +  n - the number of local matrices
    6839: -  mat - the matrices (note that this is a pointer to the array of matrices)

    6841:    Level: advanced

    6843:     Notes:
    6844:     Frees not only the matrices, but also the array that contains the matrices
    6845:            In Fortran will not free the array.

    6847: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
    6848: @*/
    6849: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
    6850: {
    6852:   PetscInt       i;

    6855:   if (!*mat) return(0);
    6856:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

    6859:   for (i=0; i<n; i++) {
    6860:     MatDestroy(&(*mat)[i]);
    6861:   }

    6863:   /* memory is allocated even if n = 0 */
    6864:   PetscFree(*mat);
    6865:   return(0);
    6866: }

    6868: /*@C
    6869:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

    6871:    Collective on Mat

    6873:    Input Parameters:
    6874: +  n - the number of local matrices
    6875: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
    6876:                        sequence of MatCreateSubMatrices())

    6878:    Level: advanced

    6880:     Notes:
    6881:     Frees not only the matrices, but also the array that contains the matrices
    6882:            In Fortran will not free the array.

    6884: .seealso: MatCreateSubMatrices()
    6885: @*/
    6886: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
    6887: {
    6889:   Mat            mat0;

    6892:   if (!*mat) return(0);
    6893:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
    6894:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

    6897:   mat0 = (*mat)[0];
    6898:   if (mat0 && mat0->ops->destroysubmatrices) {
    6899:     (mat0->ops->destroysubmatrices)(n,mat);
    6900:   } else {
    6901:     MatDestroyMatrices(n,mat);
    6902:   }
    6903:   return(0);
    6904: }

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

    6909:    Collective on Mat

    6911:    Input Parameters:
    6912: .  mat - the matrix

    6914:    Output Parameter:
    6915: .  matstruct - the sequential matrix with the nonzero structure of mat

    6917:   Level: intermediate

    6919: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
    6920: @*/
    6921: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
    6922: {

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

    6933:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
    6934:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
    6935:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
    6936:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
    6937:   return(0);
    6938: }

    6940: /*@C
    6941:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

    6943:    Collective on Mat

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

    6949:    Level: advanced

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

    6954: .seealso: MatGetSeqNonzeroStructure()
    6955: @*/
    6956: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
    6957: {

    6962:   MatDestroy(mat);
    6963:   return(0);
    6964: }

    6966: /*@
    6967:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
    6968:    replaces the index sets by larger ones that represent submatrices with
    6969:    additional overlap.

    6971:    Collective on Mat

    6973:    Input Parameters:
    6974: +  mat - the matrix
    6975: .  n   - the number of index sets
    6976: .  is  - the array of index sets (these index sets will changed during the call)
    6977: -  ov  - the additional overlap requested

    6979:    Options Database:
    6980: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

    6982:    Level: developer

    6985: .seealso: MatCreateSubMatrices()
    6986: @*/
    6987: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
    6988: {

    6994:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
    6995:   if (n) {
    6998:   }
    6999:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    7000:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    7001:   MatCheckPreallocated(mat,1);

    7003:   if (!ov) return(0);
    7004:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    7005:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
    7006:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
    7007:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
    7008:   return(0);
    7009: }

    7012: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

    7014: /*@
    7015:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
    7016:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
    7017:    additional overlap.

    7019:    Collective on Mat

    7021:    Input Parameters:
    7022: +  mat - the matrix
    7023: .  n   - the number of index sets
    7024: .  is  - the array of index sets (these index sets will changed during the call)
    7025: -  ov  - the additional overlap requested

    7027:    Options Database:
    7028: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

    7030:    Level: developer

    7033: .seealso: MatCreateSubMatrices()
    7034: @*/
    7035: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
    7036: {
    7037:   PetscInt       i;

    7043:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
    7044:   if (n) {
    7047:   }
    7048:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    7049:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    7050:   MatCheckPreallocated(mat,1);
    7051:   if (!ov) return(0);
    7052:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
    7053:   for(i=0; i<n; i++){
    7054:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
    7055:   }
    7056:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
    7057:   return(0);
    7058: }

    7063: /*@
    7064:    MatGetBlockSize - Returns the matrix block size.

    7066:    Not Collective

    7068:    Input Parameter:
    7069: .  mat - the matrix

    7071:    Output Parameter:
    7072: .  bs - block size

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

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

    7079:    Level: intermediate

    7081: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
    7082: @*/
    7083: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
    7084: {
    7088:   *bs = PetscAbs(mat->rmap->bs);
    7089:   return(0);
    7090: }

    7092: /*@
    7093:    MatGetBlockSizes - Returns the matrix block row and column sizes.

    7095:    Not Collective

    7097:    Input Parameter:
    7098: .  mat - the matrix

    7100:    Output Parameter:
    7101: +  rbs - row block size
    7102: -  cbs - column block size

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

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

    7110:    Level: intermediate

    7112: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
    7113: @*/
    7114: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
    7115: {
    7120:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
    7121:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
    7122:   return(0);
    7123: }

    7125: /*@
    7126:    MatSetBlockSize - Sets the matrix block size.

    7128:    Logically Collective on Mat

    7130:    Input Parameters:
    7131: +  mat - the matrix
    7132: -  bs - block size

    7134:    Notes:
    7135:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
    7136:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

    7138:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
    7139:     is compatible with the matrix local sizes.

    7141:    Level: intermediate

    7143: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
    7144: @*/
    7145: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
    7146: {

    7152:   MatSetBlockSizes(mat,bs,bs);
    7153:   return(0);
    7154: }

    7156: /*@
    7157:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

    7159:    Logically Collective on Mat

    7161:    Input Parameters:
    7162: +  mat - the matrix
    7163: .  nblocks - the number of blocks on this process
    7164: -  bsizes - the block sizes

    7166:    Notes:
    7167:     Currently used by PCVPBJACOBI for SeqAIJ matrices

    7169:    Level: intermediate

    7171: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
    7172: @*/
    7173: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
    7174: {
    7176:   PetscInt       i,ncnt = 0, nlocal;

    7180:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
    7181:   MatGetLocalSize(mat,&nlocal,NULL);
    7182:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
    7183:   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);
    7184:   PetscFree(mat->bsizes);
    7185:   mat->nblocks = nblocks;
    7186:   PetscMalloc1(nblocks,&mat->bsizes);
    7187:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
    7188:   return(0);
    7189: }

    7191: /*@C
    7192:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

    7194:    Logically Collective on Mat

    7196:    Input Parameters:
    7197: .  mat - the matrix

    7199:    Output Parameters:
    7200: +  nblocks - the number of blocks on this process
    7201: -  bsizes - the block sizes

    7203:    Notes: Currently not supported from Fortran

    7205:    Level: intermediate

    7207: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
    7208: @*/
    7209: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
    7210: {
    7213:   *nblocks = mat->nblocks;
    7214:   *bsizes  = mat->bsizes;
    7215:   return(0);
    7216: }

    7218: /*@
    7219:    MatSetBlockSizes - Sets the matrix block row and column sizes.

    7221:    Logically Collective on Mat

    7223:    Input Parameters:
    7224: +  mat - the matrix
    7225: .  rbs - row block size
    7226: -  cbs - column block size

    7228:    Notes:
    7229:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
    7230:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
    7231:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

    7233:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
    7234:     are compatible with the matrix local sizes.

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

    7238:    Level: intermediate

    7240: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
    7241: @*/
    7242: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
    7243: {

    7250:   if (mat->ops->setblocksizes) {
    7251:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
    7252:   }
    7253:   if (mat->rmap->refcnt) {
    7254:     ISLocalToGlobalMapping l2g = NULL;
    7255:     PetscLayout            nmap = NULL;

    7257:     PetscLayoutDuplicate(mat->rmap,&nmap);
    7258:     if (mat->rmap->mapping) {
    7259:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
    7260:     }
    7261:     PetscLayoutDestroy(&mat->rmap);
    7262:     mat->rmap = nmap;
    7263:     mat->rmap->mapping = l2g;
    7264:   }
    7265:   if (mat->cmap->refcnt) {
    7266:     ISLocalToGlobalMapping l2g = NULL;
    7267:     PetscLayout            nmap = NULL;

    7269:     PetscLayoutDuplicate(mat->cmap,&nmap);
    7270:     if (mat->cmap->mapping) {
    7271:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
    7272:     }
    7273:     PetscLayoutDestroy(&mat->cmap);
    7274:     mat->cmap = nmap;
    7275:     mat->cmap->mapping = l2g;
    7276:   }
    7277:   PetscLayoutSetBlockSize(mat->rmap,rbs);
    7278:   PetscLayoutSetBlockSize(mat->cmap,cbs);
    7279:   return(0);
    7280: }

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

    7285:    Logically Collective on Mat

    7287:    Input Parameters:
    7288: +  mat - the matrix
    7289: .  fromRow - matrix from which to copy row block size
    7290: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

    7292:    Level: developer

    7294: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
    7295: @*/
    7296: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
    7297: {

    7304:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
    7305:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
    7306:   return(0);
    7307: }

    7309: /*@
    7310:    MatResidual - Default routine to calculate the residual.

    7312:    Collective on Mat

    7314:    Input Parameters:
    7315: +  mat - the matrix
    7316: .  b   - the right-hand-side
    7317: -  x   - the approximate solution

    7319:    Output Parameter:
    7320: .  r - location to store the residual

    7322:    Level: developer

    7324: .seealso: PCMGSetResidual()
    7325: @*/
    7326: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
    7327: {

    7336:   MatCheckPreallocated(mat,1);
    7337:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
    7338:   if (!mat->ops->residual) {
    7339:     MatMult(mat,x,r);
    7340:     VecAYPX(r,-1.0,b);
    7341:   } else {
    7342:     (*mat->ops->residual)(mat,b,x,r);
    7343:   }
    7344:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
    7345:   return(0);
    7346: }

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

    7351:    Collective on Mat

    7353:     Input Parameters:
    7354: +   mat - the matrix
    7355: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
    7356: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
    7357: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
    7358:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7359:                  always used.

    7361:     Output Parameters:
    7362: +   n - number of rows in the (possibly compressed) matrix
    7363: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
    7364: .   ja - the column indices
    7365: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
    7366:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

    7368:     Level: developer

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

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

    7375:     Fortran Notes:
    7376:     In Fortran use
    7377: $
    7378: $      PetscInt ia(1), ja(1)
    7379: $      PetscOffset iia, jja
    7380: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
    7381: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

    7383:      or
    7384: $
    7385: $    PetscInt, pointer :: ia(:),ja(:)
    7386: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
    7387: $    ! Access the ith and jth entries via ia(i) and ja(j)

    7389: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
    7390: @*/
    7391: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7392: {

    7402:   MatCheckPreallocated(mat,1);
    7403:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
    7404:   else {
    7405:     *done = PETSC_TRUE;
    7406:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
    7407:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7408:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
    7409:   }
    7410:   return(0);
    7411: }

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

    7416:     Collective on Mat

    7418:     Input Parameters:
    7419: +   mat - the matrix
    7420: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
    7421: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
    7422:                 symmetrized
    7423: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
    7424:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7425:                  always used.
    7426: .   n - number of columns in the (possibly compressed) matrix
    7427: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
    7428: -   ja - the row indices

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

    7433:     Level: developer

    7435: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
    7436: @*/
    7437: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7438: {

    7448:   MatCheckPreallocated(mat,1);
    7449:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
    7450:   else {
    7451:     *done = PETSC_TRUE;
    7452:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7453:   }
    7454:   return(0);
    7455: }

    7457: /*@C
    7458:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
    7459:     MatGetRowIJ().

    7461:     Collective on Mat

    7463:     Input Parameters:
    7464: +   mat - the matrix
    7465: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
    7466: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
    7467:                 symmetrized
    7468: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
    7469:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7470:                  always used.
    7471: .   n - size of (possibly compressed) matrix
    7472: .   ia - the row pointers
    7473: -   ja - the column indices

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

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

    7483:     Level: developer

    7485: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
    7486: @*/
    7487: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7488: {

    7497:   MatCheckPreallocated(mat,1);

    7499:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
    7500:   else {
    7501:     *done = PETSC_TRUE;
    7502:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7503:     if (n)  *n = 0;
    7504:     if (ia) *ia = NULL;
    7505:     if (ja) *ja = NULL;
    7506:   }
    7507:   return(0);
    7508: }

    7510: /*@C
    7511:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
    7512:     MatGetColumnIJ().

    7514:     Collective on Mat

    7516:     Input Parameters:
    7517: +   mat - the matrix
    7518: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
    7519: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
    7520:                 symmetrized
    7521: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
    7522:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
    7523:                  always used.

    7525:     Output Parameters:
    7526: +   n - size of (possibly compressed) matrix
    7527: .   ia - the column pointers
    7528: .   ja - the row indices
    7529: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

    7531:     Level: developer

    7533: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
    7534: @*/
    7535: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
    7536: {

    7545:   MatCheckPreallocated(mat,1);

    7547:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
    7548:   else {
    7549:     *done = PETSC_TRUE;
    7550:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
    7551:     if (n)  *n = 0;
    7552:     if (ia) *ia = NULL;
    7553:     if (ja) *ja = NULL;
    7554:   }
    7555:   return(0);
    7556: }

    7558: /*@C
    7559:     MatColoringPatch -Used inside matrix coloring routines that
    7560:     use MatGetRowIJ() and/or MatGetColumnIJ().

    7562:     Collective on Mat

    7564:     Input Parameters:
    7565: +   mat - the matrix
    7566: .   ncolors - max color value
    7567: .   n   - number of entries in colorarray
    7568: -   colorarray - array indicating color for each column

    7570:     Output Parameters:
    7571: .   iscoloring - coloring generated using colorarray information

    7573:     Level: developer

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

    7577: @*/
    7578: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
    7579: {

    7587:   MatCheckPreallocated(mat,1);

    7589:   if (!mat->ops->coloringpatch) {
    7590:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
    7591:   } else {
    7592:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
    7593:   }
    7594:   return(0);
    7595: }

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

    7601:    Logically Collective on Mat

    7603:    Input Parameter:
    7604: .  mat - the factored matrix to be reset

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

    7613:    Note that one can specify in-place ILU(0) factorization by calling
    7614: .vb
    7615:      PCType(pc,PCILU);
    7616:      PCFactorSeUseInPlace(pc);
    7617: .ve
    7618:    or by using the options -pc_type ilu -pc_factor_in_place

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

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

    7629:    Level: developer

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

    7633: @*/
    7634: PetscErrorCode MatSetUnfactored(Mat mat)
    7635: {

    7641:   MatCheckPreallocated(mat,1);
    7642:   mat->factortype = MAT_FACTOR_NONE;
    7643:   if (!mat->ops->setunfactored) return(0);
    7644:   (*mat->ops->setunfactored)(mat);
    7645:   return(0);
    7646: }

    7648: /*MC
    7649:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

    7651:     Synopsis:
    7652:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

    7654:     Not collective

    7656:     Input Parameter:
    7657: .   x - matrix

    7659:     Output Parameters:
    7660: +   xx_v - the Fortran90 pointer to the array
    7661: -   ierr - error code

    7663:     Example of Usage:
    7664: .vb
    7665:       PetscScalar, pointer xx_v(:,:)
    7666:       ....
    7667:       call MatDenseGetArrayF90(x,xx_v,ierr)
    7668:       a = xx_v(3)
    7669:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
    7670: .ve

    7672:     Level: advanced

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

    7676: M*/

    7678: /*MC
    7679:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
    7680:     accessed with MatDenseGetArrayF90().

    7682:     Synopsis:
    7683:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

    7685:     Not collective

    7687:     Input Parameters:
    7688: +   x - matrix
    7689: -   xx_v - the Fortran90 pointer to the array

    7691:     Output Parameter:
    7692: .   ierr - error code

    7694:     Example of Usage:
    7695: .vb
    7696:        PetscScalar, pointer xx_v(:,:)
    7697:        ....
    7698:        call MatDenseGetArrayF90(x,xx_v,ierr)
    7699:        a = xx_v(3)
    7700:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
    7701: .ve

    7703:     Level: advanced

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

    7707: M*/

    7710: /*MC
    7711:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

    7713:     Synopsis:
    7714:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

    7716:     Not collective

    7718:     Input Parameter:
    7719: .   x - matrix

    7721:     Output Parameters:
    7722: +   xx_v - the Fortran90 pointer to the array
    7723: -   ierr - error code

    7725:     Example of Usage:
    7726: .vb
    7727:       PetscScalar, pointer xx_v(:)
    7728:       ....
    7729:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
    7730:       a = xx_v(3)
    7731:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
    7732: .ve

    7734:     Level: advanced

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

    7738: M*/

    7740: /*MC
    7741:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
    7742:     accessed with MatSeqAIJGetArrayF90().

    7744:     Synopsis:
    7745:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

    7747:     Not collective

    7749:     Input Parameters:
    7750: +   x - matrix
    7751: -   xx_v - the Fortran90 pointer to the array

    7753:     Output Parameter:
    7754: .   ierr - error code

    7756:     Example of Usage:
    7757: .vb
    7758:        PetscScalar, pointer xx_v(:)
    7759:        ....
    7760:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
    7761:        a = xx_v(3)
    7762:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
    7763: .ve

    7765:     Level: advanced

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

    7769: M*/

    7772: /*@
    7773:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
    7774:                       as the original matrix.

    7776:     Collective on Mat

    7778:     Input Parameters:
    7779: +   mat - the original matrix
    7780: .   isrow - parallel IS containing the rows this processor should obtain
    7781: .   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.
    7782: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    7784:     Output Parameter:
    7785: .   newmat - the new submatrix, of the same type as the old

    7787:     Level: advanced

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

    7792:     Some matrix types place restrictions on the row and column indices, such
    7793:     as that they be sorted or that they be equal to each other.

    7795:     The index sets may not have duplicate entries.

    7797:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
    7798:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
    7799:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
    7800:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
    7801:    you are finished using it.

    7803:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
    7804:     the input matrix.

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

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

    7814: .vb
    7815:             1  2  0  |  0  3  0  |  0  4
    7816:     Proc0   0  5  6  |  7  0  0  |  8  0
    7817:             9  0 10  | 11  0  0  | 12  0
    7818:     -------------------------------------
    7819:            13  0 14  | 15 16 17  |  0  0
    7820:     Proc1   0 18  0  | 19 20 21  |  0  0
    7821:             0  0  0  | 22 23  0  | 24  0
    7822:     -------------------------------------
    7823:     Proc2  25 26 27  |  0  0 28  | 29  0
    7824:            30  0  0  | 31 32 33  |  0 34
    7825: .ve

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

    7829: .vb
    7830:             2  0  |  0  3  0  |  0
    7831:     Proc0   5  6  |  7  0  0  |  8
    7832:     -------------------------------
    7833:     Proc1  18  0  | 19 20 21  |  0
    7834:     -------------------------------
    7835:     Proc2  26 27  |  0  0 28  | 29
    7836:             0  0  | 31 32 33  |  0
    7837: .ve

    7840: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
    7841: @*/
    7842: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
    7843: {
    7845:   PetscMPIInt    size;
    7846:   Mat            *local;
    7847:   IS             iscoltmp;
    7848:   PetscBool      flg;

    7857:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    7858:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

    7860:   MatCheckPreallocated(mat,1);
    7861:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

    7863:   if (!iscol || isrow == iscol) {
    7864:     PetscBool   stride;
    7865:     PetscMPIInt grabentirematrix = 0,grab;
    7866:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
    7867:     if (stride) {
    7868:       PetscInt first,step,n,rstart,rend;
    7869:       ISStrideGetInfo(isrow,&first,&step);
    7870:       if (step == 1) {
    7871:         MatGetOwnershipRange(mat,&rstart,&rend);
    7872:         if (rstart == first) {
    7873:           ISGetLocalSize(isrow,&n);
    7874:           if (n == rend-rstart) {
    7875:             grabentirematrix = 1;
    7876:           }
    7877:         }
    7878:       }
    7879:     }
    7880:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
    7881:     if (grab) {
    7882:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
    7883:       if (cll == MAT_INITIAL_MATRIX) {
    7884:         *newmat = mat;
    7885:         PetscObjectReference((PetscObject)mat);
    7886:       }
    7887:       return(0);
    7888:     }
    7889:   }

    7891:   if (!iscol) {
    7892:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
    7893:   } else {
    7894:     iscoltmp = iscol;
    7895:   }

    7897:   /* if original matrix is on just one processor then use submatrix generated */
    7898:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
    7899:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
    7900:     goto setproperties;
    7901:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
    7902:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
    7903:     *newmat = *local;
    7904:     PetscFree(local);
    7905:     goto setproperties;
    7906:   } else if (!mat->ops->createsubmatrix) {
    7907:     /* Create a new matrix type that implements the operation using the full matrix */
    7908:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
    7909:     switch (cll) {
    7910:     case MAT_INITIAL_MATRIX:
    7911:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
    7912:       break;
    7913:     case MAT_REUSE_MATRIX:
    7914:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
    7915:       break;
    7916:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
    7917:     }
    7918:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
    7919:     goto setproperties;
    7920:   }

    7922:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    7923:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
    7924:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
    7925:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

    7927: setproperties:
    7928:   ISEqualUnsorted(isrow,iscoltmp,&flg);
    7929:   if (flg) {
    7930:     MatPropagateSymmetryOptions(mat,*newmat);
    7931:   }
    7932:   if (!iscol) {ISDestroy(&iscoltmp);}
    7933:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
    7934:   return(0);
    7935: }

    7937: /*@
    7938:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

    7940:    Not Collective

    7942:    Input Parameters:
    7943: +  A - the matrix we wish to propagate options from
    7944: -  B - the matrix we wish to propagate options to

    7946:    Level: beginner

    7948:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

    7950: .seealso: MatSetOption()
    7951: @*/
    7952: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
    7953: {

    7959:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
    7960:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
    7961:   }
    7962:   if (A->structurally_symmetric_set) {
    7963:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
    7964:   }
    7965:   if (A->hermitian_set) {
    7966:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
    7967:   }
    7968:   if (A->spd_set) {
    7969:     MatSetOption(B,MAT_SPD,A->spd);
    7970:   }
    7971:   if (A->symmetric_set) {
    7972:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
    7973:   }
    7974:   return(0);
    7975: }

    7977: /*@
    7978:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
    7979:    used during the assembly process to store values that belong to
    7980:    other processors.

    7982:    Not Collective

    7984:    Input Parameters:
    7985: +  mat   - the matrix
    7986: .  size  - the initial size of the stash.
    7987: -  bsize - the initial size of the block-stash(if used).

    7989:    Options Database Keys:
    7990: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
    7991: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

    7993:    Level: intermediate

    7995:    Notes:
    7996:      The block-stash is used for values set with MatSetValuesBlocked() while
    7997:      the stash is used for values set with MatSetValues()

    7999:      Run with the option -info and look for output of the form
    8000:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
    8001:      to determine the appropriate value, MM, to use for size and
    8002:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
    8003:      to determine the value, BMM to use for bsize

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

    8008: @*/
    8009: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
    8010: {

    8016:   MatStashSetInitialSize_Private(&mat->stash,size);
    8017:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
    8018:   return(0);
    8019: }

    8021: /*@
    8022:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
    8023:      the matrix

    8025:    Neighbor-wise Collective on Mat

    8027:    Input Parameters:
    8028: +  mat   - the matrix
    8029: .  x,y - the vectors
    8030: -  w - where the result is stored

    8032:    Level: intermediate

    8034:    Notes:
    8035:     w may be the same vector as y.

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

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

    8042: @*/
    8043: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
    8044: {
    8046:   PetscInt       M,N,Ny;

    8054:   MatCheckPreallocated(A,1);
    8055:   MatGetSize(A,&M,&N);
    8056:   VecGetSize(y,&Ny);
    8057:   if (M == Ny) {
    8058:     MatMultAdd(A,x,y,w);
    8059:   } else {
    8060:     MatMultTransposeAdd(A,x,y,w);
    8061:   }
    8062:   return(0);
    8063: }

    8065: /*@
    8066:    MatInterpolate - y = A*x or A'*x depending on the shape of
    8067:      the matrix

    8069:    Neighbor-wise Collective on Mat

    8071:    Input Parameters:
    8072: +  mat   - the matrix
    8073: -  x,y - the vectors

    8075:    Level: intermediate

    8077:    Notes:
    8078:     This allows one to use either the restriction or interpolation (its transpose)
    8079:     matrix to do the interpolation

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

    8083: @*/
    8084: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
    8085: {
    8087:   PetscInt       M,N,Ny;

    8094:   MatCheckPreallocated(A,1);
    8095:   MatGetSize(A,&M,&N);
    8096:   VecGetSize(y,&Ny);
    8097:   if (M == Ny) {
    8098:     MatMult(A,x,y);
    8099:   } else {
    8100:     MatMultTranspose(A,x,y);
    8101:   }
    8102:   return(0);
    8103: }

    8105: /*@
    8106:    MatRestrict - y = A*x or A'*x

    8108:    Neighbor-wise Collective on Mat

    8110:    Input Parameters:
    8111: +  mat   - the matrix
    8112: -  x,y - the vectors

    8114:    Level: intermediate

    8116:    Notes:
    8117:     This allows one to use either the restriction or interpolation (its transpose)
    8118:     matrix to do the restriction

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

    8122: @*/
    8123: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
    8124: {
    8126:   PetscInt       M,N,Ny;

    8133:   MatCheckPreallocated(A,1);

    8135:   MatGetSize(A,&M,&N);
    8136:   VecGetSize(y,&Ny);
    8137:   if (M == Ny) {
    8138:     MatMult(A,x,y);
    8139:   } else {
    8140:     MatMultTranspose(A,x,y);
    8141:   }
    8142:   return(0);
    8143: }

    8145: /*@
    8146:    MatGetNullSpace - retrieves the null space of a matrix.

    8148:    Logically Collective on Mat

    8150:    Input Parameters:
    8151: +  mat - the matrix
    8152: -  nullsp - the null space object

    8154:    Level: developer

    8156: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
    8157: @*/
    8158: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
    8159: {
    8163:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
    8164:   return(0);
    8165: }

    8167: /*@
    8168:    MatSetNullSpace - attaches a null space to a matrix.

    8170:    Logically Collective on Mat

    8172:    Input Parameters:
    8173: +  mat - the matrix
    8174: -  nullsp - the null space object

    8176:    Level: advanced

    8178:    Notes:
    8179:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

    8181:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
    8182:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

    8184:       You can remove the null space by calling this routine with an nullsp of NULL

    8187:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
    8188:    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).
    8189:    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
    8190:    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
    8191:    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).

    8193:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

    8195:     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
    8196:     routine also automatically calls MatSetTransposeNullSpace().

    8198: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
    8199: @*/
    8200: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
    8201: {

    8207:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
    8208:   MatNullSpaceDestroy(&mat->nullsp);
    8209:   mat->nullsp = nullsp;
    8210:   if (mat->symmetric_set && mat->symmetric) {
    8211:     MatSetTransposeNullSpace(mat,nullsp);
    8212:   }
    8213:   return(0);
    8214: }

    8216: /*@
    8217:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

    8219:    Logically Collective on Mat

    8221:    Input Parameters:
    8222: +  mat - the matrix
    8223: -  nullsp - the null space object

    8225:    Level: developer

    8227: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
    8228: @*/
    8229: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
    8230: {
    8235:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
    8236:   return(0);
    8237: }

    8239: /*@
    8240:    MatSetTransposeNullSpace - attaches a null space to a matrix.

    8242:    Logically Collective on Mat

    8244:    Input Parameters:
    8245: +  mat - the matrix
    8246: -  nullsp - the null space object

    8248:    Level: advanced

    8250:    Notes:
    8251:       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.
    8252:       You must also call MatSetNullSpace()

    8255:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
    8256:    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).
    8257:    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
    8258:    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
    8259:    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).

    8261:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

    8263: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
    8264: @*/
    8265: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
    8266: {

    8272:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
    8273:   MatNullSpaceDestroy(&mat->transnullsp);
    8274:   mat->transnullsp = nullsp;
    8275:   return(0);
    8276: }

    8278: /*@
    8279:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
    8280:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

    8282:    Logically Collective on Mat

    8284:    Input Parameters:
    8285: +  mat - the matrix
    8286: -  nullsp - the null space object

    8288:    Level: advanced

    8290:    Notes:
    8291:       Overwrites any previous near null space that may have been attached

    8293:       You can remove the null space by calling this routine with an nullsp of NULL

    8295: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
    8296: @*/
    8297: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
    8298: {

    8305:   MatCheckPreallocated(mat,1);
    8306:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
    8307:   MatNullSpaceDestroy(&mat->nearnullsp);
    8308:   mat->nearnullsp = nullsp;
    8309:   return(0);
    8310: }

    8312: /*@
    8313:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

    8315:    Not Collective

    8317:    Input Parameter:
    8318: .  mat - the matrix

    8320:    Output Parameter:
    8321: .  nullsp - the null space object, NULL if not set

    8323:    Level: developer

    8325: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
    8326: @*/
    8327: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
    8328: {
    8333:   MatCheckPreallocated(mat,1);
    8334:   *nullsp = mat->nearnullsp;
    8335:   return(0);
    8336: }

    8338: /*@C
    8339:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

    8341:    Collective on Mat

    8343:    Input Parameters:
    8344: +  mat - the matrix
    8345: .  row - row/column permutation
    8346: .  fill - expected fill factor >= 1.0
    8347: -  level - level of fill, for ICC(k)

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

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

    8357:    Level: developer

    8360: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

    8365: @*/
    8366: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
    8367: {

    8375:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
    8376:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    8377:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    8378:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    8379:   MatCheckPreallocated(mat,1);
    8380:   (*mat->ops->iccfactor)(mat,row,info);
    8381:   PetscObjectStateIncrease((PetscObject)mat);
    8382:   return(0);
    8383: }

    8385: /*@
    8386:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
    8387:          ghosted ones.

    8389:    Not Collective

    8391:    Input Parameters:
    8392: +  mat - the matrix
    8393: -  diag = the diagonal values, including ghost ones

    8395:    Level: developer

    8397:    Notes:
    8398:     Works only for MPIAIJ and MPIBAIJ matrices

    8400: .seealso: MatDiagonalScale()
    8401: @*/
    8402: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
    8403: {
    8405:   PetscMPIInt    size;

    8412:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
    8413:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
    8414:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    8415:   if (size == 1) {
    8416:     PetscInt n,m;
    8417:     VecGetSize(diag,&n);
    8418:     MatGetSize(mat,0,&m);
    8419:     if (m == n) {
    8420:       MatDiagonalScale(mat,0,diag);
    8421:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
    8422:   } else {
    8423:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
    8424:   }
    8425:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
    8426:   PetscObjectStateIncrease((PetscObject)mat);
    8427:   return(0);
    8428: }

    8430: /*@
    8431:    MatGetInertia - Gets the inertia from a factored matrix

    8433:    Collective on Mat

    8435:    Input Parameter:
    8436: .  mat - the matrix

    8438:    Output Parameters:
    8439: +   nneg - number of negative eigenvalues
    8440: .   nzero - number of zero eigenvalues
    8441: -   npos - number of positive eigenvalues

    8443:    Level: advanced

    8445:    Notes:
    8446:     Matrix must have been factored by MatCholeskyFactor()

    8449: @*/
    8450: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
    8451: {

    8457:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    8458:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
    8459:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    8460:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
    8461:   return(0);
    8462: }

    8464: /* ----------------------------------------------------------------*/
    8465: /*@C
    8466:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

    8468:    Neighbor-wise Collective on Mats

    8470:    Input Parameters:
    8471: +  mat - the factored matrix
    8472: -  b - the right-hand-side vectors

    8474:    Output Parameter:
    8475: .  x - the result vectors

    8477:    Notes:
    8478:    The vectors b and x cannot be the same.  I.e., one cannot
    8479:    call MatSolves(A,x,x).

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

    8486:    Level: developer

    8488: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
    8489: @*/
    8490: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
    8491: {

    8497:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
    8498:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
    8499:   if (!mat->rmap->N && !mat->cmap->N) return(0);

    8501:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
    8502:   MatCheckPreallocated(mat,1);
    8503:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
    8504:   (*mat->ops->solves)(mat,b,x);
    8505:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
    8506:   return(0);
    8507: }

    8509: /*@
    8510:    MatIsSymmetric - Test whether a matrix is symmetric

    8512:    Collective on Mat

    8514:    Input Parameter:
    8515: +  A - the matrix to test
    8516: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

    8518:    Output Parameters:
    8519: .  flg - the result

    8521:    Notes:
    8522:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

    8524:    Level: intermediate

    8526: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
    8527: @*/
    8528: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
    8529: {

    8536:   if (!A->symmetric_set) {
    8537:     if (!A->ops->issymmetric) {
    8538:       MatType mattype;
    8539:       MatGetType(A,&mattype);
    8540:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
    8541:     }
    8542:     (*A->ops->issymmetric)(A,tol,flg);
    8543:     if (!tol) {
    8544:       MatSetOption(A,MAT_SYMMETRIC,*flg);
    8545:     }
    8546:   } else if (A->symmetric) {
    8547:     *flg = PETSC_TRUE;
    8548:   } else if (!tol) {
    8549:     *flg = PETSC_FALSE;
    8550:   } else {
    8551:     if (!A->ops->issymmetric) {
    8552:       MatType mattype;
    8553:       MatGetType(A,&mattype);
    8554:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
    8555:     }
    8556:     (*A->ops->issymmetric)(A,tol,flg);
    8557:   }
    8558:   return(0);
    8559: }

    8561: /*@
    8562:    MatIsHermitian - Test whether a matrix is Hermitian

    8564:    Collective on Mat

    8566:    Input Parameter:
    8567: +  A - the matrix to test
    8568: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

    8570:    Output Parameters:
    8571: .  flg - the result

    8573:    Level: intermediate

    8575: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
    8576:           MatIsSymmetricKnown(), MatIsSymmetric()
    8577: @*/
    8578: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
    8579: {

    8586:   if (!A->hermitian_set) {
    8587:     if (!A->ops->ishermitian) {
    8588:       MatType mattype;
    8589:       MatGetType(A,&mattype);
    8590:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
    8591:     }
    8592:     (*A->ops->ishermitian)(A,tol,flg);
    8593:     if (!tol) {
    8594:       MatSetOption(A,MAT_HERMITIAN,*flg);
    8595:     }
    8596:   } else if (A->hermitian) {
    8597:     *flg = PETSC_TRUE;
    8598:   } else if (!tol) {
    8599:     *flg = PETSC_FALSE;
    8600:   } else {
    8601:     if (!A->ops->ishermitian) {
    8602:       MatType mattype;
    8603:       MatGetType(A,&mattype);
    8604:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
    8605:     }
    8606:     (*A->ops->ishermitian)(A,tol,flg);
    8607:   }
    8608:   return(0);
    8609: }

    8611: /*@
    8612:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

    8614:    Not Collective

    8616:    Input Parameter:
    8617: .  A - the matrix to check

    8619:    Output Parameters:
    8620: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
    8621: -  flg - the result

    8623:    Level: advanced

    8625:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
    8626:          if you want it explicitly checked

    8628: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
    8629: @*/
    8630: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
    8631: {
    8636:   if (A->symmetric_set) {
    8637:     *set = PETSC_TRUE;
    8638:     *flg = A->symmetric;
    8639:   } else {
    8640:     *set = PETSC_FALSE;
    8641:   }
    8642:   return(0);
    8643: }

    8645: /*@
    8646:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

    8648:    Not Collective

    8650:    Input Parameter:
    8651: .  A - the matrix to check

    8653:    Output Parameters:
    8654: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
    8655: -  flg - the result

    8657:    Level: advanced

    8659:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
    8660:          if you want it explicitly checked

    8662: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
    8663: @*/
    8664: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
    8665: {
    8670:   if (A->hermitian_set) {
    8671:     *set = PETSC_TRUE;
    8672:     *flg = A->hermitian;
    8673:   } else {
    8674:     *set = PETSC_FALSE;
    8675:   }
    8676:   return(0);
    8677: }

    8679: /*@
    8680:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

    8682:    Collective on Mat

    8684:    Input Parameter:
    8685: .  A - the matrix to test

    8687:    Output Parameters:
    8688: .  flg - the result

    8690:    Level: intermediate

    8692: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
    8693: @*/
    8694: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
    8695: {

    8701:   if (!A->structurally_symmetric_set) {
    8702:     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);
    8703:     (*A->ops->isstructurallysymmetric)(A,flg);
    8704:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
    8705:   } else *flg = A->structurally_symmetric;
    8706:   return(0);
    8707: }

    8709: /*@
    8710:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
    8711:        to be communicated to other processors during the MatAssemblyBegin/End() process

    8713:     Not collective

    8715:    Input Parameter:
    8716: .   vec - the vector

    8718:    Output Parameters:
    8719: +   nstash   - the size of the stash
    8720: .   reallocs - the number of additional mallocs incurred.
    8721: .   bnstash   - the size of the block stash
    8722: -   breallocs - the number of additional mallocs incurred.in the block stash

    8724:    Level: advanced

    8726: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

    8728: @*/
    8729: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
    8730: {

    8734:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
    8735:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
    8736:   return(0);
    8737: }

    8739: /*@C
    8740:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
    8741:      parallel layout

    8743:    Collective on Mat

    8745:    Input Parameter:
    8746: .  mat - the matrix

    8748:    Output Parameter:
    8749: +   right - (optional) vector that the matrix can be multiplied against
    8750: -   left - (optional) vector that the matrix vector product can be stored in

    8752:    Notes:
    8753:     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().

    8755:   Notes:
    8756:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

    8758:   Level: advanced

    8760: .seealso: MatCreate(), VecDestroy()
    8761: @*/
    8762: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
    8763: {

    8769:   if (mat->ops->getvecs) {
    8770:     (*mat->ops->getvecs)(mat,right,left);
    8771:   } else {
    8772:     PetscInt rbs,cbs;
    8773:     MatGetBlockSizes(mat,&rbs,&cbs);
    8774:     if (right) {
    8775:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
    8776:       VecCreate(PetscObjectComm((PetscObject)mat),right);
    8777:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
    8778:       VecSetBlockSize(*right,cbs);
    8779:       VecSetType(*right,mat->defaultvectype);
    8780:       PetscLayoutReference(mat->cmap,&(*right)->map);
    8781:     }
    8782:     if (left) {
    8783:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
    8784:       VecCreate(PetscObjectComm((PetscObject)mat),left);
    8785:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
    8786:       VecSetBlockSize(*left,rbs);
    8787:       VecSetType(*left,mat->defaultvectype);
    8788:       PetscLayoutReference(mat->rmap,&(*left)->map);
    8789:     }
    8790:   }
    8791:   return(0);
    8792: }

    8794: /*@C
    8795:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
    8796:      with default values.

    8798:    Not Collective

    8800:    Input Parameters:
    8801: .    info - the MatFactorInfo data structure

    8804:    Notes:
    8805:     The solvers are generally used through the KSP and PC objects, for example
    8806:           PCLU, PCILU, PCCHOLESKY, PCICC

    8808:    Level: developer

    8810: .seealso: MatFactorInfo

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

    8815: @*/

    8817: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
    8818: {

    8822:   PetscMemzero(info,sizeof(MatFactorInfo));
    8823:   return(0);
    8824: }

    8826: /*@
    8827:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

    8829:    Collective on Mat

    8831:    Input Parameters:
    8832: +  mat - the factored matrix
    8833: -  is - the index set defining the Schur indices (0-based)

    8835:    Notes:
    8836:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

    8838:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

    8840:    Level: developer

    8842: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
    8843:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

    8845: @*/
    8846: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
    8847: {
    8848:   PetscErrorCode ierr,(*f)(Mat,IS);

    8856:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
    8857:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
    8858:   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");
    8859:   MatDestroy(&mat->schur);
    8860:   (*f)(mat,is);
    8861:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
    8862:   return(0);
    8863: }

    8865: /*@
    8866:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

    8868:    Logically Collective on Mat

    8870:    Input Parameters:
    8871: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
    8872: .  S - location where to return the Schur complement, can be NULL
    8873: -  status - the status of the Schur complement matrix, can be NULL

    8875:    Notes:
    8876:    You must call MatFactorSetSchurIS() before calling this routine.

    8878:    The routine provides a copy of the Schur matrix stored within the solver data structures.
    8879:    The caller must destroy the object when it is no longer needed.
    8880:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

    8882:    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)

    8884:    Developer Notes:
    8885:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
    8886:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

    8888:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

    8890:    Level: advanced

    8892:    References:

    8894: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
    8895: @*/
    8896: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
    8897: {

    8904:   if (S) {
    8905:     PetscErrorCode (*f)(Mat,Mat*);

    8907:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
    8908:     if (f) {
    8909:       (*f)(F,S);
    8910:     } else {
    8911:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
    8912:     }
    8913:   }
    8914:   if (status) *status = F->schur_status;
    8915:   return(0);
    8916: }

    8918: /*@
    8919:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

    8921:    Logically Collective on Mat

    8923:    Input Parameters:
    8924: +  F - the factored matrix obtained by calling MatGetFactor()
    8925: .  *S - location where to return the Schur complement, can be NULL
    8926: -  status - the status of the Schur complement matrix, can be NULL

    8928:    Notes:
    8929:    You must call MatFactorSetSchurIS() before calling this routine.

    8931:    Schur complement mode is currently implemented for sequential matrices.
    8932:    The routine returns a the Schur Complement stored within the data strutures of the solver.
    8933:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
    8934:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

    8936:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

    8938:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

    8940:    Level: advanced

    8942:    References:

    8944: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
    8945: @*/
    8946: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
    8947: {
    8952:   if (S) *S = F->schur;
    8953:   if (status) *status = F->schur_status;
    8954:   return(0);
    8955: }

    8957: /*@
    8958:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

    8960:    Logically Collective on Mat

    8962:    Input Parameters:
    8963: +  F - the factored matrix obtained by calling MatGetFactor()
    8964: .  *S - location where the Schur complement is stored
    8965: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

    8967:    Notes:

    8969:    Level: advanced

    8971:    References:

    8973: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
    8974: @*/
    8975: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
    8976: {

    8981:   if (S) {
    8983:     *S = NULL;
    8984:   }
    8985:   F->schur_status = status;
    8986:   MatFactorUpdateSchurStatus_Private(F);
    8987:   return(0);
    8988: }

    8990: /*@
    8991:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

    8993:    Logically Collective on Mat

    8995:    Input Parameters:
    8996: +  F - the factored matrix obtained by calling MatGetFactor()
    8997: .  rhs - location where the right hand side of the Schur complement system is stored
    8998: -  sol - location where the solution of the Schur complement system has to be returned

    9000:    Notes:
    9001:    The sizes of the vectors should match the size of the Schur complement

    9003:    Must be called after MatFactorSetSchurIS()

    9005:    Level: advanced

    9007:    References:

    9009: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
    9010: @*/
    9011: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
    9012: {

    9024:   MatFactorFactorizeSchurComplement(F);
    9025:   switch (F->schur_status) {
    9026:   case MAT_FACTOR_SCHUR_FACTORED:
    9027:     MatSolveTranspose(F->schur,rhs,sol);
    9028:     break;
    9029:   case MAT_FACTOR_SCHUR_INVERTED:
    9030:     MatMultTranspose(F->schur,rhs,sol);
    9031:     break;
    9032:   default:
    9033:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
    9034:     break;
    9035:   }
    9036:   return(0);
    9037: }

    9039: /*@
    9040:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

    9042:    Logically Collective on Mat

    9044:    Input Parameters:
    9045: +  F - the factored matrix obtained by calling MatGetFactor()
    9046: .  rhs - location where the right hand side of the Schur complement system is stored
    9047: -  sol - location where the solution of the Schur complement system has to be returned

    9049:    Notes:
    9050:    The sizes of the vectors should match the size of the Schur complement

    9052:    Must be called after MatFactorSetSchurIS()

    9054:    Level: advanced

    9056:    References:

    9058: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
    9059: @*/
    9060: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
    9061: {

    9073:   MatFactorFactorizeSchurComplement(F);
    9074:   switch (F->schur_status) {
    9075:   case MAT_FACTOR_SCHUR_FACTORED:
    9076:     MatSolve(F->schur,rhs,sol);
    9077:     break;
    9078:   case MAT_FACTOR_SCHUR_INVERTED:
    9079:     MatMult(F->schur,rhs,sol);
    9080:     break;
    9081:   default:
    9082:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
    9083:     break;
    9084:   }
    9085:   return(0);
    9086: }

    9088: /*@
    9089:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

    9091:    Logically Collective on Mat

    9093:    Input Parameters:
    9094: .  F - the factored matrix obtained by calling MatGetFactor()

    9096:    Notes:
    9097:     Must be called after MatFactorSetSchurIS().

    9099:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

    9101:    Level: advanced

    9103:    References:

    9105: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
    9106: @*/
    9107: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
    9108: {

    9114:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
    9115:   MatFactorFactorizeSchurComplement(F);
    9116:   MatFactorInvertSchurComplement_Private(F);
    9117:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
    9118:   return(0);
    9119: }

    9121: /*@
    9122:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

    9124:    Logically Collective on Mat

    9126:    Input Parameters:
    9127: .  F - the factored matrix obtained by calling MatGetFactor()

    9129:    Notes:
    9130:     Must be called after MatFactorSetSchurIS().

    9132:    Level: advanced

    9134:    References:

    9136: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
    9137: @*/
    9138: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
    9139: {

    9145:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
    9146:   MatFactorFactorizeSchurComplement_Private(F);
    9147:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
    9148:   return(0);
    9149: }

    9151: /*@
    9152:    MatPtAP - Creates the matrix product C = P^T * A * P

    9154:    Neighbor-wise Collective on Mat

    9156:    Input Parameters:
    9157: +  A - the matrix
    9158: .  P - the projection matrix
    9159: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9160: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
    9161:           if the result is a dense matrix this is irrelevent

    9163:    Output Parameters:
    9164: .  C - the product matrix

    9166:    Notes:
    9167:    C will be created and must be destroyed by the user with MatDestroy().

    9169:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

    9171:    Level: intermediate

    9173: .seealso: MatMatMult(), MatRARt()
    9174: @*/
    9175: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
    9176: {

    9180:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9182:   if (scall == MAT_INITIAL_MATRIX) {
    9183:     MatProductCreate(A,P,NULL,C);
    9184:     MatProductSetType(*C,MATPRODUCT_PtAP);
    9185:     MatProductSetAlgorithm(*C,"default");
    9186:     MatProductSetFill(*C,fill);

    9188:     (*C)->product->api_user = PETSC_TRUE;
    9189:     MatProductSetFromOptions(*C);
    9190:     MatProductSymbolic(*C);
    9191:   } else {
    9192:     Mat_Product *product = (*C)->product;
    9193:     if (product) { /* user may chage input matrices A or B when REUSE */
    9194:       MatProductReplaceMats(A,P,NULL,*C);
    9195:     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
    9196:   }

    9198:   MatProductNumeric(*C);
    9199:   if (A->symmetric_set && A->symmetric) {
    9200:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
    9201:   }
    9202:   return(0);
    9203: }

    9205: /*@
    9206:    MatRARt - Creates the matrix product C = R * A * R^T

    9208:    Neighbor-wise Collective on Mat

    9210:    Input Parameters:
    9211: +  A - the matrix
    9212: .  R - the projection matrix
    9213: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9214: -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
    9215:           if the result is a dense matrix this is irrelevent

    9217:    Output Parameters:
    9218: .  C - the product matrix

    9220:    Notes:
    9221:    C will be created and must be destroyed by the user with MatDestroy().

    9223:    This routine is currently only implemented for pairs of AIJ matrices and classes
    9224:    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
    9225:    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
    9226:    We recommend using MatPtAP().

    9228:    Level: intermediate

    9230: .seealso: MatMatMult(), MatPtAP()
    9231: @*/
    9232: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
    9233: {

    9237:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9239:   if (scall == MAT_INITIAL_MATRIX) {
    9240:     MatProductCreate(A,R,NULL,C);
    9241:     MatProductSetType(*C,MATPRODUCT_RARt);
    9242:     MatProductSetAlgorithm(*C,"default");
    9243:     MatProductSetFill(*C,fill);

    9245:     (*C)->product->api_user = PETSC_TRUE;
    9246:     MatProductSetFromOptions(*C);
    9247:     MatProductSymbolic(*C);
    9248:   } else { /* scall == MAT_REUSE_MATRIX */
    9249:     Mat_Product *product = (*C)->product;
    9250:     if (product) {
    9251:       /* user may chage input matrices A or R when REUSE */
    9252:       MatProductReplaceMats(A,R,NULL,*C);
    9253:     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
    9254:   }

    9256:   MatProductNumeric(*C);
    9257:   return(0);
    9258: }

    9261: static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
    9262: {
    9263:   PetscBool      clearproduct = PETSC_FALSE;

    9267:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9269:   if (scall == MAT_INITIAL_MATRIX) {
    9270:     MatProductCreate(A,B,NULL,C);
    9271:     MatProductSetType(*C,ptype);
    9272:     MatProductSetAlgorithm(*C,"default");
    9273:     MatProductSetFill(*C,fill);

    9275:     (*C)->product->api_user = PETSC_TRUE;
    9276:     MatProductSetFromOptions(*C);
    9277:     MatProductSymbolic(*C);
    9278:   } else { /* scall == MAT_REUSE_MATRIX */
    9279:     Mat_Product *product = (*C)->product;
    9280:     if (!product) {
    9281:       /* user provide the dense matrix *C without calling MatProductCreate() */
    9282:       PetscBool seqdense,mpidense,dense;
    9283: #if defined(PETSC_HAVE_CUDA)
    9284:       PetscBool seqdensecuda;
    9285: #endif
    9286:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
    9287:       PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
    9288:       PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
    9289: #if defined(PETSC_HAVE_CUDA)
    9290:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSECUDA,&seqdensecuda);
    9291:       if (seqdense || mpidense || dense || seqdensecuda) {
    9292: #else
    9293:       if (seqdense || mpidense || dense) {
    9294: #endif
    9295:         /* user wants to reuse an assembled dense matrix */
    9296:         /* Create product -- see MatCreateProduct() */
    9297:         MatProductCreate_Private(A,B,NULL,*C);
    9298:         product = (*C)->product;
    9299:         product->fill     = fill;
    9300:         product->api_user = PETSC_TRUE;

    9302:         MatProductSetType(*C,ptype);
    9303:         MatProductSetFromOptions(*C);
    9304:         MatProductSymbolic(*C);
    9305:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
    9306:       clearproduct = PETSC_TRUE;
    9307:     } else { /* user may chage input matrices A or B when REUSE */
    9308:       MatProductReplaceMats(A,B,NULL,*C);
    9309:     }
    9310:   }
    9311:   MatProductNumeric(*C);
    9312:   if (clearproduct) {
    9313:     MatProductClear(*C);
    9314:   }
    9315:   return(0);
    9316: }

    9318: /*@
    9319:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

    9321:    Neighbor-wise Collective on Mat

    9323:    Input Parameters:
    9324: +  A - the left matrix
    9325: .  B - the right matrix
    9326: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9327: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
    9328:           if the result is a dense matrix this is irrelevent

    9330:    Output Parameters:
    9331: .  C - the product matrix

    9333:    Notes:
    9334:    Unless scall is MAT_REUSE_MATRIX C will be created.

    9336:    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
    9337:    call to this function with MAT_INITIAL_MATRIX.

    9339:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.

    9341:    If you have many matrices with the same non-zero structure to multiply, you should use MatProductCreate()/MatProductSymbolic(C)/ReplaceMats(), and call MatProductNumeric() repeatedly.

    9343:    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.

    9345:    Level: intermediate

    9347: .seealso: MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
    9348: @*/
    9349: PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
    9350: {

    9354:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_AB,C);
    9355:   return(0);
    9356: }

    9358: /*@
    9359:    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.

    9361:    Neighbor-wise Collective on Mat

    9363:    Input Parameters:
    9364: +  A - the left matrix
    9365: .  B - the right matrix
    9366: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9367: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

    9369:    Output Parameters:
    9370: .  C - the product matrix

    9372:    Notes:
    9373:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

    9375:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

    9377:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
    9378:    actually needed.

    9380:    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
    9381:    and for pairs of MPIDense matrices.

    9383:    Options Database Keys:
    9384: .  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
    9385:                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
    9386:                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.

    9388:    Level: intermediate

    9390: .seealso: MatMatMult(), MatTransposeMatMult() MatPtAP()
    9391: @*/
    9392: PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
    9393: {

    9397:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_ABt,C);
    9398:   return(0);
    9399: }

    9401: /*@
    9402:    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.

    9404:    Neighbor-wise Collective on Mat

    9406:    Input Parameters:
    9407: +  A - the left matrix
    9408: .  B - the right matrix
    9409: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9410: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

    9412:    Output Parameters:
    9413: .  C - the product matrix

    9415:    Notes:
    9416:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

    9418:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call.

    9420:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
    9421:    actually needed.

    9423:    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
    9424:    which inherit from SeqAIJ.  C will be of same type as the input matrices.

    9426:    Level: intermediate

    9428: .seealso: MatMatMult(), MatMatTransposeMult(), MatPtAP()
    9429: @*/
    9430: PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
    9431: {

    9435:   MatProduct_Private(A,B,scall,fill,MATPRODUCT_AtB,C);
    9436:   return(0);
    9437: }

    9439: /*@
    9440:    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.

    9442:    Neighbor-wise Collective on Mat

    9444:    Input Parameters:
    9445: +  A - the left matrix
    9446: .  B - the middle matrix
    9447: .  C - the right matrix
    9448: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    9449: -  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
    9450:           if the result is a dense matrix this is irrelevent

    9452:    Output Parameters:
    9453: .  D - the product matrix

    9455:    Notes:
    9456:    Unless scall is MAT_REUSE_MATRIX D will be created.

    9458:    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call

    9460:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
    9461:    actually needed.

    9463:    If you have many matrices with the same non-zero structure to multiply, you
    9464:    should use MAT_REUSE_MATRIX in all calls but the first or

    9466:    Level: intermediate

    9468: .seealso: MatMatMult, MatPtAP()
    9469: @*/
    9470: PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
    9471: {

    9475:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

    9477:   if (scall == MAT_INITIAL_MATRIX) {
    9478:     MatProductCreate(A,B,C,D);
    9479:     MatProductSetType(*D,MATPRODUCT_ABC);
    9480:     MatProductSetAlgorithm(*D,"default");
    9481:     MatProductSetFill(*D,fill);

    9483:     (*D)->product->api_user = PETSC_TRUE;
    9484:     MatProductSetFromOptions(*D);

    9486:     MatProductSymbolic(*D);
    9487:   } else { /* user may chage input matrices when REUSE */
    9488:     MatProductReplaceMats(A,B,C,*D);
    9489:   }

    9491:   MatProductNumeric(*D);
    9492:   return(0);
    9493: }

    9495: /*@
    9496:    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

    9498:    Collective on Mat

    9500:    Input Parameters:
    9501: +  mat - the matrix
    9502: .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
    9503: .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
    9504: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    9506:    Output Parameter:
    9507: .  matredundant - redundant matrix

    9509:    Notes:
    9510:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
    9511:    original matrix has not changed from that last call to MatCreateRedundantMatrix().

    9513:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
    9514:    calling it.

    9516:    Level: advanced

    9519: .seealso: MatDestroy()
    9520: @*/
    9521: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
    9522: {
    9524:   MPI_Comm       comm;
    9525:   PetscMPIInt    size;
    9526:   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
    9527:   Mat_Redundant  *redund=NULL;
    9528:   PetscSubcomm   psubcomm=NULL;
    9529:   MPI_Comm       subcomm_in=subcomm;
    9530:   Mat            *matseq;
    9531:   IS             isrow,iscol;
    9532:   PetscBool      newsubcomm=PETSC_FALSE;

    9536:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
    9539:   }

    9541:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    9542:   if (size == 1 || nsubcomm == 1) {
    9543:     if (reuse == MAT_INITIAL_MATRIX) {
    9544:       MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
    9545:     } else {
    9546:       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");
    9547:       MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
    9548:     }
    9549:     return(0);
    9550:   }

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

    9556:   PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
    9557:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
    9558:     /* create psubcomm, then get subcomm */
    9559:     PetscObjectGetComm((PetscObject)mat,&comm);
    9560:     MPI_Comm_size(comm,&size);
    9561:     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);

    9563:     PetscSubcommCreate(comm,&psubcomm);
    9564:     PetscSubcommSetNumber(psubcomm,nsubcomm);
    9565:     PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
    9566:     PetscSubcommSetFromOptions(psubcomm);
    9567:     PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
    9568:     newsubcomm = PETSC_TRUE;
    9569:     PetscSubcommDestroy(&psubcomm);
    9570:   }

    9572:   /* get isrow, iscol and a local sequential matrix matseq[0] */
    9573:   if (reuse == MAT_INITIAL_MATRIX) {
    9574:     mloc_sub = PETSC_DECIDE;
    9575:     nloc_sub = PETSC_DECIDE;
    9576:     if (bs < 1) {
    9577:       PetscSplitOwnership(subcomm,&mloc_sub,&M);
    9578:       PetscSplitOwnership(subcomm,&nloc_sub,&N);
    9579:     } else {
    9580:       PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
    9581:       PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);
    9582:     }
    9583:     MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
    9584:     rstart = rend - mloc_sub;
    9585:     ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
    9586:     ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
    9587:   } else { /* reuse == MAT_REUSE_MATRIX */
    9588:     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");
    9589:     /* retrieve subcomm */
    9590:     PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
    9591:     redund = (*matredundant)->redundant;
    9592:     isrow  = redund->isrow;
    9593:     iscol  = redund->iscol;
    9594:     matseq = redund->matseq;
    9595:   }
    9596:   MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);

    9598:   /* get matredundant over subcomm */
    9599:   if (reuse == MAT_INITIAL_MATRIX) {
    9600:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);

    9602:     /* create a supporting struct and attach it to C for reuse */
    9603:     PetscNewLog(*matredundant,&redund);
    9604:     (*matredundant)->redundant = redund;
    9605:     redund->isrow              = isrow;
    9606:     redund->iscol              = iscol;
    9607:     redund->matseq             = matseq;
    9608:     if (newsubcomm) {
    9609:       redund->subcomm          = subcomm;
    9610:     } else {
    9611:       redund->subcomm          = MPI_COMM_NULL;
    9612:     }
    9613:   } else {
    9614:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
    9615:   }
    9616:   PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
    9617:   return(0);
    9618: }

    9620: /*@C
    9621:    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
    9622:    a given 'mat' object. Each submatrix can span multiple procs.

    9624:    Collective on Mat

    9626:    Input Parameters:
    9627: +  mat - the matrix
    9628: .  subcomm - the subcommunicator obtained by com_split(comm)
    9629: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    9631:    Output Parameter:
    9632: .  subMat - 'parallel submatrices each spans a given subcomm

    9634:   Notes:
    9635:   The submatrix partition across processors is dictated by 'subComm' a
    9636:   communicator obtained by com_split(comm). The comm_split
    9637:   is not restriced to be grouped with consecutive original ranks.

    9639:   Due the comm_split() usage, the parallel layout of the submatrices
    9640:   map directly to the layout of the original matrix [wrt the local
    9641:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
    9642:   into the 'DiagonalMat' of the subMat, hence it is used directly from
    9643:   the subMat. However the offDiagMat looses some columns - and this is
    9644:   reconstructed with MatSetValues()

    9646:   Level: advanced

    9649: .seealso: MatCreateSubMatrices()
    9650: @*/
    9651: PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
    9652: {
    9654:   PetscMPIInt    commsize,subCommSize;

    9657:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
    9658:   MPI_Comm_size(subComm,&subCommSize);
    9659:   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);

    9661:   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");
    9662:   PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
    9663:   (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
    9664:   PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
    9665:   return(0);
    9666: }

    9668: /*@
    9669:    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

    9671:    Not Collective

    9673:    Input Arguments:
    9674: +  mat - matrix to extract local submatrix from
    9675: .  isrow - local row indices for submatrix
    9676: -  iscol - local column indices for submatrix

    9678:    Output Arguments:
    9679: .  submat - the submatrix

    9681:    Level: intermediate

    9683:    Notes:
    9684:    The submat should be returned with MatRestoreLocalSubMatrix().

    9686:    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
    9687:    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.

    9689:    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
    9690:    MatSetValuesBlockedLocal() will also be implemented.

    9692:    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
    9693:    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.

    9695: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
    9696: @*/
    9697: PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
    9698: {

    9707:   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");

    9709:   if (mat->ops->getlocalsubmatrix) {
    9710:     (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
    9711:   } else {
    9712:     MatCreateLocalRef(mat,isrow,iscol,submat);
    9713:   }
    9714:   return(0);
    9715: }

    9717: /*@
    9718:    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering

    9720:    Not Collective

    9722:    Input Arguments:
    9723:    mat - matrix to extract local submatrix from
    9724:    isrow - local row indices for submatrix
    9725:    iscol - local column indices for submatrix
    9726:    submat - the submatrix

    9728:    Level: intermediate

    9730: .seealso: MatGetLocalSubMatrix()
    9731: @*/
    9732: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
    9733: {

    9742:   if (*submat) {
    9744:   }

    9746:   if (mat->ops->restorelocalsubmatrix) {
    9747:     (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
    9748:   } else {
    9749:     MatDestroy(submat);
    9750:   }
    9751:   *submat = NULL;
    9752:   return(0);
    9753: }

    9755: /* --------------------------------------------------------*/
    9756: /*@
    9757:    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

    9759:    Collective on Mat

    9761:    Input Parameter:
    9762: .  mat - the matrix

    9764:    Output Parameter:
    9765: .  is - if any rows have zero diagonals this contains the list of them

    9767:    Level: developer

    9769: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    9770: @*/
    9771: PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
    9772: {

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

    9781:   if (!mat->ops->findzerodiagonals) {
    9782:     Vec                diag;
    9783:     const PetscScalar *a;
    9784:     PetscInt          *rows;
    9785:     PetscInt           rStart, rEnd, r, nrow = 0;

    9787:     MatCreateVecs(mat, &diag, NULL);
    9788:     MatGetDiagonal(mat, diag);
    9789:     MatGetOwnershipRange(mat, &rStart, &rEnd);
    9790:     VecGetArrayRead(diag, &a);
    9791:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
    9792:     PetscMalloc1(nrow, &rows);
    9793:     nrow = 0;
    9794:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
    9795:     VecRestoreArrayRead(diag, &a);
    9796:     VecDestroy(&diag);
    9797:     ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);
    9798:   } else {
    9799:     (*mat->ops->findzerodiagonals)(mat, is);
    9800:   }
    9801:   return(0);
    9802: }

    9804: /*@
    9805:    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

    9807:    Collective on Mat

    9809:    Input Parameter:
    9810: .  mat - the matrix

    9812:    Output Parameter:
    9813: .  is - contains the list of rows with off block diagonal entries

    9815:    Level: developer

    9817: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
    9818: @*/
    9819: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
    9820: {

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

    9829:   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);
    9830:   (*mat->ops->findoffblockdiagonalentries)(mat,is);
    9831:   return(0);
    9832: }

    9834: /*@C
    9835:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

    9837:   Collective on Mat

    9839:   Input Parameters:
    9840: . mat - the matrix

    9842:   Output Parameters:
    9843: . values - the block inverses in column major order (FORTRAN-like)

    9845:    Note:
    9846:    This routine is not available from Fortran.

    9848:   Level: advanced

    9850: .seealso: MatInvertBockDiagonalMat
    9851: @*/
    9852: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
    9853: {

    9858:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    9859:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    9860:   if (!mat->ops->invertblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type %s",((PetscObject)mat)->type_name);
    9861:   (*mat->ops->invertblockdiagonal)(mat,values);
    9862:   return(0);
    9863: }

    9865: /*@C
    9866:   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.

    9868:   Collective on Mat

    9870:   Input Parameters:
    9871: + mat - the matrix
    9872: . nblocks - the number of blocks
    9873: - bsizes - the size of each block

    9875:   Output Parameters:
    9876: . values - the block inverses in column major order (FORTRAN-like)

    9878:    Note:
    9879:    This routine is not available from Fortran.

    9881:   Level: advanced

    9883: .seealso: MatInvertBockDiagonal()
    9884: @*/
    9885: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
    9886: {

    9891:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
    9892:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
    9893:   if (!mat->ops->invertvariableblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type",((PetscObject)mat)->type_name);
    9894:   (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);
    9895:   return(0);
    9896: }

    9898: /*@
    9899:   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A

    9901:   Collective on Mat

    9903:   Input Parameters:
    9904: . A - the matrix

    9906:   Output Parameters:
    9907: . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.

    9909:   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C

    9911:   Level: advanced

    9913: .seealso: MatInvertBockDiagonal()
    9914: @*/
    9915: PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
    9916: {
    9917:   PetscErrorCode     ierr;
    9918:   const PetscScalar *vals;
    9919:   PetscInt          *dnnz;
    9920:   PetscInt           M,N,m,n,rstart,rend,bs,i,j;

    9923:   MatInvertBlockDiagonal(A,&vals);
    9924:   MatGetBlockSize(A,&bs);
    9925:   MatGetSize(A,&M,&N);
    9926:   MatGetLocalSize(A,&m,&n);
    9927:   MatSetSizes(C,m,n,M,N);
    9928:   MatSetBlockSize(C,bs);
    9929:   PetscMalloc1(m/bs,&dnnz);
    9930:   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
    9931:   MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);
    9932:   PetscFree(dnnz);
    9933:   MatGetOwnershipRange(C,&rstart,&rend);
    9934:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);
    9935:   for (i = rstart/bs; i < rend/bs; i++) {
    9936:     MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);
    9937:   }
    9938:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
    9939:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
    9940:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);
    9941:   return(0);
    9942: }

    9944: /*@C
    9945:     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
    9946:     via MatTransposeColoringCreate().

    9948:     Collective on MatTransposeColoring

    9950:     Input Parameter:
    9951: .   c - coloring context

    9953:     Level: intermediate

    9955: .seealso: MatTransposeColoringCreate()
    9956: @*/
    9957: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
    9958: {
    9959:   PetscErrorCode       ierr;
    9960:   MatTransposeColoring matcolor=*c;

    9963:   if (!matcolor) return(0);
    9964:   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; return(0);}

    9966:   PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
    9967:   PetscFree(matcolor->rows);
    9968:   PetscFree(matcolor->den2sp);
    9969:   PetscFree(matcolor->colorforcol);
    9970:   PetscFree(matcolor->columns);
    9971:   if (matcolor->brows>0) {
    9972:     PetscFree(matcolor->lstart);
    9973:   }
    9974:   PetscHeaderDestroy(c);
    9975:   return(0);
    9976: }

    9978: /*@C
    9979:     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
    9980:     a MatTransposeColoring context has been created, computes a dense B^T by Apply
    9981:     MatTransposeColoring to sparse B.

    9983:     Collective on MatTransposeColoring

    9985:     Input Parameters:
    9986: +   B - sparse matrix B
    9987: .   Btdense - symbolic dense matrix B^T
    9988: -   coloring - coloring context created with MatTransposeColoringCreate()

    9990:     Output Parameter:
    9991: .   Btdense - dense matrix B^T

    9993:     Level: advanced

    9995:      Notes:
    9996:     These are used internally for some implementations of MatRARt()

    9998: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()

    10000: @*/
    10001: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
    10002: {

    10010:   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
    10011:   (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
    10012:   return(0);
    10013: }

    10015: /*@C
    10016:     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
    10017:     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
    10018:     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
    10019:     Csp from Cden.

    10021:     Collective on MatTransposeColoring

    10023:     Input Parameters:
    10024: +   coloring - coloring context created with MatTransposeColoringCreate()
    10025: -   Cden - matrix product of a sparse matrix and a dense matrix Btdense

    10027:     Output Parameter:
    10028: .   Csp - sparse matrix

    10030:     Level: advanced

    10032:      Notes:
    10033:     These are used internally for some implementations of MatRARt()

    10035: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()

    10037: @*/
    10038: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
    10039: {

    10047:   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
    10048:   (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
    10049:   MatAssemblyBegin(Csp,MAT_FINAL_ASSEMBLY);
    10050:   MatAssemblyEnd(Csp,MAT_FINAL_ASSEMBLY);
    10051:   return(0);
    10052: }

    10054: /*@C
    10055:    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.

    10057:    Collective on Mat

    10059:    Input Parameters:
    10060: +  mat - the matrix product C
    10061: -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()

    10063:     Output Parameter:
    10064: .   color - the new coloring context

    10066:     Level: intermediate

    10068: .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
    10069:            MatTransColoringApplyDenToSp()
    10070: @*/
    10071: PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
    10072: {
    10073:   MatTransposeColoring c;
    10074:   MPI_Comm             comm;
    10075:   PetscErrorCode       ierr;

    10078:   PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
    10079:   PetscObjectGetComm((PetscObject)mat,&comm);
    10080:   PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);

    10082:   c->ctype = iscoloring->ctype;
    10083:   if (mat->ops->transposecoloringcreate) {
    10084:     (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
    10085:   } else SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for matrix type %s",((PetscObject)mat)->type_name);

    10087:   *color = c;
    10088:   PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
    10089:   return(0);
    10090: }

    10092: /*@
    10093:       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
    10094:         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
    10095:         same, otherwise it will be larger

    10097:      Not Collective

    10099:   Input Parameter:
    10100: .    A  - the matrix

    10102:   Output Parameter:
    10103: .    state - the current state

    10105:   Notes:
    10106:     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
    10107:          different matrices

    10109:   Level: intermediate

    10111: @*/
    10112: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
    10113: {
    10116:   *state = mat->nonzerostate;
    10117:   return(0);
    10118: }

    10120: /*@
    10121:       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
    10122:                  matrices from each processor

    10124:     Collective

    10126:    Input Parameters:
    10127: +    comm - the communicators the parallel matrix will live on
    10128: .    seqmat - the input sequential matrices
    10129: .    n - number of local columns (or PETSC_DECIDE)
    10130: -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

    10132:    Output Parameter:
    10133: .    mpimat - the parallel matrix generated

    10135:     Level: advanced

    10137:    Notes:
    10138:     The number of columns of the matrix in EACH processor MUST be the same.

    10140: @*/
    10141: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
    10142: {

    10146:   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
    10147:   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");

    10149:   PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
    10150:   (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
    10151:   PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
    10152:   return(0);
    10153: }

    10155: /*@
    10156:      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
    10157:                  ranks' ownership ranges.

    10159:     Collective on A

    10161:    Input Parameters:
    10162: +    A   - the matrix to create subdomains from
    10163: -    N   - requested number of subdomains

    10166:    Output Parameters:
    10167: +    n   - number of subdomains resulting on this rank
    10168: -    iss - IS list with indices of subdomains on this rank

    10170:     Level: advanced

    10172:     Notes:
    10173:     number of subdomains must be smaller than the communicator size
    10174: @*/
    10175: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
    10176: {
    10177:   MPI_Comm        comm,subcomm;
    10178:   PetscMPIInt     size,rank,color;
    10179:   PetscInt        rstart,rend,k;
    10180:   PetscErrorCode  ierr;

    10183:   PetscObjectGetComm((PetscObject)A,&comm);
    10184:   MPI_Comm_size(comm,&size);
    10185:   MPI_Comm_rank(comm,&rank);
    10186:   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);
    10187:   *n = 1;
    10188:   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
    10189:   color = rank/k;
    10190:   MPI_Comm_split(comm,color,rank,&subcomm);
    10191:   PetscMalloc1(1,iss);
    10192:   MatGetOwnershipRange(A,&rstart,&rend);
    10193:   ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);
    10194:   MPI_Comm_free(&subcomm);
    10195:   return(0);
    10196: }

    10198: /*@
    10199:    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.

    10201:    If the interpolation and restriction operators are the same, uses MatPtAP.
    10202:    If they are not the same, use MatMatMatMult.

    10204:    Once the coarse grid problem is constructed, correct for interpolation operators
    10205:    that are not of full rank, which can legitimately happen in the case of non-nested
    10206:    geometric multigrid.

    10208:    Input Parameters:
    10209: +  restrct - restriction operator
    10210: .  dA - fine grid matrix
    10211: .  interpolate - interpolation operator
    10212: .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
    10213: -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate

    10215:    Output Parameters:
    10216: .  A - the Galerkin coarse matrix

    10218:    Options Database Key:
    10219: .  -pc_mg_galerkin <both,pmat,mat,none>

    10221:    Level: developer

    10223: .seealso: MatPtAP(), MatMatMatMult()
    10224: @*/
    10225: PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
    10226: {
    10228:   IS             zerorows;
    10229:   Vec            diag;

    10232:   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
    10233:   /* Construct the coarse grid matrix */
    10234:   if (interpolate == restrct) {
    10235:     MatPtAP(dA,interpolate,reuse,fill,A);
    10236:   } else {
    10237:     MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);
    10238:   }

    10240:   /* If the interpolation matrix is not of full rank, A will have zero rows.
    10241:      This can legitimately happen in the case of non-nested geometric multigrid.
    10242:      In that event, we set the rows of the matrix to the rows of the identity,
    10243:      ignoring the equations (as the RHS will also be zero). */

    10245:   MatFindZeroRows(*A, &zerorows);

    10247:   if (zerorows != NULL) { /* if there are any zero rows */
    10248:     MatCreateVecs(*A, &diag, NULL);
    10249:     MatGetDiagonal(*A, diag);
    10250:     VecISSet(diag, zerorows, 1.0);
    10251:     MatDiagonalSet(*A, diag, INSERT_VALUES);
    10252:     VecDestroy(&diag);
    10253:     ISDestroy(&zerorows);
    10254:   }
    10255:   return(0);
    10256: }

    10258: /*@C
    10259:     MatSetOperation - Allows user to set a matrix operation for any matrix type

    10261:    Logically Collective on Mat

    10263:     Input Parameters:
    10264: +   mat - the matrix
    10265: .   op - the name of the operation
    10266: -   f - the function that provides the operation

    10268:    Level: developer

    10270:     Usage:
    10271: $      extern PetscErrorCode usermult(Mat,Vec,Vec);
    10272: $      MatCreateXXX(comm,...&A);
    10273: $      MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);

    10275:     Notes:
    10276:     See the file include/petscmat.h for a complete list of matrix
    10277:     operations, which all have the form MATOP_<OPERATION>, where
    10278:     <OPERATION> is the name (in all capital letters) of the
    10279:     user interface routine (e.g., MatMult() -> MATOP_MULT).

    10281:     All user-provided functions (except for MATOP_DESTROY) should have the same calling
    10282:     sequence as the usual matrix interface routines, since they
    10283:     are intended to be accessed via the usual matrix interface
    10284:     routines, e.g.,
    10285: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

    10287:     In particular each function MUST return an error code of 0 on success and
    10288:     nonzero on failure.

    10290:     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.

    10292: .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
    10293: @*/
    10294: PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
    10295: {
    10298:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
    10299:     mat->ops->viewnative = mat->ops->view;
    10300:   }
    10301:   (((void(**)(void))mat->ops)[op]) = f;
    10302:   return(0);
    10303: }

    10305: /*@C
    10306:     MatGetOperation - Gets a matrix operation for any matrix type.

    10308:     Not Collective

    10310:     Input Parameters:
    10311: +   mat - the matrix
    10312: -   op - the name of the operation

    10314:     Output Parameter:
    10315: .   f - the function that provides the operation

    10317:     Level: developer

    10319:     Usage:
    10320: $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
    10321: $      MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);

    10323:     Notes:
    10324:     See the file include/petscmat.h for a complete list of matrix
    10325:     operations, which all have the form MATOP_<OPERATION>, where
    10326:     <OPERATION> is the name (in all capital letters) of the
    10327:     user interface routine (e.g., MatMult() -> MATOP_MULT).

    10329:     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.

    10331: .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
    10332: @*/
    10333: PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
    10334: {
    10337:   *f = (((void (**)(void))mat->ops)[op]);
    10338:   return(0);
    10339: }

    10341: /*@
    10342:     MatHasOperation - Determines whether the given matrix supports the particular
    10343:     operation.

    10345:    Not Collective

    10347:    Input Parameters:
    10348: +  mat - the matrix
    10349: -  op - the operation, for example, MATOP_GET_DIAGONAL

    10351:    Output Parameter:
    10352: .  has - either PETSC_TRUE or PETSC_FALSE

    10354:    Level: advanced

    10356:    Notes:
    10357:    See the file include/petscmat.h for a complete list of matrix
    10358:    operations, which all have the form MATOP_<OPERATION>, where
    10359:    <OPERATION> is the name (in all capital letters) of the
    10360:    user-level routine.  E.g., MatNorm() -> MATOP_NORM.

    10362: .seealso: MatCreateShell()
    10363: @*/
    10364: PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
    10365: {

    10372:   if (mat->ops->hasoperation) {
    10373:     (*mat->ops->hasoperation)(mat,op,has);
    10374:   } else {
    10375:     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
    10376:     else {
    10377:       *has = PETSC_FALSE;
    10378:       if (op == MATOP_CREATE_SUBMATRIX) {
    10379:         PetscMPIInt size;

    10381:         MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
    10382:         if (size == 1) {
    10383:           MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);
    10384:         }
    10385:       }
    10386:     }
    10387:   }
    10388:   return(0);
    10389: }

    10391: /*@
    10392:     MatHasCongruentLayouts - Determines whether the rows and columns layouts
    10393:     of the matrix are congruent

    10395:    Collective on mat

    10397:    Input Parameters:
    10398: .  mat - the matrix

    10400:    Output Parameter:
    10401: .  cong - either PETSC_TRUE or PETSC_FALSE

    10403:    Level: beginner

    10405:    Notes:

    10407: .seealso: MatCreate(), MatSetSizes()
    10408: @*/
    10409: PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
    10410: {

    10417:   if (!mat->rmap || !mat->cmap) {
    10418:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
    10419:     return(0);
    10420:   }
    10421:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
    10422:     PetscLayoutCompare(mat->rmap,mat->cmap,cong);
    10423:     if (*cong) mat->congruentlayouts = 1;
    10424:     else       mat->congruentlayouts = 0;
    10425:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
    10426:   return(0);
    10427: }

    10429: /*@
    10430:     MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
    10431:     e.g., matrx product of MatPtAP.

    10433:    Collective on mat

    10435:    Input Parameters:
    10436: .  mat - the matrix

    10438:    Output Parameter:
    10439: .  mat - the matrix with intermediate data structures released

    10441:    Level: advanced

    10443:    Notes:

    10445: .seealso: MatPtAP(), MatMatMult()
    10446: @*/
    10447: PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
    10448: {

    10454:   if (mat->ops->freeintermediatedatastructures) {
    10455:     (*mat->ops->freeintermediatedatastructures)(mat);
    10456:   }
    10457:   return(0);
    10458: }