Actual source code: matrix.c

  1: #define PETSCMAT_DLL

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

 7:  #include include/private/matimpl.h
 8:  #include private/vecimpl.h

 10: /* Logging support */
 11: PetscCookie  MAT_COOKIE = 0;
 12: PetscEvent  MAT_Mult = 0, MAT_Mults = 0, MAT_MultConstrained = 0, MAT_MultAdd = 0, MAT_MultTranspose = 0;
 13: PetscEvent  MAT_MultTransposeConstrained = 0, MAT_MultTransposeAdd = 0, MAT_Solve = 0, MAT_Solves = 0, MAT_SolveAdd = 0, MAT_SolveTranspose = 0, MAT_MatSolve = 0;
 14: PetscEvent  MAT_SolveTransposeAdd = 0, MAT_Relax = 0, MAT_ForwardSolve = 0, MAT_BackwardSolve = 0, MAT_LUFactor = 0, MAT_LUFactorSymbolic = 0;
 15: PetscEvent  MAT_LUFactorNumeric = 0, MAT_CholeskyFactor = 0, MAT_CholeskyFactorSymbolic = 0, MAT_CholeskyFactorNumeric = 0, MAT_ILUFactor = 0;
 16: PetscEvent  MAT_ILUFactorSymbolic = 0, MAT_ICCFactorSymbolic = 0, MAT_Copy = 0, MAT_Convert = 0, MAT_Scale = 0, MAT_AssemblyBegin = 0;
 17: PetscEvent  MAT_AssemblyEnd = 0, MAT_SetValues = 0, MAT_GetValues = 0, MAT_GetRow = 0, MAT_GetRowIJ = 0, MAT_GetSubMatrices = 0, MAT_GetColoring = 0, MAT_GetOrdering = 0, MAT_GetRedundantMatrix = 0, MAT_GetSeqNonzeroStructure = 0;
 18: PetscEvent  MAT_IncreaseOverlap = 0, MAT_Partitioning = 0, MAT_ZeroEntries = 0, MAT_Load = 0, MAT_View = 0, MAT_AXPY = 0, MAT_FDColoringCreate = 0;
 19: PetscEvent  MAT_FDColoringApply = 0,MAT_Transpose = 0,MAT_FDColoringFunction = 0;
 20: PetscEvent  MAT_MatMult = 0, MAT_MatMultSymbolic = 0, MAT_MatMultNumeric = 0;
 21: PetscEvent  MAT_PtAP = 0, MAT_PtAPSymbolic = 0, MAT_PtAPNumeric = 0;
 22: PetscEvent  MAT_MatMultTranspose = 0, MAT_MatMultTransposeSymbolic = 0, MAT_MatMultTransposeNumeric = 0;
 23: PetscEvent  MAT_Getsymtranspose = 0, MAT_Getsymtransreduced = 0, MAT_Transpose_SeqAIJ = 0, MAT_GetBrowsOfAcols = 0;
 24: PetscEvent  MAT_GetBrowsOfAocols = 0, MAT_Getlocalmat = 0, MAT_Getlocalmatcondensed = 0, MAT_Seqstompi = 0, MAT_Seqstompinum = 0, MAT_Seqstompisym = 0;
 25: PetscEvent  MAT_Applypapt = 0, MAT_Applypapt_numeric = 0, MAT_Applypapt_symbolic = 0, MAT_GetSequentialNonzeroStructure = 0;

 27: /* nasty global values for MatSetValue() */
 28: PetscInt     MatSetValue_Row = 0;
 29: PetscInt     MatSetValue_Column = 0;
 30: PetscScalar  MatSetValue_Value = 0.0;

 34: /*@
 35:    MatRealPart - Zeros out the imaginary part of the matrix

 37:    Collective on Mat

 39:    Input Parameters:
 40: .  mat - the matrix

 42:    Level: advanced


 45: .seealso: MatImaginaryPart()
 46: @*/

 48: PetscErrorCode  MatRealPart(Mat mat)
 49: {

 55:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
 56:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
 57:   if (!mat->ops->realpart) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
 58:   MatPreallocated(mat);
 59:   (*mat->ops->realpart)(mat);
 60:   return(0);
 61: }


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

 69:    Collective on Mat

 71:    Input Parameters:
 72: .  mat - the matrix

 74:    Level: advanced


 77: .seealso: MatRealPart()
 78: @*/

 80: PetscErrorCode  MatImaginaryPart(Mat mat)
 81: {

 87:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
 88:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
 89:   if (!mat->ops->imaginarypart) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
 90:   MatPreallocated(mat);
 91:   (*mat->ops->imaginarypart)(mat);
 92:   return(0);
 93: }

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

100:    Collective on Mat

102:    Input Parameter:
103: .  mat - the matrix

105:    Output Parameters:
106: +  missing - is any diagonal missing
107: -  dd - first diagonal entry that is missing (optional)

109:    Level: advanced


112: .seealso: MatRealPart()
113: @*/

115: PetscErrorCode  MatMissingDiagonal(Mat mat,PetscTruth *missing,PetscInt *dd)
116: {

122:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
123:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
124:   if (!mat->ops->missingdiagonal) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
125:   (*mat->ops->missingdiagonal)(mat,missing,dd);
126:   return(0);
127: }

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

136:    Not Collective

138:    Input Parameters:
139: +  mat - the matrix
140: -  row - the row to get

142:    Output Parameters:
143: +  ncols -  if not NULL, the number of nonzeros in the row
144: .  cols - if not NULL, the column numbers
145: -  vals - if not NULL, the values

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

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

155:    For better efficiency, set cols and/or vals to PETSC_NULL if you do
156:    not wish to extract these quantities.

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

162:    You can only have one call to MatGetRow() outstanding for a particular
163:    matrix at a time, per processor. MatGetRow() can only obtain rows
164:    associated with the given processor, it cannot get rows from the 
165:    other processors; for that we suggest using MatGetSubMatrices(), then
166:    MatGetRow() on the submatrix. The row indix passed to MatGetRows() 
167:    is in the global number of rows.

169:    Fortran Notes:
170:    The calling sequence from Fortran is 
171: .vb
172:    MatGetRow(matrix,row,ncols,cols,values,ierr)
173:          Mat     matrix (input)
174:          integer row    (input)
175:          integer ncols  (output)
176:          integer cols(maxcols) (output)
177:          double precision (or double complex) values(maxcols) output
178: .ve
179:    where maxcols >= maximum nonzeros in any row of the matrix.


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

186:    Level: advanced

188:    Concepts: matrices^row access

190: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatGetSubMatrices(), MatGetDiagonal()
191: @*/

193: PetscErrorCode  MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
194: {
196:   PetscInt       incols;

201:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
202:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
203:   if (!mat->ops->getrow) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
204:   MatPreallocated(mat);
206:   (*mat->ops->getrow)(mat,row,&incols,(PetscInt **)cols,(PetscScalar **)vals);
207:   if (ncols) *ncols = incols;
209:   return(0);
210: }

214: /*@
215:    MatConjugate - replaces the matrix values with their complex conjugates

217:    Collective on Mat

219:    Input Parameters:
220: .  mat - the matrix

222:    Level: advanced

224: .seealso:  VecConjugate()
225: @*/
226: PetscErrorCode  MatConjugate(Mat mat)
227: {

232:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
233:   if (!mat->ops->conjugate) SETERRQ(PETSC_ERR_SUP,"Not provided for this matrix format, send email to petsc-maint@mcs.anl.gov");
234:   (*mat->ops->conjugate)(mat);
235:   return(0);
236: }

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

243:    Not Collective

245:    Input Parameters:
246: +  mat - the matrix
247: .  row - the row to get
248: .  ncols, cols - the number of nonzeros and their columns
249: -  vals - if nonzero the column values

251:    Notes: 
252:    This routine should be called after you have finished examining the entries.

254:    Fortran Notes:
255:    The calling sequence from Fortran is 
256: .vb
257:    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
258:       Mat     matrix (input)
259:       integer row    (input)
260:       integer ncols  (output)
261:       integer cols(maxcols) (output)
262:       double precision (or double complex) values(maxcols) output
263: .ve
264:    Where maxcols >= maximum nonzeros in any row of the matrix. 

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

269:    Level: advanced

271: .seealso:  MatGetRow()
272: @*/
273: PetscErrorCode  MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
274: {

280:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
281:   if (!mat->ops->restorerow) return(0);
282:   (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
283:   return(0);
284: }

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

292:    Not Collective

294:    Input Parameters:
295: +  mat - the matrix

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

300:    Level: advanced

302:    Concepts: matrices^row access

304: .seealso: MatRestoreRowRowUpperTriangular()
305: @*/

307: PetscErrorCode  MatGetRowUpperTriangular(Mat mat)
308: {

314:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
315:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
316:   if (!mat->ops->getrowuppertriangular) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
317:   MatPreallocated(mat);
318:   (*mat->ops->getrowuppertriangular)(mat);
319:   return(0);
320: }

324: /*@C  
325:    MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.  

327:    Not Collective

329:    Input Parameters:
330: +  mat - the matrix

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


336:    Level: advanced

338: .seealso:  MatGetRowUpperTriangular()
339: @*/
340: PetscErrorCode  MatRestoreRowUpperTriangular(Mat mat)
341: {

346:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
347:   if (!mat->ops->restorerowuppertriangular) return(0);
348:   (*mat->ops->restorerowuppertriangular)(mat);
349:   return(0);
350: }

354: /*@C
355:    MatSetOptionsPrefix - Sets the prefix used for searching for all 
356:    Mat options in the database.

358:    Collective on Mat

360:    Input Parameter:
361: +  A - the Mat context
362: -  prefix - the prefix to prepend to all option names

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

368:    Level: advanced

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

372: .seealso: MatSetFromOptions()
373: @*/
374: PetscErrorCode  MatSetOptionsPrefix(Mat A,const char prefix[])
375: {

380:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
381:   return(0);
382: }

386: /*@C
387:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all 
388:    Mat options in the database.

390:    Collective on Mat

392:    Input Parameters:
393: +  A - the Mat context
394: -  prefix - the prefix to prepend to all option names

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

400:    Level: advanced

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

404: .seealso: MatGetOptionsPrefix()
405: @*/
406: PetscErrorCode  MatAppendOptionsPrefix(Mat A,const char prefix[])
407: {
409: 
412:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
413:   return(0);
414: }

418: /*@C
419:    MatGetOptionsPrefix - Sets the prefix used for searching for all 
420:    Mat options in the database.

422:    Not Collective

424:    Input Parameter:
425: .  A - the Mat context

427:    Output Parameter:
428: .  prefix - pointer to the prefix string used

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

433:    Level: advanced

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

437: .seealso: MatAppendOptionsPrefix()
438: @*/
439: PetscErrorCode  MatGetOptionsPrefix(Mat A,const char *prefix[])
440: {

445:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
446:   return(0);
447: }

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

454:    Collective on Mat

456:    Input Parameters:
457: .  A - the Mat context

459:    Notes:
460:    For basic use of the Mat classes the user need not explicitly call
461:    MatSetUp(), since these actions will happen automatically.

463:    Level: advanced

465: .keywords: Mat, setup

467: .seealso: MatCreate(), MatDestroy()
468: @*/
469: PetscErrorCode  MatSetUp(Mat A)
470: {
471:   PetscMPIInt    size;

476:   if (!((PetscObject)A)->type_name) {
477:     MPI_Comm_size(((PetscObject)A)->comm, &size);
478:     if (size == 1) {
479:       MatSetType(A, MATSEQAIJ);
480:     } else {
481:       MatSetType(A, MATMPIAIJ);
482:     }
483:   }
484:   MatSetUpPreallocation(A);
485:   return(0);
486: }

490: /*@C
491:    MatView - Visualizes a matrix object.

493:    Collective on Mat

495:    Input Parameters:
496: +  mat - the matrix
497: -  viewer - visualization context

499:   Notes:
500:   The available visualization contexts include
501: +    PETSC_VIEWER_STDOUT_SELF - standard output (default)
502: .    PETSC_VIEWER_STDOUT_WORLD - synchronized standard
503:         output where only the first processor opens
504:         the file.  All other processors send their 
505:         data to the first processor to print. 
506: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

508:    The user can open alternative visualization contexts with
509: +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
510: .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
511:          specified file; corresponding input uses MatLoad()
512: .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to 
513:          an X window display
514: -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
515:          Currently only the sequential dense and AIJ
516:          matrix types support the Socket viewer.

518:    The user can call PetscViewerSetFormat() to specify the output
519:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
520:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
521: +    PETSC_VIEWER_ASCII_DEFAULT - default, prints matrix contents
522: .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
523: .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
524: .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse 
525:          format common among all matrix types
526: .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific 
527:          format (which is in many cases the same as the default)
528: .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
529:          size and structure (not the matrix entries)
530: .    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
531:          the matrix structure

533:    Options Database Keys:
534: +  -mat_view_info - Prints info on matrix at conclusion of MatEndAssembly()
535: .  -mat_view_info_detailed - Prints more detailed info
536: .  -mat_view - Prints matrix in ASCII format
537: .  -mat_view_matlab - Prints matrix in Matlab format
538: .  -mat_view_draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
539: .  -display <name> - Sets display name (default is host)
540: .  -draw_pause <sec> - Sets number of seconds to pause after display
541: .  -mat_view_socket - Sends matrix to socket, can be accessed from Matlab (see users manual)
542: .  -viewer_socket_machine <machine>
543: .  -viewer_socket_port <port>
544: .  -mat_view_binary - save matrix to file in binary format
545: -  -viewer_binary_filename <name>
546:    Level: beginner

548:    Concepts: matrices^viewing
549:    Concepts: matrices^plotting
550:    Concepts: matrices^printing

552: .seealso: PetscViewerSetFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(), 
553:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
554: @*/
555: PetscErrorCode  MatView(Mat mat,PetscViewer viewer)
556: {
557:   PetscErrorCode    ierr;
558:   PetscInt          rows,cols;
559:   PetscTruth        iascii;
560:   const char        *cstr;
561:   PetscViewerFormat format;

566:   if (!viewer) {
567:     PetscViewerASCIIGetStdout(((PetscObject)mat)->comm,&viewer);
568:   }
571:   if (!mat->assembled) SETERRQ(PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
572:   MatPreallocated(mat);

574:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&iascii);
575:   if (iascii) {
576:     PetscViewerGetFormat(viewer,&format);
577:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
578:       if (((PetscObject)mat)->prefix) {
579:         PetscViewerASCIIPrintf(viewer,"Matrix Object:(%s)\n",((PetscObject)mat)->prefix);
580:       } else {
581:         PetscViewerASCIIPrintf(viewer,"Matrix Object:\n");
582:       }
583:       PetscViewerASCIIPushTab(viewer);
584:       MatGetType(mat,&cstr);
585:       MatGetSize(mat,&rows,&cols);
586:       PetscViewerASCIIPrintf(viewer,"type=%s, rows=%D, cols=%D\n",cstr,rows,cols);
587:       if (mat->ops->getinfo) {
588:         MatInfo info;
589:         MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
590:         PetscViewerASCIIPrintf(viewer,"total: nonzeros=%D, allocated nonzeros=%D\n",
591:                           (PetscInt)info.nz_used,(PetscInt)info.nz_allocated);
592:       }
593:     }
594:   }
595:   if (mat->ops->view) {
596:     PetscViewerASCIIPushTab(viewer);
597:     (*mat->ops->view)(mat,viewer);
598:     PetscViewerASCIIPopTab(viewer);
599:   } else if (!iascii) {
600:     SETERRQ1(PETSC_ERR_SUP,"Viewer type %s not supported",((PetscObject)viewer)->type_name);
601:   }
602:   if (iascii) {
603:     PetscViewerGetFormat(viewer,&format);
604:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
605:       PetscViewerASCIIPopTab(viewer);
606:     }
607:   }
608:   return(0);
609: }

613: /*@
614:    MatScaleSystem - Scale a vector solution and right hand side to 
615:    match the scaling of a scaled matrix.
616:   
617:    Collective on Mat

619:    Input Parameter:
620: +  mat - the matrix
621: .  b - right hand side vector (or PETSC_NULL)
622: -  x - solution vector (or PETSC_NULL)


625:    Notes: 
626:    For AIJ, BAIJ, and BDiag matrix formats, the matrices are not 
627:    internally scaled, so this does nothing. For MPIROWBS it
628:    permutes and diagonally scales.

630:    The KSP methods automatically call this routine when required
631:    (via PCPreSolve()) so it is rarely used directly.

633:    Level: Developer            

635:    Concepts: matrices^scaling

637: .seealso: MatUseScaledForm(), MatUnScaleSystem()
638: @*/
639: PetscErrorCode  MatScaleSystem(Mat mat,Vec b,Vec x)
640: {

646:   MatPreallocated(mat);

650:   if (mat->ops->scalesystem) {
651:     (*mat->ops->scalesystem)(mat,b,x);
652:   }
653:   return(0);
654: }

658: /*@
659:    MatUnScaleSystem - Unscales a vector solution and right hand side to 
660:    match the original scaling of a scaled matrix.
661:   
662:    Collective on Mat

664:    Input Parameter:
665: +  mat - the matrix
666: .  b - right hand side vector (or PETSC_NULL)
667: -  x - solution vector (or PETSC_NULL)


670:    Notes: 
671:    For AIJ, BAIJ, and BDiag matrix formats, the matrices are not 
672:    internally scaled, so this does nothing. For MPIROWBS it
673:    permutes and diagonally scales.

675:    The KSP methods automatically call this routine when required
676:    (via PCPreSolve()) so it is rarely used directly.

678:    Level: Developer            

680: .seealso: MatUseScaledForm(), MatScaleSystem()
681: @*/
682: PetscErrorCode  MatUnScaleSystem(Mat mat,Vec b,Vec x)
683: {

689:   MatPreallocated(mat);
692:   if (mat->ops->unscalesystem) {
693:     (*mat->ops->unscalesystem)(mat,b,x);
694:   }
695:   return(0);
696: }

700: /*@
701:    MatUseScaledForm - For matrix storage formats that scale the 
702:    matrix (for example MPIRowBS matrices are diagonally scaled on
703:    assembly) indicates matrix operations (MatMult() etc) are 
704:    applied using the scaled matrix.
705:   
706:    Collective on Mat

708:    Input Parameter:
709: +  mat - the matrix
710: -  scaled - PETSC_TRUE for applying the scaled, PETSC_FALSE for 
711:             applying the original matrix

713:    Notes: 
714:    For scaled matrix formats, applying the original, unscaled matrix
715:    will be slightly more expensive

717:    Level: Developer            

719: .seealso: MatScaleSystem(), MatUnScaleSystem()
720: @*/
721: PetscErrorCode  MatUseScaledForm(Mat mat,PetscTruth scaled)
722: {

728:   MatPreallocated(mat);
729:   if (mat->ops->usescaledform) {
730:     (*mat->ops->usescaledform)(mat,scaled);
731:   }
732:   return(0);
733: }

737: /*@
738:    MatDestroy - Frees space taken by a matrix.
739:   
740:    Collective on Mat

742:    Input Parameter:
743: .  A - the matrix

745:    Level: beginner

747: @*/
748: PetscErrorCode  MatDestroy(Mat A)
749: {
753:   if (--((PetscObject)A)->refct > 0) return(0);
754:   MatPreallocated(A);
755:   /* if memory was published with AMS then destroy it */
756:   PetscObjectDepublish(A);
757:   if (A->ops->destroy) {
758:     (*A->ops->destroy)(A);
759:   }
760:   if (A->mapping) {
761:     ISLocalToGlobalMappingDestroy(A->mapping);
762:   }
763:   if (A->bmapping) {
764:     ISLocalToGlobalMappingDestroy(A->bmapping);
765:   }
766:   PetscFree(A->rmap.range);
767:   PetscFree(A->cmap.range);
768:   if (A->spptr){PetscFree(A->spptr);}
769:   PetscHeaderDestroy(A);
770:   return(0);
771: }

775: /*@
776:    MatValid - Checks whether a matrix object is valid.

778:    Collective on Mat

780:    Input Parameter:
781: .  m - the matrix to check 

783:    Output Parameter:
784:    flg - flag indicating matrix status, either
785:    PETSC_TRUE if matrix is valid, or PETSC_FALSE otherwise.

787:    Level: developer

789:    Concepts: matrices^validity
790: @*/
791: PetscErrorCode  MatValid(Mat m,PetscTruth *flg)
792: {
795:   if (!m)                                          *flg = PETSC_FALSE;
796:   else if (((PetscObject)m)->cookie != MAT_COOKIE) *flg = PETSC_FALSE;
797:   else                                             *flg = PETSC_TRUE;
798:   return(0);
799: }

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

808:    Not Collective

810:    Input Parameters:
811: +  mat - the matrix
812: .  v - a logically two-dimensional array of values
813: .  m, idxm - the number of rows and their global indices 
814: .  n, idxn - the number of columns and their global indices
815: -  addv - either ADD_VALUES or INSERT_VALUES, where
816:    ADD_VALUES adds values to any existing entries, and
817:    INSERT_VALUES replaces existing entries with new values

819:    Notes:
820:    By default the values, v, are row-oriented and unsorted.
821:    See MatSetOption() for other options.

823:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES 
824:    options cannot be mixed without intervening calls to the assembly
825:    routines.

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

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

835:    Efficiency Alert:
836:    The routine MatSetValuesBlocked() may offer much better efficiency
837:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

839:    Level: beginner

841:    Concepts: matrices^putting entries in

843: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
844:           InsertMode, INSERT_VALUES, ADD_VALUES
845: @*/
846: PetscErrorCode  MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
847: {

851:   if (!m || !n) return(0); /* no values to insert */
857:   MatPreallocated(mat);
858:   if (mat->insertmode == NOT_SET_VALUES) {
859:     mat->insertmode = addv;
860:   }
861: #if defined(PETSC_USE_DEBUG)
862:   else if (mat->insertmode != addv) {
863:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
864:   }
865:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
866: #endif

868:   if (mat->assembled) {
869:     mat->was_assembled = PETSC_TRUE;
870:     mat->assembled     = PETSC_FALSE;
871:   }
873:   if (!mat->ops->setvalues) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
874:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
876:   return(0);
877: }


882: /*@ 
883:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
884:         values into a matrix

886:    Not Collective

888:    Input Parameters:
889: +  mat - the matrix
890: .  row - the (block) row to set
891: -  v - a logically two-dimensional array of values

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

896:    All the nonzeros in the row must be provided

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

900:    The row must belong to this process

902:    Level: intermediate

904:    Concepts: matrices^putting entries in

906: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
907:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
908: @*/
909: PetscErrorCode  MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
910: {

917:   MatSetValuesRow(mat, mat->mapping->indices[row],v);
918:   return(0);
919: }

923: /*@ 
924:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
925:         values into a matrix

927:    Not Collective

929:    Input Parameters:
930: +  mat - the matrix
931: .  row - the (block) row to set
932: -  v - a logically two-dimensional array of values

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

937:    All the nonzeros in the row must be provided

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

941:    The row must belong to this process

943:    Level: intermediate

945:    Concepts: matrices^putting entries in

947: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
948:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
949: @*/
950: PetscErrorCode  MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
951: {

958: #if defined(PETSC_USE_DEBUG)
959:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
960:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
961: #endif
962:   mat->insertmode = INSERT_VALUES;

964:   if (mat->assembled) {
965:     mat->was_assembled = PETSC_TRUE;
966:     mat->assembled     = PETSC_FALSE;
967:   }
969:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
970:   (*mat->ops->setvaluesrow)(mat,row,v);
972:   return(0);
973: }

977: /*@
978:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
979:      Using structured grid indexing

981:    Not Collective

983:    Input Parameters:
984: +  mat - the matrix
985: .  v - a logically two-dimensional array of values
986: .  m - number of rows being entered
987: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
988: .  n - number of columns being entered
989: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered 
990: -  addv - either ADD_VALUES or INSERT_VALUES, where
991:    ADD_VALUES adds values to any existing entries, and
992:    INSERT_VALUES replaces existing entries with new values

994:    Notes:
995:    By default the values, v, are row-oriented and unsorted.
996:    See MatSetOption() for other options.

998:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES 
999:    options cannot be mixed without intervening calls to the assembly
1000:    routines.

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

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

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

1009:    In order to use this routine you must either obtain the matrix with DAGetMatrix()
1010:    or call MatSetLocalToGlobalMapping() and MatSetStencil() first.

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

1018:    In Fortran idxm and idxn should be declared as
1019: $     MatStencil idxm(4,m),idxn(4,n)
1020:    and the values inserted using
1021: $    idxm(MatStencil_i,1) = i
1022: $    idxm(MatStencil_j,1) = j
1023: $    idxm(MatStencil_k,1) = k
1024: $    idxm(MatStencil_c,1) = c
1025:    etc

1027:    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be 
1028:    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1029:    etc to obtain values that obtained by wrapping the values from the left edge.

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

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

1037:    Efficiency Alert:
1038:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1039:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1041:    Level: beginner

1043:    Concepts: matrices^putting entries in

1045: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1046:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DAGetMatrix(), DAVecGetArray(), MatStencil
1047: @*/
1048: PetscErrorCode  MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1049: {
1051:   PetscInt       j,i,jdxm[128],jdxn[256],dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1052:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1062:   if (m > 128) SETERRQ1(PETSC_ERR_SUP,"Can only set 128 rows at a time; trying to set %D",m);
1063:   if (n > 256) SETERRQ1(PETSC_ERR_SUP,"Can only set 256 columns at a time; trying to set %D",n);

1065:   for (i=0; i<m; i++) {
1066:     for (j=0; j<3-sdim; j++) dxm++;
1067:     tmp = *dxm++ - starts[0];
1068:     for (j=0; j<dim-1; j++) {
1069:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1070:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1071:     }
1072:     if (mat->stencil.noc) dxm++;
1073:     jdxm[i] = tmp;
1074:   }
1075:   for (i=0; i<n; i++) {
1076:     for (j=0; j<3-sdim; j++) dxn++;
1077:     tmp = *dxn++ - starts[0];
1078:     for (j=0; j<dim-1; j++) {
1079:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1080:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1081:     }
1082:     if (mat->stencil.noc) dxn++;
1083:     jdxn[i] = tmp;
1084:   }
1085:   MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1086:   return(0);
1087: }

1091: /*@C 
1092:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1093:      Using structured grid indexing

1095:    Not Collective

1097:    Input Parameters:
1098: +  mat - the matrix
1099: .  v - a logically two-dimensional array of values
1100: .  m - number of rows being entered
1101: .  idxm - grid coordinates for matrix rows being entered
1102: .  n - number of columns being entered
1103: .  idxn - grid coordinates for matrix columns being entered 
1104: -  addv - either ADD_VALUES or INSERT_VALUES, where
1105:    ADD_VALUES adds values to any existing entries, and
1106:    INSERT_VALUES replaces existing entries with new values

1108:    Notes:
1109:    By default the values, v, are row-oriented and unsorted.
1110:    See MatSetOption() for other options.

1112:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES 
1113:    options cannot be mixed without intervening calls to the assembly
1114:    routines.

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

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

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

1123:    In order to use this routine you must either obtain the matrix with DAGetMatrix()
1124:    or call MatSetLocalToGlobalMapping() and MatSetStencil() first.

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

1132:    In Fortran idxm and idxn should be declared as
1133: $     MatStencil idxm(4,m),idxn(4,n)
1134:    and the values inserted using
1135: $    idxm(MatStencil_i,1) = i
1136: $    idxm(MatStencil_j,1) = j
1137: $    idxm(MatStencil_k,1) = k
1138:    etc

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

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

1148:    Level: beginner

1150:    Concepts: matrices^putting entries in

1152: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1153:           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DAGetMatrix(), DAVecGetArray(), MatStencil
1154: @*/
1155: PetscErrorCode  MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1156: {
1158:   PetscInt       j,i,jdxm[128],jdxn[256],dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1159:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

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

1169:   if (m > 128) SETERRQ1(PETSC_ERR_SUP,"Can only set 128 rows at a time; trying to set %D",m);
1170:   if (n > 128) SETERRQ1(PETSC_ERR_SUP,"Can only set 256 columns at a time; trying to set %D",n);

1172:   for (i=0; i<m; i++) {
1173:     for (j=0; j<3-sdim; j++) dxm++;
1174:     tmp = *dxm++ - starts[0];
1175:     for (j=0; j<sdim-1; j++) {
1176:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1177:       else                                      tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1178:     }
1179:     dxm++;
1180:     jdxm[i] = tmp;
1181:   }
1182:   for (i=0; i<n; i++) {
1183:     for (j=0; j<3-sdim; j++) dxn++;
1184:     tmp = *dxn++ - starts[0];
1185:     for (j=0; j<sdim-1; j++) {
1186:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1187:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1188:     }
1189:     dxn++;
1190:     jdxn[i] = tmp;
1191:   }
1192:   MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1193:   return(0);
1194: }

1198: /*@ 
1199:    MatSetStencil - Sets the grid information for setting values into a matrix via
1200:         MatSetValuesStencil()

1202:    Not Collective

1204:    Input Parameters:
1205: +  mat - the matrix
1206: .  dim - dimension of the grid 1, 2, or 3
1207: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1208: .  starts - starting point of ghost nodes on your processor in x, y, and z direction 
1209: -  dof - number of degrees of freedom per node


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

1215:    For matrices generated with DAGetMatrix() this routine is automatically called and so not needed by the
1216:    user.
1217:    
1218:    Level: beginner

1220:    Concepts: matrices^putting entries in

1222: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1223:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1224: @*/
1225: PetscErrorCode  MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1226: {
1227:   PetscInt i;


1234:   mat->stencil.dim = dim + (dof > 1);
1235:   for (i=0; i<dim; i++) {
1236:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1237:     mat->stencil.starts[i] = starts[dim-i-1];
1238:   }
1239:   mat->stencil.dims[dim]   = dof;
1240:   mat->stencil.starts[dim] = 0;
1241:   mat->stencil.noc         = (PetscTruth)(dof == 1);
1242:   return(0);
1243: }

1247: /*@ 
1248:    MatSetValuesBlocked - Inserts or adds a block of values into a matrix.

1250:    Not Collective

1252:    Input Parameters:
1253: +  mat - the matrix
1254: .  v - a logically two-dimensional array of values
1255: .  m, idxm - the number of block rows and their global block indices 
1256: .  n, idxn - the number of block columns and their global block indices
1257: -  addv - either ADD_VALUES or INSERT_VALUES, where
1258:    ADD_VALUES adds values to any existing entries, and
1259:    INSERT_VALUES replaces existing entries with new values

1261:    Notes:
1262:    The m and n count the NUMBER of blocks in the row direction and column direction,
1263:    NOT the total number of rows/columns; for example, if the block size is 2 and 
1264:    you are passing in values for rows 2,3,4,5  then m would be 2 (not 4).

1266:    By default the values, v, are row-oriented and unsorted. So the layout of 
1267:    v is the same as for MatSetValues(). See MatSetOption() for other options.

1269:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES 
1270:    options cannot be mixed without intervening calls to the assembly
1271:    routines.

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

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

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

1287:    Example:
1288: $   Suppose m=n=2 and block size(bs) = 2 The matrix is 
1289: $
1290: $   1  2  | 3  4
1291: $   5  6  | 7  8
1292: $   - - - | - - -
1293: $   9  10 | 11 12
1294: $   13 14 | 15 16
1295: $
1296: $   v[] should be passed in like
1297: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

1299:    Restrictions:
1300:    MatSetValuesBlocked() is currently supported only for the BAIJ and SBAIJ formats

1302:    Level: intermediate

1304:    Concepts: matrices^putting entries in blocked

1306: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1307: @*/
1308: PetscErrorCode  MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1309: {

1313:   if (!m || !n) return(0); /* no values to insert */
1319:   MatPreallocated(mat);
1320:   if (mat->insertmode == NOT_SET_VALUES) {
1321:     mat->insertmode = addv;
1322:   }
1323: #if defined(PETSC_USE_DEBUG) 
1324:   else if (mat->insertmode != addv) {
1325:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1326:   }
1327:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1328: #endif

1330:   if (mat->assembled) {
1331:     mat->was_assembled = PETSC_TRUE;
1332:     mat->assembled     = PETSC_FALSE;
1333:   }
1335:   if (!mat->ops->setvaluesblocked) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1336:   (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1338:   return(0);
1339: }

1343: /*@ 
1344:    MatGetValues - Gets a block of values from a matrix.

1346:    Not Collective; currently only returns a local block

1348:    Input Parameters:
1349: +  mat - the matrix
1350: .  v - a logically two-dimensional array for storing the values
1351: .  m, idxm - the number of rows and their global indices 
1352: -  n, idxn - the number of columns and their global indices

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

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

1362:    MatGetValues() requires that the matrix has been assembled
1363:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1364:    MatSetValues() and MatGetValues() CANNOT be made in succession
1365:    without intermediate matrix assembly.

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

1370:    Level: advanced

1372:    Concepts: matrices^accessing values

1374: .seealso: MatGetRow(), MatGetSubMatrices(), MatSetValues()
1375: @*/
1376: PetscErrorCode  MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1377: {

1386:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1387:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1388:   if (!mat->ops->getvalues) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1389:   MatPreallocated(mat);

1392:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1394:   return(0);
1395: }

1399: /*@
1400:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1401:    the routine MatSetValuesLocal() to allow users to insert matrix entries
1402:    using a local (per-processor) numbering.

1404:    Not Collective

1406:    Input Parameters:
1407: +  x - the matrix
1408: -  mapping - mapping created with ISLocalToGlobalMappingCreate() 
1409:              or ISLocalToGlobalMappingCreateIS()

1411:    Level: intermediate

1413:    Concepts: matrices^local to global mapping
1414:    Concepts: local to global mapping^for matrices

1416: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
1417: @*/
1418: PetscErrorCode  MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping mapping)
1419: {
1425:   if (x->mapping) {
1426:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Mapping already set for matrix");
1427:   }
1428:   MatPreallocated(x);

1430:   if (x->ops->setlocaltoglobalmapping) {
1431:     (*x->ops->setlocaltoglobalmapping)(x,mapping);
1432:   } else {
1433:     PetscObjectReference((PetscObject)mapping);
1434:     if (x->mapping) { ISLocalToGlobalMappingDestroy(x->mapping); }
1435:     x->mapping = mapping;
1436:   }
1437:   return(0);
1438: }

1442: /*@
1443:    MatSetLocalToGlobalMappingBlock - Sets a local-to-global numbering for use
1444:    by the routine MatSetValuesBlockedLocal() to allow users to insert matrix
1445:    entries using a local (per-processor) numbering.

1447:    Not Collective

1449:    Input Parameters:
1450: +  x - the matrix
1451: -  mapping - mapping created with ISLocalToGlobalMappingCreate() or
1452:              ISLocalToGlobalMappingCreateIS()

1454:    Level: intermediate

1456:    Concepts: matrices^local to global mapping blocked
1457:    Concepts: local to global mapping^for matrices, blocked

1459: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal(),
1460:            MatSetValuesBlocked(), MatSetValuesLocal()
1461: @*/
1462: PetscErrorCode  MatSetLocalToGlobalMappingBlock(Mat x,ISLocalToGlobalMapping mapping)
1463: {
1469:   if (x->bmapping) {
1470:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Mapping already set for matrix");
1471:   }
1472:   PetscObjectReference((PetscObject)mapping);
1473:   if (x->bmapping) { ISLocalToGlobalMappingDestroy(x->mapping); }
1474:   x->bmapping = mapping;
1475:   return(0);
1476: }

1480: /*@
1481:    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
1482:    using a local ordering of the nodes. 

1484:    Not Collective

1486:    Input Parameters:
1487: +  x - the matrix
1488: .  nrow, irow - number of rows and their local indices
1489: .  ncol, icol - number of columns and their local indices
1490: .  y -  a logically two-dimensional array of values
1491: -  addv - either INSERT_VALUES or ADD_VALUES, where
1492:    ADD_VALUES adds values to any existing entries, and
1493:    INSERT_VALUES replaces existing entries with new values

1495:    Notes:
1496:    Before calling MatSetValuesLocal(), the user must first set the
1497:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

1499:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES 
1500:    options cannot be mixed without intervening calls to the assembly
1501:    routines.

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

1506:    Level: intermediate

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

1510: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1511:            MatSetValueLocal()
1512: @*/
1513: PetscErrorCode  MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
1514: {
1516:   PetscInt       irowm[2048],icolm[2048];

1524:   MatPreallocated(mat);
1525:   if (mat->insertmode == NOT_SET_VALUES) {
1526:     mat->insertmode = addv;
1527:   }
1528: #if defined(PETSC_USE_DEBUG) 
1529:   else if (mat->insertmode != addv) {
1530:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1531:   }
1532:   if (!mat->ops->setvalueslocal && (nrow > 2048 || ncol > 2048)) {
1533:     SETERRQ2(PETSC_ERR_SUP,"Number column/row indices must be <= 2048: are %D %D",nrow,ncol);
1534:   }
1535:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1536: #endif

1538:   if (mat->assembled) {
1539:     mat->was_assembled = PETSC_TRUE;
1540:     mat->assembled     = PETSC_FALSE;
1541:   }
1543:   if (!mat->ops->setvalueslocal) {
1544:     ISLocalToGlobalMappingApply(mat->mapping,nrow,irow,irowm);
1545:     ISLocalToGlobalMappingApply(mat->mapping,ncol,icol,icolm);
1546:     (*mat->ops->setvalues)(mat,nrow,irowm,ncol,icolm,y,addv);
1547:   } else {
1548:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
1549:   }
1550:   mat->same_nonzero = PETSC_FALSE;
1552:   return(0);
1553: }

1557: /*@
1558:    MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
1559:    using a local ordering of the nodes a block at a time. 

1561:    Not Collective

1563:    Input Parameters:
1564: +  x - the matrix
1565: .  nrow, irow - number of rows and their local indices
1566: .  ncol, icol - number of columns and their local indices
1567: .  y -  a logically two-dimensional array of values
1568: -  addv - either INSERT_VALUES or ADD_VALUES, where
1569:    ADD_VALUES adds values to any existing entries, and
1570:    INSERT_VALUES replaces existing entries with new values

1572:    Notes:
1573:    Before calling MatSetValuesBlockedLocal(), the user must first set the
1574:    local-to-global mapping by calling MatSetLocalToGlobalMappingBlock(),
1575:    where the mapping MUST be set for matrix blocks, not for matrix elements.

1577:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES 
1578:    options cannot be mixed without intervening calls to the assembly
1579:    routines.

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

1584:    Level: intermediate

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

1588: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesLocal(), MatSetLocalToGlobalMappingBlock(), MatSetValuesBlocked()
1589: @*/
1590: PetscErrorCode  MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
1591: {
1593:   PetscInt       irowm[2048],icolm[2048];

1601:   MatPreallocated(mat);
1602:   if (mat->insertmode == NOT_SET_VALUES) {
1603:     mat->insertmode = addv;
1604:   }
1605: #if defined(PETSC_USE_DEBUG) 
1606:   else if (mat->insertmode != addv) {
1607:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1608:   }
1609:   if (!mat->bmapping) {
1610:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Local to global never set with MatSetLocalToGlobalMappingBlock()");
1611:   }
1612:   if (nrow > 2048 || ncol > 2048) {
1613:     SETERRQ2(PETSC_ERR_SUP,"Number column/row indices must be <= 2048: are %D %D",nrow,ncol);
1614:   }
1615:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1616: #endif

1618:   if (mat->assembled) {
1619:     mat->was_assembled = PETSC_TRUE;
1620:     mat->assembled     = PETSC_FALSE;
1621:   }
1623:   ISLocalToGlobalMappingApply(mat->bmapping,nrow,irow,irowm);
1624:   ISLocalToGlobalMappingApply(mat->bmapping,ncol,icol,icolm);
1625:   (*mat->ops->setvaluesblocked)(mat,nrow,irowm,ncol,icolm,y,addv);
1627:   return(0);
1628: }

1630: /* --------------------------------------------------------*/
1633: /*@
1634:    MatMult - Computes the matrix-vector product, y = Ax.

1636:    Collective on Mat and Vec

1638:    Input Parameters:
1639: +  mat - the matrix
1640: -  x   - the vector to be multiplied

1642:    Output Parameters:
1643: .  y - the result

1645:    Notes:
1646:    The vectors x and y cannot be the same.  I.e., one cannot
1647:    call MatMult(A,y,y).

1649:    Level: beginner

1651:    Concepts: matrix-vector product

1653: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
1654: @*/
1655: PetscErrorCode  MatMult(Mat mat,Vec x,Vec y)
1656: {


1665:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1666:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1667:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1668: #ifndef PETSC_HAVE_CONSTRAINTS
1669:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
1670:   if (mat->rmap.N != y->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap.N,y->map.N);
1671:   if (mat->rmap.n != y->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap.n,y->map.n);
1672: #endif
1673:   MatPreallocated(mat);

1675:   if (mat->nullsp) {
1676:     MatNullSpaceRemove(mat->nullsp,x,&x);
1677:   }

1679:   if (!mat->ops->mult) SETERRQ(PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
1681:   (*mat->ops->mult)(mat,x,y);

1684:   if (mat->nullsp) {
1685:     MatNullSpaceRemove(mat->nullsp,y,PETSC_NULL);
1686:   }
1687:   PetscObjectStateIncrease((PetscObject)y);
1688:   return(0);
1689: }

1693: /*@
1694:    MatMultTranspose - Computes matrix transpose times a vector.

1696:    Collective on Mat and Vec

1698:    Input Parameters:
1699: +  mat - the matrix
1700: -  x   - the vector to be multilplied

1702:    Output Parameters:
1703: .  y - the result

1705:    Notes:
1706:    The vectors x and y cannot be the same.  I.e., one cannot
1707:    call MatMultTranspose(A,y,y).

1709:    Level: beginner

1711:    Concepts: matrix vector product^transpose

1713: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd()
1714: @*/
1715: PetscErrorCode  MatMultTranspose(Mat mat,Vec x,Vec y)
1716: {


1725:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1726:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1727:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1728: #ifndef PETSC_HAVE_CONSTRAINTS
1729:   if (mat->rmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap.N,x->map.N);
1730:   if (mat->cmap.N != y->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap.N,y->map.N);
1731: #endif
1732:   MatPreallocated(mat);

1734:   if (!mat->ops->multtranspose) SETERRQ(PETSC_ERR_SUP,"This matrix type does not have a multiply tranpose defined");
1736:   (*mat->ops->multtranspose)(mat,x,y);
1738:   PetscObjectStateIncrease((PetscObject)y);
1739:   return(0);
1740: }

1744: /*@
1745:     MatMultAdd -  Computes v3 = v2 + A * v1.

1747:     Collective on Mat and Vec

1749:     Input Parameters:
1750: +   mat - the matrix
1751: -   v1, v2 - the vectors

1753:     Output Parameters:
1754: .   v3 - the result

1756:     Notes:
1757:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
1758:     call MatMultAdd(A,v1,v2,v1).

1760:     Level: beginner

1762:     Concepts: matrix vector product^addition

1764: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
1765: @*/
1766: PetscErrorCode  MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
1767: {


1777:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1778:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1779:   if (mat->cmap.N != v1->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->cmap.N,v1->map.N);
1780:   if (mat->rmap.N != v2->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->rmap.N,v2->map.N);
1781:   if (mat->rmap.N != v3->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->rmap.N,v3->map.N);
1782:   if (mat->rmap.n != v3->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: local dim %D %D",mat->rmap.n,v3->map.n);
1783:   if (mat->rmap.n != v2->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: local dim %D %D",mat->rmap.n,v2->map.n);
1784:   if (v1 == v3) SETERRQ(PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
1785:   MatPreallocated(mat);

1788:   (*mat->ops->multadd)(mat,v1,v2,v3);
1790:   PetscObjectStateIncrease((PetscObject)v3);
1791:   return(0);
1792: }

1796: /*@
1797:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

1799:    Collective on Mat and Vec

1801:    Input Parameters:
1802: +  mat - the matrix
1803: -  v1, v2 - the vectors

1805:    Output Parameters:
1806: .  v3 - the result

1808:    Notes:
1809:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
1810:    call MatMultTransposeAdd(A,v1,v2,v1).

1812:    Level: beginner

1814:    Concepts: matrix vector product^transpose and addition

1816: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
1817: @*/
1818: PetscErrorCode  MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
1819: {


1829:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1830:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1831:   if (!mat->ops->multtransposeadd) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1832:   if (v1 == v3) SETERRQ(PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
1833:   if (mat->rmap.N != v1->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap.N,v1->map.N);
1834:   if (mat->cmap.N != v2->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap.N,v2->map.N);
1835:   if (mat->cmap.N != v3->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap.N,v3->map.N);
1836:   MatPreallocated(mat);

1839:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
1841:   PetscObjectStateIncrease((PetscObject)v3);
1842:   return(0);
1843: }

1847: /*@
1848:    MatMultConstrained - The inner multiplication routine for a
1849:    constrained matrix P^T A P.

1851:    Collective on Mat and Vec

1853:    Input Parameters:
1854: +  mat - the matrix
1855: -  x   - the vector to be multilplied

1857:    Output Parameters:
1858: .  y - the result

1860:    Notes:
1861:    The vectors x and y cannot be the same.  I.e., one cannot
1862:    call MatMult(A,y,y).

1864:    Level: beginner

1866: .keywords: matrix, multiply, matrix-vector product, constraint
1867: .seealso: MatMult(), MatMultTrans(), MatMultAdd(), MatMultTransAdd()
1868: @*/
1869: PetscErrorCode  MatMultConstrained(Mat mat,Vec x,Vec y)
1870: {

1877:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1878:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1879:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1880:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
1881:   if (mat->rmap.N != y->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap.N,y->map.N);
1882:   if (mat->rmap.n != y->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap.n,y->map.n);

1885:   (*mat->ops->multconstrained)(mat,x,y);
1887:   PetscObjectStateIncrease((PetscObject)y);

1889:   return(0);
1890: }

1894: /*@
1895:    MatMultTransposeConstrained - The inner multiplication routine for a
1896:    constrained matrix P^T A^T P.

1898:    Collective on Mat and Vec

1900:    Input Parameters:
1901: +  mat - the matrix
1902: -  x   - the vector to be multilplied

1904:    Output Parameters:
1905: .  y - the result

1907:    Notes:
1908:    The vectors x and y cannot be the same.  I.e., one cannot
1909:    call MatMult(A,y,y).

1911:    Level: beginner

1913: .keywords: matrix, multiply, matrix-vector product, constraint
1914: .seealso: MatMult(), MatMultTrans(), MatMultAdd(), MatMultTransAdd()
1915: @*/
1916: PetscErrorCode  MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
1917: {

1924:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1925:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1926:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1927:   if (mat->rmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
1928:   if (mat->cmap.N != y->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap.N,y->map.N);

1931:   (*mat->ops->multtransposeconstrained)(mat,x,y);
1933:   PetscObjectStateIncrease((PetscObject)y);

1935:   return(0);
1936: }
1937: /* ------------------------------------------------------------*/
1940: /*@
1941:    MatGetInfo - Returns information about matrix storage (number of
1942:    nonzeros, memory, etc.).

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

1947:    Input Parameters:
1948: .  mat - the matrix

1950:    Output Parameters:
1951: +  flag - flag indicating the type of parameters to be returned
1952:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
1953:    MAT_GLOBAL_SUM - sum over all processors)
1954: -  info - matrix information context

1956:    Notes:
1957:    The MatInfo context contains a variety of matrix data, including
1958:    number of nonzeros allocated and used, number of mallocs during
1959:    matrix assembly, etc.  Additional information for factored matrices
1960:    is provided (such as the fill ratio, number of mallocs during
1961:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
1962:    when using the runtime options 
1963: $       -info -mat_view_info

1965:    Example for C/C++ Users:
1966:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
1967:    data within the MatInfo context.  For example, 
1968: .vb
1969:       MatInfo info;
1970:       Mat     A;
1971:       double  mal, nz_a, nz_u;

1973:       MatGetInfo(A,MAT_LOCAL,&info);
1974:       mal  = info.mallocs;
1975:       nz_a = info.nz_allocated;
1976: .ve

1978:    Example for Fortran Users:
1979:    Fortran users should declare info as a double precision
1980:    array of dimension MAT_INFO_SIZE, and then extract the parameters
1981:    of interest.  See the file ${PETSC_DIR}/include/finclude/petscmat.h
1982:    a complete list of parameter names.
1983: .vb
1984:       double  precision info(MAT_INFO_SIZE)
1985:       double  precision mal, nz_a
1986:       Mat     A
1987:       integer ierr

1989:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
1990:       mal = info(MAT_INFO_MALLOCS)
1991:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
1992: .ve

1994:     Level: intermediate

1996:     Concepts: matrices^getting information on
1997:  
1998: @*/
1999: PetscErrorCode  MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2000: {

2007:   if (!mat->ops->getinfo) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2008:   MatPreallocated(mat);
2009:   (*mat->ops->getinfo)(mat,flag,info);
2010:   return(0);
2011: }

2013: /* ----------------------------------------------------------*/
2016: /*@C  
2017:    MatILUDTFactor - Performs a drop tolerance ILU factorization.

2019:    Collective on Mat

2021:    Input Parameters:
2022: +  mat - the matrix
2023: .  row - row permutation
2024: .  col - column permutation
2025: -  info - information about the factorization to be done

2027:    Output Parameters:
2028: .  fact - the factored matrix

2030:    Level: developer

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

2037:    This is currently only supported for the SeqAIJ matrix format using code
2038:    from Yousef Saad's SPARSEKIT2  package (translated to C with f2c) and/or
2039:    Matlab. SPARSEKIT2 is copyrighted by Yousef Saad with the GNU copyright
2040:    and thus can be distributed with PETSc.

2042:     Concepts: matrices^ILUDT factorization

2044: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2045: @*/
2046: PetscErrorCode  MatILUDTFactor(Mat mat,IS row,IS col,MatFactorInfo *info,Mat *fact)
2047: {

2057:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2058:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2059:   if (!mat->ops->iludtfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2060:   MatPreallocated(mat);
2062:   (*mat->ops->iludtfactor)(mat,row,col,info,fact);
2064:   PetscObjectStateIncrease((PetscObject)*fact);

2066:   return(0);
2067: }

2071: /*@  
2072:    MatLUFactor - Performs in-place LU factorization of matrix.

2074:    Collective on Mat

2076:    Input Parameters:
2077: +  mat - the matrix
2078: .  row - row permutation
2079: .  col - column permutation
2080: -  info - options for factorization, includes 
2081: $          fill - expected fill as ratio of original fill.
2082: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2083: $                   Run with the option -info to determine an optimal value to use

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

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

2093:    Level: developer

2095:    Concepts: matrices^LU factorization

2097: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2098:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo

2100: @*/
2101: PetscErrorCode  MatLUFactor(Mat mat,IS row,IS col,MatFactorInfo *info)
2102: {

2111:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2112:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2113:   if (!mat->ops->lufactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2114:   MatPreallocated(mat);

2117:   (*mat->ops->lufactor)(mat,row,col,info);
2119:   PetscObjectStateIncrease((PetscObject)mat);
2120:   return(0);
2121: }

2125: /*@  
2126:    MatILUFactor - Performs in-place ILU factorization of matrix.

2128:    Collective on Mat

2130:    Input Parameters:
2131: +  mat - the matrix
2132: .  row - row permutation
2133: .  col - column permutation
2134: -  info - structure containing 
2135: $      levels - number of levels of fill.
2136: $      expected fill - as ratio of original fill.
2137: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2138:                 missing diagonal entries)

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

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

2148:    Level: developer

2150:    Concepts: matrices^ILU factorization

2152: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2153: @*/
2154: PetscErrorCode  MatILUFactor(Mat mat,IS row,IS col,MatFactorInfo *info)
2155: {

2164:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"matrix must be square");
2165:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2166:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2167:   if (!mat->ops->ilufactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2168:   MatPreallocated(mat);

2171:   (*mat->ops->ilufactor)(mat,row,col,info);
2173:   PetscObjectStateIncrease((PetscObject)mat);
2174:   return(0);
2175: }

2179: /*@  
2180:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2181:    Call this routine before calling MatLUFactorNumeric().

2183:    Collective on Mat

2185:    Input Parameters:
2186: +  mat - the matrix
2187: .  row, col - row and column permutations
2188: -  info - options for factorization, includes 
2189: $          fill - expected fill as ratio of original fill.
2190: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2191: $                   Run with the option -info to determine an optimal value to use

2193:    Output Parameter:
2194: .  fact - new matrix that has been symbolically factored

2196:    Notes:
2197:    See the users manual for additional information about
2198:    choosing the fill factor for better efficiency.

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

2204:    Level: developer

2206:    Concepts: matrices^LU symbolic factorization

2208: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2209: @*/
2210: PetscErrorCode  MatLUFactorSymbolic(Mat mat,IS row,IS col,MatFactorInfo *info,Mat *fact)
2211: {

2221:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2222:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2223:   if (!mat->ops->lufactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic LU",((PetscObject)mat)->type_name);
2224:   MatPreallocated(mat);

2227:   (*mat->ops->lufactorsymbolic)(mat,row,col,info,fact);
2229:   PetscObjectStateIncrease((PetscObject)*fact);
2230:   return(0);
2231: }

2235: /*@  
2236:    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
2237:    Call this routine after first calling MatLUFactorSymbolic().

2239:    Collective on Mat

2241:    Input Parameters:
2242: +  mat - the matrix
2243: .  info - options for factorization
2244: -  fact - the matrix generated for the factor, from MatLUFactorSymbolic()

2246:    Notes:
2247:    See MatLUFactor() for in-place factorization.  See 
2248:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.  

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

2254:    Level: developer

2256:    Concepts: matrices^LU numeric factorization

2258: .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
2259: @*/
2260: PetscErrorCode  MatLUFactorNumeric(Mat mat,MatFactorInfo *info,Mat *fact)
2261: {

2269:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2270:   if (mat->rmap.N != (*fact)->rmap.N || mat->cmap.N != (*fact)->cmap.N) {
2271:     SETERRQ4(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);
2272:   }
2273:   if (!(*fact)->ops->lufactornumeric) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2274:   MatPreallocated(mat);
2276:   (*(*fact)->ops->lufactornumeric)(mat,info,fact);

2279:   MatView_Private(*fact);
2280:   PetscObjectStateIncrease((PetscObject)*fact);
2281:   return(0);
2282: }

2286: /*@  
2287:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
2288:    symmetric matrix. 

2290:    Collective on Mat

2292:    Input Parameters:
2293: +  mat - the matrix
2294: .  perm - row and column permutations
2295: -  f - expected fill as ratio of original fill

2297:    Notes:
2298:    See MatLUFactor() for the nonsymmetric case.  See also
2299:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

2305:    Level: developer

2307:    Concepts: matrices^Cholesky factorization

2309: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
2310:           MatGetOrdering()

2312: @*/
2313: PetscErrorCode  MatCholeskyFactor(Mat mat,IS perm,MatFactorInfo *info)
2314: {

2322:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"Matrix must be square");
2323:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2324:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2325:   if (!mat->ops->choleskyfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2326:   MatPreallocated(mat);

2329:   (*mat->ops->choleskyfactor)(mat,perm,info);
2331:   PetscObjectStateIncrease((PetscObject)mat);
2332:   return(0);
2333: }

2337: /*@  
2338:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
2339:    of a symmetric matrix. 

2341:    Collective on Mat

2343:    Input Parameters:
2344: +  mat - the matrix
2345: .  perm - row and column permutations
2346: -  info - options for factorization, includes 
2347: $          fill - expected fill as ratio of original fill.
2348: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2349: $                   Run with the option -info to determine an optimal value to use

2351:    Output Parameter:
2352: .  fact - the factored matrix

2354:    Notes:
2355:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
2356:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

2362:    Level: developer

2364:    Concepts: matrices^Cholesky symbolic factorization

2366: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
2367:           MatGetOrdering()

2369: @*/
2370: PetscErrorCode  MatCholeskyFactorSymbolic(Mat mat,IS perm,MatFactorInfo *info,Mat *fact)
2371: {

2380:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"Matrix must be square");
2381:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2382:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2383:   if (!mat->ops->choleskyfactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2384:   MatPreallocated(mat);

2387:   (*mat->ops->choleskyfactorsymbolic)(mat,perm,info,fact);
2389:   PetscObjectStateIncrease((PetscObject)*fact);
2390:   return(0);
2391: }

2395: /*@  
2396:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
2397:    of a symmetric matrix. Call this routine after first calling
2398:    MatCholeskyFactorSymbolic().

2400:    Collective on Mat

2402:    Input Parameter:
2403: .  mat - the initial matrix
2404: .  info - options for factorization
2405: -  fact - the symbolic factor of mat

2407:    Output Parameter:
2408: .  fact - the factored matrix

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

2415:    Level: developer

2417:    Concepts: matrices^Cholesky numeric factorization

2419: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
2420: @*/
2421: PetscErrorCode  MatCholeskyFactorNumeric(Mat mat,MatFactorInfo *info,Mat *fact)
2422: {

2430:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2431:   if (!(*fact)->ops->choleskyfactornumeric) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2432:   if (mat->rmap.N != (*fact)->rmap.N || mat->cmap.N != (*fact)->cmap.N) {
2433:     SETERRQ4(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);
2434:   }
2435:   MatPreallocated(mat);

2438:   (*(*fact)->ops->choleskyfactornumeric)(mat,info,fact);

2441:   MatView_Private(*fact);
2442:   PetscObjectStateIncrease((PetscObject)*fact);
2443:   return(0);
2444: }

2446: /* ----------------------------------------------------------------*/
2449: /*@
2450:    MatSolve - Solves A x = b, given a factored matrix.

2452:    Collective on Mat and Vec

2454:    Input Parameters:
2455: +  mat - the factored matrix
2456: -  b - the right-hand-side vector

2458:    Output Parameter:
2459: .  x - the result vector

2461:    Notes:
2462:    The vectors b and x cannot be the same.  I.e., one cannot
2463:    call MatSolve(A,x,x).

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

2470:    Level: developer

2472:    Concepts: matrices^triangular solves

2474: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
2475: @*/
2476: PetscErrorCode  MatSolve(Mat mat,Vec b,Vec x)
2477: {

2487:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2488:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2489:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
2490:   if (mat->rmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap.N,b->map.N);
2491:   if (mat->rmap.n != b->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap.n,b->map.n);
2492:   if (!mat->rmap.N && !mat->cmap.N) return(0);
2493:   if (!mat->ops->solve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2494:   MatPreallocated(mat);

2497:   (*mat->ops->solve)(mat,b,x);
2499:   PetscObjectStateIncrease((PetscObject)x);
2500:   return(0);
2501: }

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

2508:    Collective on Mat 

2510:    Input Parameters:
2511: +  mat - the factored matrix
2512: -  b - the right-hand-side matrix  (dense matrix)

2514:    Output Parameter:
2515: .  x - the result matrix (dense matrix)

2517:    Notes:
2518:    The matrices b and x cannot be the same.  I.e., one cannot
2519:    call MatMatSolve(A,x,x).

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

2527:    Level: developer

2529:    Concepts: matrices^triangular solves

2531: .seealso: MatMatSolveAdd(), MatMatSolveTranspose(), MatMatSolveTransposeAdd()
2532: @*/
2533: PetscErrorCode  MatMatSolve(Mat A,Mat B,Mat X)
2534: {

2544:   if (X == B) SETERRQ(PETSC_ERR_ARG_IDN,"X and B must be different matrices");
2545:   if (!A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2546:   if (A->cmap.N != X->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap.N,X->rmap.N);
2547:   if (A->rmap.N != B->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap.N,B->rmap.N);
2548:   if (A->rmap.n != B->rmap.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat A,Mat B: local dim %D %D",A->rmap.n,B->rmap.n);
2549:   if (!A->rmap.N && !A->cmap.N) return(0);
2550:   if (!A->ops->matsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
2551:   MatPreallocated(A);

2554:   (*A->ops->matsolve)(A,B,X);
2556:   PetscObjectStateIncrease((PetscObject)X);
2557:   return(0);
2558: }


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

2567:    Collective on Mat and Vec

2569:    Input Parameters:
2570: +  mat - the factored matrix
2571: -  b - the right-hand-side vector

2573:    Output Parameter:
2574: .  x - the result vector

2576:    Notes:
2577:    MatSolve() should be used for most applications, as it performs
2578:    a forward solve followed by a backward solve.

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

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

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

2593:    Level: developer

2595:    Concepts: matrices^forward solves

2597: .seealso: MatSolve(), MatBackwardSolve()
2598: @ */
2599: PetscErrorCode  MatForwardSolve(Mat mat,Vec b,Vec x)
2600: {

2610:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2611:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2612:   if (!mat->ops->forwardsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2613:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
2614:   if (mat->rmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap.N,b->map.N);
2615:   if (mat->rmap.n != b->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap.n,b->map.n);
2616:   MatPreallocated(mat);
2618:   (*mat->ops->forwardsolve)(mat,b,x);
2620:   PetscObjectStateIncrease((PetscObject)x);
2621:   return(0);
2622: }

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

2630:    Collective on Mat and Vec

2632:    Input Parameters:
2633: +  mat - the factored matrix
2634: -  b - the right-hand-side vector

2636:    Output Parameter:
2637: .  x - the result vector

2639:    Notes:
2640:    MatSolve() should be used for most applications, as it performs
2641:    a forward solve followed by a backward solve.

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

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

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

2656:    Level: developer

2658:    Concepts: matrices^backward solves

2660: .seealso: MatSolve(), MatForwardSolve()
2661: @ */
2662: PetscErrorCode  MatBackwardSolve(Mat mat,Vec b,Vec x)
2663: {

2673:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2674:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2675:   if (!mat->ops->backwardsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2676:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
2677:   if (mat->rmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap.N,b->map.N);
2678:   if (mat->rmap.n != b->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap.n,b->map.n);
2679:   MatPreallocated(mat);

2682:   (*mat->ops->backwardsolve)(mat,b,x);
2684:   PetscObjectStateIncrease((PetscObject)x);
2685:   return(0);
2686: }

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

2693:    Collective on Mat and Vec

2695:    Input Parameters:
2696: +  mat - the factored matrix
2697: .  b - the right-hand-side vector
2698: -  y - the vector to be added to 

2700:    Output Parameter:
2701: .  x - the result vector

2703:    Notes:
2704:    The vectors b and x cannot be the same.  I.e., one cannot
2705:    call MatSolveAdd(A,x,y,x).

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

2711:    Level: developer

2713:    Concepts: matrices^triangular solves

2715: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
2716: @*/
2717: PetscErrorCode  MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
2718: {
2719:   PetscScalar    one = 1.0;
2720:   Vec            tmp;

2732:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2733:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2734:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
2735:   if (mat->rmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap.N,b->map.N);
2736:   if (mat->rmap.N != y->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap.N,y->map.N);
2737:   if (mat->rmap.n != b->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap.n,b->map.n);
2738:   if (x->map.n != y->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map.n,y->map.n);
2739:   MatPreallocated(mat);

2742:   if (mat->ops->solveadd)  {
2743:     (*mat->ops->solveadd)(mat,b,y,x);
2744:   } else {
2745:     /* do the solve then the add manually */
2746:     if (x != y) {
2747:       MatSolve(mat,b,x);
2748:       VecAXPY(x,one,y);
2749:     } else {
2750:       VecDuplicate(x,&tmp);
2751:       PetscLogObjectParent(mat,tmp);
2752:       VecCopy(x,tmp);
2753:       MatSolve(mat,b,x);
2754:       VecAXPY(x,one,tmp);
2755:       VecDestroy(tmp);
2756:     }
2757:   }
2759:   PetscObjectStateIncrease((PetscObject)x);
2760:   return(0);
2761: }

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

2768:    Collective on Mat and Vec

2770:    Input Parameters:
2771: +  mat - the factored matrix
2772: -  b - the right-hand-side vector

2774:    Output Parameter:
2775: .  x - the result vector

2777:    Notes:
2778:    The vectors b and x cannot be the same.  I.e., one cannot
2779:    call MatSolveTranspose(A,x,x).

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

2785:    Level: developer

2787:    Concepts: matrices^triangular solves

2789: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
2790: @*/
2791: PetscErrorCode  MatSolveTranspose(Mat mat,Vec b,Vec x)
2792: {

2802:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2803:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2804:   if (!mat->ops->solvetranspose) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
2805:   if (mat->rmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap.N,x->map.N);
2806:   if (mat->cmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap.N,b->map.N);
2807:   MatPreallocated(mat);
2809:   (*mat->ops->solvetranspose)(mat,b,x);
2811:   PetscObjectStateIncrease((PetscObject)x);
2812:   return(0);
2813: }

2817: /*@
2818:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a 
2819:                       factored matrix. 

2821:    Collective on Mat and Vec

2823:    Input Parameters:
2824: +  mat - the factored matrix
2825: .  b - the right-hand-side vector
2826: -  y - the vector to be added to 

2828:    Output Parameter:
2829: .  x - the result vector

2831:    Notes:
2832:    The vectors b and x cannot be the same.  I.e., one cannot
2833:    call MatSolveTransposeAdd(A,x,y,x).

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

2839:    Level: developer

2841:    Concepts: matrices^triangular solves

2843: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
2844: @*/
2845: PetscErrorCode  MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
2846: {
2847:   PetscScalar    one = 1.0;
2849:   Vec            tmp;

2860:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2861:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2862:   if (mat->rmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap.N,x->map.N);
2863:   if (mat->cmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap.N,b->map.N);
2864:   if (mat->cmap.N != y->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap.N,y->map.N);
2865:   if (x->map.n != y->map.n)   SETERRQ2(PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map.n,y->map.n);
2866:   MatPreallocated(mat);

2869:   if (mat->ops->solvetransposeadd) {
2870:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
2871:   } else {
2872:     /* do the solve then the add manually */
2873:     if (x != y) {
2874:       MatSolveTranspose(mat,b,x);
2875:       VecAXPY(x,one,y);
2876:     } else {
2877:       VecDuplicate(x,&tmp);
2878:       PetscLogObjectParent(mat,tmp);
2879:       VecCopy(x,tmp);
2880:       MatSolveTranspose(mat,b,x);
2881:       VecAXPY(x,one,tmp);
2882:       VecDestroy(tmp);
2883:     }
2884:   }
2886:   PetscObjectStateIncrease((PetscObject)x);
2887:   return(0);
2888: }
2889: /* ----------------------------------------------------------------*/

2893: /*@
2894:    MatRelax - Computes relaxation (SOR, Gauss-Seidel) sweeps.

2896:    Collective on Mat and Vec

2898:    Input Parameters:
2899: +  mat - the matrix
2900: .  b - the right hand side
2901: .  omega - the relaxation factor
2902: .  flag - flag indicating the type of SOR (see below)
2903: .  shift -  diagonal shift
2904: -  its - the number of iterations
2905: -  lits - the number of local iterations 

2907:    Output Parameters:
2908: .  x - the solution (can contain an initial guess)

2910:    SOR Flags:
2911: .     SOR_FORWARD_SWEEP - forward SOR
2912: .     SOR_BACKWARD_SWEEP - backward SOR
2913: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
2914: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR 
2915: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR 
2916: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
2917: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies 
2918:          upper/lower triangular part of matrix to
2919:          vector (with omega)
2920: .     SOR_ZERO_INITIAL_GUESS - zero initial guess

2922:    Notes:
2923:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
2924:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
2925:    on each processor. 

2927:    Application programmers will not generally use MatRelax() directly,
2928:    but instead will employ the KSP/PC interface.

2930:    Notes for Advanced Users:
2931:    The flags are implemented as bitwise inclusive or operations.
2932:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
2933:    to specify a zero initial guess for SSOR.

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

2939:    See also, MatPBRelax(). This routine will automatically call the point block
2940:    version if the point version is not available.

2942:    Level: developer

2944:    Concepts: matrices^relaxation
2945:    Concepts: matrices^SOR
2946:    Concepts: matrices^Gauss-Seidel

2948: @*/
2949: PetscErrorCode  MatRelax(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
2950: {

2960:   if (!mat->ops->relax && !mat->ops->pbrelax) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2961:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2962:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2963:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
2964:   if (mat->rmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap.N,b->map.N);
2965:   if (mat->rmap.n != b->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap.n,b->map.n);
2966:   if (its <= 0) SETERRQ1(PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
2967:   if (lits <= 0) SETERRQ1(PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);

2969:   MatPreallocated(mat);
2971:   if (mat->ops->relax) {
2972:     ierr =(*mat->ops->relax)(mat,b,omega,flag,shift,its,lits,x);
2973:   } else {
2974:     ierr =(*mat->ops->pbrelax)(mat,b,omega,flag,shift,its,lits,x);
2975:   }
2977:   PetscObjectStateIncrease((PetscObject)x);
2978:   return(0);
2979: }

2983: /*@
2984:    MatPBRelax - Computes relaxation (SOR, Gauss-Seidel) sweeps.

2986:    Collective on Mat and Vec

2988:    See MatRelax() for usage

2990:    For multi-component PDEs where the Jacobian is stored in a point block format
2991:    (with the PETSc BAIJ matrix formats) the relaxation is done one point block at 
2992:    a time. That is, the small (for example, 4 by 4) blocks along the diagonal are solved
2993:    simultaneously (that is a 4 by 4 linear solve is done) to update all the values at a point.

2995:    Level: developer

2997: @*/
2998: PetscErrorCode  MatPBRelax(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
2999: {

3009:   if (!mat->ops->pbrelax) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3010:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3011:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3012:   if (mat->cmap.N != x->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap.N,x->map.N);
3013:   if (mat->rmap.N != b->map.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap.N,b->map.N);
3014:   if (mat->rmap.n != b->map.n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap.n,b->map.n);
3015:   MatPreallocated(mat);

3018:   ierr =(*mat->ops->pbrelax)(mat,b,omega,flag,shift,its,lits,x);
3020:   PetscObjectStateIncrease((PetscObject)x);
3021:   return(0);
3022: }

3026: /*
3027:       Default matrix copy routine.
3028: */
3029: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3030: {
3031:   PetscErrorCode    ierr;
3032:   PetscInt          i,rstart,rend,nz;
3033:   const PetscInt    *cwork;
3034:   const PetscScalar *vwork;

3037:   if (B->assembled) {
3038:     MatZeroEntries(B);
3039:   }
3040:   MatGetOwnershipRange(A,&rstart,&rend);
3041:   for (i=rstart; i<rend; i++) {
3042:     MatGetRow(A,i,&nz,&cwork,&vwork);
3043:     MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3044:     MatRestoreRow(A,i,&nz,&cwork,&vwork);
3045:   }
3046:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3047:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3048:   PetscObjectStateIncrease((PetscObject)B);
3049:   return(0);
3050: }

3054: /*@
3055:    MatCopy - Copys a matrix to another matrix.

3057:    Collective on Mat

3059:    Input Parameters:
3060: +  A - the matrix
3061: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

3063:    Output Parameter:
3064: .  B - where the copy is put

3066:    Notes:
3067:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the 
3068:    same nonzero pattern or the routine will crash.

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

3074:    Level: intermediate
3075:    
3076:    Concepts: matrices^copying

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

3080: @*/
3081: PetscErrorCode  MatCopy(Mat A,Mat B,MatStructure str)
3082: {

3090:   MatPreallocated(B);
3092:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3093:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3094:   if (A->rmap.N != B->rmap.N || A->cmap.N != B->cmap.N) SETERRQ4(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);
3095:   MatPreallocated(A);

3098:   if (A->ops->copy) {
3099:     (*A->ops->copy)(A,B,str);
3100:   } else { /* generic conversion */
3101:     MatCopy_Basic(A,B,str);
3102:   }
3103:   if (A->mapping) {
3104:     if (B->mapping) {ISLocalToGlobalMappingDestroy(B->mapping);B->mapping = 0;}
3105:     MatSetLocalToGlobalMapping(B,A->mapping);
3106:   }
3107:   if (A->bmapping) {
3108:     if (B->bmapping) {ISLocalToGlobalMappingDestroy(B->bmapping);B->bmapping = 0;}
3109:     MatSetLocalToGlobalMappingBlock(B,A->mapping);
3110:   }
3112:   PetscObjectStateIncrease((PetscObject)B);
3113:   return(0);
3114: }

3118: /*@C  
3119:    MatConvert - Converts a matrix to another matrix, either of the same
3120:    or different type.

3122:    Collective on Mat

3124:    Input Parameters:
3125: +  mat - the matrix
3126: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
3127:    same type as the original matrix.
3128: -  reuse - denotes if the destination matrix is to be created or reused.  Currently
3129:    MAT_REUSE_MATRIX is only supported for inplace conversion, otherwise use
3130:    MAT_INITIAL_MATRIX.

3132:    Output Parameter:
3133: .  M - pointer to place new matrix

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

3140:    Level: intermediate

3142:    Concepts: matrices^converting between storage formats

3144: .seealso: MatCopy(), MatDuplicate()
3145: @*/
3146: PetscErrorCode  MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
3147: {
3148:   PetscErrorCode         ierr;
3149:   PetscTruth             sametype,issame,flg;
3150:   char                   convname[256],mtype[256];
3151:   Mat                    B;

3157:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3158:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3159:   MatPreallocated(mat);

3161:   PetscOptionsGetString(((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
3162:   if (flg) {
3163:     newtype = mtype;
3164:   }
3165:   PetscTypeCompare((PetscObject)mat,newtype,&sametype);
3166:   PetscStrcmp(newtype,"same",&issame);
3167:   if ((reuse==MAT_REUSE_MATRIX) && (mat != *M)) {
3168:     SETERRQ(PETSC_ERR_SUP,"MAT_REUSE_MATRIX only supported for in-place conversion currently");
3169:   }
3170:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
3171:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
3172:   } else {
3173:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=PETSC_NULL;
3174:     const char     *prefix[3] = {"seq","mpi",""};
3175:     PetscInt       i;
3176:     /* 
3177:        Order of precedence:
3178:        1) See if a specialized converter is known to the current matrix.
3179:        2) See if a specialized converter is known to the desired matrix class.
3180:        3) See if a good general converter is registered for the desired class
3181:           (as of 6/27/03 only MATMPIADJ falls into this category).
3182:        4) See if a good general converter is known for the current matrix.
3183:        5) Use a really basic converter.
3184:     */
3185: 
3186:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
3187:     for (i=0; i<3; i++) {
3188:       PetscStrcpy(convname,"MatConvert_");
3189:       PetscStrcat(convname,((PetscObject)mat)->type_name);
3190:       PetscStrcat(convname,"_");
3191:       PetscStrcat(convname,prefix[i]);
3192:       PetscStrcat(convname,newtype);
3193:       PetscStrcat(convname,"_C");
3194:       PetscObjectQueryFunction((PetscObject)mat,convname,(void (**)(void))&conv);
3195:       if (conv) goto foundconv;
3196:     }

3198:     /* 2)  See if a specialized converter is known to the desired matrix class. */
3199:     MatCreate(((PetscObject)mat)->comm,&B);
3200:     MatSetSizes(B,mat->rmap.n,mat->cmap.n,mat->rmap.N,mat->cmap.N);
3201:     MatSetType(B,newtype);
3202:     for (i=0; i<3; i++) {
3203:       PetscStrcpy(convname,"MatConvert_");
3204:       PetscStrcat(convname,((PetscObject)mat)->type_name);
3205:       PetscStrcat(convname,"_");
3206:       PetscStrcat(convname,prefix[i]);
3207:       PetscStrcat(convname,newtype);
3208:       PetscStrcat(convname,"_C");
3209:       PetscObjectQueryFunction((PetscObject)B,convname,(void (**)(void))&conv);
3210:       if (conv) {
3211:         MatDestroy(B);
3212:         goto foundconv;
3213:       }
3214:     }

3216:     /* 3) See if a good general converter is registered for the desired class */
3217:     conv = B->ops->convertfrom;
3218:     MatDestroy(B);
3219:     if (conv) goto foundconv;

3221:     /* 4) See if a good general converter is known for the current matrix */
3222:     if (mat->ops->convert) {
3223:       conv = mat->ops->convert;
3224:     }
3225:     if (conv) goto foundconv;

3227:     /* 5) Use a really basic converter. */
3228:     conv = MatConvert_Basic;

3230:     foundconv:
3232:     (*conv)(mat,newtype,reuse,M);
3234:   }
3235:   B = *M;
3236:   PetscObjectStateIncrease((PetscObject)B);
3237:   return(0);
3238: }


3243: /*@
3244:    MatDuplicate - Duplicates a matrix including the non-zero structure.

3246:    Collective on Mat

3248:    Input Parameters:
3249: +  mat - the matrix
3250: -  op - either MAT_DO_NOT_COPY_VALUES or MAT_COPY_VALUES, cause it to copy nonzero
3251:         values as well or not

3253:    Output Parameter:
3254: .  M - pointer to place new matrix

3256:    Level: intermediate

3258:    Concepts: matrices^duplicating

3260: .seealso: MatCopy(), MatConvert()
3261: @*/
3262: PetscErrorCode  MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
3263: {
3265:   Mat            B;

3271:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3272:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3273:   MatPreallocated(mat);

3275:   *M  = 0;
3276:   if (!mat->ops->duplicate) {
3277:     SETERRQ(PETSC_ERR_SUP,"Not written for this matrix type");
3278:   }
3280:   (*mat->ops->duplicate)(mat,op,M);
3281:   B = *M;
3282:   if (mat->mapping) {
3283:     MatSetLocalToGlobalMapping(B,mat->mapping);
3284:   }
3285:   if (mat->bmapping) {
3286:     MatSetLocalToGlobalMappingBlock(B,mat->bmapping);
3287:   }
3288:   PetscMapCopy(((PetscObject)mat)->comm,&mat->rmap,&B->rmap);
3289:   PetscMapCopy(((PetscObject)mat)->comm,&mat->cmap,&B->cmap);
3290: 
3292:   PetscObjectStateIncrease((PetscObject)B);
3293:   return(0);
3294: }

3298: /*@ 
3299:    MatGetDiagonal - Gets the diagonal of a matrix.

3301:    Collective on Mat and Vec

3303:    Input Parameters:
3304: +  mat - the matrix
3305: -  v - the vector for storing the diagonal

3307:    Output Parameter:
3308: .  v - the diagonal of the matrix

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

3313:    Level: intermediate

3315:    Concepts: matrices^accessing diagonals

3317: .seealso: MatGetRow(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs()
3318: @*/
3319: PetscErrorCode  MatGetDiagonal(Mat mat,Vec v)
3320: {

3327:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3328:   if (!mat->ops->getdiagonal) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3329:   MatPreallocated(mat);

3331:   (*mat->ops->getdiagonal)(mat,v);
3332:   PetscObjectStateIncrease((PetscObject)v);
3333:   return(0);
3334: }

3338: /*@ 
3339:    MatGetRowMin - Gets the minimum value (of the real part) of each
3340:         row of the matrix

3342:    Collective on Mat and Vec

3344:    Input Parameters:
3345: .  mat - the matrix

3347:    Output Parameter:
3348: +  v - the vector for storing the maximums
3349: -  idx - the indices of the column found for each row (optional)

3351:    Level: intermediate

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

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

3358:    Concepts: matrices^getting row maximums

3360: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(),
3361:           MatGetRowMax()
3362: @*/
3363: PetscErrorCode  MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
3364: {

3371:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3372:   if (!mat->ops->getrowmax) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3373:   MatPreallocated(mat);

3375:   (*mat->ops->getrowmin)(mat,v,idx);
3376:   PetscObjectStateIncrease((PetscObject)v);
3377:   return(0);
3378: }

3382: /*@ 
3383:    MatGetRowMax - Gets the maximum value (of the real part) of each
3384:         row of the matrix

3386:    Collective on Mat and Vec

3388:    Input Parameters:
3389: .  mat - the matrix

3391:    Output Parameter:
3392: +  v - the vector for storing the maximums
3393: -  idx - the indices of the column found for each row (optional)

3395:    Level: intermediate

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

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

3402:    Concepts: matrices^getting row maximums

3404: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(), MatGetRowMin()
3405: @*/
3406: PetscErrorCode  MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
3407: {

3414:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3415:   if (!mat->ops->getrowmax) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3416:   MatPreallocated(mat);

3418:   (*mat->ops->getrowmax)(mat,v,idx);
3419:   PetscObjectStateIncrease((PetscObject)v);
3420:   return(0);
3421: }

3425: /*@ 
3426:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
3427:         row of the matrix

3429:    Collective on Mat and Vec

3431:    Input Parameters:
3432: .  mat - the matrix

3434:    Output Parameter:
3435: +  v - the vector for storing the maximums
3436: -  idx - the indices of the column found for each row (optional)

3438:    Level: intermediate

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

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

3445:    Concepts: matrices^getting row maximums

3447: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
3448: @*/
3449: PetscErrorCode  MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
3450: {

3457:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3458:   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3459:   MatPreallocated(mat);

3461:   (*mat->ops->getrowmaxabs)(mat,v,idx);
3462:   PetscObjectStateIncrease((PetscObject)v);
3463:   return(0);
3464: }

3468: /*@ 
3469:    MatGetRowSum - Gets the sum of each row of the matrix

3471:    Collective on Mat and Vec

3473:    Input Parameters:
3474: .  mat - the matrix

3476:    Output Parameter:
3477: .  v - the vector for storing the maximums

3479:    Level: intermediate

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

3483:    Concepts: matrices^getting row sums

3485: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
3486: @*/
3487: PetscErrorCode  MatGetRowSum(Mat mat, Vec v)
3488: {
3489:   PetscInt       start, end, row;
3490:   PetscScalar   *array;

3497:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3498:   MatPreallocated(mat);
3499:   MatGetOwnershipRange(mat, &start, &end);
3500:   VecGetArray(v, &array);
3501:   for(row = start; row < end; ++row) {
3502:     PetscInt           ncols, col;
3503:     const PetscInt    *cols;
3504:     const PetscScalar *vals;

3506:     array[row - start] = 0.0;
3507:     MatGetRow(mat, row, &ncols, &cols, &vals);
3508:     for(col = 0; col < ncols; col++) {
3509:       array[row - start] += vals[col];
3510:     }
3511:     MatRestoreRow(mat, row, &ncols, &cols, &vals);
3512:   }
3513:   VecRestoreArray(v, &array);
3514:   PetscObjectStateIncrease((PetscObject) v);
3515:   return(0);
3516: }

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

3523:    Collective on Mat

3525:    Input Parameter:
3526: .  mat - the matrix to transpose

3528:    Output Parameters:
3529: .  B - the transpose 

3531:    Notes:
3532:      If you  pass in PETSC_NULL for B an in-place transpose in mat will be done

3534:    Level: intermediate

3536:    Concepts: matrices^transposing

3538: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose()
3539: @*/
3540: PetscErrorCode  MatTranspose(Mat mat,Mat *B)
3541: {

3547:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3548:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3549:   if (!mat->ops->transpose) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3550:   MatPreallocated(mat);

3553:   (*mat->ops->transpose)(mat,B);
3555:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
3556:   return(0);
3557: }

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

3565:    Collective on Mat

3567:    Input Parameter:
3568: +  A - the matrix to test
3569: -  B - the matrix to test against, this can equal the first parameter

3571:    Output Parameters:
3572: .  flg - the result

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

3579:    Level: intermediate

3581:    Concepts: matrices^transposing, matrix^symmetry

3583: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
3584: @*/
3585: PetscErrorCode  MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscTruth *flg)
3586: {
3587:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscTruth*),(*g)(Mat,Mat,PetscReal,PetscTruth*);

3593:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",(void (**)(void))&f);
3594:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",(void (**)(void))&g);
3595:   if (f && g) {
3596:     if (f==g) {
3597:       (*f)(A,B,tol,flg);
3598:     } else {
3599:       SETERRQ(PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
3600:     }
3601:   }
3602:   return(0);
3603: }

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

3610:    Collective on Mat

3612:    Input Parameter:
3613: +  A - the matrix to test
3614: -  B - the matrix to test against, this can equal the first parameter

3616:    Output Parameters:
3617: .  flg - the result

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

3624:    Level: intermediate

3626:    Concepts: matrices^transposing, matrix^symmetry

3628: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
3629: @*/
3630: PetscErrorCode  MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscTruth *flg)
3631: {
3632:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscTruth*),(*g)(Mat,Mat,PetscReal,PetscTruth*);

3638:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",(void (**)(void))&f);
3639:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",(void (**)(void))&g);
3640:   if (f && g) {
3641:     if (f==g) {
3642:       (*f)(A,B,tol,flg);
3643:     } else {
3644:       SETERRQ(PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
3645:     }
3646:   }
3647:   return(0);
3648: }

3652: /*@
3653:    MatPermute - Creates a new matrix with rows and columns permuted from the 
3654:    original.

3656:    Collective on Mat

3658:    Input Parameters:
3659: +  mat - the matrix to permute
3660: .  row - row permutation, each processor supplies only the permutation for its rows
3661: -  col - column permutation, each processor needs the entire column permutation, that is
3662:          this is the same size as the total number of columns in the matrix

3664:    Output Parameters:
3665: .  B - the permuted matrix

3667:    Level: advanced

3669:    Concepts: matrices^permuting

3671: .seealso: MatGetOrdering()
3672: @*/
3673: PetscErrorCode  MatPermute(Mat mat,IS row,IS col,Mat *B)
3674: {

3683:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3684:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3685:   if (!mat->ops->permute) SETERRQ1(PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
3686:   MatPreallocated(mat);

3688:   (*mat->ops->permute)(mat,row,col,B);
3689:   PetscObjectStateIncrease((PetscObject)*B);
3690:   return(0);
3691: }

3695: /*@
3696:   MatPermuteSparsify - Creates a new matrix with rows and columns permuted from the 
3697:   original and sparsified to the prescribed tolerance.

3699:   Collective on Mat

3701:   Input Parameters:
3702: + A    - The matrix to permute
3703: . band - The half-bandwidth of the sparsified matrix, or PETSC_DECIDE
3704: . frac - The half-bandwidth as a fraction of the total size, or 0.0
3705: . tol  - The drop tolerance
3706: . rowp - The row permutation
3707: - colp - The column permutation

3709:   Output Parameter:
3710: . B    - The permuted, sparsified matrix

3712:   Level: advanced

3714:   Note:
3715:   The default behavior (band = PETSC_DECIDE and frac = 0.0) is to
3716:   restrict the half-bandwidth of the resulting matrix to 5% of the
3717:   total matrix size.

3719: .keywords: matrix, permute, sparsify

3721: .seealso: MatGetOrdering(), MatPermute()
3722: @*/
3723: PetscErrorCode  MatPermuteSparsify(Mat A, PetscInt band, PetscReal frac, PetscReal tol, IS rowp, IS colp, Mat *B)
3724: {
3725:   IS                irowp, icolp;
3726:   PetscInt          *rows, *cols;
3727:   PetscInt          M, N, locRowStart, locRowEnd;
3728:   PetscInt          nz, newNz;
3729:   const PetscInt    *cwork;
3730:   PetscInt          *cnew;
3731:   const PetscScalar *vwork;
3732:   PetscScalar       *vnew;
3733:   PetscInt          bw, issize;
3734:   PetscInt          row, locRow, newRow, col, newCol;
3735:   PetscErrorCode    ierr;

3742:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3743:   if (A->factor)     SETERRQ(PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3744:   if (!A->ops->permutesparsify) {
3745:     MatGetSize(A, &M, &N);
3746:     MatGetOwnershipRange(A, &locRowStart, &locRowEnd);
3747:     ISGetSize(rowp, &issize);
3748:     if (issize != M) SETERRQ2(PETSC_ERR_ARG_WRONG, "Wrong size %D for row permutation, should be %D", issize, M);
3749:     ISGetSize(colp, &issize);
3750:     if (issize != N) SETERRQ2(PETSC_ERR_ARG_WRONG, "Wrong size %D for column permutation, should be %D", issize, N);
3751:     ISInvertPermutation(rowp, 0, &irowp);
3752:     ISGetIndices(irowp, &rows);
3753:     ISInvertPermutation(colp, 0, &icolp);
3754:     ISGetIndices(icolp, &cols);
3755:     PetscMalloc(N * sizeof(PetscInt),         &cnew);
3756:     PetscMalloc(N * sizeof(PetscScalar), &vnew);

3758:     /* Setup bandwidth to include */
3759:     if (band == PETSC_DECIDE) {
3760:       if (frac <= 0.0)
3761:         bw = (PetscInt) (M * 0.05);
3762:       else
3763:         bw = (PetscInt) (M * frac);
3764:     } else {
3765:       if (band <= 0) SETERRQ(PETSC_ERR_ARG_WRONG, "Bandwidth must be a positive integer");
3766:       bw = band;
3767:     }

3769:     /* Put values into new matrix */
3770:     MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, B);
3771:     for(row = locRowStart, locRow = 0; row < locRowEnd; row++, locRow++) {
3772:       MatGetRow(A, row, &nz, &cwork, &vwork);
3773:       newRow   = rows[locRow]+locRowStart;
3774:       for(col = 0, newNz = 0; col < nz; col++) {
3775:         newCol = cols[cwork[col]];
3776:         if ((newCol >= newRow - bw) && (newCol < newRow + bw) && (PetscAbsScalar(vwork[col]) >= tol)) {
3777:           cnew[newNz] = newCol;
3778:           vnew[newNz] = vwork[col];
3779:           newNz++;
3780:         }
3781:       }
3782:       MatSetValues(*B, 1, &newRow, newNz, cnew, vnew, INSERT_VALUES);
3783:       MatRestoreRow(A, row, &nz, &cwork, &vwork);
3784:     }
3785:     PetscFree(cnew);
3786:     PetscFree(vnew);
3787:     MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY);
3788:     MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY);
3789:     ISRestoreIndices(irowp, &rows);
3790:     ISRestoreIndices(icolp, &cols);
3791:     ISDestroy(irowp);
3792:     ISDestroy(icolp);
3793:   } else {
3794:     (*A->ops->permutesparsify)(A, band, frac, tol, rowp, colp, B);
3795:   }
3796:   PetscObjectStateIncrease((PetscObject)*B);
3797:   return(0);
3798: }

3802: /*@
3803:    MatEqual - Compares two matrices.

3805:    Collective on Mat

3807:    Input Parameters:
3808: +  A - the first matrix
3809: -  B - the second matrix

3811:    Output Parameter:
3812: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

3814:    Level: intermediate

3816:    Concepts: matrices^equality between
3817: @*/
3818: PetscErrorCode  MatEqual(Mat A,Mat B,PetscTruth *flg)
3819: {

3827:   MatPreallocated(B);
3830:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3831:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3832:   if (A->rmap.N != B->rmap.N || A->cmap.N != B->cmap.N) SETERRQ4(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);
3833:   if (!A->ops->equal) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3834:   if (!B->ops->equal) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
3835:   if (A->ops->equal != B->ops->equal) SETERRQ2(PETSC_ERR_ARG_INCOMP,"A is type: %s\nB is type: %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
3836:   MatPreallocated(A);

3838:   (*A->ops->equal)(A,B,flg);
3839:   return(0);
3840: }

3844: /*@
3845:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
3846:    matrices that are stored as vectors.  Either of the two scaling
3847:    matrices can be PETSC_NULL.

3849:    Collective on Mat

3851:    Input Parameters:
3852: +  mat - the matrix to be scaled
3853: .  l - the left scaling vector (or PETSC_NULL)
3854: -  r - the right scaling vector (or PETSC_NULL)

3856:    Notes:
3857:    MatDiagonalScale() computes A = LAR, where
3858:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)

3860:    Level: intermediate

3862:    Concepts: matrices^diagonal scaling
3863:    Concepts: diagonal scaling of matrices

3865: .seealso: MatScale()
3866: @*/
3867: PetscErrorCode  MatDiagonalScale(Mat mat,Vec l,Vec r)
3868: {

3874:   if (!mat->ops->diagonalscale) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3877:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3878:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3879:   MatPreallocated(mat);

3882:   (*mat->ops->diagonalscale)(mat,l,r);
3884:   PetscObjectStateIncrease((PetscObject)mat);
3885:   return(0);
3886: }

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

3893:     Collective on Mat

3895:     Input Parameters:
3896: +   mat - the matrix to be scaled
3897: -   a  - the scaling value

3899:     Output Parameter:
3900: .   mat - the scaled matrix

3902:     Level: intermediate

3904:     Concepts: matrices^scaling all entries

3906: .seealso: MatDiagonalScale()
3907: @*/
3908: PetscErrorCode  MatScale(Mat mat,PetscScalar a)
3909: {

3915:   if (!mat->ops->scale) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3916:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3917:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3918:   MatPreallocated(mat);

3921:   (*mat->ops->scale)(mat,a);
3923:   PetscObjectStateIncrease((PetscObject)mat);
3924:   return(0);
3925: }

3929: /*@ 
3930:    MatNorm - Calculates various norms of a matrix.

3932:    Collective on Mat

3934:    Input Parameters:
3935: +  mat - the matrix
3936: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

3938:    Output Parameters:
3939: .  nrm - the resulting norm 

3941:    Level: intermediate

3943:    Concepts: matrices^norm
3944:    Concepts: norm^of matrix
3945: @*/
3946: PetscErrorCode  MatNorm(Mat mat,NormType type,PetscReal *nrm)
3947: {


3955:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3956:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3957:   if (!mat->ops->norm) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3958:   MatPreallocated(mat);

3960:   (*mat->ops->norm)(mat,type,nrm);
3961:   return(0);
3962: }

3964: /* 
3965:      This variable is used to prevent counting of MatAssemblyBegin() that
3966:    are called from within a MatAssemblyEnd().
3967: */
3968: static PetscInt MatAssemblyEnd_InUse = 0;
3971: /*@
3972:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
3973:    be called after completing all calls to MatSetValues().

3975:    Collective on Mat

3977:    Input Parameters:
3978: +  mat - the matrix 
3979: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
3980:  
3981:    Notes: 
3982:    MatSetValues() generally caches the values.  The matrix is ready to
3983:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
3984:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
3985:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
3986:    using the matrix.

3988:    Level: beginner

3990:    Concepts: matrices^assembling

3992: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
3993: @*/
3994: PetscErrorCode  MatAssemblyBegin(Mat mat,MatAssemblyType type)
3995: {

4001:   MatPreallocated(mat);
4002:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
4003:   if (mat->assembled) {
4004:     mat->was_assembled = PETSC_TRUE;
4005:     mat->assembled     = PETSC_FALSE;
4006:   }
4007:   if (!MatAssemblyEnd_InUse) {
4009:     if (mat->ops->assemblybegin){(*mat->ops->assemblybegin)(mat,type);}
4011:   } else {
4012:     if (mat->ops->assemblybegin){(*mat->ops->assemblybegin)(mat,type);}
4013:   }
4014:   return(0);
4015: }

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

4023:    Collective on Mat

4025:    Input Parameter:
4026: .  mat - the matrix 

4028:    Output Parameter:
4029: .  assembled - PETSC_TRUE or PETSC_FALSE

4031:    Level: advanced

4033:    Concepts: matrices^assembled?

4035: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
4036: @*/
4037: PetscErrorCode  MatAssembled(Mat mat,PetscTruth *assembled)
4038: {
4043:   *assembled = mat->assembled;
4044:   return(0);
4045: }

4049: /*
4050:     Processes command line options to determine if/how a matrix
4051:   is to be viewed. Called by MatAssemblyEnd() and MatLoad().
4052: */
4053: PetscErrorCode MatView_Private(Mat mat)
4054: {
4055:   PetscErrorCode    ierr;
4056:   PetscTruth        flg1,flg2,flg3,flg4,flg6,flg7,flg8;
4057:   static PetscTruth incall = PETSC_FALSE;
4058: #if defined(PETSC_USE_SOCKET_VIEWER)
4059:   PetscTruth        flg5;
4060: #endif

4063:   if (incall) return(0);
4064:   incall = PETSC_TRUE;
4065:   PetscOptionsBegin(((PetscObject)mat)->comm,((PetscObject)mat)->prefix,"Matrix Options","Mat");
4066:     PetscOptionsName("-mat_view_info","Information on matrix size","MatView",&flg1);
4067:     PetscOptionsName("-mat_view_info_detailed","Nonzeros in the matrix","MatView",&flg2);
4068:     PetscOptionsName("-mat_view","Print matrix to stdout","MatView",&flg3);
4069:     PetscOptionsName("-mat_view_matlab","Print matrix to stdout in a format Matlab can read","MatView",&flg4);
4070: #if defined(PETSC_USE_SOCKET_VIEWER)
4071:     PetscOptionsName("-mat_view_socket","Send matrix to socket (can be read from matlab)","MatView",&flg5);
4072: #endif
4073:     PetscOptionsName("-mat_view_binary","Save matrix to file in binary format","MatView",&flg6);
4074:     PetscOptionsName("-mat_view_draw","Draw the matrix nonzero structure","MatView",&flg7);
4075:   PetscOptionsEnd();

4077:   if (flg1) {
4078:     PetscViewer viewer;

4080:     PetscViewerASCIIGetStdout(((PetscObject)mat)->comm,&viewer);
4081:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO);
4082:     MatView(mat,viewer);
4083:     PetscViewerPopFormat(viewer);
4084:   }
4085:   if (flg2) {
4086:     PetscViewer viewer;

4088:     PetscViewerASCIIGetStdout(((PetscObject)mat)->comm,&viewer);
4089:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO_DETAIL);
4090:     MatView(mat,viewer);
4091:     PetscViewerPopFormat(viewer);
4092:   }
4093:   if (flg3) {
4094:     PetscViewer viewer;

4096:     PetscViewerASCIIGetStdout(((PetscObject)mat)->comm,&viewer);
4097:     MatView(mat,viewer);
4098:   }
4099:   if (flg4) {
4100:     PetscViewer viewer;

4102:     PetscViewerASCIIGetStdout(((PetscObject)mat)->comm,&viewer);
4103:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
4104:     MatView(mat,viewer);
4105:     PetscViewerPopFormat(viewer);
4106:   }
4107: #if defined(PETSC_USE_SOCKET_VIEWER)
4108:   if (flg5) {
4109:     MatView(mat,PETSC_VIEWER_SOCKET_(((PetscObject)mat)->comm));
4110:     PetscViewerFlush(PETSC_VIEWER_SOCKET_(((PetscObject)mat)->comm));
4111:   }
4112: #endif
4113:   if (flg6) {
4114:     MatView(mat,PETSC_VIEWER_BINARY_(((PetscObject)mat)->comm));
4115:     PetscViewerFlush(PETSC_VIEWER_BINARY_(((PetscObject)mat)->comm));
4116:   }
4117:   if (flg7) {
4118:     PetscOptionsHasName(((PetscObject)mat)->prefix,"-mat_view_contour",&flg8);
4119:     if (flg8) {
4120:       PetscViewerPushFormat(PETSC_VIEWER_DRAW_(((PetscObject)mat)->comm),PETSC_VIEWER_DRAW_CONTOUR);
4121:     }
4122:     MatView(mat,PETSC_VIEWER_DRAW_(((PetscObject)mat)->comm));
4123:     PetscViewerFlush(PETSC_VIEWER_DRAW_(((PetscObject)mat)->comm));
4124:     if (flg8) {
4125:       PetscViewerPopFormat(PETSC_VIEWER_DRAW_(((PetscObject)mat)->comm));
4126:     }
4127:   }
4128:   incall = PETSC_FALSE;
4129:   return(0);
4130: }

4134: /*@
4135:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
4136:    be called after MatAssemblyBegin().

4138:    Collective on Mat

4140:    Input Parameters:
4141: +  mat - the matrix 
4142: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

4144:    Options Database Keys:
4145: +  -mat_view_info - Prints info on matrix at conclusion of MatEndAssembly()
4146: .  -mat_view_info_detailed - Prints more detailed info
4147: .  -mat_view - Prints matrix in ASCII format
4148: .  -mat_view_matlab - Prints matrix in Matlab format
4149: .  -mat_view_draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
4150: .  -display <name> - Sets display name (default is host)
4151: .  -draw_pause <sec> - Sets number of seconds to pause after display
4152: .  -mat_view_socket - Sends matrix to socket, can be accessed from Matlab (see users manual)
4153: .  -viewer_socket_machine <machine>
4154: .  -viewer_socket_port <port>
4155: .  -mat_view_binary - save matrix to file in binary format
4156: -  -viewer_binary_filename <name>

4158:    Notes: 
4159:    MatSetValues() generally caches the values.  The matrix is ready to
4160:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
4161:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
4162:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
4163:    using the matrix.

4165:    Level: beginner

4167: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), MatView(), MatAssembled(), PetscViewerSocketOpen()
4168: @*/
4169: PetscErrorCode  MatAssemblyEnd(Mat mat,MatAssemblyType type)
4170: {
4171:   PetscErrorCode  ierr;
4172:   static PetscInt inassm = 0;
4173:   PetscTruth      flg;


4179:   inassm++;
4180:   MatAssemblyEnd_InUse++;
4181:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
4183:     if (mat->ops->assemblyend) {
4184:       (*mat->ops->assemblyend)(mat,type);
4185:     }
4187:   } else {
4188:     if (mat->ops->assemblyend) {
4189:       (*mat->ops->assemblyend)(mat,type);
4190:     }
4191:   }

4193:   /* Flush assembly is not a true assembly */
4194:   if (type != MAT_FLUSH_ASSEMBLY) {
4195:     mat->assembled  = PETSC_TRUE; mat->num_ass++;
4196:   }
4197:   mat->insertmode = NOT_SET_VALUES;
4198:   MatAssemblyEnd_InUse--;
4199:   PetscObjectStateIncrease((PetscObject)mat);
4200:   if (!mat->symmetric_eternal) {
4201:     mat->symmetric_set              = PETSC_FALSE;
4202:     mat->hermitian_set              = PETSC_FALSE;
4203:     mat->structurally_symmetric_set = PETSC_FALSE;
4204:   }
4205:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
4206:     MatView_Private(mat);
4207:     PetscOptionsHasName(((PetscObject)mat)->prefix,"-mat_is_symmetric",&flg);
4208:     if (flg) {
4209:       PetscReal tol = 0.0;
4210:       PetscOptionsGetReal(((PetscObject)mat)->prefix,"-mat_is_symmetric",&tol,PETSC_NULL);
4211:       MatIsSymmetric(mat,tol,&flg);
4212:       if (flg) {
4213:         PetscPrintf(((PetscObject)mat)->comm,"Matrix is symmetric (tolerance %G)\n",tol);
4214:       } else {
4215:         PetscPrintf(((PetscObject)mat)->comm,"Matrix is not symmetric (tolerance %G)\n",tol);
4216:       }
4217:     }
4218:   }
4219:   inassm--;
4220:   return(0);
4221: }


4226: /*@
4227:    MatCompress - Tries to store the matrix in as little space as 
4228:    possible.  May fail if memory is already fully used, since it
4229:    tries to allocate new space.

4231:    Collective on Mat

4233:    Input Parameters:
4234: .  mat - the matrix 

4236:    Level: advanced

4238: @*/
4239: PetscErrorCode  MatCompress(Mat mat)
4240: {

4246:   MatPreallocated(mat);
4247:   if (mat->ops->compress) {(*mat->ops->compress)(mat);}
4248:   return(0);
4249: }

4253: /*@
4254:    MatSetOption - Sets a parameter option for a matrix. Some options
4255:    may be specific to certain storage formats.  Some options
4256:    determine how values will be inserted (or added). Sorted, 
4257:    row-oriented input will generally assemble the fastest. The default
4258:    is row-oriented, nonsorted input. 

4260:    Collective on Mat

4262:    Input Parameters:
4263: +  mat - the matrix 
4264: -  option - the option, one of those listed below (and possibly others),

4266:    Options Describing Matrix Structure:
4267: +    MAT_SYMMETRIC - symmetric in terms of both structure and value
4268: .    MAT_HERMITIAN - transpose is the complex conjugation
4269: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
4270: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
4271:                             you set to be kept with all future use of the matrix
4272:                             including after MatAssemblyBegin/End() which could
4273:                             potentially change the symmetry structure, i.e. you 
4274:                             KNOW the matrix will ALWAYS have the property you set.


4277:    Options For Use with MatSetValues():
4278:    Insert a logically dense subblock, which can be
4279: .    MAT_ROW_ORIENTED - row-oriented (default)

4281:    Not these options reflect the data you pass in with MatSetValues(); it has 
4282:    nothing to do with how the data is stored internally in the matrix 
4283:    data structure.

4285:    When (re)assembling a matrix, we can restrict the input for
4286:    efficiency/debugging purposes.  These options include
4287: +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be
4288:         allowed if they generate a new nonzero
4289: .    MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
4290: .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
4291: .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
4292: -    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly

4294:    Notes:
4295:    Some options are relevant only for particular matrix types and
4296:    are thus ignored by others.  Other options are not supported by
4297:    certain matrix types and will generate an error message if set.

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

4303:    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion 
4304:    that would generate a new entry in the nonzero structure is instead
4305:    ignored.  Thus, if memory has not alredy been allocated for this particular 
4306:    data, then the insertion is ignored. For dense matrices, in which
4307:    the entire array is allocated, no entries are ever ignored. 
4308:    Set after the first MatAssemblyEnd()

4310:    MAT_NEW_NONZERO_LOCATION_ERR indicates that any add or insertion 
4311:    that would generate a new entry in the nonzero structure instead produces 
4312:    an error. (Currently supported for AIJ and BAIJ formats only.)
4313:    This is a useful flag when using SAME_NONZERO_PATTERN in calling
4314:    KSPSetOperators() to ensure that the nonzero pattern truely does 
4315:    remain unchanged. Set after the first MatAssemblyEnd()

4317:    MAT_NEW_NONZERO_ALLOCATION_ERR indicates that any add or insertion 
4318:    that would generate a new entry that has not been preallocated will 
4319:    instead produce an error. (Currently supported for AIJ and BAIJ formats
4320:    only.) This is a useful flag when debugging matrix memory preallocation.

4322:    MAT_IGNORE_OFF_PROC_ENTRIES indicates entries destined for 
4323:    other processors should be dropped, rather than stashed.
4324:    This is useful if you know that the "owning" processor is also 
4325:    always generating the correct matrix entries, so that PETSc need
4326:    not transfer duplicate entries generated on another processor.
4327:    
4328:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
4329:    searches during matrix assembly. When this flag is set, the hash table
4330:    is created during the first Matrix Assembly. This hash table is
4331:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
4332:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag 
4333:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
4334:    supported by MATMPIBAIJ format only.

4336:    MAT_KEEP_ZEROED_ROWS indicates when MatZeroRows() is called the zeroed entries
4337:    are kept in the nonzero structure

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

4342:    MAT_USE_INODES - indicates using inode version of the code - works with AIJ and 
4343:    ROWBS matrix types

4345:    Level: intermediate

4347:    Concepts: matrices^setting options

4349: @*/
4350: PetscErrorCode  MatSetOption(Mat mat,MatOption op,PetscTruth flg)
4351: {

4357:   MatPreallocated(mat);
4358:   switch (op) {
4359:   case MAT_SYMMETRIC:
4360:     mat->symmetric                  = flg;
4361:     if (flg) mat->structurally_symmetric     = PETSC_TRUE;
4362:     mat->symmetric_set              = PETSC_TRUE;
4363:     mat->structurally_symmetric_set = flg;
4364:     break;
4365:   case MAT_HERMITIAN:
4366:     mat->hermitian                  = flg;
4367:     if (flg) mat->structurally_symmetric     = PETSC_TRUE;
4368:     mat->hermitian_set              = PETSC_TRUE;
4369:     mat->structurally_symmetric_set = flg;
4370:     break;
4371:   case MAT_STRUCTURALLY_SYMMETRIC:
4372:     mat->structurally_symmetric     = flg;
4373:     mat->structurally_symmetric_set = PETSC_TRUE;
4374:     break;
4375:   case MAT_SYMMETRY_ETERNAL:
4376:     mat->symmetric_eternal          = flg;
4377:     break;
4378:   default:
4379:     break;
4380:   }
4381:   if (mat->ops->setoption) {
4382:     (*mat->ops->setoption)(mat,op,flg);
4383:   }
4384:   return(0);
4385: }

4389: /*@
4390:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
4391:    this routine retains the old nonzero structure.

4393:    Collective on Mat

4395:    Input Parameters:
4396: .  mat - the matrix 

4398:    Level: intermediate

4400:    Concepts: matrices^zeroing

4402: .seealso: MatZeroRows()
4403: @*/
4404: PetscErrorCode  MatZeroEntries(Mat mat)
4405: {

4411:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4412:   if (mat->insertmode != NOT_SET_VALUES) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for matrices where you have set values but not yet assembled");
4413:   if (!mat->ops->zeroentries) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4414:   MatPreallocated(mat);

4417:   (*mat->ops->zeroentries)(mat);
4419:   PetscObjectStateIncrease((PetscObject)mat);
4420:   return(0);
4421: }

4425: /*@C
4426:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
4427:    of a set of rows of a matrix.

4429:    Collective on Mat

4431:    Input Parameters:
4432: +  mat - the matrix
4433: .  numRows - the number of rows to remove
4434: .  rows - the global row indices
4435: -  diag - value put in all diagonals of eliminated rows

4437:    Notes:
4438:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
4439:    but does not release memory.  For the dense and block diagonal
4440:    formats this does not alter the nonzero structure.

4442:    If the option MatSetOption(mat,MAT_KEEP_ZEROED_ROWS,PETSC_TRUE) the nonzero structure
4443:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
4444:    merely zeroed.

4446:    The user can set a value in the diagonal entry (or for the AIJ and
4447:    row formats can optionally remove the main diagonal entry from the
4448:    nonzero structure as well, by passing 0.0 as the final argument).

4450:    For the parallel case, all processes that share the matrix (i.e.,
4451:    those in the communicator used for matrix creation) MUST call this
4452:    routine, regardless of whether any rows being zeroed are owned by
4453:    them.

4455:    Each processor should list the rows that IT wants zeroed

4457:    Level: intermediate

4459:    Concepts: matrices^zeroing rows

4461: .seealso: MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
4462: @*/
4463: PetscErrorCode  MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag)
4464: {

4471:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4472:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4473:   if (!mat->ops->zerorows) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4474:   MatPreallocated(mat);

4476:   (*mat->ops->zerorows)(mat,numRows,rows,diag);
4477:   MatView_Private(mat);
4478:   PetscObjectStateIncrease((PetscObject)mat);
4479:   return(0);
4480: }

4484: /*@C
4485:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
4486:    of a set of rows of a matrix.

4488:    Collective on Mat

4490:    Input Parameters:
4491: +  mat - the matrix
4492: .  is - index set of rows to remove
4493: -  diag - value put in all diagonals of eliminated rows

4495:    Notes:
4496:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
4497:    but does not release memory.  For the dense and block diagonal
4498:    formats this does not alter the nonzero structure.

4500:    If the option MatSetOption(mat,MAT_KEEP_ZEROED_ROWS,PETSC_TRUE) the nonzero structure
4501:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
4502:    merely zeroed.

4504:    The user can set a value in the diagonal entry (or for the AIJ and
4505:    row formats can optionally remove the main diagonal entry from the
4506:    nonzero structure as well, by passing 0.0 as the final argument).

4508:    For the parallel case, all processes that share the matrix (i.e.,
4509:    those in the communicator used for matrix creation) MUST call this
4510:    routine, regardless of whether any rows being zeroed are owned by
4511:    them.

4513:    Each processor should list the rows that IT wants zeroed

4515:    Level: intermediate

4517:    Concepts: matrices^zeroing rows

4519: .seealso: MatZeroRows(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
4520: @*/
4521: PetscErrorCode  MatZeroRowsIS(Mat mat,IS is,PetscScalar diag)
4522: {
4523:   PetscInt       numRows;
4524:   PetscInt       *rows;

4531:   ISGetLocalSize(is,&numRows);
4532:   ISGetIndices(is,&rows);
4533:   MatZeroRows(mat,numRows,rows,diag);
4534:   ISRestoreIndices(is,&rows);
4535:   return(0);
4536: }

4540: /*@C 
4541:    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
4542:    of a set of rows of a matrix; using local numbering of rows.

4544:    Collective on Mat

4546:    Input Parameters:
4547: +  mat - the matrix
4548: .  numRows - the number of rows to remove
4549: .  rows - the global row indices
4550: -  diag - value put in all diagonals of eliminated rows

4552:    Notes:
4553:    Before calling MatZeroRowsLocal(), the user must first set the
4554:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

4556:    For the AIJ matrix formats this removes the old nonzero structure,
4557:    but does not release memory.  For the dense and block diagonal
4558:    formats this does not alter the nonzero structure.

4560:    If the option MatSetOption(mat,MAT_KEEP_ZEROED_ROWS,PETSC_TRUE) the nonzero structure
4561:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
4562:    merely zeroed.

4564:    The user can set a value in the diagonal entry (or for the AIJ and
4565:    row formats can optionally remove the main diagonal entry from the
4566:    nonzero structure as well, by passing 0.0 as the final argument).

4568:    Level: intermediate

4570:    Concepts: matrices^zeroing

4572: .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
4573: @*/
4574: PetscErrorCode  MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag)
4575: {

4582:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4583:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4584:   MatPreallocated(mat);

4586:   if (mat->ops->zerorowslocal) {
4587:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag);
4588:   } else {
4589:     IS is, newis;
4590:     PetscInt *newRows;

4592:     if (!mat->mapping) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
4593:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,&is);
4594:     ISLocalToGlobalMappingApplyIS(mat->mapping,is,&newis);
4595:     ISGetIndices(newis,&newRows);
4596:     (*mat->ops->zerorows)(mat,numRows,newRows,diag);
4597:     ISRestoreIndices(newis,&newRows);
4598:     ISDestroy(newis);
4599:     ISDestroy(is);
4600:   }
4601:   PetscObjectStateIncrease((PetscObject)mat);
4602:   return(0);
4603: }

4607: /*@C 
4608:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
4609:    of a set of rows of a matrix; using local numbering of rows.

4611:    Collective on Mat

4613:    Input Parameters:
4614: +  mat - the matrix
4615: .  is - index set of rows to remove
4616: -  diag - value put in all diagonals of eliminated rows

4618:    Notes:
4619:    Before calling MatZeroRowsLocalIS(), the user must first set the
4620:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

4622:    For the AIJ matrix formats this removes the old nonzero structure,
4623:    but does not release memory.  For the dense and block diagonal
4624:    formats this does not alter the nonzero structure.

4626:    If the option MatSetOption(mat,MAT_KEEP_ZEROED_ROWS,PETSC_TRUE) the nonzero structure
4627:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
4628:    merely zeroed.

4630:    The user can set a value in the diagonal entry (or for the AIJ and
4631:    row formats can optionally remove the main diagonal entry from the
4632:    nonzero structure as well, by passing 0.0 as the final argument).

4634:    Level: intermediate

4636:    Concepts: matrices^zeroing

4638: .seealso: MatZeroRows(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
4639: @*/
4640: PetscErrorCode  MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag)
4641: {
4643:   PetscInt       numRows;
4644:   PetscInt       *rows;

4650:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4651:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4652:   MatPreallocated(mat);

4654:   ISGetLocalSize(is,&numRows);
4655:   ISGetIndices(is,&rows);
4656:   MatZeroRowsLocal(mat,numRows,rows,diag);
4657:   ISRestoreIndices(is,&rows);
4658:   return(0);
4659: }

4663: /*@
4664:    MatGetSize - Returns the numbers of rows and columns in a matrix.

4666:    Not Collective

4668:    Input Parameter:
4669: .  mat - the matrix

4671:    Output Parameters:
4672: +  m - the number of global rows
4673: -  n - the number of global columns

4675:    Note: both output parameters can be PETSC_NULL on input.

4677:    Level: beginner

4679:    Concepts: matrices^size

4681: .seealso: MatGetLocalSize()
4682: @*/
4683: PetscErrorCode  MatGetSize(Mat mat,PetscInt *m,PetscInt* n)
4684: {
4687:   if (m) *m = mat->rmap.N;
4688:   if (n) *n = mat->cmap.N;
4689:   return(0);
4690: }

4694: /*@
4695:    MatGetLocalSize - Returns the number of rows and columns in a matrix
4696:    stored locally.  This information may be implementation dependent, so
4697:    use with care.

4699:    Not Collective

4701:    Input Parameters:
4702: .  mat - the matrix

4704:    Output Parameters:
4705: +  m - the number of local rows
4706: -  n - the number of local columns

4708:    Note: both output parameters can be PETSC_NULL on input.

4710:    Level: beginner

4712:    Concepts: matrices^local size

4714: .seealso: MatGetSize()
4715: @*/
4716: PetscErrorCode  MatGetLocalSize(Mat mat,PetscInt *m,PetscInt* n)
4717: {
4722:   if (m) *m = mat->rmap.n;
4723:   if (n) *n = mat->cmap.n;
4724:   return(0);
4725: }

4729: /*@
4730:    MatGetOwnershipRangeColumn - Returns the range of matrix columns owned by
4731:    this processor.

4733:    Not Collective

4735:    Input Parameters:
4736: .  mat - the matrix

4738:    Output Parameters:
4739: +  m - the global index of the first local column
4740: -  n - one more than the global index of the last local column

4742:    Notes: both output parameters can be PETSC_NULL on input.

4744:    Level: developer

4746:    Concepts: matrices^column ownership
4747: @*/
4748: PetscErrorCode  MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt* n)
4749: {

4757:   MatPreallocated(mat);
4758:   if (m) *m = mat->cmap.rstart;
4759:   if (n) *n = mat->cmap.rend;
4760:   return(0);
4761: }

4765: /*@
4766:    MatGetOwnershipRange - Returns the range of matrix rows owned by
4767:    this processor, assuming that the matrix is laid out with the first
4768:    n1 rows on the first processor, the next n2 rows on the second, etc.
4769:    For certain parallel layouts this range may not be well defined.

4771:    Not Collective

4773:    Input Parameters:
4774: .  mat - the matrix

4776:    Output Parameters:
4777: +  m - the global index of the first local row
4778: -  n - one more than the global index of the last local row

4780:    Note: both output parameters can be PETSC_NULL on input.

4782:    Level: beginner

4784:    Concepts: matrices^row ownership

4786: .seealso:   MatGetOwnershipRanges()

4788: @*/
4789: PetscErrorCode  MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt* n)
4790: {

4798:   MatPreallocated(mat);
4799:   if (m) *m = mat->rmap.rstart;
4800:   if (n) *n = mat->rmap.rend;
4801:   return(0);
4802: }

4806: /*@C
4807:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
4808:    each process

4810:    Not Collective

4812:    Input Parameters:
4813: .  mat - the matrix

4815:    Output Parameters:
4816: .  ranges - start of each processors portion plus one more then the total length at the end

4818:    Level: beginner

4820:    Concepts: matrices^row ownership

4822: .seealso:   MatGetOwnershipRange()

4824: @*/
4825: PetscErrorCode  MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
4826: {

4832:   PetscMapGetGlobalRange(&mat->rmap,ranges);
4833:   return(0);
4834: }

4838: /*@  
4839:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
4840:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric() 
4841:    to complete the factorization.

4843:    Collective on Mat

4845:    Input Parameters:
4846: +  mat - the matrix
4847: .  row - row permutation
4848: .  column - column permutation
4849: -  info - structure containing 
4850: $      levels - number of levels of fill.
4851: $      expected fill - as ratio of original fill.
4852: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
4853:                 missing diagonal entries)

4855:    Output Parameters:
4856: .  fact - new matrix that has been symbolically factored

4858:    Notes:
4859:    See the users manual for additional information about
4860:    choosing the fill factor for better efficiency.

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

4866:    Level: developer

4868:   Concepts: matrices^symbolic LU factorization
4869:   Concepts: matrices^factorization
4870:   Concepts: LU^symbolic factorization

4872: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
4873:           MatGetOrdering(), MatFactorInfo

4875: @*/
4876: PetscErrorCode  MatILUFactorSymbolic(Mat mat,IS row,IS col,MatFactorInfo *info,Mat *fact)
4877: {

4887:   if (info->levels < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
4888:   if (info->fill < 1.0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %G",info->fill);
4889:   if (!mat->ops->ilufactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic ILU",((PetscObject)mat)->type_name);
4890:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4891:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4892:   MatPreallocated(mat);

4895:   (*mat->ops->ilufactorsymbolic)(mat,row,col,info,fact);
4897:   return(0);
4898: }

4902: /*@  
4903:    MatICCFactorSymbolic - Performs symbolic incomplete
4904:    Cholesky factorization for a symmetric matrix.  Use 
4905:    MatCholeskyFactorNumeric() to complete the factorization.

4907:    Collective on Mat

4909:    Input Parameters:
4910: +  mat - the matrix
4911: .  perm - row and column permutation
4912: -  info - structure containing 
4913: $      levels - number of levels of fill.
4914: $      expected fill - as ratio of original fill.

4916:    Output Parameter:
4917: .  fact - the factored matrix

4919:    Notes:
4920:    Most users should employ the KSP interface for linear solvers
4921:    instead of working directly with matrix algebra routines such as this.
4922:    See, e.g., KSPCreate().

4924:    Level: developer

4926:   Concepts: matrices^symbolic incomplete Cholesky factorization
4927:   Concepts: matrices^factorization
4928:   Concepts: Cholsky^symbolic factorization

4930: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
4931: @*/
4932: PetscErrorCode  MatICCFactorSymbolic(Mat mat,IS perm,MatFactorInfo *info,Mat *fact)
4933: {

4942:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4943:   if (info->levels < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
4944:   if (info->fill < 1.0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %G",info->fill);
4945:   if (!mat->ops->iccfactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic ICC",((PetscObject)mat)->type_name);
4946:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4947:   MatPreallocated(mat);

4950:   (*mat->ops->iccfactorsymbolic)(mat,perm,info,fact);
4952:   return(0);
4953: }

4957: /*@C
4958:    MatGetArray - Returns a pointer to the element values in the matrix.
4959:    The result of this routine is dependent on the underlying matrix data
4960:    structure, and may not even work for certain matrix types.  You MUST
4961:    call MatRestoreArray() when you no longer need to access the array.

4963:    Not Collective

4965:    Input Parameter:
4966: .  mat - the matrix

4968:    Output Parameter:
4969: .  v - the location of the values


4972:    Fortran Note:
4973:    This routine is used differently from Fortran, e.g.,
4974: .vb
4975:         Mat         mat
4976:         PetscScalar mat_array(1)
4977:         PetscOffset i_mat
4978:         PetscErrorCode ierr
4979:         call MatGetArray(mat,mat_array,i_mat,ierr)

4981:   C  Access first local entry in matrix; note that array is
4982:   C  treated as one dimensional
4983:         value = mat_array(i_mat + 1)

4985:         [... other code ...]
4986:         call MatRestoreArray(mat,mat_array,i_mat,ierr)
4987: .ve

4989:    See the Fortran chapter of the users manual and 
4990:    petsc/src/mat/examples/tests for details.

4992:    Level: advanced

4994:    Concepts: matrices^access array

4996: .seealso: MatRestoreArray(), MatGetArrayF90(), MatGetRowIJ()
4997: @*/
4998: PetscErrorCode  MatGetArray(Mat mat,PetscScalar *v[])
4999: {

5006:   if (!mat->ops->getarray) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5007:   MatPreallocated(mat);
5008:   (*mat->ops->getarray)(mat,v);
5009:   CHKMEMQ;
5010:   return(0);
5011: }

5015: /*@C
5016:    MatRestoreArray - Restores the matrix after MatGetArray() has been called.

5018:    Not Collective

5020:    Input Parameter:
5021: +  mat - the matrix
5022: -  v - the location of the values

5024:    Fortran Note:
5025:    This routine is used differently from Fortran, e.g.,
5026: .vb
5027:         Mat         mat
5028:         PetscScalar mat_array(1)
5029:         PetscOffset i_mat
5030:         PetscErrorCode ierr
5031:         call MatGetArray(mat,mat_array,i_mat,ierr)

5033:   C  Access first local entry in matrix; note that array is
5034:   C  treated as one dimensional
5035:         value = mat_array(i_mat + 1)

5037:         [... other code ...]
5038:         call MatRestoreArray(mat,mat_array,i_mat,ierr)
5039: .ve

5041:    See the Fortran chapter of the users manual and 
5042:    petsc/src/mat/examples/tests for details

5044:    Level: advanced

5046: .seealso: MatGetArray(), MatRestoreArrayF90()
5047: @*/
5048: PetscErrorCode  MatRestoreArray(Mat mat,PetscScalar *v[])
5049: {

5056: #if defined(PETSC_USE_DEBUG)
5057:   CHKMEMQ;
5058: #endif
5059:   if (!mat->ops->restorearray) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5060:   (*mat->ops->restorearray)(mat,v);
5061:   PetscObjectStateIncrease((PetscObject)mat);
5062:   return(0);
5063: }

5067: /*@C
5068:    MatGetSubMatrices - Extracts several submatrices from a matrix. If submat
5069:    points to an array of valid matrices, they may be reused to store the new
5070:    submatrices.

5072:    Collective on Mat

5074:    Input Parameters:
5075: +  mat - the matrix
5076: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
5077: .  irow, icol - index sets of rows and columns to extract
5078: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5080:    Output Parameter:
5081: .  submat - the array of submatrices

5083:    Notes:
5084:    MatGetSubMatrices() can extract only sequential submatrices
5085:    (from both sequential and parallel matrices). Use MatGetSubMatrix()
5086:    to extract a parallel submatrix.

5088:    When extracting submatrices from a parallel matrix, each processor can
5089:    form a different submatrix by setting the rows and columns of its
5090:    individual index sets according to the local submatrix desired.

5092:    When finished using the submatrices, the user should destroy
5093:    them with MatDestroyMatrices().

5095:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the 
5096:    original matrix has not changed from that last call to MatGetSubMatrices().

5098:    This routine creates the matrices in submat; you should NOT create them before
5099:    calling it. It also allocates the array of matrix pointers submat.

5101:    For BAIJ matrices the index sets must respect the block structure, that is if they
5102:    request one row/column in a block, they must request all rows/columns that are in
5103:    that block. For example, if the block size is 2 you cannot request just row 0 and 
5104:    column 0.

5106:    Fortran Note:
5107:    The Fortran interface is slightly different from that given below; it 
5108:    requires one to pass in  as submat a Mat (integer) array of size at least m.

5110:    Level: advanced

5112:    Concepts: matrices^accessing submatrices
5113:    Concepts: submatrices

5115: .seealso: MatDestroyMatrices(), MatGetSubMatrix(), MatGetRow(), MatGetDiagonal()
5116: @*/
5117: PetscErrorCode  MatGetSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
5118: {
5120:   PetscInt        i;
5121:   PetscTruth      eq;

5126:   if (n) {
5131:   }
5133:   if (n && scall == MAT_REUSE_MATRIX) {
5136:   }
5137:   if (!mat->ops->getsubmatrices) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5138:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5139:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5140:   MatPreallocated(mat);

5143:   (*mat->ops->getsubmatrices)(mat,n,irow,icol,scall,submat);
5145:   for (i=0; i<n; i++) {
5146:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
5147:       ISEqual(irow[i],icol[i],&eq);
5148:       if (eq) {
5149:         if (mat->symmetric){
5150:           MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
5151:         } else if (mat->hermitian) {
5152:           MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
5153:         } else if (mat->structurally_symmetric) {
5154:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
5155:         }
5156:       }
5157:     }
5158:   }
5159:   return(0);
5160: }

5164: /*@C
5165:    MatDestroyMatrices - Destroys a set of matrices obtained with MatGetSubMatrices().

5167:    Collective on Mat

5169:    Input Parameters:
5170: +  n - the number of local matrices
5171: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
5172:                        sequence of MatGetSubMatrices())

5174:    Level: advanced

5176:     Notes: Frees not only the matrices, but also the array that contains the matrices

5178: .seealso: MatGetSubMatrices()
5179: @*/
5180: PetscErrorCode  MatDestroyMatrices(PetscInt n,Mat *mat[])
5181: {
5183:   PetscInt       i;

5186:   if (n < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
5188:   for (i=0; i<n; i++) {
5189:     MatDestroy((*mat)[i]);
5190:   }
5191:   /* memory is allocated even if n = 0 */
5192:   PetscFree(*mat);
5193:   return(0);
5194: }

5198: /*@C
5199:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix. 

5201:    Collective on Mat

5203:    Input Parameters:
5204: .  mat - the matrix

5206:    Output Parameter:
5207: .  matstruct - the sequential matrix with the nonzero structure of mat
5208: .seealso: MatDestroySeqNonzeroStructure(), MatGetSubMatrices(), MatDestroyMatrices()
5209: @*/
5210: PetscErrorCode  MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct[])
5211: {

5217: 
5219:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5220:   MatPreallocated(mat);

5223:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
5225:   return(0);
5226: }

5230: /*@C
5231:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

5233:    Collective on Mat

5235:    Input Parameters:
5236: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
5237:                        sequence of MatGetSequentialNonzeroStructure())

5239:    Level: advanced

5241:     Notes: Frees not only the matrices, but also the array that contains the matrices

5243: .seealso: MatGetSeqNonzeroStructure()
5244: @*/
5245: PetscErrorCode  MatDestroySeqNonzeroStructure(Mat *mat[])
5246: {

5251:   MatDestroyMatrices(1,mat);
5252:   return(0);
5253: }

5257: /*@
5258:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
5259:    replaces the index sets by larger ones that represent submatrices with
5260:    additional overlap.

5262:    Collective on Mat

5264:    Input Parameters:
5265: +  mat - the matrix
5266: .  n   - the number of index sets
5267: .  is  - the array of index sets (these index sets will changed during the call)
5268: -  ov  - the additional overlap requested

5270:    Level: developer

5272:    Concepts: overlap
5273:    Concepts: ASM^computing overlap

5275: .seealso: MatGetSubMatrices()
5276: @*/
5277: PetscErrorCode  MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
5278: {

5284:   if (n < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
5285:   if (n) {
5288:   }
5289:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5290:   if (mat->factor)     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5291:   MatPreallocated(mat);

5293:   if (!ov) return(0);
5294:   if (!mat->ops->increaseoverlap) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5296:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
5298:   return(0);
5299: }

5303: /*@
5304:    MatGetBlockSize - Returns the matrix block size; useful especially for the
5305:    block row and block diagonal formats.
5306:    
5307:    Not Collective

5309:    Input Parameter:
5310: .  mat - the matrix

5312:    Output Parameter:
5313: .  bs - block size

5315:    Notes:
5316:    Block diagonal formats are MATSEQBDIAG, MATMPIBDIAG.
5317:    Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ

5319:    Level: intermediate

5321:    Concepts: matrices^block size

5323: .seealso: MatCreateSeqBAIJ(), MatCreateMPIBAIJ(), MatCreateSeqBDiag(), MatCreateMPIBDiag()
5324: @*/
5325: PetscErrorCode  MatGetBlockSize(Mat mat,PetscInt *bs)
5326: {

5333:   MatPreallocated(mat);
5334:   *bs = mat->rmap.bs;
5335:   return(0);
5336: }

5340: /*@
5341:    MatSetBlockSize - Sets the matrix block size; for many matrix types you 
5342:      cannot use this and MUST set the blocksize when you preallocate the matrix
5343:    
5344:    Not Collective

5346:    Input Parameters:
5347: +  mat - the matrix
5348: -  bs - block size

5350:    Notes:
5351:      Only works for shell and AIJ matrices

5353:    Level: intermediate

5355:    Concepts: matrices^block size

5357: .seealso: MatCreateSeqBAIJ(), MatCreateMPIBAIJ(), MatCreateSeqBDiag(), MatCreateMPIBDiag(), MatGetBlockSize()
5358: @*/
5359: PetscErrorCode  MatSetBlockSize(Mat mat,PetscInt bs)
5360: {

5366:   MatPreallocated(mat);
5367:   if (mat->ops->setblocksize) {
5368:     mat->rmap.bs = bs;
5369:     (*mat->ops->setblocksize)(mat,bs);
5370:   } else {
5371:     SETERRQ1(PETSC_ERR_ARG_INCOMP,"Cannot set the blocksize for matrix type %s",((PetscObject)mat)->type_name);
5372:   }
5373:   return(0);
5374: }

5378: /*@C
5379:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

5381:    Collective on Mat

5383:     Input Parameters:
5384: +   mat - the matrix
5385: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
5386: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5387:                 symmetrized
5388: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5389:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5390:                  nonzero structure which is different than the full nonzero structure]

5392:     Output Parameters:
5393: +   n - number of rows in the (possibly compressed) matrix
5394: .   ia - the row pointers [of length n+1]
5395: .   ja - the column indices
5396: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
5397:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

5399:     Level: developer

5401:     Notes: You CANNOT change any of the ia[] or ja[] values.

5403:            Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values

5405:     Fortran Node

5407:            In Fortran use
5408: $           PetscInt ia(1), ja(1)
5409: $           PetscOffset iia, jja
5410: $      call MatGetRowIJ(mat,shift,symmetric,blockcompressed,n,ia,iia,ja,jja,done,ierr)
5411:  
5412:        Acess the ith and jth entries via ia(iia + i) and ja(jja + j)

5414: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatGetArray()
5415: @*/
5416: PetscErrorCode  MatGetRowIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5417: {

5427:   MatPreallocated(mat);
5428:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
5429:   else {
5430:     *done = PETSC_TRUE;
5432:     (*mat->ops->getrowij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5434:   }
5435:   return(0);
5436: }

5440: /*@C
5441:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

5443:     Collective on Mat

5445:     Input Parameters:
5446: +   mat - the matrix
5447: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
5448: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5449:                 symmetrized
5450: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5451:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5452:                  nonzero structure which is different than the full nonzero structure]

5454:     Output Parameters:
5455: +   n - number of columns in the (possibly compressed) matrix
5456: .   ia - the column pointers
5457: .   ja - the row indices
5458: -   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

5460:     Level: developer

5462: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
5463: @*/
5464: PetscErrorCode  MatGetColumnIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5465: {

5475:   MatPreallocated(mat);
5476:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
5477:   else {
5478:     *done = PETSC_TRUE;
5479:     (*mat->ops->getcolumnij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5480:   }
5481:   return(0);
5482: }

5486: /*@C
5487:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
5488:     MatGetRowIJ().

5490:     Collective on Mat

5492:     Input Parameters:
5493: +   mat - the matrix
5494: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
5495: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5496:                 symmetrized
5497: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5498:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5499:                  nonzero structure which is different than the full nonzero structure]

5501:     Output Parameters:
5502: +   n - size of (possibly compressed) matrix
5503: .   ia - the row pointers
5504: .   ja - the column indices
5505: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

5507:     Level: developer

5509: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
5510: @*/
5511: PetscErrorCode  MatRestoreRowIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5512: {

5521:   MatPreallocated(mat);

5523:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
5524:   else {
5525:     *done = PETSC_TRUE;
5526:     (*mat->ops->restorerowij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5527:   }
5528:   return(0);
5529: }

5533: /*@C
5534:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
5535:     MatGetColumnIJ().

5537:     Collective on Mat

5539:     Input Parameters:
5540: +   mat - the matrix
5541: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
5542: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5543:                 symmetrized
5544: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5545:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5546:                  nonzero structure which is different than the full nonzero structure]

5548:     Output Parameters:
5549: +   n - size of (possibly compressed) matrix
5550: .   ia - the column pointers
5551: .   ja - the row indices
5552: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

5554:     Level: developer

5556: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
5557: @*/
5558: PetscErrorCode  MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5559: {

5568:   MatPreallocated(mat);

5570:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
5571:   else {
5572:     *done = PETSC_TRUE;
5573:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5574:   }
5575:   return(0);
5576: }

5580: /*@C
5581:     MatColoringPatch -Used inside matrix coloring routines that 
5582:     use MatGetRowIJ() and/or MatGetColumnIJ().

5584:     Collective on Mat

5586:     Input Parameters:
5587: +   mat - the matrix
5588: .   ncolors - max color value
5589: .   n   - number of entries in colorarray
5590: -   colorarray - array indicating color for each column

5592:     Output Parameters:
5593: .   iscoloring - coloring generated using colorarray information

5595:     Level: developer

5597: .seealso: MatGetRowIJ(), MatGetColumnIJ()

5599: @*/
5600: PetscErrorCode  MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
5601: {

5609:   MatPreallocated(mat);

5611:   if (!mat->ops->coloringpatch){
5612:     ISColoringCreate(((PetscObject)mat)->comm,ncolors,n,colorarray,iscoloring);
5613:   } else {
5614:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
5615:   }
5616:   return(0);
5617: }


5622: /*@
5623:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

5625:    Collective on Mat

5627:    Input Parameter:
5628: .  mat - the factored matrix to be reset

5630:    Notes: 
5631:    This routine should be used only with factored matrices formed by in-place
5632:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
5633:    format).  This option can save memory, for example, when solving nonlinear
5634:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
5635:    ILU(0) preconditioner.  

5637:    Note that one can specify in-place ILU(0) factorization by calling 
5638: .vb
5639:      PCType(pc,PCILU);
5640:      PCFactorSeUseInPlace(pc);
5641: .ve
5642:    or by using the options -pc_type ilu -pc_factor_in_place

5644:    In-place factorization ILU(0) can also be used as a local
5645:    solver for the blocks within the block Jacobi or additive Schwarz
5646:    methods (runtime option: -sub_pc_factor_in_place).  See the discussion 
5647:    of these preconditioners in the users manual for details on setting
5648:    local solver options.

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

5654:    Level: developer

5656: .seealso: PCFactorSetUseInPlace()

5658:    Concepts: matrices^unfactored

5660: @*/
5661: PetscErrorCode  MatSetUnfactored(Mat mat)
5662: {

5668:   MatPreallocated(mat);
5669:   mat->factor = 0;
5670:   if (!mat->ops->setunfactored) return(0);
5671:   (*mat->ops->setunfactored)(mat);
5672:   return(0);
5673: }

5675: /*MC
5676:     MatGetArrayF90 - Accesses a matrix array from Fortran90.

5678:     Synopsis:
5679:     MatGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

5681:     Not collective

5683:     Input Parameter:
5684: .   x - matrix

5686:     Output Parameters:
5687: +   xx_v - the Fortran90 pointer to the array
5688: -   ierr - error code

5690:     Example of Usage: 
5691: .vb
5692:       PetscScalar, pointer xx_v(:)
5693:       ....
5694:       call MatGetArrayF90(x,xx_v,ierr)
5695:       a = xx_v(3)
5696:       call MatRestoreArrayF90(x,xx_v,ierr)
5697: .ve

5699:     Notes:
5700:     Not yet supported for all F90 compilers

5702:     Level: advanced

5704: .seealso:  MatRestoreArrayF90(), MatGetArray(), MatRestoreArray()

5706:     Concepts: matrices^accessing array

5708: M*/

5710: /*MC
5711:     MatRestoreArrayF90 - Restores a matrix array that has been
5712:     accessed with MatGetArrayF90().

5714:     Synopsis:
5715:     MatRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

5717:     Not collective

5719:     Input Parameters:
5720: +   x - matrix
5721: -   xx_v - the Fortran90 pointer to the array

5723:     Output Parameter:
5724: .   ierr - error code

5726:     Example of Usage: 
5727: .vb
5728:        PetscScalar, pointer xx_v(:)
5729:        ....
5730:        call MatGetArrayF90(x,xx_v,ierr)
5731:        a = xx_v(3)
5732:        call MatRestoreArrayF90(x,xx_v,ierr)
5733: .ve
5734:    
5735:     Notes:
5736:     Not yet supported for all F90 compilers

5738:     Level: advanced

5740: .seealso:  MatGetArrayF90(), MatGetArray(), MatRestoreArray()

5742: M*/


5747: /*@
5748:     MatGetSubMatrix - Gets a single submatrix on the same number of processors
5749:                       as the original matrix.

5751:     Collective on Mat

5753:     Input Parameters:
5754: +   mat - the original matrix
5755: .   isrow - rows this processor should obtain
5756: .   iscol - columns for all processors you wish to keep
5757: .   csize - number of columns "local" to this processor (does nothing for sequential 
5758:             matrices). This should match the result from VecGetLocalSize(x,...) if you 
5759:             plan to use the matrix in a A*x; alternatively, you can use PETSC_DECIDE
5760: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5762:     Output Parameter:
5763: .   newmat - the new submatrix, of the same type as the old

5765:     Level: advanced

5767:     Notes: the iscol argument MUST be the same on each processor. You might be 
5768:     able to create the iscol argument with ISAllGather(). The rows is isrow will be
5769:     sorted into the same order as the original matrix.

5771:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
5772:    the MatGetSubMatrix() routine will create the newmat for you. Any additional calls
5773:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX  
5774:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when 
5775:    you are finished using it.

5777:     Concepts: matrices^submatrices

5779: .seealso: MatGetSubMatrices(), ISAllGather()
5780: @*/
5781: PetscErrorCode  MatGetSubMatrix(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse cll,Mat *newmat)
5782: {
5784:   PetscMPIInt    size;
5785:   Mat            *local;

5794:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5795:   MatPreallocated(mat);
5796:   MPI_Comm_size(((PetscObject)mat)->comm,&size);

5798:   /* if original matrix is on just one processor then use submatrix generated */
5799:   if (!mat->ops->getsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
5800:     MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,&newmat);
5801:     return(0);
5802:   } else if (!mat->ops->getsubmatrix && size == 1) {
5803:     MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&local);
5804:     *newmat = *local;
5805:     PetscFree(local);
5806:     return(0);
5807:   }

5809:   if (!mat->ops->getsubmatrix) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5810:   (*mat->ops->getsubmatrix)(mat,isrow,iscol,csize,cll,newmat);
5811:   PetscObjectStateIncrease((PetscObject)*newmat);
5812:   return(0);
5813: }

5817: /*@
5818:     MatGetSubMatrixRaw - Gets a single submatrix on the same number of processors
5819:                          as the original matrix.

5821:     Collective on Mat

5823:     Input Parameters:
5824: +   mat - the original matrix
5825: .   nrows - the number of rows this processor should obtain
5826: .   rows - rows this processor should obtain
5827: .   ncols - the number of columns for all processors you wish to keep
5828: .   cols - columns for all processors you wish to keep
5829: .   csize - number of columns "local" to this processor (does nothing for sequential 
5830:             matrices). This should match the result from VecGetLocalSize(x,...) if you 
5831:             plan to use the matrix in a A*x; alternatively, you can use PETSC_DECIDE
5832: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5834:     Output Parameter:
5835: .   newmat - the new submatrix, of the same type as the old

5837:     Level: advanced

5839:     Notes: the iscol argument MUST be the same on each processor. You might be 
5840:     able to create the iscol argument with ISAllGather().

5842:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
5843:    the MatGetSubMatrix() routine will create the newmat for you. Any additional calls
5844:    to this routine with a mat of the same nonzero structure and with a cll of MAT_REUSE_MATRIX  
5845:    will reuse the matrix generated the first time.

5847:     Concepts: matrices^submatrices

5849: .seealso: MatGetSubMatrices(), ISAllGather()
5850: @*/
5851: PetscErrorCode  MatGetSubMatrixRaw(Mat mat,PetscInt nrows,const PetscInt rows[],PetscInt ncols,const PetscInt cols[],PetscInt csize,MatReuse cll,Mat *newmat)
5852: {
5853:   IS             isrow, iscol;

5863:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5864:   MatPreallocated(mat);
5865:   ISCreateGeneralWithArray(PETSC_COMM_SELF, nrows, (PetscInt *) rows, &isrow);
5866:   ISCreateGeneralWithArray(PETSC_COMM_SELF, ncols, (PetscInt *) cols, &iscol);
5867:   MatGetSubMatrix(mat, isrow, iscol, csize, cll, newmat);
5868:   ISDestroy(isrow);
5869:   ISDestroy(iscol);
5870:   return(0);
5871: }

5875: /*@
5876:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
5877:    used during the assembly process to store values that belong to 
5878:    other processors.

5880:    Not Collective

5882:    Input Parameters:
5883: +  mat   - the matrix
5884: .  size  - the initial size of the stash.
5885: -  bsize - the initial size of the block-stash(if used).

5887:    Options Database Keys:
5888: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
5889: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

5891:    Level: intermediate

5893:    Notes: 
5894:      The block-stash is used for values set with MatSetValuesBlocked() while
5895:      the stash is used for values set with MatSetValues()

5897:      Run with the option -info and look for output of the form
5898:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
5899:      to determine the appropriate value, MM, to use for size and 
5900:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
5901:      to determine the value, BMM to use for bsize

5903:    Concepts: stash^setting matrix size
5904:    Concepts: matrices^stash

5906: @*/
5907: PetscErrorCode  MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
5908: {

5914:   MatStashSetInitialSize_Private(&mat->stash,size);
5915:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
5916:   return(0);
5917: }

5921: /*@
5922:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of 
5923:      the matrix

5925:    Collective on Mat

5927:    Input Parameters:
5928: +  mat   - the matrix
5929: .  x,y - the vectors
5930: -  w - where the result is stored

5932:    Level: intermediate

5934:    Notes: 
5935:     w may be the same vector as y. 

5937:     This allows one to use either the restriction or interpolation (its transpose)
5938:     matrix to do the interpolation

5940:     Concepts: interpolation

5942: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

5944: @*/
5945: PetscErrorCode  MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
5946: {
5948:   PetscInt       M,N;

5956:   MatPreallocated(A);
5957:   MatGetSize(A,&M,&N);
5958:   if (N > M) {
5959:     MatMultTransposeAdd(A,x,y,w);
5960:   } else {
5961:     MatMultAdd(A,x,y,w);
5962:   }
5963:   return(0);
5964: }

5968: /*@
5969:    MatInterpolate - y = A*x or A'*x depending on the shape of 
5970:      the matrix

5972:    Collective on Mat

5974:    Input Parameters:
5975: +  mat   - the matrix
5976: -  x,y - the vectors

5978:    Level: intermediate

5980:    Notes: 
5981:     This allows one to use either the restriction or interpolation (its transpose)
5982:     matrix to do the interpolation

5984:    Concepts: matrices^interpolation

5986: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

5988: @*/
5989: PetscErrorCode  MatInterpolate(Mat A,Vec x,Vec y)
5990: {
5992:   PetscInt       M,N;

5999:   MatPreallocated(A);
6000:   MatGetSize(A,&M,&N);
6001:   if (N > M) {
6002:     MatMultTranspose(A,x,y);
6003:   } else {
6004:     MatMult(A,x,y);
6005:   }
6006:   return(0);
6007: }

6011: /*@
6012:    MatRestrict - y = A*x or A'*x

6014:    Collective on Mat

6016:    Input Parameters:
6017: +  mat   - the matrix
6018: -  x,y - the vectors

6020:    Level: intermediate

6022:    Notes: 
6023:     This allows one to use either the restriction or interpolation (its transpose)
6024:     matrix to do the restriction

6026:    Concepts: matrices^restriction

6028: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

6030: @*/
6031: PetscErrorCode  MatRestrict(Mat A,Vec x,Vec y)
6032: {
6034:   PetscInt       M,N;

6041:   MatPreallocated(A);

6043:   MatGetSize(A,&M,&N);
6044:   if (N > M) {
6045:     MatMult(A,x,y);
6046:   } else {
6047:     MatMultTranspose(A,x,y);
6048:   }
6049:   return(0);
6050: }

6054: /*@
6055:    MatNullSpaceAttach - attaches a null space to a matrix.
6056:         This null space will be removed from the resulting vector whenever
6057:         MatMult() is called

6059:    Collective on Mat

6061:    Input Parameters:
6062: +  mat - the matrix
6063: -  nullsp - the null space object

6065:    Level: developer

6067:    Notes:
6068:       Overwrites any previous null space that may have been attached

6070:    Concepts: null space^attaching to matrix

6072: .seealso: MatCreate(), MatNullSpaceCreate()
6073: @*/
6074: PetscErrorCode  MatNullSpaceAttach(Mat mat,MatNullSpace nullsp)
6075: {

6082:   MatPreallocated(mat);
6083:   PetscObjectReference((PetscObject)nullsp);
6084:   if (mat->nullsp) { MatNullSpaceDestroy(mat->nullsp); }
6085:   mat->nullsp = nullsp;
6086:   return(0);
6087: }

6091: /*@  
6092:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

6094:    Collective on Mat

6096:    Input Parameters:
6097: +  mat - the matrix
6098: .  row - row/column permutation
6099: .  fill - expected fill factor >= 1.0
6100: -  level - level of fill, for ICC(k)

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

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

6110:    Level: developer

6112:    Concepts: matrices^incomplete Cholesky factorization
6113:    Concepts: Cholesky factorization

6115: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6116: @*/
6117: PetscErrorCode  MatICCFactor(Mat mat,IS row,MatFactorInfo* info)
6118: {

6126:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"matrix must be square");
6127:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6128:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6129:   if (!mat->ops->iccfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6130:   MatPreallocated(mat);
6131:   (*mat->ops->iccfactor)(mat,row,info);
6132:   PetscObjectStateIncrease((PetscObject)mat);
6133:   return(0);
6134: }

6138: /*@ 
6139:    MatSetValuesAdic - Sets values computed with ADIC automatic differentiation into a matrix.

6141:    Not Collective

6143:    Input Parameters:
6144: +  mat - the matrix
6145: -  v - the values compute with ADIC

6147:    Level: developer

6149:    Notes:
6150:      Must call MatSetColoring() before using this routine. Also this matrix must already
6151:      have its nonzero pattern determined.

6153: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
6154:           MatSetValues(), MatSetColoring(), MatSetValuesAdifor()
6155: @*/
6156: PetscErrorCode  MatSetValuesAdic(Mat mat,void *v)
6157: {


6165:   if (!mat->assembled) {
6166:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
6167:   }
6169:   if (!mat->ops->setvaluesadic) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6170:   (*mat->ops->setvaluesadic)(mat,v);
6172:   MatView_Private(mat);
6173:   PetscObjectStateIncrease((PetscObject)mat);
6174:   return(0);
6175: }


6180: /*@ 
6181:    MatSetColoring - Sets a coloring used by calls to MatSetValuesAdic()

6183:    Not Collective

6185:    Input Parameters:
6186: +  mat - the matrix
6187: -  coloring - the coloring

6189:    Level: developer

6191: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
6192:           MatSetValues(), MatSetValuesAdic()
6193: @*/
6194: PetscErrorCode  MatSetColoring(Mat mat,ISColoring coloring)
6195: {


6203:   if (!mat->assembled) {
6204:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
6205:   }
6206:   if (!mat->ops->setcoloring) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6207:   (*mat->ops->setcoloring)(mat,coloring);
6208:   return(0);
6209: }

6213: /*@ 
6214:    MatSetValuesAdifor - Sets values computed with automatic differentiation into a matrix.

6216:    Not Collective

6218:    Input Parameters:
6219: +  mat - the matrix
6220: .  nl - leading dimension of v
6221: -  v - the values compute with ADIFOR

6223:    Level: developer

6225:    Notes:
6226:      Must call MatSetColoring() before using this routine. Also this matrix must already
6227:      have its nonzero pattern determined.

6229: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
6230:           MatSetValues(), MatSetColoring()
6231: @*/
6232: PetscErrorCode  MatSetValuesAdifor(Mat mat,PetscInt nl,void *v)
6233: {


6241:   if (!mat->assembled) {
6242:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
6243:   }
6245:   if (!mat->ops->setvaluesadifor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6246:   (*mat->ops->setvaluesadifor)(mat,nl,v);
6248:   PetscObjectStateIncrease((PetscObject)mat);
6249:   return(0);
6250: }

6254: /*@ 
6255:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the 
6256:          ghosted ones.

6258:    Not Collective

6260:    Input Parameters:
6261: +  mat - the matrix
6262: -  diag = the diagonal values, including ghost ones

6264:    Level: developer

6266:    Notes: Works only for MPIAIJ and MPIBAIJ matrices
6267:       
6268: .seealso: MatDiagonalScale()
6269: @*/
6270: PetscErrorCode  MatDiagonalScaleLocal(Mat mat,Vec diag)
6271: {
6273:   PetscMPIInt    size;


6280:   if (!mat->assembled) {
6281:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
6282:   }
6284:   MPI_Comm_size(((PetscObject)mat)->comm,&size);
6285:   if (size == 1) {
6286:     PetscInt n,m;
6287:     VecGetSize(diag,&n);
6288:     MatGetSize(mat,0,&m);
6289:     if (m == n) {
6290:       MatDiagonalScale(mat,0,diag);
6291:     } else {
6292:       SETERRQ(PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
6293:     }
6294:   } else {
6295:     PetscErrorCode (*f)(Mat,Vec);
6296:     PetscObjectQueryFunction((PetscObject)mat,"MatDiagonalScaleLocal_C",(void (**)(void))&f);
6297:     if (f) {
6298:       (*f)(mat,diag);
6299:     } else {
6300:       SETERRQ(PETSC_ERR_SUP,"Only supported for MPIAIJ and MPIBAIJ parallel matrices");
6301:     }
6302:   }
6304:   PetscObjectStateIncrease((PetscObject)mat);
6305:   return(0);
6306: }

6310: /*@ 
6311:    MatGetInertia - Gets the inertia from a factored matrix

6313:    Collective on Mat

6315:    Input Parameter:
6316: .  mat - the matrix

6318:    Output Parameters:
6319: +   nneg - number of negative eigenvalues
6320: .   nzero - number of zero eigenvalues
6321: -   npos - number of positive eigenvalues

6323:    Level: advanced

6325:    Notes: Matrix must have been factored by MatCholeskyFactor()


6328: @*/
6329: PetscErrorCode  MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
6330: {

6336:   if (!mat->factor)    SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
6337:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
6338:   if (!mat->ops->getinertia) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6339:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
6340:   return(0);
6341: }

6343: /* ----------------------------------------------------------------*/
6346: /*@
6347:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

6349:    Collective on Mat and Vecs

6351:    Input Parameters:
6352: +  mat - the factored matrix
6353: -  b - the right-hand-side vectors

6355:    Output Parameter:
6356: .  x - the result vectors

6358:    Notes:
6359:    The vectors b and x cannot be the same.  I.e., one cannot
6360:    call MatSolves(A,x,x).

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

6367:    Level: developer

6369:    Concepts: matrices^triangular solves

6371: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
6372: @*/
6373: PetscErrorCode  MatSolves(Mat mat,Vecs b,Vecs x)
6374: {

6380:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
6381:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
6382:   if (!mat->rmap.N && !mat->cmap.N) return(0);

6384:   if (!mat->ops->solves) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6385:   MatPreallocated(mat);
6387:   (*mat->ops->solves)(mat,b,x);
6389:   return(0);
6390: }

6394: /*@
6395:    MatIsSymmetric - Test whether a matrix is symmetric

6397:    Collective on Mat

6399:    Input Parameter:
6400: +  A - the matrix to test
6401: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

6403:    Output Parameters:
6404: .  flg - the result

6406:    Level: intermediate

6408:    Concepts: matrix^symmetry

6410: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
6411: @*/
6412: PetscErrorCode  MatIsSymmetric(Mat A,PetscReal tol,PetscTruth *flg)
6413: {

6419:   if (!A->symmetric_set) {
6420:     if (!A->ops->issymmetric) {
6421:       MatType mattype;
6422:       MatGetType(A,&mattype);
6423:       SETERRQ1(PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
6424:     }
6425:     (*A->ops->issymmetric)(A,tol,&A->symmetric);
6426:     A->symmetric_set = PETSC_TRUE;
6427:     if (A->symmetric) {
6428:       A->structurally_symmetric_set = PETSC_TRUE;
6429:       A->structurally_symmetric     = PETSC_TRUE;
6430:     }
6431:   }
6432:   *flg = A->symmetric;
6433:   return(0);
6434: }

6438: /*@
6439:    MatIsHermitian - Test whether a matrix is Hermitian

6441:    Collective on Mat

6443:    Input Parameter:
6444: +  A - the matrix to test
6445: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

6447:    Output Parameters:
6448: .  flg - the result

6450:    Level: intermediate

6452:    Concepts: matrix^symmetry

6454: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
6455: @*/
6456: PetscErrorCode  MatIsHermitian(Mat A,PetscReal tol,PetscTruth *flg)
6457: {

6463:   if (!A->hermitian_set) {
6464:     if (!A->ops->ishermitian) {
6465:       MatType mattype;
6466:       MatGetType(A,&mattype);
6467:       SETERRQ1(PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for Hermitian",mattype);
6468:     }
6469:     (*A->ops->ishermitian)(A,tol,&A->hermitian);
6470:     A->hermitian_set = PETSC_TRUE;
6471:     if (A->hermitian) {
6472:       A->structurally_symmetric_set = PETSC_TRUE;
6473:       A->structurally_symmetric     = PETSC_TRUE;
6474:     }
6475:   }
6476:   *flg = A->hermitian;
6477:   return(0);
6478: }

6482: /*@
6483:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

6485:    Collective on Mat

6487:    Input Parameter:
6488: .  A - the matrix to check

6490:    Output Parameters:
6491: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
6492: -  flg - the result

6494:    Level: advanced

6496:    Concepts: matrix^symmetry

6498:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
6499:          if you want it explicitly checked

6501: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
6502: @*/
6503: PetscErrorCode  MatIsSymmetricKnown(Mat A,PetscTruth *set,PetscTruth *flg)
6504: {
6509:   if (A->symmetric_set) {
6510:     *set = PETSC_TRUE;
6511:     *flg = A->symmetric;
6512:   } else {
6513:     *set = PETSC_FALSE;
6514:   }
6515:   return(0);
6516: }

6520: /*@
6521:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

6523:    Collective on Mat

6525:    Input Parameter:
6526: .  A - the matrix to check

6528:    Output Parameters:
6529: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
6530: -  flg - the result

6532:    Level: advanced

6534:    Concepts: matrix^symmetry

6536:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
6537:          if you want it explicitly checked

6539: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
6540: @*/
6541: PetscErrorCode  MatIsHermitianKnown(Mat A,PetscTruth *set,PetscTruth *flg)
6542: {
6547:   if (A->hermitian_set) {
6548:     *set = PETSC_TRUE;
6549:     *flg = A->hermitian;
6550:   } else {
6551:     *set = PETSC_FALSE;
6552:   }
6553:   return(0);
6554: }

6558: /*@
6559:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

6561:    Collective on Mat

6563:    Input Parameter:
6564: .  A - the matrix to test

6566:    Output Parameters:
6567: .  flg - the result

6569:    Level: intermediate

6571:    Concepts: matrix^symmetry

6573: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
6574: @*/
6575: PetscErrorCode  MatIsStructurallySymmetric(Mat A,PetscTruth *flg)
6576: {

6582:   if (!A->structurally_symmetric_set) {
6583:     if (!A->ops->isstructurallysymmetric) SETERRQ(PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
6584:     (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);
6585:     A->structurally_symmetric_set = PETSC_TRUE;
6586:   }
6587:   *flg = A->structurally_symmetric;
6588:   return(0);
6589: }

6594: /*@ 
6595:    MatStashGetInfo - Gets how many values are currently in the vector stash, i.e. need
6596:        to be communicated to other processors during the MatAssemblyBegin/End() process

6598:     Not collective

6600:    Input Parameter:
6601: .   vec - the vector

6603:    Output Parameters:
6604: +   nstash   - the size of the stash
6605: .   reallocs - the number of additional mallocs incurred.
6606: .   bnstash   - the size of the block stash
6607: -   breallocs - the number of additional mallocs incurred.in the block stash
6608:  
6609:    Level: advanced

6611: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
6612:   
6613: @*/
6614: PetscErrorCode  MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
6615: {
6618:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
6619:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
6620:   return(0);
6621: }

6625: /*@
6626:    MatGetVecs - Get vector(s) compatible with the matrix, i.e. with the same 
6627:      parallel layout
6628:    
6629:    Collective on Mat

6631:    Input Parameter:
6632: .  mat - the matrix

6634:    Output Parameter:
6635: +   right - (optional) vector that the matrix can be multiplied against
6636: -   left - (optional) vector that the matrix vector product can be stored in

6638:   Level: advanced

6640: .seealso: MatCreate()
6641: @*/
6642: PetscErrorCode  MatGetVecs(Mat mat,Vec *right,Vec *left)
6643: {

6649:   MatPreallocated(mat);
6650:   if (mat->ops->getvecs) {
6651:     (*mat->ops->getvecs)(mat,right,left);
6652:   } else {
6653:     PetscMPIInt size;
6654:     MPI_Comm_size(((PetscObject)mat)->comm, &size);
6655:     if (right) {
6656:       VecCreate(((PetscObject)mat)->comm,right);
6657:       VecSetSizes(*right,mat->cmap.n,PETSC_DETERMINE);
6658:       if (size > 1) {VecSetType(*right,VECMPI);}
6659:       else {VecSetType(*right,VECSEQ);}
6660:     }
6661:     if (left) {
6662:       VecCreate(((PetscObject)mat)->comm,left);
6663:       VecSetSizes(*left,mat->rmap.n,PETSC_DETERMINE);
6664:       if (size > 1) {VecSetType(*left,VECMPI);}
6665:       else {VecSetType(*left,VECSEQ);}
6666:     }
6667:   }
6668:   if (right) {VecSetBlockSize(*right,mat->rmap.bs);}
6669:   if (left) {VecSetBlockSize(*left,mat->rmap.bs);}
6670:   if (mat->mapping) {
6671:     if (right) {VecSetLocalToGlobalMapping(*right,mat->mapping);}
6672:     if (left) {VecSetLocalToGlobalMapping(*left,mat->mapping);}
6673:   }
6674:   if (mat->bmapping) {
6675:     if (right) {VecSetLocalToGlobalMappingBlock(*right,mat->bmapping);}
6676:     if (left) {VecSetLocalToGlobalMappingBlock(*left,mat->bmapping);}
6677:   }
6678:   return(0);
6679: }

6683: /*@
6684:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
6685:      with default values.

6687:    Not Collective

6689:    Input Parameters:
6690: .    info - the MatFactorInfo data structure


6693:    Notes: The solvers are generally used through the KSP and PC objects, for example
6694:           PCLU, PCILU, PCCHOLESKY, PCICC

6696:    Level: developer

6698: .seealso: MatFactorInfo
6699: @*/

6701: PetscErrorCode  MatFactorInfoInitialize(MatFactorInfo *info)
6702: {

6706:   PetscMemzero(info,sizeof(MatFactorInfo));
6707:   return(0);
6708: }

6712: /*@
6713:    MatPtAP - Creates the matrix projection C = P^T * A * P

6715:    Collective on Mat

6717:    Input Parameters:
6718: +  A - the matrix
6719: .  P - the projection matrix
6720: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6721: -  fill - expected fill as ratio of nnz(C)/nnz(A) 

6723:    Output Parameters:
6724: .  C - the product matrix

6726:    Notes:
6727:    C will be created and must be destroyed by the user with MatDestroy().

6729:    This routine is currently only implemented for pairs of AIJ matrices and classes
6730:    which inherit from AIJ.  

6732:    Level: intermediate

6734: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult()
6735: @*/
6736: PetscErrorCode  MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
6737: {

6743:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6744:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6747:   MatPreallocated(P);
6748:   if (!P->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6749:   if (P->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6751:   if (P->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap.N,A->cmap.N);
6752:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be >= 1.0",fill);
6753:   MatPreallocated(A);

6756:   (*A->ops->ptap)(A,P,scall,fill,C);

6759:   return(0);
6760: }

6764: /*@
6765:    MatPtAPNumeric - Computes the matrix projection C = P^T * A * P

6767:    Collective on Mat

6769:    Input Parameters:
6770: +  A - the matrix
6771: -  P - the projection matrix

6773:    Output Parameters:
6774: .  C - the product matrix

6776:    Notes:
6777:    C must have been created by calling MatPtAPSymbolic and must be destroyed by
6778:    the user using MatDeatroy().

6780:    This routine is currently only implemented for pairs of AIJ matrices and classes
6781:    which inherit from AIJ.  C will be of type MATAIJ.

6783:    Level: intermediate

6785: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
6786: @*/
6787: PetscErrorCode  MatPtAPNumeric(Mat A,Mat P,Mat C)
6788: {

6794:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6795:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6798:   MatPreallocated(P);
6799:   if (!P->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6800:   if (P->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6803:   MatPreallocated(C);
6804:   if (C->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6805:   if (P->cmap.N!=C->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap.N,C->rmap.N);
6806:   if (P->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap.N,A->cmap.N);
6807:   if (A->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap.N,A->cmap.N);
6808:   if (P->cmap.N!=C->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap.N,C->cmap.N);
6809:   MatPreallocated(A);

6812:   (*A->ops->ptapnumeric)(A,P,C);
6814:   return(0);
6815: }

6819: /*@
6820:    MatPtAPSymbolic - Creates the (i,j) structure of the matrix projection C = P^T * A * P

6822:    Collective on Mat

6824:    Input Parameters:
6825: +  A - the matrix
6826: -  P - the projection matrix

6828:    Output Parameters:
6829: .  C - the (i,j) structure of the product matrix

6831:    Notes:
6832:    C will be created and must be destroyed by the user with MatDestroy().

6834:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
6835:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
6836:    this (i,j) structure by calling MatPtAPNumeric().

6838:    Level: intermediate

6840: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
6841: @*/
6842: PetscErrorCode  MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
6843: {

6849:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6850:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6851:   if (fill <1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be >= 1.0",fill);
6854:   MatPreallocated(P);
6855:   if (!P->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6856:   if (P->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6859:   if (P->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap.N,A->cmap.N);
6860:   if (A->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap.N,A->cmap.N);
6861:   MatPreallocated(A);
6863:   (*A->ops->ptapsymbolic)(A,P,fill,C);

6866:   MatSetBlockSize(*C,A->rmap.bs);

6868:   return(0);
6869: }

6873: /*@
6874:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

6876:    Collective on Mat

6878:    Input Parameters:
6879: +  A - the left matrix
6880: .  B - the right matrix
6881: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6882: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B))

6884:    Output Parameters:
6885: .  C - the product matrix

6887:    Notes:
6888:    C will be created and must be destroyed by the user with MatDestroy().
6889:    Unless scall is MAT_REUSE_MATRIX

6891:    If you have many matrices with the same non-zero structure to multiply, you 
6892:    should either 
6893: $   1) use MAT_REUSE_MATRIX in all calls but the first or
6894: $   2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed

6896:    Level: intermediate

6898: .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatPtAP()
6899: @*/
6900: PetscErrorCode  MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
6901: {
6903:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
6904:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
6905:   PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat *)=PETSC_NULL;

6910:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6911:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6914:   MatPreallocated(B);
6915:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6916:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6918:   if (B->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->cmap.N);
6919:   if (scall == MAT_REUSE_MATRIX){
6922:   }
6923:   if (fill == PETSC_DEFAULT) fill = 2.0;
6924:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be >= 1.0",fill);
6925:   MatPreallocated(A);

6927:   fA = A->ops->matmult;
6928:   fB = B->ops->matmult;
6929:   if (fB == fA) {
6930:     if (!fB) SETERRQ1(PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",((PetscObject)B)->type_name);
6931:     mult = fB;
6932:   } else {
6933:     /* dispatch based on the type of A and B */
6934:     char  multname[256];
6935:     PetscStrcpy(multname,"MatMatMult_");
6936:     PetscStrcat(multname,((PetscObject)A)->type_name);
6937:     PetscStrcat(multname,"_");
6938:     PetscStrcat(multname,((PetscObject)B)->type_name);
6939:     PetscStrcat(multname,"_C"); /* e.g., multname = "MatMatMult_aij_dense_C" */
6940:     PetscObjectQueryFunction((PetscObject)B,multname,(void (**)(void))&mult);
6941:     if (!mult) SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
6942:   }
6944:   (*mult)(A,B,scall,fill,C);
6946:   return(0);
6947: }

6951: /*@
6952:    MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
6953:    of the matrix-matrix product C=A*B.  Call this routine before calling MatMatMultNumeric().

6955:    Collective on Mat

6957:    Input Parameters:
6958: +  A - the left matrix
6959: .  B - the right matrix
6960: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B))

6962:    Output Parameters:
6963: .  C - the matrix containing the ij structure of product matrix

6965:    Notes:
6966:    C will be created and must be destroyed by the user with MatDestroy().

6968:    This routine is currently implemented for 
6969:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
6970:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type MATDENSE.

6972:    Level: intermediate

6974: .seealso: MatMatMult(), MatMatMultNumeric()
6975: @*/
6976: PetscErrorCode  MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
6977: {
6979:   PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat *);
6980:   PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat *);
6981:   PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat *)=PETSC_NULL;

6986:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6987:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6991:   MatPreallocated(B);
6992:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6993:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6996:   if (B->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->cmap.N);
6997:   if (fill == PETSC_DEFAULT) fill = 2.0;
6998:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be > 1.0",fill);
6999:   MatPreallocated(A);
7000: 
7001:   Asymbolic = A->ops->matmultsymbolic;
7002:   Bsymbolic = B->ops->matmultsymbolic;
7003:   if (Asymbolic == Bsymbolic){
7004:     if (!Bsymbolic) SETERRQ1(PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
7005:     symbolic = Bsymbolic;
7006:   } else { /* dispatch based on the type of A and B */
7007:     char  symbolicname[256];
7008:     PetscStrcpy(symbolicname,"MatMatMultSymbolic_");
7009:     PetscStrcat(symbolicname,((PetscObject)A)->type_name);
7010:     PetscStrcat(symbolicname,"_");
7011:     PetscStrcat(symbolicname,((PetscObject)B)->type_name);
7012:     PetscStrcat(symbolicname,"_C");
7013:     PetscObjectQueryFunction((PetscObject)B,symbolicname,(void (**)(void))&symbolic);
7014:     if (!symbolic) SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMultSymbolic requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
7015:   }
7017:   (*symbolic)(A,B,fill,C);
7019:   return(0);
7020: }

7024: /*@
7025:    MatMatMultNumeric - Performs the numeric matrix-matrix product.
7026:    Call this routine after first calling MatMatMultSymbolic().

7028:    Collective on Mat

7030:    Input Parameters:
7031: +  A - the left matrix
7032: -  B - the right matrix

7034:    Output Parameters:
7035: .  C - the product matrix, whose ij structure was defined from MatMatMultSymbolic().

7037:    Notes:
7038:    C must have been created with MatMatMultSymbolic.

7040:    This routine is currently implemented for 
7041:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
7042:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type MATDENSE.

7044:    Level: intermediate

7046: .seealso: MatMatMult(), MatMatMultSymbolic()
7047: @*/
7048: PetscErrorCode  MatMatMultNumeric(Mat A,Mat B,Mat C)
7049: {
7051:   PetscErrorCode (*Anumeric)(Mat,Mat,Mat);
7052:   PetscErrorCode (*Bnumeric)(Mat,Mat,Mat);
7053:   PetscErrorCode (*numeric)(Mat,Mat,Mat)=PETSC_NULL;

7058:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7059:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

7063:   MatPreallocated(B);
7064:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7065:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

7069:   MatPreallocated(C);
7070:   if (!C->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7071:   if (C->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

7073:   if (B->cmap.N!=C->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->cmap.N,C->cmap.N);
7074:   if (B->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->cmap.N);
7075:   if (A->rmap.N!=C->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",A->rmap.N,C->rmap.N);
7076:   MatPreallocated(A);

7078:   Anumeric = A->ops->matmultnumeric;
7079:   Bnumeric = B->ops->matmultnumeric;
7080:   if (Anumeric == Bnumeric){
7081:     if (!Bnumeric) SETERRQ1(PETSC_ERR_SUP,"MatMatMultNumeric not supported for B of type %s",((PetscObject)B)->type_name);
7082:     numeric = Bnumeric;
7083:   } else {
7084:     char  numericname[256];
7085:     PetscStrcpy(numericname,"MatMatMultNumeric_");
7086:     PetscStrcat(numericname,((PetscObject)A)->type_name);
7087:     PetscStrcat(numericname,"_");
7088:     PetscStrcat(numericname,((PetscObject)B)->type_name);
7089:     PetscStrcat(numericname,"_C");
7090:     PetscObjectQueryFunction((PetscObject)B,numericname,(void (**)(void))&numeric);
7091:     if (!numeric)
7092:       SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMultNumeric requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
7093:   }
7095:   (*numeric)(A,B,C);
7097:   return(0);
7098: }

7102: /*@
7103:    MatMatMultTranspose - Performs Matrix-Matrix Multiplication C=A^T*B.

7105:    Collective on Mat

7107:    Input Parameters:
7108: +  A - the left matrix
7109: .  B - the right matrix
7110: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7111: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B))

7113:    Output Parameters:
7114: .  C - the product matrix

7116:    Notes:
7117:    C will be created and must be destroyed by the user with MatDestroy().

7119:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
7120:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.

7122:    Level: intermediate

7124: .seealso: MatMatMultTransposeSymbolic(), MatMatMultTransposeNumeric(), MatPtAP()
7125: @*/
7126: PetscErrorCode  MatMatMultTranspose(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
7127: {
7129:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
7130:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);

7135:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7136:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7139:   MatPreallocated(B);
7140:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7141:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7143:   if (B->rmap.N!=A->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->rmap.N);
7144:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be > 1.0",fill);
7145:   MatPreallocated(A);

7147:   fA = A->ops->matmulttranspose;
7148:   if (!fA) SETERRQ1(PETSC_ERR_SUP,"MatMatMultTranspose not supported for A of type %s",((PetscObject)A)->type_name);
7149:   fB = B->ops->matmulttranspose;
7150:   if (!fB) SETERRQ1(PETSC_ERR_SUP,"MatMatMultTranspose not supported for B of type %s",((PetscObject)B)->type_name);
7151:   if (fB!=fA) SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMultTranspose requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);

7154:   (*A->ops->matmulttranspose)(A,B,scall,fill,C);
7156: 
7157:   return(0);
7158: }

7162: /*@C
7163:    MatGetRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators. 

7165:    Collective on Mat

7167:    Input Parameters:
7168: +  mat - the matrix
7169: .  nsubcomm - the number of subcommunicators (= number of redundant pareallel or sequential matrices)
7170: .  subcomm - MPI communicator split from the communicator where mat resides in
7171: .  mlocal_red - number of local rows of the redundant matrix
7172: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7174:    Output Parameter:
7175: .  matredundant - redundant matrix

7177:    Notes:
7178:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the 
7179:    original matrix has not changed from that last call to MatGetRedundantMatrix().

7181:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
7182:    calling it. 

7184:    Only MPIAIJ matrix is supported. 
7185:    
7186:    Level: advanced

7188:    Concepts: subcommunicator
7189:    Concepts: duplicate matrix

7191: .seealso: MatDestroy()
7192: @*/
7193: PetscErrorCode  MatGetRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,PetscInt mlocal_red,MatReuse reuse,Mat *matredundant)
7194: {

7199:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
7202:   }
7203:   if (!mat->ops->getredundantmatrix) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7204:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7205:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7206:   MatPreallocated(mat);

7209:   (*mat->ops->getredundantmatrix)(mat,nsubcomm,subcomm,mlocal_red,reuse,matredundant);
7211:   return(0);
7212: }