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;
 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;

 24: /* nasty global values for MatSetValue() */
 25: PetscInt     MatSetValue_Row = 0;
 26: PetscInt     MatSetValue_Column = 0;
 27: PetscScalar  MatSetValue_Value = 0.0;

 31: /*@
 32:    MatRealPart - Zeros out the imaginary part of the matrix

 34:    Collective on Mat

 36:    Input Parameters:
 37: .  mat - the matrix

 39:    Level: advanced


 42: .seealso: MatImaginaryPart()
 43: @*/

 45: PetscErrorCode  MatRealPart(Mat mat)
 46: {

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

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

 65:    Collective on Mat

 67:    Input Parameters:
 68: .  mat - the matrix

 70:    Level: advanced


 73: .seealso: MatRealPart()
 74: @*/

 76: PetscErrorCode  MatImaginaryPart(Mat mat)
 77: {

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

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

 98:    Not Collective

100:    Input Parameters:
101: +  mat - the matrix
102: -  row - the row to get

104:    Output Parameters:
105: +  ncols -  if not NULL, the number of nonzeros in the row
106: .  cols - if not NULL, the column numbers
107: -  vals - if not NULL, the values

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

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

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

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

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

131:    Fortran Notes:
132:    The calling sequence from Fortran is 
133: .vb
134:    MatGetRow(matrix,row,ncols,cols,values,ierr)
135:          Mat     matrix (input)
136:          integer row    (input)
137:          integer ncols  (output)
138:          integer cols(maxcols) (output)
139:          double precision (or double complex) values(maxcols) output
140: .ve
141:    where maxcols >= maximum nonzeros in any row of the matrix.


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

148:    Level: advanced

150:    Concepts: matrices^row access

152: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatGetSubMatrices(), MatGetDiagonal()
153: @*/

155: PetscErrorCode  MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
156: {
158:   PetscInt       incols;

163:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
164:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
165:   if (!mat->ops->getrow) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
166:   MatPreallocated(mat);
168:   (*mat->ops->getrow)(mat,row,&incols,(PetscInt **)cols,(PetscScalar **)vals);
169:   if (ncols) *ncols = incols;
171:   return(0);
172: }

176: /*@
177:    MatConjugate - replaces the matrix values with their complex conjugates

179:    Collective on Mat

181:    Input Parameters:
182: .  mat - the matrix

184:    Level: advanced

186: .seealso:  VecConjugate()
187: @*/
188: PetscErrorCode  MatConjugate(Mat mat)
189: {

194:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
195:   if (!mat->ops->conjugate) SETERRQ(PETSC_ERR_SUP,"Not provided for this matrix format, send email to petsc-maint@mcs.anl.gov");
196:   (*mat->ops->conjugate)(mat);
197:   return(0);
198: }

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

205:    Not Collective

207:    Input Parameters:
208: +  mat - the matrix
209: .  row - the row to get
210: .  ncols, cols - the number of nonzeros and their columns
211: -  vals - if nonzero the column values

213:    Notes: 
214:    This routine should be called after you have finished examining the entries.

216:    Fortran Notes:
217:    The calling sequence from Fortran is 
218: .vb
219:    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
220:       Mat     matrix (input)
221:       integer row    (input)
222:       integer ncols  (output)
223:       integer cols(maxcols) (output)
224:       double precision (or double complex) values(maxcols) output
225: .ve
226:    Where maxcols >= maximum nonzeros in any row of the matrix. 

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

231:    Level: advanced

233: .seealso:  MatGetRow()
234: @*/
235: PetscErrorCode  MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
236: {

242:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
243:   if (!mat->ops->restorerow) return(0);
244:   (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
245:   return(0);
246: }

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

254:    Not Collective

256:    Input Parameters:
257: +  mat - the matrix

259:    Notes:
260:    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.

262:    Level: advanced

264:    Concepts: matrices^row access

266: .seealso: MatRestoreRowRowUpperTriangular()
267: @*/

269: PetscErrorCode  MatGetRowUpperTriangular(Mat mat)
270: {

276:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
277:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
278:   if (!mat->ops->getrowuppertriangular) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
279:   MatPreallocated(mat);
280:   (*mat->ops->getrowuppertriangular)(mat);
281:   return(0);
282: }

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

289:    Not Collective

291:    Input Parameters:
292: +  mat - the matrix

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


298:    Level: advanced

300: .seealso:  MatGetRowUpperTriangular()
301: @*/
302: PetscErrorCode  MatRestoreRowUpperTriangular(Mat mat)
303: {

308:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
309:   if (!mat->ops->restorerowuppertriangular) return(0);
310:   (*mat->ops->restorerowuppertriangular)(mat);
311:   return(0);
312: }

316: /*@C
317:    MatSetOptionsPrefix - Sets the prefix used for searching for all 
318:    Mat options in the database.

320:    Collective on Mat

322:    Input Parameter:
323: +  A - the Mat context
324: -  prefix - the prefix to prepend to all option names

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

330:    Level: advanced

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

334: .seealso: MatSetFromOptions()
335: @*/
336: PetscErrorCode  MatSetOptionsPrefix(Mat A,const char prefix[])
337: {

342:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
343:   return(0);
344: }

348: /*@C
349:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all 
350:    Mat options in the database.

352:    Collective on Mat

354:    Input Parameters:
355: +  A - the Mat context
356: -  prefix - the prefix to prepend to all option names

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

362:    Level: advanced

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

366: .seealso: MatGetOptionsPrefix()
367: @*/
368: PetscErrorCode  MatAppendOptionsPrefix(Mat A,const char prefix[])
369: {
371: 
374:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
375:   return(0);
376: }

380: /*@C
381:    MatGetOptionsPrefix - Sets the prefix used for searching for all 
382:    Mat options in the database.

384:    Not Collective

386:    Input Parameter:
387: .  A - the Mat context

389:    Output Parameter:
390: .  prefix - pointer to the prefix string used

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

395:    Level: advanced

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

399: .seealso: MatAppendOptionsPrefix()
400: @*/
401: PetscErrorCode  MatGetOptionsPrefix(Mat A,const char *prefix[])
402: {

407:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
408:   return(0);
409: }

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

416:    Collective on Mat

418:    Input Parameters:
419: .  A - the Mat context

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

425:    Level: advanced

427: .keywords: Mat, setup

429: .seealso: MatCreate(), MatDestroy()
430: @*/
431: PetscErrorCode  MatSetUp(Mat A)
432: {

437:   MatSetUpPreallocation(A);
438:   MatSetFromOptions(A);
439:   return(0);
440: }

444: /*@C
445:    MatView - Visualizes a matrix object.

447:    Collective on Mat

449:    Input Parameters:
450: +  mat - the matrix
451: -  viewer - visualization context

453:   Notes:
454:   The available visualization contexts include
455: +    PETSC_VIEWER_STDOUT_SELF - standard output (default)
456: .    PETSC_VIEWER_STDOUT_WORLD - synchronized standard
457:         output where only the first processor opens
458:         the file.  All other processors send their 
459:         data to the first processor to print. 
460: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

462:    The user can open alternative visualization contexts with
463: +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
464: .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
465:          specified file; corresponding input uses MatLoad()
466: .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to 
467:          an X window display
468: -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
469:          Currently only the sequential dense and AIJ
470:          matrix types support the Socket viewer.

472:    The user can call PetscViewerSetFormat() to specify the output
473:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
474:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
475: +    PETSC_VIEWER_ASCII_DEFAULT - default, prints matrix contents
476: .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
477: .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
478: .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse 
479:          format common among all matrix types
480: .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific 
481:          format (which is in many cases the same as the default)
482: .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
483:          size and structure (not the matrix entries)
484: .    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
485:          the matrix structure

487:    Options Database Keys:
488: +  -mat_view_info - Prints info on matrix at conclusion of MatEndAssembly()
489: .  -mat_view_info_detailed - Prints more detailed info
490: .  -mat_view - Prints matrix in ASCII format
491: .  -mat_view_matlab - Prints matrix in Matlab format
492: .  -mat_view_draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
493: .  -display <name> - Sets display name (default is host)
494: .  -draw_pause <sec> - Sets number of seconds to pause after display
495: .  -mat_view_socket - Sends matrix to socket, can be accessed from Matlab (see users manual)
496: .  -viewer_socket_machine <machine>
497: .  -viewer_socket_port <port>
498: .  -mat_view_binary - save matrix to file in binary format
499: -  -viewer_binary_filename <name>
500:    Level: beginner

502:    Concepts: matrices^viewing
503:    Concepts: matrices^plotting
504:    Concepts: matrices^printing

506: .seealso: PetscViewerSetFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(), 
507:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
508: @*/
509: PetscErrorCode  MatView(Mat mat,PetscViewer viewer)
510: {
511:   PetscErrorCode    ierr;
512:   PetscInt          rows,cols;
513:   PetscTruth        iascii;
514:   const char        *cstr;
515:   PetscViewerFormat format;

520:   if (!viewer) {
521:     PetscViewerASCIIGetStdout(mat->comm,&viewer);
522:   }
525:   if (!mat->assembled) SETERRQ(PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
526:   MatPreallocated(mat);

528:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&iascii);
529:   if (iascii) {
530:     PetscViewerGetFormat(viewer,&format);
531:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
532:       if (mat->prefix) {
533:         PetscViewerASCIIPrintf(viewer,"Matrix Object:(%s)\n",mat->prefix);
534:       } else {
535:         PetscViewerASCIIPrintf(viewer,"Matrix Object:\n");
536:       }
537:       PetscViewerASCIIPushTab(viewer);
538:       MatGetType(mat,&cstr);
539:       MatGetSize(mat,&rows,&cols);
540:       PetscViewerASCIIPrintf(viewer,"type=%s, rows=%D, cols=%D\n",cstr,rows,cols);
541:       if (mat->ops->getinfo) {
542:         MatInfo info;
543:         MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
544:         PetscViewerASCIIPrintf(viewer,"total: nonzeros=%D, allocated nonzeros=%D\n",
545:                           (PetscInt)info.nz_used,(PetscInt)info.nz_allocated);
546:       }
547:     }
548:   }
549:   if (mat->ops->view) {
550:     PetscViewerASCIIPushTab(viewer);
551:     (*mat->ops->view)(mat,viewer);
552:     PetscViewerASCIIPopTab(viewer);
553:   } else if (!iascii) {
554:     SETERRQ1(PETSC_ERR_SUP,"Viewer type %s not supported",((PetscObject)viewer)->type_name);
555:   }
556:   if (iascii) {
557:     PetscViewerGetFormat(viewer,&format);
558:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
559:       PetscViewerASCIIPopTab(viewer);
560:     }
561:   }
562:   return(0);
563: }

567: /*@C
568:    MatScaleSystem - Scale a vector solution and right hand side to 
569:    match the scaling of a scaled matrix.
570:   
571:    Collective on Mat

573:    Input Parameter:
574: +  mat - the matrix
575: .  b - right hand side vector (or PETSC_NULL)
576: -  x - solution vector (or PETSC_NULL)


579:    Notes: 
580:    For AIJ, BAIJ, and BDiag matrix formats, the matrices are not 
581:    internally scaled, so this does nothing. For MPIROWBS it
582:    permutes and diagonally scales.

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

587:    Level: Developer            

589:    Concepts: matrices^scaling

591: .seealso: MatUseScaledForm(), MatUnScaleSystem()
592: @*/
593: PetscErrorCode  MatScaleSystem(Mat mat,Vec b,Vec x)
594: {

600:   MatPreallocated(mat);

604:   if (mat->ops->scalesystem) {
605:     (*mat->ops->scalesystem)(mat,b,x);
606:   }
607:   return(0);
608: }

612: /*@C
613:    MatUnScaleSystem - Unscales a vector solution and right hand side to 
614:    match the original scaling of a scaled matrix.
615:   
616:    Collective on Mat

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


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

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

632:    Level: Developer            

634: .seealso: MatUseScaledForm(), MatScaleSystem()
635: @*/
636: PetscErrorCode  MatUnScaleSystem(Mat mat,Vec b,Vec x)
637: {

643:   MatPreallocated(mat);
646:   if (mat->ops->unscalesystem) {
647:     (*mat->ops->unscalesystem)(mat,b,x);
648:   }
649:   return(0);
650: }

654: /*@C
655:    MatUseScaledForm - For matrix storage formats that scale the 
656:    matrix (for example MPIRowBS matrices are diagonally scaled on
657:    assembly) indicates matrix operations (MatMult() etc) are 
658:    applied using the scaled matrix.
659:   
660:    Collective on Mat

662:    Input Parameter:
663: +  mat - the matrix
664: -  scaled - PETSC_TRUE for applying the scaled, PETSC_FALSE for 
665:             applying the original matrix

667:    Notes: 
668:    For scaled matrix formats, applying the original, unscaled matrix
669:    will be slightly more expensive

671:    Level: Developer            

673: .seealso: MatScaleSystem(), MatUnScaleSystem()
674: @*/
675: PetscErrorCode  MatUseScaledForm(Mat mat,PetscTruth scaled)
676: {

682:   MatPreallocated(mat);
683:   if (mat->ops->usescaledform) {
684:     (*mat->ops->usescaledform)(mat,scaled);
685:   }
686:   return(0);
687: }

691: /*@
692:    MatDestroy - Frees space taken by a matrix.
693:   
694:    Collective on Mat

696:    Input Parameter:
697: .  A - the matrix

699:    Level: beginner

701: @*/
702: PetscErrorCode  MatDestroy(Mat A)
703: {
707:   if (--A->refct > 0) return(0);
708:   MatPreallocated(A);
709:   /* if memory was published with AMS then destroy it */
710:   PetscObjectDepublish(A);
711:   if (A->ops->destroy) {
712:     (*A->ops->destroy)(A);
713:   }
714:   if (A->mapping) {
715:     ISLocalToGlobalMappingDestroy(A->mapping);
716:   }
717:   if (A->bmapping) {
718:     ISLocalToGlobalMappingDestroy(A->bmapping);
719:   }
720:   PetscFree(A->rmap.range);
721:   PetscFree(A->cmap.range);
722:   if (A->spptr){PetscFree(A->spptr);}
723:   PetscHeaderDestroy(A);
724:   return(0);
725: }

729: /*@
730:    MatValid - Checks whether a matrix object is valid.

732:    Collective on Mat

734:    Input Parameter:
735: .  m - the matrix to check 

737:    Output Parameter:
738:    flg - flag indicating matrix status, either
739:    PETSC_TRUE if matrix is valid, or PETSC_FALSE otherwise.

741:    Level: developer

743:    Concepts: matrices^validity
744: @*/
745: PetscErrorCode  MatValid(Mat m,PetscTruth *flg)
746: {
749:   if (!m)                           *flg = PETSC_FALSE;
750:   else if (m->cookie != MAT_COOKIE) *flg = PETSC_FALSE;
751:   else                              *flg = PETSC_TRUE;
752:   return(0);
753: }

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

762:    Not Collective

764:    Input Parameters:
765: +  mat - the matrix
766: .  v - a logically two-dimensional array of values
767: .  m, idxm - the number of rows and their global indices 
768: .  n, idxn - the number of columns and their global indices
769: -  addv - either ADD_VALUES or INSERT_VALUES, where
770:    ADD_VALUES adds values to any existing entries, and
771:    INSERT_VALUES replaces existing entries with new values

773:    Notes:
774:    By default the values, v, are row-oriented and unsorted.
775:    See MatSetOption() for other options.

777:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES 
778:    options cannot be mixed without intervening calls to the assembly
779:    routines.

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

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

789:    Efficiency Alert:
790:    The routine MatSetValuesBlocked() may offer much better efficiency
791:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

793:    Level: beginner

795:    Concepts: matrices^putting entries in

797: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
798:           InsertMode, INSERT_VALUES, ADD_VALUES
799: @*/
800: PetscErrorCode  MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
801: {

805:   if (!m || !n) return(0); /* no values to insert */
811:   MatPreallocated(mat);
812:   if (mat->insertmode == NOT_SET_VALUES) {
813:     mat->insertmode = addv;
814:   }
815: #if defined(PETSC_USE_DEBUG)
816:   else if (mat->insertmode != addv) {
817:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
818:   }
819:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
820: #endif

822:   if (mat->assembled) {
823:     mat->was_assembled = PETSC_TRUE;
824:     mat->assembled     = PETSC_FALSE;
825:   }
827:   if (!mat->ops->setvalues) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
828:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
830:   return(0);
831: }


836: /*@ 
837:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
838:         values into a matrix

840:    Not Collective

842:    Input Parameters:
843: +  mat - the matrix
844: .  row - the (block) row to set
845: -  v - a logically two-dimensional array of values

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

850:    All the nonzeros in the row must be provided

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

854:    The row must belong to this process

856:    Level: intermediate

858:    Concepts: matrices^putting entries in

860: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
861:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
862: @*/
863: PetscErrorCode  MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
864: {

871:   MatSetValuesRow(mat, mat->mapping->indices[row],v);
872:   return(0);
873: }

877: /*@ 
878:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
879:         values into a matrix

881:    Not Collective

883:    Input Parameters:
884: +  mat - the matrix
885: .  row - the (block) row to set
886: -  v - a logically two-dimensional array of values

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

891:    All the nonzeros in the row must be provided

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

895:    The row must belong to this process

897:    Level: intermediate

899:    Concepts: matrices^putting entries in

901: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
902:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
903: @*/
904: PetscErrorCode  MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
905: {

912: #if defined(PETSC_USE_DEBUG)
913:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
914:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
915: #endif
916:   mat->insertmode = INSERT_VALUES;

918:   if (mat->assembled) {
919:     mat->was_assembled = PETSC_TRUE;
920:     mat->assembled     = PETSC_FALSE;
921:   }
923:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
924:   (*mat->ops->setvaluesrow)(mat,row,v);
926:   return(0);
927: }

931: /*@
932:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
933:      Using structured grid indexing

935:    Not Collective

937:    Input Parameters:
938: +  mat - the matrix
939: .  v - a logically two-dimensional array of values
940: .  m - number of rows being entered
941: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
942: .  n - number of columns being entered
943: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered 
944: -  addv - either ADD_VALUES or INSERT_VALUES, where
945:    ADD_VALUES adds values to any existing entries, and
946:    INSERT_VALUES replaces existing entries with new values

948:    Notes:
949:    By default the values, v, are row-oriented and unsorted.
950:    See MatSetOption() for other options.

952:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES 
953:    options cannot be mixed without intervening calls to the assembly
954:    routines.

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

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

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

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

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

972:    In Fortran idxm and idxn should be declared as
973: $     MatStencil idxm(4,m),idxn(4,n)
974:    and the values inserted using
975: $    idxm(MatStencil_i,1) = i
976: $    idxm(MatStencil_j,1) = j
977: $    idxm(MatStencil_k,1) = k
978: $    idxm(MatStencil_c,1) = c
979:    etc

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

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

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

991:    Efficiency Alert:
992:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
993:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

995:    Level: beginner

997:    Concepts: matrices^putting entries in

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

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

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

1019:   for (i=0; i<m; i++) {
1020:     for (j=0; j<3-sdim; j++) dxm++;
1021:     tmp = *dxm++ - starts[0];
1022:     for (j=0; j<dim-1; j++) {
1023:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1024:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1025:     }
1026:     if (mat->stencil.noc) dxm++;
1027:     jdxm[i] = tmp;
1028:   }
1029:   for (i=0; i<n; i++) {
1030:     for (j=0; j<3-sdim; j++) dxn++;
1031:     tmp = *dxn++ - starts[0];
1032:     for (j=0; j<dim-1; j++) {
1033:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1034:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1035:     }
1036:     if (mat->stencil.noc) dxn++;
1037:     jdxn[i] = tmp;
1038:   }
1039:   MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1040:   return(0);
1041: }

1045: /*@C 
1046:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1047:      Using structured grid indexing

1049:    Not Collective

1051:    Input Parameters:
1052: +  mat - the matrix
1053: .  v - a logically two-dimensional array of values
1054: .  m - number of rows being entered
1055: .  idxm - grid coordinates for matrix rows being entered
1056: .  n - number of columns being entered
1057: .  idxn - grid coordinates for matrix columns being entered 
1058: -  addv - either ADD_VALUES or INSERT_VALUES, where
1059:    ADD_VALUES adds values to any existing entries, and
1060:    INSERT_VALUES replaces existing entries with new values

1062:    Notes:
1063:    By default the values, v, are row-oriented and unsorted.
1064:    See MatSetOption() for other options.

1066:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES 
1067:    options cannot be mixed without intervening calls to the assembly
1068:    routines.

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

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

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

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

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

1086:    In Fortran idxm and idxn should be declared as
1087: $     MatStencil idxm(4,m),idxn(4,n)
1088:    and the values inserted using
1089: $    idxm(MatStencil_i,1) = i
1090: $    idxm(MatStencil_j,1) = j
1091: $    idxm(MatStencil_k,1) = k
1092:    etc

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

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

1102:    Level: beginner

1104:    Concepts: matrices^putting entries in

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

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

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

1126:   for (i=0; i<m; i++) {
1127:     for (j=0; j<3-sdim; j++) dxm++;
1128:     tmp = *dxm++ - starts[0];
1129:     for (j=0; j<sdim-1; j++) {
1130:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1131:       else                                      tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1132:     }
1133:     dxm++;
1134:     jdxm[i] = tmp;
1135:   }
1136:   for (i=0; i<n; i++) {
1137:     for (j=0; j<3-sdim; j++) dxn++;
1138:     tmp = *dxn++ - starts[0];
1139:     for (j=0; j<sdim-1; j++) {
1140:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
1141:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1142:     }
1143:     dxn++;
1144:     jdxn[i] = tmp;
1145:   }
1146:   MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1147:   return(0);
1148: }

1152: /*@ 
1153:    MatSetStencil - Sets the grid information for setting values into a matrix via
1154:         MatSetValuesStencil()

1156:    Not Collective

1158:    Input Parameters:
1159: +  mat - the matrix
1160: .  dim - dimension of the grid 1, 2, or 3
1161: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1162: .  starts - starting point of ghost nodes on your processor in x, y, and z direction 
1163: -  dof - number of degrees of freedom per node


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

1169:    For matrices generated with DAGetMatrix() this routine is automatically called and so not needed by the
1170:    user.
1171:    
1172:    Level: beginner

1174:    Concepts: matrices^putting entries in

1176: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1177:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1178: @*/
1179: PetscErrorCode  MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1180: {
1181:   PetscInt i;


1188:   mat->stencil.dim = dim + (dof > 1);
1189:   for (i=0; i<dim; i++) {
1190:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1191:     mat->stencil.starts[i] = starts[dim-i-1];
1192:   }
1193:   mat->stencil.dims[dim]   = dof;
1194:   mat->stencil.starts[dim] = 0;
1195:   mat->stencil.noc         = (PetscTruth)(dof == 1);
1196:   return(0);
1197: }

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

1204:    Not Collective

1206:    Input Parameters:
1207: +  mat - the matrix
1208: .  v - a logically two-dimensional array of values
1209: .  m, idxm - the number of block rows and their global block indices 
1210: .  n, idxn - the number of block columns and their global block indices
1211: -  addv - either ADD_VALUES or INSERT_VALUES, where
1212:    ADD_VALUES adds values to any existing entries, and
1213:    INSERT_VALUES replaces existing entries with new values

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

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

1223:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES 
1224:    options cannot be mixed without intervening calls to the assembly
1225:    routines.

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

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

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

1241:    Example:
1242: $   Suppose m=n=2 and block size(bs) = 2 The matrix is 
1243: $
1244: $   1  2  | 3  4
1245: $   5  6  | 7  8
1246: $   - - - | - - -
1247: $   9  10 | 11 12
1248: $   13 14 | 15 16
1249: $
1250: $   v[] should be passed in like
1251: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

1253:    Restrictions:
1254:    MatSetValuesBlocked() is currently supported only for the BAIJ and SBAIJ formats

1256:    Level: intermediate

1258:    Concepts: matrices^putting entries in blocked

1260: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1261: @*/
1262: PetscErrorCode  MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1263: {

1267:   if (!m || !n) return(0); /* no values to insert */
1273:   MatPreallocated(mat);
1274:   if (mat->insertmode == NOT_SET_VALUES) {
1275:     mat->insertmode = addv;
1276:   }
1277: #if defined(PETSC_USE_DEBUG) 
1278:   else if (mat->insertmode != addv) {
1279:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1280:   }
1281:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1282: #endif

1284:   if (mat->assembled) {
1285:     mat->was_assembled = PETSC_TRUE;
1286:     mat->assembled     = PETSC_FALSE;
1287:   }
1289:   if (!mat->ops->setvaluesblocked) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1290:   (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1292:   return(0);
1293: }

1297: /*@ 
1298:    MatGetValues - Gets a block of values from a matrix.

1300:    Not Collective; currently only returns a local block

1302:    Input Parameters:
1303: +  mat - the matrix
1304: .  v - a logically two-dimensional array for storing the values
1305: .  m, idxm - the number of rows and their global indices 
1306: -  n, idxn - the number of columns and their global indices

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

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

1316:    MatGetValues() requires that the matrix has been assembled
1317:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1318:    MatSetValues() and MatGetValues() CANNOT be made in succession
1319:    without intermediate matrix assembly.

1321:    Level: advanced

1323:    Concepts: matrices^accessing values

1325: .seealso: MatGetRow(), MatGetSubMatrices(), MatSetValues()
1326: @*/
1327: PetscErrorCode  MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1328: {

1337:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1338:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1339:   if (!mat->ops->getvalues) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1340:   MatPreallocated(mat);

1343:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1345:   return(0);
1346: }

1350: /*@
1351:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1352:    the routine MatSetValuesLocal() to allow users to insert matrix entries
1353:    using a local (per-processor) numbering.

1355:    Not Collective

1357:    Input Parameters:
1358: +  x - the matrix
1359: -  mapping - mapping created with ISLocalToGlobalMappingCreate() 
1360:              or ISLocalToGlobalMappingCreateIS()

1362:    Level: intermediate

1364:    Concepts: matrices^local to global mapping
1365:    Concepts: local to global mapping^for matrices

1367: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
1368: @*/
1369: PetscErrorCode  MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping mapping)
1370: {
1376:   if (x->mapping) {
1377:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Mapping already set for matrix");
1378:   }
1379:   MatPreallocated(x);

1381:   if (x->ops->setlocaltoglobalmapping) {
1382:     (*x->ops->setlocaltoglobalmapping)(x,mapping);
1383:   } else {
1384:     PetscObjectReference((PetscObject)mapping);
1385:     if (x->mapping) { ISLocalToGlobalMappingDestroy(x->mapping); }
1386:     x->mapping = mapping;
1387:   }
1388:   return(0);
1389: }

1393: /*@
1394:    MatSetLocalToGlobalMappingBlock - Sets a local-to-global numbering for use
1395:    by the routine MatSetValuesBlockedLocal() to allow users to insert matrix
1396:    entries using a local (per-processor) numbering.

1398:    Not Collective

1400:    Input Parameters:
1401: +  x - the matrix
1402: -  mapping - mapping created with ISLocalToGlobalMappingCreate() or
1403:              ISLocalToGlobalMappingCreateIS()

1405:    Level: intermediate

1407:    Concepts: matrices^local to global mapping blocked
1408:    Concepts: local to global mapping^for matrices, blocked

1410: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal(),
1411:            MatSetValuesBlocked(), MatSetValuesLocal()
1412: @*/
1413: PetscErrorCode  MatSetLocalToGlobalMappingBlock(Mat x,ISLocalToGlobalMapping mapping)
1414: {
1420:   if (x->bmapping) {
1421:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Mapping already set for matrix");
1422:   }
1423:   PetscObjectReference((PetscObject)mapping);
1424:   if (x->bmapping) { ISLocalToGlobalMappingDestroy(x->mapping); }
1425:   x->bmapping = mapping;
1426:   return(0);
1427: }

1431: /*@
1432:    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
1433:    using a local ordering of the nodes. 

1435:    Not Collective

1437:    Input Parameters:
1438: +  x - the matrix
1439: .  nrow, irow - number of rows and their local indices
1440: .  ncol, icol - number of columns and their local indices
1441: .  y -  a logically two-dimensional array of values
1442: -  addv - either INSERT_VALUES or ADD_VALUES, where
1443:    ADD_VALUES adds values to any existing entries, and
1444:    INSERT_VALUES replaces existing entries with new values

1446:    Notes:
1447:    Before calling MatSetValuesLocal(), the user must first set the
1448:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

1450:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES 
1451:    options cannot be mixed without intervening calls to the assembly
1452:    routines.

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

1457:    Level: intermediate

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

1461: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1462:            MatSetValueLocal()
1463: @*/
1464: PetscErrorCode  MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
1465: {
1467:   PetscInt       irowm[2048],icolm[2048];

1475:   MatPreallocated(mat);
1476:   if (mat->insertmode == NOT_SET_VALUES) {
1477:     mat->insertmode = addv;
1478:   }
1479: #if defined(PETSC_USE_DEBUG) 
1480:   else if (mat->insertmode != addv) {
1481:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1482:   }
1483:   if (!mat->ops->setvalueslocal && (nrow > 2048 || ncol > 2048)) {
1484:     SETERRQ2(PETSC_ERR_SUP,"Number column/row indices must be <= 2048: are %D %D",nrow,ncol);
1485:   }
1486:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1487: #endif

1489:   if (mat->assembled) {
1490:     mat->was_assembled = PETSC_TRUE;
1491:     mat->assembled     = PETSC_FALSE;
1492:   }
1494:   if (!mat->ops->setvalueslocal) {
1495:     ISLocalToGlobalMappingApply(mat->mapping,nrow,irow,irowm);
1496:     ISLocalToGlobalMappingApply(mat->mapping,ncol,icol,icolm);
1497:     (*mat->ops->setvalues)(mat,nrow,irowm,ncol,icolm,y,addv);
1498:   } else {
1499:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
1500:   }
1501:   mat->same_nonzero = PETSC_FALSE;
1503:   return(0);
1504: }

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

1512:    Not Collective

1514:    Input Parameters:
1515: +  x - the matrix
1516: .  nrow, irow - number of rows and their local indices
1517: .  ncol, icol - number of columns and their local indices
1518: .  y -  a logically two-dimensional array of values
1519: -  addv - either INSERT_VALUES or ADD_VALUES, where
1520:    ADD_VALUES adds values to any existing entries, and
1521:    INSERT_VALUES replaces existing entries with new values

1523:    Notes:
1524:    Before calling MatSetValuesBlockedLocal(), the user must first set the
1525:    local-to-global mapping by calling MatSetLocalToGlobalMappingBlock(),
1526:    where the mapping MUST be set for matrix blocks, not for matrix elements.

1528:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES 
1529:    options cannot be mixed without intervening calls to the assembly
1530:    routines.

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

1535:    Level: intermediate

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

1539: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesLocal(), MatSetLocalToGlobalMappingBlock(), MatSetValuesBlocked()
1540: @*/
1541: PetscErrorCode  MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
1542: {
1544:   PetscInt       irowm[2048],icolm[2048];

1552:   MatPreallocated(mat);
1553:   if (mat->insertmode == NOT_SET_VALUES) {
1554:     mat->insertmode = addv;
1555:   }
1556: #if defined(PETSC_USE_DEBUG) 
1557:   else if (mat->insertmode != addv) {
1558:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1559:   }
1560:   if (!mat->bmapping) {
1561:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Local to global never set with MatSetLocalToGlobalMappingBlock()");
1562:   }
1563:   if (nrow > 2048 || ncol > 2048) {
1564:     SETERRQ2(PETSC_ERR_SUP,"Number column/row indices must be <= 2048: are %D %D",nrow,ncol);
1565:   }
1566:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1567: #endif

1569:   if (mat->assembled) {
1570:     mat->was_assembled = PETSC_TRUE;
1571:     mat->assembled     = PETSC_FALSE;
1572:   }
1574:   ISLocalToGlobalMappingApply(mat->bmapping,nrow,irow,irowm);
1575:   ISLocalToGlobalMappingApply(mat->bmapping,ncol,icol,icolm);
1576:   (*mat->ops->setvaluesblocked)(mat,nrow,irowm,ncol,icolm,y,addv);
1578:   return(0);
1579: }

1581: /* --------------------------------------------------------*/
1584: /*@
1585:    MatMult - Computes the matrix-vector product, y = Ax.

1587:    Collective on Mat and Vec

1589:    Input Parameters:
1590: +  mat - the matrix
1591: -  x   - the vector to be multiplied

1593:    Output Parameters:
1594: .  y - the result

1596:    Notes:
1597:    The vectors x and y cannot be the same.  I.e., one cannot
1598:    call MatMult(A,y,y).

1600:    Level: beginner

1602:    Concepts: matrix-vector product

1604: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
1605: @*/
1606: PetscErrorCode  MatMult(Mat mat,Vec x,Vec y)
1607: {


1616:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1617:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1618:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1619: #ifndef PETSC_HAVE_CONSTRAINTS
1620:   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);
1621:   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);
1622:   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);
1623: #endif
1624:   MatPreallocated(mat);

1626:   if (mat->nullsp) {
1627:     MatNullSpaceRemove(mat->nullsp,x,&x);
1628:   }

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

1635:   if (mat->nullsp) {
1636:     MatNullSpaceRemove(mat->nullsp,y,PETSC_NULL);
1637:   }
1638:   PetscObjectStateIncrease((PetscObject)y);
1639:   return(0);
1640: }

1644: /*@
1645:    MatMultTranspose - Computes matrix transpose times a vector.

1647:    Collective on Mat and Vec

1649:    Input Parameters:
1650: +  mat - the matrix
1651: -  x   - the vector to be multilplied

1653:    Output Parameters:
1654: .  y - the result

1656:    Notes:
1657:    The vectors x and y cannot be the same.  I.e., one cannot
1658:    call MatMultTranspose(A,y,y).

1660:    Level: beginner

1662:    Concepts: matrix vector product^transpose

1664: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd()
1665: @*/
1666: PetscErrorCode  MatMultTranspose(Mat mat,Vec x,Vec y)
1667: {


1676:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1677:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1678:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1679: #ifndef PETSC_HAVE_CONSTRAINTS
1680:   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);
1681:   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);
1682: #endif
1683:   MatPreallocated(mat);

1685:   if (!mat->ops->multtranspose) SETERRQ(PETSC_ERR_SUP,"This matrix type does not have a multiply tranpose defined");
1687:   (*mat->ops->multtranspose)(mat,x,y);
1689:   PetscObjectStateIncrease((PetscObject)y);
1690:   return(0);
1691: }

1695: /*@
1696:     MatMultAdd -  Computes v3 = v2 + A * v1.

1698:     Collective on Mat and Vec

1700:     Input Parameters:
1701: +   mat - the matrix
1702: -   v1, v2 - the vectors

1704:     Output Parameters:
1705: .   v3 - the result

1707:     Notes:
1708:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
1709:     call MatMultAdd(A,v1,v2,v1).

1711:     Level: beginner

1713:     Concepts: matrix vector product^addition

1715: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
1716: @*/
1717: PetscErrorCode  MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
1718: {


1728:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1729:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1730:   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);
1731:   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);
1732:   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);
1733:   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);
1734:   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);
1735:   if (v1 == v3) SETERRQ(PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
1736:   MatPreallocated(mat);

1739:   (*mat->ops->multadd)(mat,v1,v2,v3);
1741:   PetscObjectStateIncrease((PetscObject)v3);
1742:   return(0);
1743: }

1747: /*@
1748:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

1750:    Collective on Mat and Vec

1752:    Input Parameters:
1753: +  mat - the matrix
1754: -  v1, v2 - the vectors

1756:    Output Parameters:
1757: .  v3 - the result

1759:    Notes:
1760:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
1761:    call MatMultTransposeAdd(A,v1,v2,v1).

1763:    Level: beginner

1765:    Concepts: matrix vector product^transpose and addition

1767: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
1768: @*/
1769: PetscErrorCode  MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
1770: {


1780:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1781:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1782:   if (!mat->ops->multtransposeadd) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1783:   if (v1 == v3) SETERRQ(PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
1784:   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);
1785:   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);
1786:   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);
1787:   MatPreallocated(mat);

1790:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
1792:   PetscObjectStateIncrease((PetscObject)v3);
1793:   return(0);
1794: }

1798: /*@
1799:    MatMultConstrained - The inner multiplication routine for a
1800:    constrained matrix P^T A P.

1802:    Collective on Mat and Vec

1804:    Input Parameters:
1805: +  mat - the matrix
1806: -  x   - the vector to be multilplied

1808:    Output Parameters:
1809: .  y - the result

1811:    Notes:
1812:    The vectors x and y cannot be the same.  I.e., one cannot
1813:    call MatMult(A,y,y).

1815:    Level: beginner

1817: .keywords: matrix, multiply, matrix-vector product, constraint
1818: .seealso: MatMult(), MatMultTrans(), MatMultAdd(), MatMultTransAdd()
1819: @*/
1820: PetscErrorCode  MatMultConstrained(Mat mat,Vec x,Vec y)
1821: {

1828:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1829:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1830:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1831:   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);
1832:   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);
1833:   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);

1836:   (*mat->ops->multconstrained)(mat,x,y);
1838:   PetscObjectStateIncrease((PetscObject)y);

1840:   return(0);
1841: }

1845: /*@
1846:    MatMultTransposeConstrained - The inner multiplication routine for a
1847:    constrained matrix P^T A^T P.

1849:    Collective on Mat and Vec

1851:    Input Parameters:
1852: +  mat - the matrix
1853: -  x   - the vector to be multilplied

1855:    Output Parameters:
1856: .  y - the result

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

1862:    Level: beginner

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

1875:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1876:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1877:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1878:   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);
1879:   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);

1882:   (*mat->ops->multtransposeconstrained)(mat,x,y);
1884:   PetscObjectStateIncrease((PetscObject)y);

1886:   return(0);
1887: }
1888: /* ------------------------------------------------------------*/
1891: /*@
1892:    MatGetInfo - Returns information about matrix storage (number of
1893:    nonzeros, memory, etc.).

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

1898:    Input Parameters:
1899: .  mat - the matrix

1901:    Output Parameters:
1902: +  flag - flag indicating the type of parameters to be returned
1903:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
1904:    MAT_GLOBAL_SUM - sum over all processors)
1905: -  info - matrix information context

1907:    Notes:
1908:    The MatInfo context contains a variety of matrix data, including
1909:    number of nonzeros allocated and used, number of mallocs during
1910:    matrix assembly, etc.  Additional information for factored matrices
1911:    is provided (such as the fill ratio, number of mallocs during
1912:    factorization, etc.).  Much of this info is printed to STDOUT
1913:    when using the runtime options 
1914: $       -info -mat_view_info

1916:    Example for C/C++ Users:
1917:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
1918:    data within the MatInfo context.  For example, 
1919: .vb
1920:       MatInfo info;
1921:       Mat     A;
1922:       double  mal, nz_a, nz_u;

1924:       MatGetInfo(A,MAT_LOCAL,&info);
1925:       mal  = info.mallocs;
1926:       nz_a = info.nz_allocated;
1927: .ve

1929:    Example for Fortran Users:
1930:    Fortran users should declare info as a double precision
1931:    array of dimension MAT_INFO_SIZE, and then extract the parameters
1932:    of interest.  See the file ${PETSC_DIR}/include/finclude/petscmat.h
1933:    a complete list of parameter names.
1934: .vb
1935:       double  precision info(MAT_INFO_SIZE)
1936:       double  precision mal, nz_a
1937:       Mat     A
1938:       integer ierr

1940:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
1941:       mal = info(MAT_INFO_MALLOCS)
1942:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
1943: .ve

1945:     Level: intermediate

1947:     Concepts: matrices^getting information on
1948:  
1949: @*/
1950: PetscErrorCode  MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
1951: {

1958:   if (!mat->ops->getinfo) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1959:   MatPreallocated(mat);
1960:   (*mat->ops->getinfo)(mat,flag,info);
1961:   return(0);
1962: }

1964: /* ----------------------------------------------------------*/
1967: /*@C  
1968:    MatILUDTFactor - Performs a drop tolerance ILU factorization.

1970:    Collective on Mat

1972:    Input Parameters:
1973: +  mat - the matrix
1974: .  row - row permutation
1975: .  col - column permutation
1976: -  info - information about the factorization to be done

1978:    Output Parameters:
1979: .  fact - the factored matrix

1981:    Level: developer

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

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

1993:     Concepts: matrices^ILUDT factorization

1995: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
1996: @*/
1997: PetscErrorCode  MatILUDTFactor(Mat mat,IS row,IS col,MatFactorInfo *info,Mat *fact)
1998: {

2008:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2009:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2010:   if (!mat->ops->iludtfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2011:   MatPreallocated(mat);
2013:   (*mat->ops->iludtfactor)(mat,row,col,info,fact);
2015:   PetscObjectStateIncrease((PetscObject)*fact);

2017:   return(0);
2018: }

2022: /*@  
2023:    MatLUFactor - Performs in-place LU factorization of matrix.

2025:    Collective on Mat

2027:    Input Parameters:
2028: +  mat - the matrix
2029: .  row - row permutation
2030: .  col - column permutation
2031: -  info - options for factorization, includes 
2032: $          fill - expected fill as ratio of original fill.
2033: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2034: $                   Run with the option -info to determine an optimal value to use

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

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

2044:    Level: developer

2046:    Concepts: matrices^LU factorization

2048: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2049:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo

2051: @*/
2052: PetscErrorCode  MatLUFactor(Mat mat,IS row,IS col,MatFactorInfo *info)
2053: {

2062:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2063:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2064:   if (!mat->ops->lufactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2065:   MatPreallocated(mat);

2068:   (*mat->ops->lufactor)(mat,row,col,info);
2070:   PetscObjectStateIncrease((PetscObject)mat);
2071:   return(0);
2072: }

2076: /*@  
2077:    MatILUFactor - Performs in-place ILU factorization of matrix.

2079:    Collective on Mat

2081:    Input Parameters:
2082: +  mat - the matrix
2083: .  row - row permutation
2084: .  col - column permutation
2085: -  info - structure containing 
2086: $      levels - number of levels of fill.
2087: $      expected fill - as ratio of original fill.
2088: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2089:                 missing diagonal entries)

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

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

2099:    Level: developer

2101:    Concepts: matrices^ILU factorization

2103: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2104: @*/
2105: PetscErrorCode  MatILUFactor(Mat mat,IS row,IS col,MatFactorInfo *info)
2106: {

2115:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"matrix must be square");
2116:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2117:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2118:   if (!mat->ops->ilufactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2119:   MatPreallocated(mat);

2122:   (*mat->ops->ilufactor)(mat,row,col,info);
2124:   PetscObjectStateIncrease((PetscObject)mat);
2125:   return(0);
2126: }

2130: /*@  
2131:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2132:    Call this routine before calling MatLUFactorNumeric().

2134:    Collective on Mat

2136:    Input Parameters:
2137: +  mat - the matrix
2138: .  row, col - row and column permutations
2139: -  info - options for factorization, includes 
2140: $          fill - expected fill as ratio of original fill.
2141: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2142: $                   Run with the option -info to determine an optimal value to use

2144:    Output Parameter:
2145: .  fact - new matrix that has been symbolically factored

2147:    Notes:
2148:    See the users manual for additional information about
2149:    choosing the fill factor for better efficiency.

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

2155:    Level: developer

2157:    Concepts: matrices^LU symbolic factorization

2159: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2160: @*/
2161: PetscErrorCode  MatLUFactorSymbolic(Mat mat,IS row,IS col,MatFactorInfo *info,Mat *fact)
2162: {

2172:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2173:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2174:   if (!mat->ops->lufactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic LU",mat->type_name);
2175:   MatPreallocated(mat);

2178:   (*mat->ops->lufactorsymbolic)(mat,row,col,info,fact);
2180:   PetscObjectStateIncrease((PetscObject)*fact);
2181:   return(0);
2182: }

2186: /*@  
2187:    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
2188:    Call this routine after first calling MatLUFactorSymbolic().

2190:    Collective on Mat

2192:    Input Parameters:
2193: +  mat - the matrix
2194: .  info - options for factorization
2195: -  fact - the matrix generated for the factor, from MatLUFactorSymbolic()

2197:    Notes:
2198:    See MatLUFactor() for in-place factorization.  See 
2199:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.  

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

2205:    Level: developer

2207:    Concepts: matrices^LU numeric factorization

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

2220:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2221:   if (mat->rmap.N != (*fact)->rmap.N || mat->cmap.N != (*fact)->cmap.N) {
2222:     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);
2223:   }
2224:   if (!(*fact)->ops->lufactornumeric) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2225:   MatPreallocated(mat);
2227:   (*(*fact)->ops->lufactornumeric)(mat,info,fact);

2230:   MatView_Private(*fact);
2231:   PetscObjectStateIncrease((PetscObject)*fact);
2232:   return(0);
2233: }

2237: /*@  
2238:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
2239:    symmetric matrix. 

2241:    Collective on Mat

2243:    Input Parameters:
2244: +  mat - the matrix
2245: .  perm - row and column permutations
2246: -  f - expected fill as ratio of original fill

2248:    Notes:
2249:    See MatLUFactor() for the nonsymmetric case.  See also
2250:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

2256:    Level: developer

2258:    Concepts: matrices^Cholesky factorization

2260: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
2261:           MatGetOrdering()

2263: @*/
2264: PetscErrorCode  MatCholeskyFactor(Mat mat,IS perm,MatFactorInfo *info)
2265: {

2273:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"Matrix must be square");
2274:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2275:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2276:   if (!mat->ops->choleskyfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2277:   MatPreallocated(mat);

2280:   (*mat->ops->choleskyfactor)(mat,perm,info);
2282:   PetscObjectStateIncrease((PetscObject)mat);
2283:   return(0);
2284: }

2288: /*@  
2289:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
2290:    of a symmetric matrix. 

2292:    Collective on Mat

2294:    Input Parameters:
2295: +  mat - the matrix
2296: .  perm - row and column permutations
2297: -  info - options for factorization, includes 
2298: $          fill - expected fill as ratio of original fill.
2299: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2300: $                   Run with the option -info to determine an optimal value to use

2302:    Output Parameter:
2303: .  fact - the factored matrix

2305:    Notes:
2306:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
2307:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

2313:    Level: developer

2315:    Concepts: matrices^Cholesky symbolic factorization

2317: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
2318:           MatGetOrdering()

2320: @*/
2321: PetscErrorCode  MatCholeskyFactorSymbolic(Mat mat,IS perm,MatFactorInfo *info,Mat *fact)
2322: {

2331:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"Matrix must be square");
2332:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2333:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2334:   if (!mat->ops->choleskyfactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2335:   MatPreallocated(mat);

2338:   (*mat->ops->choleskyfactorsymbolic)(mat,perm,info,fact);
2340:   PetscObjectStateIncrease((PetscObject)*fact);
2341:   return(0);
2342: }

2346: /*@  
2347:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
2348:    of a symmetric matrix. Call this routine after first calling
2349:    MatCholeskyFactorSymbolic().

2351:    Collective on Mat

2353:    Input Parameter:
2354: .  mat - the initial matrix
2355: .  info - options for factorization
2356: -  fact - the symbolic factor of mat

2358:    Output Parameter:
2359: .  fact - the factored matrix

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

2366:    Level: developer

2368:    Concepts: matrices^Cholesky numeric factorization

2370: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
2371: @*/
2372: PetscErrorCode  MatCholeskyFactorNumeric(Mat mat,MatFactorInfo *info,Mat *fact)
2373: {

2381:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2382:   if (!(*fact)->ops->choleskyfactornumeric) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2383:   if (mat->rmap.N != (*fact)->rmap.N || mat->cmap.N != (*fact)->cmap.N) {
2384:     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);
2385:   }
2386:   MatPreallocated(mat);

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

2392:   MatView_Private(*fact);
2393:   PetscObjectStateIncrease((PetscObject)*fact);
2394:   return(0);
2395: }

2397: /* ----------------------------------------------------------------*/
2400: /*@
2401:    MatSolve - Solves A x = b, given a factored matrix.

2403:    Collective on Mat and Vec

2405:    Input Parameters:
2406: +  mat - the factored matrix
2407: -  b - the right-hand-side vector

2409:    Output Parameter:
2410: .  x - the result vector

2412:    Notes:
2413:    The vectors b and x cannot be the same.  I.e., one cannot
2414:    call MatSolve(A,x,x).

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

2421:    Level: developer

2423:    Concepts: matrices^triangular solves

2425: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
2426: @*/
2427: PetscErrorCode  MatSolve(Mat mat,Vec b,Vec x)
2428: {

2438:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2439:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2440:   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);
2441:   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);
2442:   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);
2443:   if (!mat->rmap.N && !mat->cmap.N) return(0);
2444:   if (!mat->ops->solve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2445:   MatPreallocated(mat);

2448:   (*mat->ops->solve)(mat,b,x);
2450:   PetscObjectStateIncrease((PetscObject)x);
2451:   return(0);
2452: }

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

2459:    Collective on Mat 

2461:    Input Parameters:
2462: +  mat - the factored matrix
2463: -  b - the right-hand-side vector

2465:    Output Parameter:
2466: .  x - the result vector

2468:    Notes:
2469:    The vectors b and x cannot be the same.  I.e., one cannot
2470:    call MatMatSolve(A,x,x).

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

2477:    Level: developer

2479:    Concepts: matrices^triangular solves

2481: .seealso: MatMatSolveAdd(), MatMatSolveTranspose(), MatMatSolveTransposeAdd()
2482: @*/
2483: PetscErrorCode  MatMatSolve(Mat A,Mat B,Mat X)
2484: {

2494:   if (X == B) SETERRQ(PETSC_ERR_ARG_IDN,"X and B must be different matrices");
2495:   if (!A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2496:   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);
2497:   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);
2498:   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);
2499:   if (!A->rmap.N && !A->cmap.N) return(0);
2500:   if (!A->ops->matsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",A->type_name);
2501:   MatPreallocated(A);

2504:   (*A->ops->matsolve)(A,B,X);
2506:   PetscObjectStateIncrease((PetscObject)X);
2507:   return(0);
2508: }


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

2517:    Collective on Mat and Vec

2519:    Input Parameters:
2520: +  mat - the factored matrix
2521: -  b - the right-hand-side vector

2523:    Output Parameter:
2524: .  x - the result vector

2526:    Notes:
2527:    MatSolve() should be used for most applications, as it performs
2528:    a forward solve followed by a backward solve.

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

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

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

2543:    Level: developer

2545:    Concepts: matrices^forward solves

2547: .seealso: MatSolve(), MatBackwardSolve()
2548: @ */
2549: PetscErrorCode  MatForwardSolve(Mat mat,Vec b,Vec x)
2550: {

2560:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2561:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2562:   if (!mat->ops->forwardsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2563:   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);
2564:   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);
2565:   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);
2566:   MatPreallocated(mat);
2568:   (*mat->ops->forwardsolve)(mat,b,x);
2570:   PetscObjectStateIncrease((PetscObject)x);
2571:   return(0);
2572: }

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

2580:    Collective on Mat and Vec

2582:    Input Parameters:
2583: +  mat - the factored matrix
2584: -  b - the right-hand-side vector

2586:    Output Parameter:
2587: .  x - the result vector

2589:    Notes:
2590:    MatSolve() should be used for most applications, as it performs
2591:    a forward solve followed by a backward solve.

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

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

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

2606:    Level: developer

2608:    Concepts: matrices^backward solves

2610: .seealso: MatSolve(), MatForwardSolve()
2611: @ */
2612: PetscErrorCode  MatBackwardSolve(Mat mat,Vec b,Vec x)
2613: {

2623:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2624:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2625:   if (!mat->ops->backwardsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2626:   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);
2627:   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);
2628:   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);
2629:   MatPreallocated(mat);

2632:   (*mat->ops->backwardsolve)(mat,b,x);
2634:   PetscObjectStateIncrease((PetscObject)x);
2635:   return(0);
2636: }

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

2643:    Collective on Mat and Vec

2645:    Input Parameters:
2646: +  mat - the factored matrix
2647: .  b - the right-hand-side vector
2648: -  y - the vector to be added to 

2650:    Output Parameter:
2651: .  x - the result vector

2653:    Notes:
2654:    The vectors b and x cannot be the same.  I.e., one cannot
2655:    call MatSolveAdd(A,x,y,x).

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

2661:    Level: developer

2663:    Concepts: matrices^triangular solves

2665: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
2666: @*/
2667: PetscErrorCode  MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
2668: {
2669:   PetscScalar    one = 1.0;
2670:   Vec            tmp;

2682:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2683:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2684:   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);
2685:   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);
2686:   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);
2687:   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);
2688:   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);
2689:   MatPreallocated(mat);

2692:   if (mat->ops->solveadd)  {
2693:     (*mat->ops->solveadd)(mat,b,y,x);
2694:   } else {
2695:     /* do the solve then the add manually */
2696:     if (x != y) {
2697:       MatSolve(mat,b,x);
2698:       VecAXPY(x,one,y);
2699:     } else {
2700:       VecDuplicate(x,&tmp);
2701:       PetscLogObjectParent(mat,tmp);
2702:       VecCopy(x,tmp);
2703:       MatSolve(mat,b,x);
2704:       VecAXPY(x,one,tmp);
2705:       VecDestroy(tmp);
2706:     }
2707:   }
2709:   PetscObjectStateIncrease((PetscObject)x);
2710:   return(0);
2711: }

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

2718:    Collective on Mat and Vec

2720:    Input Parameters:
2721: +  mat - the factored matrix
2722: -  b - the right-hand-side vector

2724:    Output Parameter:
2725: .  x - the result vector

2727:    Notes:
2728:    The vectors b and x cannot be the same.  I.e., one cannot
2729:    call MatSolveTranspose(A,x,x).

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

2735:    Level: developer

2737:    Concepts: matrices^triangular solves

2739: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
2740: @*/
2741: PetscErrorCode  MatSolveTranspose(Mat mat,Vec b,Vec x)
2742: {

2752:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2753:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2754:   if (!mat->ops->solvetranspose) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s",mat->type_name);
2755:   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);
2756:   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);
2757:   MatPreallocated(mat);
2759:   (*mat->ops->solvetranspose)(mat,b,x);
2761:   PetscObjectStateIncrease((PetscObject)x);
2762:   return(0);
2763: }

2767: /*@
2768:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a 
2769:                       factored matrix. 

2771:    Collective on Mat and Vec

2773:    Input Parameters:
2774: +  mat - the factored matrix
2775: .  b - the right-hand-side vector
2776: -  y - the vector to be added to 

2778:    Output Parameter:
2779: .  x - the result vector

2781:    Notes:
2782:    The vectors b and x cannot be the same.  I.e., one cannot
2783:    call MatSolveTransposeAdd(A,x,y,x).

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

2789:    Level: developer

2791:    Concepts: matrices^triangular solves

2793: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
2794: @*/
2795: PetscErrorCode  MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
2796: {
2797:   PetscScalar    one = 1.0;
2799:   Vec            tmp;

2810:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2811:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2812:   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);
2813:   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);
2814:   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);
2815:   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);
2816:   MatPreallocated(mat);

2819:   if (mat->ops->solvetransposeadd) {
2820:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
2821:   } else {
2822:     /* do the solve then the add manually */
2823:     if (x != y) {
2824:       MatSolveTranspose(mat,b,x);
2825:       VecAXPY(x,one,y);
2826:     } else {
2827:       VecDuplicate(x,&tmp);
2828:       PetscLogObjectParent(mat,tmp);
2829:       VecCopy(x,tmp);
2830:       MatSolveTranspose(mat,b,x);
2831:       VecAXPY(x,one,tmp);
2832:       VecDestroy(tmp);
2833:     }
2834:   }
2836:   PetscObjectStateIncrease((PetscObject)x);
2837:   return(0);
2838: }
2839: /* ----------------------------------------------------------------*/

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

2846:    Collective on Mat and Vec

2848:    Input Parameters:
2849: +  mat - the matrix
2850: .  b - the right hand side
2851: .  omega - the relaxation factor
2852: .  flag - flag indicating the type of SOR (see below)
2853: .  shift -  diagonal shift
2854: -  its - the number of iterations
2855: -  lits - the number of local iterations 

2857:    Output Parameters:
2858: .  x - the solution (can contain an initial guess)

2860:    SOR Flags:
2861: .     SOR_FORWARD_SWEEP - forward SOR
2862: .     SOR_BACKWARD_SWEEP - backward SOR
2863: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
2864: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR 
2865: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR 
2866: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
2867: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies 
2868:          upper/lower triangular part of matrix to
2869:          vector (with omega)
2870: .     SOR_ZERO_INITIAL_GUESS - zero initial guess

2872:    Notes:
2873:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
2874:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
2875:    on each processor. 

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

2880:    Notes for Advanced Users:
2881:    The flags are implemented as bitwise inclusive or operations.
2882:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
2883:    to specify a zero initial guess for SSOR.

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

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

2892:    Level: developer

2894:    Concepts: matrices^relaxation
2895:    Concepts: matrices^SOR
2896:    Concepts: matrices^Gauss-Seidel

2898: @*/
2899: PetscErrorCode  MatRelax(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
2900: {

2910:   if (!mat->ops->relax && !mat->ops->pbrelax) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2911:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2912:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2913:   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);
2914:   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);
2915:   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);
2916:   MatPreallocated(mat);
2918:   if (mat->ops->relax) {
2919:     ierr =(*mat->ops->relax)(mat,b,omega,flag,shift,its,lits,x);
2920:   } else {
2921:     ierr =(*mat->ops->pbrelax)(mat,b,omega,flag,shift,its,lits,x);
2922:   }
2924:   PetscObjectStateIncrease((PetscObject)x);
2925:   return(0);
2926: }

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

2933:    Collective on Mat and Vec

2935:    See MatRelax() for usage

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

2942:    Level: developer

2944: @*/
2945: PetscErrorCode  MatPBRelax(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
2946: {

2956:   if (!mat->ops->pbrelax) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2957:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2958:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2959:   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);
2960:   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);
2961:   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);
2962:   MatPreallocated(mat);

2965:   ierr =(*mat->ops->pbrelax)(mat,b,omega,flag,shift,its,lits,x);
2967:   PetscObjectStateIncrease((PetscObject)x);
2968:   return(0);
2969: }

2973: /*
2974:       Default matrix copy routine.
2975: */
2976: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
2977: {
2978:   PetscErrorCode    ierr;
2979:   PetscInt          i,rstart,rend,nz;
2980:   const PetscInt    *cwork;
2981:   const PetscScalar *vwork;

2984:   if (B->assembled) {
2985:     MatZeroEntries(B);
2986:   }
2987:   MatGetOwnershipRange(A,&rstart,&rend);
2988:   for (i=rstart; i<rend; i++) {
2989:     MatGetRow(A,i,&nz,&cwork,&vwork);
2990:     MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
2991:     MatRestoreRow(A,i,&nz,&cwork,&vwork);
2992:   }
2993:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
2994:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
2995:   PetscObjectStateIncrease((PetscObject)B);
2996:   return(0);
2997: }

3001: /*@
3002:    MatCopy - Copys a matrix to another matrix.

3004:    Collective on Mat

3006:    Input Parameters:
3007: +  A - the matrix
3008: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

3010:    Output Parameter:
3011: .  B - where the copy is put

3013:    Notes:
3014:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the 
3015:    same nonzero pattern or the routine will crash.

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

3021:    Level: intermediate
3022:    
3023:    Concepts: matrices^copying

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

3027: @*/
3028: PetscErrorCode  MatCopy(Mat A,Mat B,MatStructure str)
3029: {

3037:   MatPreallocated(B);
3039:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3040:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3041:   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);
3042:   MatPreallocated(A);

3045:   if (A->ops->copy) {
3046:     (*A->ops->copy)(A,B,str);
3047:   } else { /* generic conversion */
3048:     MatCopy_Basic(A,B,str);
3049:   }
3050:   if (A->mapping) {
3051:     if (B->mapping) {ISLocalToGlobalMappingDestroy(B->mapping);B->mapping = 0;}
3052:     MatSetLocalToGlobalMapping(B,A->mapping);
3053:   }
3054:   if (A->bmapping) {
3055:     if (B->bmapping) {ISLocalToGlobalMappingDestroy(B->bmapping);B->bmapping = 0;}
3056:     MatSetLocalToGlobalMappingBlock(B,A->mapping);
3057:   }
3059:   PetscObjectStateIncrease((PetscObject)B);
3060:   return(0);
3061: }

3065: /*@C  
3066:    MatConvert - Converts a matrix to another matrix, either of the same
3067:    or different type.

3069:    Collective on Mat

3071:    Input Parameters:
3072: +  mat - the matrix
3073: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
3074:    same type as the original matrix.
3075: -  reuse - denotes if the destination matrix is to be created or reused.  Currently
3076:    MAT_REUSE_MATRIX is only supported for inplace conversion, otherwise use
3077:    MAT_INITIAL_MATRIX.

3079:    Output Parameter:
3080: .  M - pointer to place new matrix

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

3087:    Level: intermediate

3089:    Concepts: matrices^converting between storage formats

3091: .seealso: MatCopy(), MatDuplicate()
3092: @*/
3093: PetscErrorCode  MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
3094: {
3095:   PetscErrorCode         ierr;
3096:   PetscTruth             sametype,issame,flg;
3097:   char                   convname[256],mtype[256];
3098:   Mat                    B;

3104:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3105:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3106:   MatPreallocated(mat);

3108:   PetscOptionsGetString(PETSC_NULL,"-matconvert_type",mtype,256,&flg);
3109:   if (flg) {
3110:     newtype = mtype;
3111:   }
3112:   PetscTypeCompare((PetscObject)mat,newtype,&sametype);
3113:   PetscStrcmp(newtype,"same",&issame);
3114:   if ((reuse==MAT_REUSE_MATRIX) && (mat != *M)) {
3115:     SETERRQ(PETSC_ERR_SUP,"MAT_REUSE_MATRIX only supported for in-place conversion currently");
3116:   }
3117:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
3118:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
3119:   } else {
3120:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=PETSC_NULL;
3121:     const char     *prefix[3] = {"seq","mpi",""};
3122:     PetscInt       i;
3123:     /* 
3124:        Order of precedence:
3125:        1) See if a specialized converter is known to the current matrix.
3126:        2) See if a specialized converter is known to the desired matrix class.
3127:        3) See if a good general converter is registered for the desired class
3128:           (as of 6/27/03 only MATMPIADJ falls into this category).
3129:        4) See if a good general converter is known for the current matrix.
3130:        5) Use a really basic converter.
3131:     */
3132: 
3133:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
3134:     for (i=0; i<3; i++) {
3135:       PetscStrcpy(convname,"MatConvert_");
3136:       PetscStrcat(convname,mat->type_name);
3137:       PetscStrcat(convname,"_");
3138:       PetscStrcat(convname,prefix[i]);
3139:       PetscStrcat(convname,newtype);
3140:       PetscStrcat(convname,"_C");
3141:       PetscObjectQueryFunction((PetscObject)mat,convname,(void (**)(void))&conv);
3142:       if (conv) goto foundconv;
3143:     }

3145:     /* 2)  See if a specialized converter is known to the desired matrix class. */
3146:     MatCreate(mat->comm,&B);
3147:     MatSetSizes(B,mat->rmap.n,mat->cmap.n,mat->rmap.N,mat->cmap.N);
3148:     MatSetType(B,newtype);
3149:     for (i=0; i<3; i++) {
3150:       PetscStrcpy(convname,"MatConvert_");
3151:       PetscStrcat(convname,mat->type_name);
3152:       PetscStrcat(convname,"_");
3153:       PetscStrcat(convname,prefix[i]);
3154:       PetscStrcat(convname,newtype);
3155:       PetscStrcat(convname,"_C");
3156:       PetscObjectQueryFunction((PetscObject)B,convname,(void (**)(void))&conv);
3157:       if (conv) {
3158:         MatDestroy(B);
3159:         goto foundconv;
3160:       }
3161:     }

3163:     /* 3) See if a good general converter is registered for the desired class */
3164:     conv = B->ops->convertfrom;
3165:     MatDestroy(B);
3166:     if (conv) goto foundconv;

3168:     /* 4) See if a good general converter is known for the current matrix */
3169:     if (mat->ops->convert) {
3170:       conv = mat->ops->convert;
3171:     }
3172:     if (conv) goto foundconv;

3174:     /* 5) Use a really basic converter. */
3175:     conv = MatConvert_Basic;

3177:     foundconv:
3179:     (*conv)(mat,newtype,reuse,M);
3181:   }
3182:   B = *M;
3183:   PetscObjectStateIncrease((PetscObject)B);
3184:   return(0);
3185: }


3190: /*@
3191:    MatDuplicate - Duplicates a matrix including the non-zero structure.

3193:    Collective on Mat

3195:    Input Parameters:
3196: +  mat - the matrix
3197: -  op - either MAT_DO_NOT_COPY_VALUES or MAT_COPY_VALUES, cause it to copy nonzero
3198:         values as well or not

3200:    Output Parameter:
3201: .  M - pointer to place new matrix

3203:    Level: intermediate

3205:    Concepts: matrices^duplicating

3207: .seealso: MatCopy(), MatConvert()
3208: @*/
3209: PetscErrorCode  MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
3210: {
3212:   Mat            B;

3218:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3219:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3220:   MatPreallocated(mat);

3222:   *M  = 0;
3223:   if (!mat->ops->duplicate) {
3224:     SETERRQ(PETSC_ERR_SUP,"Not written for this matrix type");
3225:   }
3227:   (*mat->ops->duplicate)(mat,op,M);
3228:   B = *M;
3229:   if (mat->mapping) {
3230:     MatSetLocalToGlobalMapping(B,mat->mapping);
3231:   }
3232:   if (mat->bmapping) {
3233:     MatSetLocalToGlobalMappingBlock(B,mat->bmapping);
3234:   }
3235:   PetscMapCopy(mat->comm,&mat->rmap,&B->rmap);
3236:   PetscMapCopy(mat->comm,&mat->cmap,&B->cmap);
3237: 
3239:   PetscObjectStateIncrease((PetscObject)B);
3240:   return(0);
3241: }

3245: /*@ 
3246:    MatGetDiagonal - Gets the diagonal of a matrix.

3248:    Collective on Mat and Vec

3250:    Input Parameters:
3251: +  mat - the matrix
3252: -  v - the vector for storing the diagonal

3254:    Output Parameter:
3255: .  v - the diagonal of the matrix

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

3260:    Level: intermediate

3262:    Concepts: matrices^accessing diagonals

3264: .seealso: MatGetRow(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs()
3265: @*/
3266: PetscErrorCode  MatGetDiagonal(Mat mat,Vec v)
3267: {

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

3278:   (*mat->ops->getdiagonal)(mat,v);
3279:   PetscObjectStateIncrease((PetscObject)v);
3280:   return(0);
3281: }

3285: /*@ 
3286:    MatGetRowMin - Gets the minimum value (of the real part) of each
3287:         row of the matrix

3289:    Collective on Mat and Vec

3291:    Input Parameters:
3292: .  mat - the matrix

3294:    Output Parameter:
3295: +  v - the vector for storing the maximums
3296: -  idx - the indices of the column found for each row (optional)

3298:    Level: intermediate

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

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

3305:    Concepts: matrices^getting row maximums

3307: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(),
3308:           MatGetRowMax()
3309: @*/
3310: PetscErrorCode  MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
3311: {

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

3322:   (*mat->ops->getrowmin)(mat,v,idx);
3323:   PetscObjectStateIncrease((PetscObject)v);
3324:   return(0);
3325: }

3329: /*@ 
3330:    MatGetRowMax - Gets the maximum value (of the real part) of each
3331:         row of the matrix

3333:    Collective on Mat and Vec

3335:    Input Parameters:
3336: .  mat - the matrix

3338:    Output Parameter:
3339: +  v - the vector for storing the maximums
3340: -  idx - the indices of the column found for each row (optional)

3342:    Level: intermediate

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

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

3349:    Concepts: matrices^getting row maximums

3351: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(), MatGetRowMin()
3352: @*/
3353: PetscErrorCode  MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
3354: {

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

3365:   (*mat->ops->getrowmax)(mat,v,idx);
3366:   PetscObjectStateIncrease((PetscObject)v);
3367:   return(0);
3368: }

3372: /*@ 
3373:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
3374:         row of the matrix

3376:    Collective on Mat and Vec

3378:    Input Parameters:
3379: .  mat - the matrix

3381:    Output Parameter:
3382: +  v - the vector for storing the maximums
3383: -  idx - the indices of the column found for each row (optional)

3385:    Level: intermediate

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

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

3392:    Concepts: matrices^getting row maximums

3394: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
3395: @*/
3396: PetscErrorCode  MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
3397: {

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

3408:   (*mat->ops->getrowmaxabs)(mat,v,idx);
3409:   PetscObjectStateIncrease((PetscObject)v);
3410:   return(0);
3411: }

3415: /*@ 
3416:    MatGetRowSum - Gets the sum of each row of the matrix

3418:    Collective on Mat and Vec

3420:    Input Parameters:
3421: .  mat - the matrix

3423:    Output Parameter:
3424: .  v - the vector for storing the maximums

3426:    Level: intermediate

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

3430:    Concepts: matrices^getting row sums

3432: .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
3433: @*/
3434: PetscErrorCode  MatGetRowSum(Mat mat, Vec v)
3435: {
3436:   PetscInt       start, end, row;
3437:   PetscScalar   *array;

3444:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3445:   MatPreallocated(mat);
3446:   MatGetOwnershipRange(mat, &start, &end);
3447:   VecGetArray(v, &array);
3448:   for(row = start; row < end; ++row) {
3449:     PetscInt           ncols, col;
3450:     const PetscInt    *cols;
3451:     const PetscScalar *vals;

3453:     array[row - start] = 0.0;
3454:     MatGetRow(mat, row, &ncols, &cols, &vals);
3455:     for(col = 0; col < ncols; col++) {
3456:       array[row - start] += vals[col];
3457:     }
3458:     MatRestoreRow(mat, row, &ncols, &cols, &vals);
3459:   }
3460:   VecRestoreArray(v, &array);
3461:   PetscObjectStateIncrease((PetscObject) v);
3462:   return(0);
3463: }

3467: /*@C
3468:    MatTranspose - Computes an in-place or out-of-place transpose of a matrix.

3470:    Collective on Mat

3472:    Input Parameter:
3473: .  mat - the matrix to transpose

3475:    Output Parameters:
3476: .  B - the transpose 

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

3481:    Level: intermediate

3483:    Concepts: matrices^transposing

3485: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose()
3486: @*/
3487: PetscErrorCode  MatTranspose(Mat mat,Mat *B)
3488: {

3494:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3495:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3496:   if (!mat->ops->transpose) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3497:   MatPreallocated(mat);

3500:   (*mat->ops->transpose)(mat,B);
3502:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
3503:   return(0);
3504: }

3508: /*@C
3509:    MatIsTranspose - Test whether a matrix is another one's transpose, 
3510:         or its own, in which case it tests symmetry.

3512:    Collective on Mat

3514:    Input Parameter:
3515: +  A - the matrix to test
3516: -  B - the matrix to test against, this can equal the first parameter

3518:    Output Parameters:
3519: .  flg - the result

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

3526:    Level: intermediate

3528:    Concepts: matrices^transposing, matrix^symmetry

3530: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
3531: @*/
3532: PetscErrorCode  MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscTruth *flg)
3533: {
3534:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscTruth*),(*g)(Mat,Mat,PetscReal,PetscTruth*);

3540:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",(void (**)(void))&f);
3541:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",(void (**)(void))&g);
3542:   if (f && g) {
3543:     if (f==g) {
3544:       (*f)(A,B,tol,flg);
3545:     } else {
3546:       SETERRQ(PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
3547:     }
3548:   }
3549:   return(0);
3550: }

3554: /*@C
3555:    MatPermute - Creates a new matrix with rows and columns permuted from the 
3556:    original.

3558:    Collective on Mat

3560:    Input Parameters:
3561: +  mat - the matrix to permute
3562: .  row - row permutation, each processor supplies only the permutation for its rows
3563: -  col - column permutation, each processor needs the entire column permutation, that is
3564:          this is the same size as the total number of columns in the matrix

3566:    Output Parameters:
3567: .  B - the permuted matrix

3569:    Level: advanced

3571:    Concepts: matrices^permuting

3573: .seealso: MatGetOrdering()
3574: @*/
3575: PetscErrorCode  MatPermute(Mat mat,IS row,IS col,Mat *B)
3576: {

3585:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3586:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3587:   if (!mat->ops->permute) SETERRQ1(PETSC_ERR_SUP,"MatPermute not available for Mat type %s",mat->type_name);
3588:   MatPreallocated(mat);

3590:   (*mat->ops->permute)(mat,row,col,B);
3591:   PetscObjectStateIncrease((PetscObject)*B);
3592:   return(0);
3593: }

3597: /*@C
3598:   MatPermuteSparsify - Creates a new matrix with rows and columns permuted from the 
3599:   original and sparsified to the prescribed tolerance.

3601:   Collective on Mat

3603:   Input Parameters:
3604: + A    - The matrix to permute
3605: . band - The half-bandwidth of the sparsified matrix, or PETSC_DECIDE
3606: . frac - The half-bandwidth as a fraction of the total size, or 0.0
3607: . tol  - The drop tolerance
3608: . rowp - The row permutation
3609: - colp - The column permutation

3611:   Output Parameter:
3612: . B    - The permuted, sparsified matrix

3614:   Level: advanced

3616:   Note:
3617:   The default behavior (band = PETSC_DECIDE and frac = 0.0) is to
3618:   restrict the half-bandwidth of the resulting matrix to 5% of the
3619:   total matrix size.

3621: .keywords: matrix, permute, sparsify

3623: .seealso: MatGetOrdering(), MatPermute()
3624: @*/
3625: PetscErrorCode  MatPermuteSparsify(Mat A, PetscInt band, PetscReal frac, PetscReal tol, IS rowp, IS colp, Mat *B)
3626: {
3627:   IS                irowp, icolp;
3628:   PetscInt          *rows, *cols;
3629:   PetscInt          M, N, locRowStart, locRowEnd;
3630:   PetscInt          nz, newNz;
3631:   const PetscInt    *cwork;
3632:   PetscInt          *cnew;
3633:   const PetscScalar *vwork;
3634:   PetscScalar       *vnew;
3635:   PetscInt          bw, issize;
3636:   PetscInt          row, locRow, newRow, col, newCol;
3637:   PetscErrorCode    ierr;

3644:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3645:   if (A->factor)     SETERRQ(PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3646:   if (!A->ops->permutesparsify) {
3647:     MatGetSize(A, &M, &N);
3648:     MatGetOwnershipRange(A, &locRowStart, &locRowEnd);
3649:     ISGetSize(rowp, &issize);
3650:     if (issize != M) SETERRQ2(PETSC_ERR_ARG_WRONG, "Wrong size %D for row permutation, should be %D", issize, M);
3651:     ISGetSize(colp, &issize);
3652:     if (issize != N) SETERRQ2(PETSC_ERR_ARG_WRONG, "Wrong size %D for column permutation, should be %D", issize, N);
3653:     ISInvertPermutation(rowp, 0, &irowp);
3654:     ISGetIndices(irowp, &rows);
3655:     ISInvertPermutation(colp, 0, &icolp);
3656:     ISGetIndices(icolp, &cols);
3657:     PetscMalloc(N * sizeof(PetscInt),         &cnew);
3658:     PetscMalloc(N * sizeof(PetscScalar), &vnew);

3660:     /* Setup bandwidth to include */
3661:     if (band == PETSC_DECIDE) {
3662:       if (frac <= 0.0)
3663:         bw = (PetscInt) (M * 0.05);
3664:       else
3665:         bw = (PetscInt) (M * frac);
3666:     } else {
3667:       if (band <= 0) SETERRQ(PETSC_ERR_ARG_WRONG, "Bandwidth must be a positive integer");
3668:       bw = band;
3669:     }

3671:     /* Put values into new matrix */
3672:     MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, B);
3673:     for(row = locRowStart, locRow = 0; row < locRowEnd; row++, locRow++) {
3674:       MatGetRow(A, row, &nz, &cwork, &vwork);
3675:       newRow   = rows[locRow]+locRowStart;
3676:       for(col = 0, newNz = 0; col < nz; col++) {
3677:         newCol = cols[cwork[col]];
3678:         if ((newCol >= newRow - bw) && (newCol < newRow + bw) && (PetscAbsScalar(vwork[col]) >= tol)) {
3679:           cnew[newNz] = newCol;
3680:           vnew[newNz] = vwork[col];
3681:           newNz++;
3682:         }
3683:       }
3684:       MatSetValues(*B, 1, &newRow, newNz, cnew, vnew, INSERT_VALUES);
3685:       MatRestoreRow(A, row, &nz, &cwork, &vwork);
3686:     }
3687:     PetscFree(cnew);
3688:     PetscFree(vnew);
3689:     MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY);
3690:     MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY);
3691:     ISRestoreIndices(irowp, &rows);
3692:     ISRestoreIndices(icolp, &cols);
3693:     ISDestroy(irowp);
3694:     ISDestroy(icolp);
3695:   } else {
3696:     (*A->ops->permutesparsify)(A, band, frac, tol, rowp, colp, B);
3697:   }
3698:   PetscObjectStateIncrease((PetscObject)*B);
3699:   return(0);
3700: }

3704: /*@
3705:    MatEqual - Compares two matrices.

3707:    Collective on Mat

3709:    Input Parameters:
3710: +  A - the first matrix
3711: -  B - the second matrix

3713:    Output Parameter:
3714: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

3716:    Level: intermediate

3718:    Concepts: matrices^equality between
3719: @*/
3720: PetscErrorCode  MatEqual(Mat A,Mat B,PetscTruth *flg)
3721: {

3729:   MatPreallocated(B);
3732:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3733:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3734:   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);
3735:   if (!A->ops->equal) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",A->type_name);
3736:   if (!B->ops->equal) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",B->type_name);
3737:   if (A->ops->equal != B->ops->equal) SETERRQ2(PETSC_ERR_ARG_INCOMP,"A is type: %s\nB is type: %s",A->type_name,B->type_name);
3738:   MatPreallocated(A);

3740:   (*A->ops->equal)(A,B,flg);
3741:   return(0);
3742: }

3746: /*@
3747:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
3748:    matrices that are stored as vectors.  Either of the two scaling
3749:    matrices can be PETSC_NULL.

3751:    Collective on Mat

3753:    Input Parameters:
3754: +  mat - the matrix to be scaled
3755: .  l - the left scaling vector (or PETSC_NULL)
3756: -  r - the right scaling vector (or PETSC_NULL)

3758:    Notes:
3759:    MatDiagonalScale() computes A = LAR, where
3760:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)

3762:    Level: intermediate

3764:    Concepts: matrices^diagonal scaling
3765:    Concepts: diagonal scaling of matrices

3767: .seealso: MatScale()
3768: @*/
3769: PetscErrorCode  MatDiagonalScale(Mat mat,Vec l,Vec r)
3770: {

3776:   if (!mat->ops->diagonalscale) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3779:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3780:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3781:   MatPreallocated(mat);

3784:   (*mat->ops->diagonalscale)(mat,l,r);
3786:   PetscObjectStateIncrease((PetscObject)mat);
3787:   return(0);
3788: }

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

3795:     Collective on Mat

3797:     Input Parameters:
3798: +   mat - the matrix to be scaled
3799: -   a  - the scaling value

3801:     Output Parameter:
3802: .   mat - the scaled matrix

3804:     Level: intermediate

3806:     Concepts: matrices^scaling all entries

3808: .seealso: MatDiagonalScale()
3809: @*/
3810: PetscErrorCode  MatScale(Mat mat,PetscScalar a)
3811: {

3817:   if (!mat->ops->scale) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3818:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3819:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3820:   MatPreallocated(mat);

3823:   (*mat->ops->scale)(mat,a);
3825:   PetscObjectStateIncrease((PetscObject)mat);
3826:   return(0);
3827: }

3831: /*@ 
3832:    MatNorm - Calculates various norms of a matrix.

3834:    Collective on Mat

3836:    Input Parameters:
3837: +  mat - the matrix
3838: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

3840:    Output Parameters:
3841: .  nrm - the resulting norm 

3843:    Level: intermediate

3845:    Concepts: matrices^norm
3846:    Concepts: norm^of matrix
3847: @*/
3848: PetscErrorCode  MatNorm(Mat mat,NormType type,PetscReal *nrm)
3849: {


3857:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3858:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3859:   if (!mat->ops->norm) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3860:   MatPreallocated(mat);

3862:   (*mat->ops->norm)(mat,type,nrm);
3863:   return(0);
3864: }

3866: /* 
3867:      This variable is used to prevent counting of MatAssemblyBegin() that
3868:    are called from within a MatAssemblyEnd().
3869: */
3870: static PetscInt MatAssemblyEnd_InUse = 0;
3873: /*@
3874:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
3875:    be called after completing all calls to MatSetValues().

3877:    Collective on Mat

3879:    Input Parameters:
3880: +  mat - the matrix 
3881: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
3882:  
3883:    Notes: 
3884:    MatSetValues() generally caches the values.  The matrix is ready to
3885:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
3886:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
3887:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
3888:    using the matrix.

3890:    Level: beginner

3892:    Concepts: matrices^assembling

3894: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
3895: @*/
3896: PetscErrorCode  MatAssemblyBegin(Mat mat,MatAssemblyType type)
3897: {

3903:   MatPreallocated(mat);
3904:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
3905:   if (mat->assembled) {
3906:     mat->was_assembled = PETSC_TRUE;
3907:     mat->assembled     = PETSC_FALSE;
3908:   }
3909:   if (!MatAssemblyEnd_InUse) {
3911:     if (mat->ops->assemblybegin){(*mat->ops->assemblybegin)(mat,type);}
3913:   } else {
3914:     if (mat->ops->assemblybegin){(*mat->ops->assemblybegin)(mat,type);}
3915:   }
3916:   return(0);
3917: }

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

3925:    Collective on Mat

3927:    Input Parameter:
3928: .  mat - the matrix 

3930:    Output Parameter:
3931: .  assembled - PETSC_TRUE or PETSC_FALSE

3933:    Level: advanced

3935:    Concepts: matrices^assembled?

3937: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
3938: @*/
3939: PetscErrorCode  MatAssembled(Mat mat,PetscTruth *assembled)
3940: {
3945:   *assembled = mat->assembled;
3946:   return(0);
3947: }

3951: /*
3952:     Processes command line options to determine if/how a matrix
3953:   is to be viewed. Called by MatAssemblyEnd() and MatLoad().
3954: */
3955: PetscErrorCode MatView_Private(Mat mat)
3956: {
3957:   PetscErrorCode    ierr;
3958:   PetscTruth        flg1,flg2,flg3,flg4,flg6,flg7,flg8;
3959:   static PetscTruth incall = PETSC_FALSE;
3960: #if defined(PETSC_USE_SOCKET_VIEWER)
3961:   PetscTruth        flg5;
3962: #endif

3965:   if (incall) return(0);
3966:   incall = PETSC_TRUE;
3967:   PetscOptionsBegin(mat->comm,mat->prefix,"Matrix Options","Mat");
3968:     PetscOptionsName("-mat_view_info","Information on matrix size","MatView",&flg1);
3969:     PetscOptionsName("-mat_view_info_detailed","Nonzeros in the matrix","MatView",&flg2);
3970:     PetscOptionsName("-mat_view","Print matrix to stdout","MatView",&flg3);
3971:     PetscOptionsName("-mat_view_matlab","Print matrix to stdout in a format Matlab can read","MatView",&flg4);
3972: #if defined(PETSC_USE_SOCKET_VIEWER)
3973:     PetscOptionsName("-mat_view_socket","Send matrix to socket (can be read from matlab)","MatView",&flg5);
3974: #endif
3975:     PetscOptionsName("-mat_view_binary","Save matrix to file in binary format","MatView",&flg6);
3976:     PetscOptionsName("-mat_view_draw","Draw the matrix nonzero structure","MatView",&flg7);
3977:   PetscOptionsEnd();

3979:   if (flg1) {
3980:     PetscViewer viewer;

3982:     PetscViewerASCIIGetStdout(mat->comm,&viewer);
3983:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO);
3984:     MatView(mat,viewer);
3985:     PetscViewerPopFormat(viewer);
3986:   }
3987:   if (flg2) {
3988:     PetscViewer viewer;

3990:     PetscViewerASCIIGetStdout(mat->comm,&viewer);
3991:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO_DETAIL);
3992:     MatView(mat,viewer);
3993:     PetscViewerPopFormat(viewer);
3994:   }
3995:   if (flg3) {
3996:     PetscViewer viewer;

3998:     PetscViewerASCIIGetStdout(mat->comm,&viewer);
3999:     MatView(mat,viewer);
4000:   }
4001:   if (flg4) {
4002:     PetscViewer viewer;

4004:     PetscViewerASCIIGetStdout(mat->comm,&viewer);
4005:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
4006:     MatView(mat,viewer);
4007:     PetscViewerPopFormat(viewer);
4008:   }
4009: #if defined(PETSC_USE_SOCKET_VIEWER)
4010:   if (flg5) {
4011:     MatView(mat,PETSC_VIEWER_SOCKET_(mat->comm));
4012:     PetscViewerFlush(PETSC_VIEWER_SOCKET_(mat->comm));
4013:   }
4014: #endif
4015:   if (flg6) {
4016:     MatView(mat,PETSC_VIEWER_BINARY_(mat->comm));
4017:     PetscViewerFlush(PETSC_VIEWER_BINARY_(mat->comm));
4018:   }
4019:   if (flg7) {
4020:     PetscOptionsHasName(mat->prefix,"-mat_view_contour",&flg8);
4021:     if (flg8) {
4022:       PetscViewerPushFormat(PETSC_VIEWER_DRAW_(mat->comm),PETSC_VIEWER_DRAW_CONTOUR);
4023:     }
4024:     MatView(mat,PETSC_VIEWER_DRAW_(mat->comm));
4025:     PetscViewerFlush(PETSC_VIEWER_DRAW_(mat->comm));
4026:     if (flg8) {
4027:       PetscViewerPopFormat(PETSC_VIEWER_DRAW_(mat->comm));
4028:     }
4029:   }
4030:   incall = PETSC_FALSE;
4031:   return(0);
4032: }

4036: /*@
4037:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
4038:    be called after MatAssemblyBegin().

4040:    Collective on Mat

4042:    Input Parameters:
4043: +  mat - the matrix 
4044: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

4046:    Options Database Keys:
4047: +  -mat_view_info - Prints info on matrix at conclusion of MatEndAssembly()
4048: .  -mat_view_info_detailed - Prints more detailed info
4049: .  -mat_view - Prints matrix in ASCII format
4050: .  -mat_view_matlab - Prints matrix in Matlab format
4051: .  -mat_view_draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
4052: .  -display <name> - Sets display name (default is host)
4053: .  -draw_pause <sec> - Sets number of seconds to pause after display
4054: .  -mat_view_socket - Sends matrix to socket, can be accessed from Matlab (see users manual)
4055: .  -viewer_socket_machine <machine>
4056: .  -viewer_socket_port <port>
4057: .  -mat_view_binary - save matrix to file in binary format
4058: -  -viewer_binary_filename <name>

4060:    Notes: 
4061:    MatSetValues() generally caches the values.  The matrix is ready to
4062:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
4063:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
4064:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
4065:    using the matrix.

4067:    Level: beginner

4069: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), MatView(), MatAssembled(), PetscViewerSocketOpen()
4070: @*/
4071: PetscErrorCode  MatAssemblyEnd(Mat mat,MatAssemblyType type)
4072: {
4073:   PetscErrorCode  ierr;
4074:   static PetscInt inassm = 0;
4075:   PetscTruth      flg;


4081:   inassm++;
4082:   MatAssemblyEnd_InUse++;
4083:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
4085:     if (mat->ops->assemblyend) {
4086:       (*mat->ops->assemblyend)(mat,type);
4087:     }
4089:   } else {
4090:     if (mat->ops->assemblyend) {
4091:       (*mat->ops->assemblyend)(mat,type);
4092:     }
4093:   }

4095:   /* Flush assembly is not a true assembly */
4096:   if (type != MAT_FLUSH_ASSEMBLY) {
4097:     mat->assembled  = PETSC_TRUE; mat->num_ass++;
4098:   }
4099:   mat->insertmode = NOT_SET_VALUES;
4100:   MatAssemblyEnd_InUse--;
4101:   PetscObjectStateIncrease((PetscObject)mat);
4102:   if (!mat->symmetric_eternal) {
4103:     mat->symmetric_set              = PETSC_FALSE;
4104:     mat->hermitian_set              = PETSC_FALSE;
4105:     mat->structurally_symmetric_set = PETSC_FALSE;
4106:   }
4107:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
4108:     MatView_Private(mat);
4109:     PetscOptionsHasName(mat->prefix,"-mat_is_symmetric",&flg);
4110:     if (flg) {
4111:       PetscReal tol = 0.0;
4112:       PetscOptionsGetReal(mat->prefix,"-mat_is_symmetric",&tol,PETSC_NULL);
4113:       MatIsSymmetric(mat,tol,&flg);
4114:       if (flg) {
4115:         PetscPrintf(mat->comm,"Matrix is symmetric (tolerance %G)\n",tol);
4116:       } else {
4117:         PetscPrintf(mat->comm,"Matrix is not symmetric (tolerance %G)\n",tol);
4118:       }
4119:     }
4120:   }
4121:   inassm--;
4122:   return(0);
4123: }


4128: /*@
4129:    MatCompress - Tries to store the matrix in as little space as 
4130:    possible.  May fail if memory is already fully used, since it
4131:    tries to allocate new space.

4133:    Collective on Mat

4135:    Input Parameters:
4136: .  mat - the matrix 

4138:    Level: advanced

4140: @*/
4141: PetscErrorCode  MatCompress(Mat mat)
4142: {

4148:   MatPreallocated(mat);
4149:   if (mat->ops->compress) {(*mat->ops->compress)(mat);}
4150:   return(0);
4151: }

4155: /*@
4156:    MatSetOption - Sets a parameter option for a matrix. Some options
4157:    may be specific to certain storage formats.  Some options
4158:    determine how values will be inserted (or added). Sorted, 
4159:    row-oriented input will generally assemble the fastest. The default
4160:    is row-oriented, nonsorted input. 

4162:    Collective on Mat

4164:    Input Parameters:
4165: +  mat - the matrix 
4166: -  option - the option, one of those listed below (and possibly others),
4167:              e.g., MAT_ROWS_SORTED, MAT_NEW_NONZERO_LOCATION_ERR

4169:    Options Describing Matrix Structure:
4170: +    MAT_SYMMETRIC - symmetric in terms of both structure and value
4171: .    MAT_HERMITIAN - transpose is the complex conjugation
4172: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
4173: .    MAT_NOT_SYMMETRIC - not symmetric in value
4174: .    MAT_NOT_HERMITIAN - transpose is not the complex conjugation
4175: .    MAT_NOT_STRUCTURALLY_SYMMETRIC - not symmetric nonzero structure
4176: .    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
4177:                             you set to be kept with all future use of the matrix
4178:                             including after MatAssemblyBegin/End() which could
4179:                             potentially change the symmetry structure, i.e. you 
4180:                             KNOW the matrix will ALWAYS have the property you set.
4181: -    MAT_NOT_SYMMETRY_ETERNAL - if MatAssemblyBegin/End() is called then the 
4182:                                 flags you set will be dropped (in case potentially
4183:                                 the symmetry etc was lost).

4185:    Options For Use with MatSetValues():
4186:    Insert a logically dense subblock, which can be
4187: +    MAT_ROW_ORIENTED - row-oriented (default)
4188: .    MAT_COLUMN_ORIENTED - column-oriented
4189: .    MAT_ROWS_SORTED - sorted by row
4190: .    MAT_ROWS_UNSORTED - not sorted by row (default)
4191: .    MAT_COLUMNS_SORTED - sorted by column
4192: -    MAT_COLUMNS_UNSORTED - not sorted by column (default)

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

4198:    When (re)assembling a matrix, we can restrict the input for
4199:    efficiency/debugging purposes.  These options include
4200: +    MAT_NO_NEW_NONZERO_LOCATIONS - additional insertions will not be
4201:         allowed if they generate a new nonzero
4202: .    MAT_YES_NEW_NONZERO_LOCATIONS - additional insertions will be allowed
4203: .    MAT_NO_NEW_DIAGONALS - additional insertions will not be allowed if
4204:          they generate a nonzero in a new diagonal (for block diagonal format only)
4205: .    MAT_YES_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
4206: .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
4207: .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
4208: -    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly

4210:    Notes:
4211:    Some options are relevant only for particular matrix types and
4212:    are thus ignored by others.  Other options are not supported by
4213:    certain matrix types and will generate an error message if set.

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

4219:    MAT_NO_NEW_NONZERO_LOCATIONS indicates that any add or insertion 
4220:    that would generate a new entry in the nonzero structure is instead
4221:    ignored.  Thus, if memory has not alredy been allocated for this particular 
4222:    data, then the insertion is ignored. For dense matrices, in which
4223:    the entire array is allocated, no entries are ever ignored. 
4224:    Set after the first MatAssemblyEnd()

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

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

4238:    MAT_IGNORE_OFF_PROC_ENTRIES indicates entries destined for 
4239:    other processors should be dropped, rather than stashed.
4240:    This is useful if you know that the "owning" processor is also 
4241:    always generating the correct matrix entries, so that PETSc need
4242:    not transfer duplicate entries generated on another processor.
4243:    
4244:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
4245:    searches during matrix assembly. When this flag is set, the hash table
4246:    is created during the first Matrix Assembly. This hash table is
4247:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
4248:    to improve the searching of indices. MAT_NO_NEW_NONZERO_LOCATIONS flag 
4249:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
4250:    supported by MATMPIBAIJ format only.

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

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

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

4261:    MAT_DO_NOT_USE_INODES - indicates not using inode version of the code - works
4262:    with AIJ and ROWBS matrix types (database option "-mat_no_inode")

4264:    Level: intermediate

4266:    Concepts: matrices^setting options

4268: @*/
4269: PetscErrorCode  MatSetOption(Mat mat,MatOption op)
4270: {

4276:   MatPreallocated(mat);
4277:   switch (op) {
4278:   case MAT_SYMMETRIC:
4279:     mat->symmetric                  = PETSC_TRUE;
4280:     mat->structurally_symmetric     = PETSC_TRUE;
4281:     mat->symmetric_set              = PETSC_TRUE;
4282:     mat->structurally_symmetric_set = PETSC_TRUE;
4283:     break;
4284:   case MAT_HERMITIAN:
4285:     mat->hermitian                  = PETSC_TRUE;
4286:     mat->structurally_symmetric     = PETSC_TRUE;
4287:     mat->hermitian_set              = PETSC_TRUE;
4288:     mat->structurally_symmetric_set = PETSC_TRUE;
4289:     break;
4290:   case MAT_STRUCTURALLY_SYMMETRIC:
4291:     mat->structurally_symmetric     = PETSC_TRUE;
4292:     mat->structurally_symmetric_set = PETSC_TRUE;
4293:     break;
4294:   case MAT_NOT_SYMMETRIC:
4295:     mat->symmetric                  = PETSC_FALSE;
4296:     mat->symmetric_set              = PETSC_TRUE;
4297:     break;
4298:   case MAT_NOT_HERMITIAN:
4299:     mat->hermitian                  = PETSC_FALSE;
4300:     mat->hermitian_set              = PETSC_TRUE;
4301:     break;
4302:   case MAT_NOT_STRUCTURALLY_SYMMETRIC:
4303:     mat->structurally_symmetric     = PETSC_FALSE;
4304:     mat->structurally_symmetric_set = PETSC_TRUE;
4305:     break;
4306:   case MAT_SYMMETRY_ETERNAL:
4307:     mat->symmetric_eternal          = PETSC_TRUE;
4308:     break;
4309:   case MAT_NOT_SYMMETRY_ETERNAL:
4310:     mat->symmetric_eternal          = PETSC_FALSE;
4311:     break;
4312:   default:
4313:     break;
4314:   }
4315:   if (mat->ops->setoption) {
4316:     (*mat->ops->setoption)(mat,op);
4317:   }
4318:   return(0);
4319: }

4323: /*@
4324:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
4325:    this routine retains the old nonzero structure.

4327:    Collective on Mat

4329:    Input Parameters:
4330: .  mat - the matrix 

4332:    Level: intermediate

4334:    Concepts: matrices^zeroing

4336: .seealso: MatZeroRows()
4337: @*/
4338: PetscErrorCode  MatZeroEntries(Mat mat)
4339: {

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

4351:   (*mat->ops->zeroentries)(mat);
4353:   PetscObjectStateIncrease((PetscObject)mat);
4354:   return(0);
4355: }

4359: /*@C
4360:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
4361:    of a set of rows of a matrix.

4363:    Collective on Mat

4365:    Input Parameters:
4366: +  mat - the matrix
4367: .  numRows - the number of rows to remove
4368: .  rows - the global row indices
4369: -  diag - value put in all diagonals of eliminated rows

4371:    Notes:
4372:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
4373:    but does not release memory.  For the dense and block diagonal
4374:    formats this does not alter the nonzero structure.

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

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

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

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

4391:    Level: intermediate

4393:    Concepts: matrices^zeroing rows

4395: .seealso: MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
4396: @*/
4397: PetscErrorCode  MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag)
4398: {

4405:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4406:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4407:   if (!mat->ops->zerorows) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4408:   MatPreallocated(mat);

4410:   (*mat->ops->zerorows)(mat,numRows,rows,diag);
4411:   MatView_Private(mat);
4412:   PetscObjectStateIncrease((PetscObject)mat);
4413:   return(0);
4414: }

4418: /*@C
4419:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
4420:    of a set of rows of a matrix.

4422:    Collective on Mat

4424:    Input Parameters:
4425: +  mat - the matrix
4426: .  is - index set of rows to remove
4427: -  diag - value put in all diagonals of eliminated rows

4429:    Notes:
4430:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
4431:    but does not release memory.  For the dense and block diagonal
4432:    formats this does not alter the nonzero structure.

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

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

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

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

4449:    Level: intermediate

4451:    Concepts: matrices^zeroing rows

4453: .seealso: MatZeroRows(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
4454: @*/
4455: PetscErrorCode  MatZeroRowsIS(Mat mat,IS is,PetscScalar diag)
4456: {
4457:   PetscInt       numRows;
4458:   PetscInt       *rows;

4465:   ISGetLocalSize(is,&numRows);
4466:   ISGetIndices(is,&rows);
4467:   MatZeroRows(mat,numRows,rows,diag);
4468:   ISRestoreIndices(is,&rows);
4469:   return(0);
4470: }

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

4478:    Collective on Mat

4480:    Input Parameters:
4481: +  mat - the matrix
4482: .  numRows - the number of rows to remove
4483: .  rows - the global row indices
4484: -  diag - value put in all diagonals of eliminated rows

4486:    Notes:
4487:    Before calling MatZeroRowsLocal(), the user must first set the
4488:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

4490:    For the AIJ matrix formats this removes the old nonzero structure,
4491:    but does not release memory.  For the dense and block diagonal
4492:    formats this does not alter the nonzero structure.

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

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

4502:    Level: intermediate

4504:    Concepts: matrices^zeroing

4506: .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
4507: @*/
4508: PetscErrorCode  MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag)
4509: {

4516:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4517:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4518:   MatPreallocated(mat);

4520:   if (mat->ops->zerorowslocal) {
4521:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag);
4522:   } else {
4523:     IS is, newis;
4524:     PetscInt *newRows;

4526:     if (!mat->mapping) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
4527:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,&is);
4528:     ISLocalToGlobalMappingApplyIS(mat->mapping,is,&newis);
4529:     ISGetIndices(newis,&newRows);
4530:     (*mat->ops->zerorows)(mat,numRows,newRows,diag);
4531:     ISRestoreIndices(newis,&newRows);
4532:     ISDestroy(newis);
4533:     ISDestroy(is);
4534:   }
4535:   PetscObjectStateIncrease((PetscObject)mat);
4536:   return(0);
4537: }

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

4545:    Collective on Mat

4547:    Input Parameters:
4548: +  mat - the matrix
4549: .  is - index set of rows to remove
4550: -  diag - value put in all diagonals of eliminated rows

4552:    Notes:
4553:    Before calling MatZeroRowsLocalIS(), 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) 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(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
4573: @*/
4574: PetscErrorCode  MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag)
4575: {
4577:   PetscInt       numRows;
4578:   PetscInt       *rows;

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

4588:   ISGetLocalSize(is,&numRows);
4589:   ISGetIndices(is,&rows);
4590:   MatZeroRowsLocal(mat,numRows,rows,diag);
4591:   ISRestoreIndices(is,&rows);
4592:   return(0);
4593: }

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

4600:    Not Collective

4602:    Input Parameter:
4603: .  mat - the matrix

4605:    Output Parameters:
4606: +  m - the number of global rows
4607: -  n - the number of global columns

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

4611:    Level: beginner

4613:    Concepts: matrices^size

4615: .seealso: MatGetLocalSize()
4616: @*/
4617: PetscErrorCode  MatGetSize(Mat mat,PetscInt *m,PetscInt* n)
4618: {
4621:   if (m) *m = mat->rmap.N;
4622:   if (n) *n = mat->cmap.N;
4623:   return(0);
4624: }

4628: /*@
4629:    MatGetLocalSize - Returns the number of rows and columns in a matrix
4630:    stored locally.  This information may be implementation dependent, so
4631:    use with care.

4633:    Not Collective

4635:    Input Parameters:
4636: .  mat - the matrix

4638:    Output Parameters:
4639: +  m - the number of local rows
4640: -  n - the number of local columns

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

4644:    Level: beginner

4646:    Concepts: matrices^local size

4648: .seealso: MatGetSize()
4649: @*/
4650: PetscErrorCode  MatGetLocalSize(Mat mat,PetscInt *m,PetscInt* n)
4651: {
4656:   if (m) *m = mat->rmap.n;
4657:   if (n) *n = mat->cmap.n;
4658:   return(0);
4659: }


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

4670:    Not Collective

4672:    Input Parameters:
4673: .  mat - the matrix

4675:    Output Parameters:
4676: +  m - the global index of the first local row
4677: -  n - one more than the global index of the last local row

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

4681:    Level: beginner

4683:    Concepts: matrices^row ownership

4685: .seealso:   MatGetOwnershipRanges()

4687: @*/
4688: PetscErrorCode  MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt* n)
4689: {

4697:   MatPreallocated(mat);
4698:   if (m) *m = mat->rmap.rstart;
4699:   if (n) *n = mat->rmap.rend;
4700:   return(0);
4701: }

4705: /*@C
4706:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
4707:    each process

4709:    Not Collective

4711:    Input Parameters:
4712: .  mat - the matrix

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

4717:    Level: beginner

4719:    Concepts: matrices^row ownership

4721: .seealso:   MatGetOwnershipRange()

4723: @*/
4724: PetscErrorCode  MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
4725: {

4731:   PetscMapGetGlobalRange(&mat->rmap,ranges);
4732:   return(0);
4733: }

4737: /*@  
4738:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
4739:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric() 
4740:    to complete the factorization.

4742:    Collective on Mat

4744:    Input Parameters:
4745: +  mat - the matrix
4746: .  row - row permutation
4747: .  column - column permutation
4748: -  info - structure containing 
4749: $      levels - number of levels of fill.
4750: $      expected fill - as ratio of original fill.
4751: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
4752:                 missing diagonal entries)

4754:    Output Parameters:
4755: .  fact - new matrix that has been symbolically factored

4757:    Notes:
4758:    See the users manual for additional information about
4759:    choosing the fill factor for better efficiency.

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

4765:    Level: developer

4767:   Concepts: matrices^symbolic LU factorization
4768:   Concepts: matrices^factorization
4769:   Concepts: LU^symbolic factorization

4771: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
4772:           MatGetOrdering(), MatFactorInfo

4774: @*/
4775: PetscErrorCode  MatILUFactorSymbolic(Mat mat,IS row,IS col,MatFactorInfo *info,Mat *fact)
4776: {

4786:   if (info->levels < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
4787:   if (info->fill < 1.0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %G",info->fill);
4788:   if (!mat->ops->ilufactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic ILU",mat->type_name);
4789:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4790:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4791:   MatPreallocated(mat);

4794:   (*mat->ops->ilufactorsymbolic)(mat,row,col,info,fact);
4796:   return(0);
4797: }

4801: /*@  
4802:    MatICCFactorSymbolic - Performs symbolic incomplete
4803:    Cholesky factorization for a symmetric matrix.  Use 
4804:    MatCholeskyFactorNumeric() to complete the factorization.

4806:    Collective on Mat

4808:    Input Parameters:
4809: +  mat - the matrix
4810: .  perm - row and column permutation
4811: -  info - structure containing 
4812: $      levels - number of levels of fill.
4813: $      expected fill - as ratio of original fill.

4815:    Output Parameter:
4816: .  fact - the factored matrix

4818:    Notes:
4819:    Most users should employ the KSP interface for linear solvers
4820:    instead of working directly with matrix algebra routines such as this.
4821:    See, e.g., KSPCreate().

4823:    Level: developer

4825:   Concepts: matrices^symbolic incomplete Cholesky factorization
4826:   Concepts: matrices^factorization
4827:   Concepts: Cholsky^symbolic factorization

4829: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
4830: @*/
4831: PetscErrorCode  MatICCFactorSymbolic(Mat mat,IS perm,MatFactorInfo *info,Mat *fact)
4832: {

4841:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4842:   if (info->levels < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
4843:   if (info->fill < 1.0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %G",info->fill);
4844:   if (!mat->ops->iccfactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic ICC",mat->type_name);
4845:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4846:   MatPreallocated(mat);

4849:   (*mat->ops->iccfactorsymbolic)(mat,perm,info,fact);
4851:   return(0);
4852: }

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

4862:    Not Collective

4864:    Input Parameter:
4865: .  mat - the matrix

4867:    Output Parameter:
4868: .  v - the location of the values


4871:    Fortran Note:
4872:    This routine is used differently from Fortran, e.g.,
4873: .vb
4874:         Mat         mat
4875:         PetscScalar mat_array(1)
4876:         PetscOffset i_mat
4877:         PetscErrorCode ierr
4878:         call MatGetArray(mat,mat_array,i_mat,ierr)

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

4884:         [... other code ...]
4885:         call MatRestoreArray(mat,mat_array,i_mat,ierr)
4886: .ve

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

4891:    Level: advanced

4893:    Concepts: matrices^access array

4895: .seealso: MatRestoreArray(), MatGetArrayF90(), MatGetRowIJ()
4896: @*/
4897: PetscErrorCode  MatGetArray(Mat mat,PetscScalar *v[])
4898: {

4905:   if (!mat->ops->getarray) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4906:   MatPreallocated(mat);
4907:   (*mat->ops->getarray)(mat,v);
4908:   CHKMEMQ;
4909:   return(0);
4910: }

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

4917:    Not Collective

4919:    Input Parameter:
4920: +  mat - the matrix
4921: -  v - the location of the values

4923:    Fortran Note:
4924:    This routine is used differently from Fortran, e.g.,
4925: .vb
4926:         Mat         mat
4927:         PetscScalar mat_array(1)
4928:         PetscOffset i_mat
4929:         PetscErrorCode ierr
4930:         call MatGetArray(mat,mat_array,i_mat,ierr)

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

4936:         [... other code ...]
4937:         call MatRestoreArray(mat,mat_array,i_mat,ierr)
4938: .ve

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

4943:    Level: advanced

4945: .seealso: MatGetArray(), MatRestoreArrayF90()
4946: @*/
4947: PetscErrorCode  MatRestoreArray(Mat mat,PetscScalar *v[])
4948: {

4955: #if defined(PETSC_USE_DEBUG)
4956:   CHKMEMQ;
4957: #endif
4958:   if (!mat->ops->restorearray) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4959:   (*mat->ops->restorearray)(mat,v);
4960:   PetscObjectStateIncrease((PetscObject)mat);
4961:   return(0);
4962: }

4966: /*@C
4967:    MatGetSubMatrices - Extracts several submatrices from a matrix. If submat
4968:    points to an array of valid matrices, they may be reused to store the new
4969:    submatrices.

4971:    Collective on Mat

4973:    Input Parameters:
4974: +  mat - the matrix
4975: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
4976: .  irow, icol - index sets of rows and columns to extract
4977: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4979:    Output Parameter:
4980: .  submat - the array of submatrices

4982:    Notes:
4983:    MatGetSubMatrices() can extract only sequential submatrices
4984:    (from both sequential and parallel matrices). Use MatGetSubMatrix()
4985:    to extract a parallel submatrix.

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

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

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

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

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

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

5009:    Level: advanced

5011:    Concepts: matrices^accessing submatrices
5012:    Concepts: submatrices

5014: .seealso: MatDestroyMatrices(), MatGetSubMatrix(), MatGetRow(), MatGetDiagonal()
5015: @*/
5016: PetscErrorCode  MatGetSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
5017: {
5019:   PetscInt        i;
5020:   PetscTruth      eq;

5025:   if (n) {
5030:   }
5032:   if (n && scall == MAT_REUSE_MATRIX) {
5035:   }
5036:   if (!mat->ops->getsubmatrices) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
5037:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5038:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5039:   MatPreallocated(mat);

5042:   (*mat->ops->getsubmatrices)(mat,n,irow,icol,scall,submat);
5044:   for (i=0; i<n; i++) {
5045:     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
5046:       ISEqual(irow[i],icol[i],&eq);
5047:       if (eq) {
5048:         if (mat->symmetric){
5049:           MatSetOption((*submat)[i],MAT_SYMMETRIC);
5050:         } else if (mat->hermitian) {
5051:           MatSetOption((*submat)[i],MAT_HERMITIAN);
5052:         } else if (mat->structurally_symmetric) {
5053:           MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC);
5054:         }
5055:       }
5056:     }
5057:   }
5058:   return(0);
5059: }

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

5066:    Collective on Mat

5068:    Input Parameters:
5069: +  n - the number of local matrices
5070: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
5071:                        sequence of MatGetSubMatrices())

5073:    Level: advanced

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

5077: .seealso: MatGetSubMatrices()
5078: @*/
5079: PetscErrorCode  MatDestroyMatrices(PetscInt n,Mat *mat[])
5080: {
5082:   PetscInt       i;

5085:   if (n < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
5087:   for (i=0; i<n; i++) {
5088:     MatDestroy((*mat)[i]);
5089:   }
5090:   /* memory is allocated even if n = 0 */
5091:   PetscFree(*mat);
5092:   return(0);
5093: }

5097: /*@
5098:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
5099:    replaces the index sets by larger ones that represent submatrices with
5100:    additional overlap.

5102:    Collective on Mat

5104:    Input Parameters:
5105: +  mat - the matrix
5106: .  n   - the number of index sets
5107: .  is  - the array of index sets (these index sets will changed during the call)
5108: -  ov  - the additional overlap requested

5110:    Level: developer

5112:    Concepts: overlap
5113:    Concepts: ASM^computing overlap

5115: .seealso: MatGetSubMatrices()
5116: @*/
5117: PetscErrorCode  MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
5118: {

5124:   if (n < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
5125:   if (n) {
5128:   }
5129:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5130:   if (mat->factor)     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5131:   MatPreallocated(mat);

5133:   if (!ov) return(0);
5134:   if (!mat->ops->increaseoverlap) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
5136:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
5138:   return(0);
5139: }

5143: /*@
5144:    MatGetBlockSize - Returns the matrix block size; useful especially for the
5145:    block row and block diagonal formats.
5146:    
5147:    Not Collective

5149:    Input Parameter:
5150: .  mat - the matrix

5152:    Output Parameter:
5153: .  bs - block size

5155:    Notes:
5156:    Block diagonal formats are MATSEQBDIAG, MATMPIBDIAG.
5157:    Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ

5159:    Level: intermediate

5161:    Concepts: matrices^block size

5163: .seealso: MatCreateSeqBAIJ(), MatCreateMPIBAIJ(), MatCreateSeqBDiag(), MatCreateMPIBDiag()
5164: @*/
5165: PetscErrorCode  MatGetBlockSize(Mat mat,PetscInt *bs)
5166: {

5173:   MatPreallocated(mat);
5174:   *bs = mat->rmap.bs;
5175:   return(0);
5176: }

5180: /*@
5181:    MatSetBlockSize - Sets the matrix block size; for many matrix types you 
5182:      cannot use this and MUST set the blocksize when you preallocate the matrix
5183:    
5184:    Not Collective

5186:    Input Parameters:
5187: +  mat - the matrix
5188: -  bs - block size

5190:    Notes:
5191:      Only works for shell and AIJ matrices

5193:    Level: intermediate

5195:    Concepts: matrices^block size

5197: .seealso: MatCreateSeqBAIJ(), MatCreateMPIBAIJ(), MatCreateSeqBDiag(), MatCreateMPIBDiag(), MatGetBlockSize()
5198: @*/
5199: PetscErrorCode  MatSetBlockSize(Mat mat,PetscInt bs)
5200: {

5206:   MatPreallocated(mat);
5207:   if (mat->ops->setblocksize) {
5208:     mat->rmap.bs = bs;
5209:     (*mat->ops->setblocksize)(mat,bs);
5210:   } else {
5211:     SETERRQ1(PETSC_ERR_ARG_INCOMP,"Cannot set the blocksize for matrix type %s",mat->type_name);
5212:   }
5213:   return(0);
5214: }

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

5221:    Collective on Mat

5223:     Input Parameters:
5224: +   mat - the matrix
5225: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
5226: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5227:                 symmetrized
5228: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5229:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5230:                  nonzero structure which is different than the full nonzero structure]

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

5239:     Level: developer

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

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

5245: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatGetArray()
5246: @*/
5247: PetscErrorCode  MatGetRowIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5248: {

5258:   MatPreallocated(mat);
5259:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
5260:   else {
5261:     *done = PETSC_TRUE;
5263:     (*mat->ops->getrowij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5265:   }
5266:   return(0);
5267: }

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

5274:     Collective on Mat

5276:     Input Parameters:
5277: +   mat - the matrix
5278: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
5279: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5280:                 symmetrized
5281: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5282:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5283:                  nonzero structure which is different than the full nonzero structure]

5285:     Output Parameters:
5286: +   n - number of columns in the (possibly compressed) matrix
5287: .   ia - the column pointers
5288: .   ja - the row indices
5289: -   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

5291:     Level: developer

5293: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
5294: @*/
5295: PetscErrorCode  MatGetColumnIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5296: {

5306:   MatPreallocated(mat);
5307:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
5308:   else {
5309:     *done = PETSC_TRUE;
5310:     (*mat->ops->getcolumnij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5311:   }
5312:   return(0);
5313: }

5317: /*@C
5318:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
5319:     MatGetRowIJ().

5321:     Collective on Mat

5323:     Input Parameters:
5324: +   mat - the matrix
5325: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
5326: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5327:                 symmetrized
5328: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5329:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5330:                  nonzero structure which is different than the full nonzero structure]

5332:     Output Parameters:
5333: +   n - size of (possibly compressed) matrix
5334: .   ia - the row pointers
5335: .   ja - the column indices
5336: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

5338:     Level: developer

5340: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
5341: @*/
5342: PetscErrorCode  MatRestoreRowIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5343: {

5352:   MatPreallocated(mat);

5354:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
5355:   else {
5356:     *done = PETSC_TRUE;
5357:     (*mat->ops->restorerowij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5358:   }
5359:   return(0);
5360: }

5364: /*@C
5365:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
5366:     MatGetColumnIJ().

5368:     Collective on Mat

5370:     Input Parameters:
5371: +   mat - the matrix
5372: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
5373: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
5374:                 symmetrized
5375: -   blockcompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
5376:                  blockcompressed matrix is desired or not [inode, baij have blockcompressed 
5377:                  nonzero structure which is different than the full nonzero structure]

5379:     Output Parameters:
5380: +   n - size of (possibly compressed) matrix
5381: .   ia - the column pointers
5382: .   ja - the row indices
5383: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

5385:     Level: developer

5387: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
5388: @*/
5389: PetscErrorCode  MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscTruth symmetric,PetscTruth blockcompressed,PetscInt *n,PetscInt *ia[],PetscInt* ja[],PetscTruth *done)
5390: {

5399:   MatPreallocated(mat);

5401:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
5402:   else {
5403:     *done = PETSC_TRUE;
5404:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,blockcompressed,n,ia,ja,done);
5405:   }
5406:   return(0);
5407: }

5411: /*@C
5412:     MatColoringPatch -Used inside matrix coloring routines that 
5413:     use MatGetRowIJ() and/or MatGetColumnIJ().

5415:     Collective on Mat

5417:     Input Parameters:
5418: +   mat - the matrix
5419: .   ncolors - max color value
5420: .   n   - number of entries in colorarray
5421: -   colorarray - array indicating color for each column

5423:     Output Parameters:
5424: .   iscoloring - coloring generated using colorarray information

5426:     Level: developer

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

5430: @*/
5431: PetscErrorCode  MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
5432: {

5440:   MatPreallocated(mat);

5442:   if (!mat->ops->coloringpatch){
5443:     ISColoringCreate(mat->comm,ncolors,n,colorarray,iscoloring);
5444:   } else {
5445:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
5446:   }
5447:   return(0);
5448: }


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

5456:    Collective on Mat

5458:    Input Parameter:
5459: .  mat - the factored matrix to be reset

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

5468:    Note that one can specify in-place ILU(0) factorization by calling 
5469: .vb
5470:      PCType(pc,PCILU);
5471:      PCFactorSeUseInPlace(pc);
5472: .ve
5473:    or by using the options -pc_type ilu -pc_factor_in_place

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

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

5485:    Level: developer

5487: .seealso: PCFactorSetUseInPlace()

5489:    Concepts: matrices^unfactored

5491: @*/
5492: PetscErrorCode  MatSetUnfactored(Mat mat)
5493: {

5499:   MatPreallocated(mat);
5500:   mat->factor = 0;
5501:   if (!mat->ops->setunfactored) return(0);
5502:   (*mat->ops->setunfactored)(mat);
5503:   return(0);
5504: }

5506: /*MC
5507:     MatGetArrayF90 - Accesses a matrix array from Fortran90.

5509:     Synopsis:
5510:     MatGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

5512:     Not collective

5514:     Input Parameter:
5515: .   x - matrix

5517:     Output Parameters:
5518: +   xx_v - the Fortran90 pointer to the array
5519: -   ierr - error code

5521:     Example of Usage: 
5522: .vb
5523:       PetscScalar, pointer xx_v(:)
5524:       ....
5525:       call MatGetArrayF90(x,xx_v,ierr)
5526:       a = xx_v(3)
5527:       call MatRestoreArrayF90(x,xx_v,ierr)
5528: .ve

5530:     Notes:
5531:     Not yet supported for all F90 compilers

5533:     Level: advanced

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

5537:     Concepts: matrices^accessing array

5539: M*/

5541: /*MC
5542:     MatRestoreArrayF90 - Restores a matrix array that has been
5543:     accessed with MatGetArrayF90().

5545:     Synopsis:
5546:     MatRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

5548:     Not collective

5550:     Input Parameters:
5551: +   x - matrix
5552: -   xx_v - the Fortran90 pointer to the array

5554:     Output Parameter:
5555: .   ierr - error code

5557:     Example of Usage: 
5558: .vb
5559:        PetscScalar, pointer xx_v(:)
5560:        ....
5561:        call MatGetArrayF90(x,xx_v,ierr)
5562:        a = xx_v(3)
5563:        call MatRestoreArrayF90(x,xx_v,ierr)
5564: .ve
5565:    
5566:     Notes:
5567:     Not yet supported for all F90 compilers

5569:     Level: advanced

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

5573: M*/


5578: /*@
5579:     MatGetSubMatrix - Gets a single submatrix on the same number of processors
5580:                       as the original matrix.

5582:     Collective on Mat

5584:     Input Parameters:
5585: +   mat - the original matrix
5586: .   isrow - rows this processor should obtain
5587: .   iscol - columns for all processors you wish to keep
5588: .   csize - number of columns "local" to this processor (does nothing for sequential 
5589:             matrices). This should match the result from VecGetLocalSize(x,...) if you 
5590:             plan to use the matrix in a A*x; alternatively, you can use PETSC_DECIDE
5591: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5593:     Output Parameter:
5594: .   newmat - the new submatrix, of the same type as the old

5596:     Level: advanced

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

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

5608:     Concepts: matrices^submatrices

5610: .seealso: MatGetSubMatrices(), ISAllGather()
5611: @*/
5612: PetscErrorCode  MatGetSubMatrix(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse cll,Mat *newmat)
5613: {
5615:   PetscMPIInt    size;
5616:   Mat            *local;

5625:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5626:   MatPreallocated(mat);
5627:   MPI_Comm_size(mat->comm,&size);

5629:   /* if original matrix is on just one processor then use submatrix generated */
5630:   if (!mat->ops->getsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
5631:     MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,&newmat);
5632:     return(0);
5633:   } else if (!mat->ops->getsubmatrix && size == 1) {
5634:     MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&local);
5635:     *newmat = *local;
5636:     PetscFree(local);
5637:     return(0);
5638:   }

5640:   if (!mat->ops->getsubmatrix) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
5641:   (*mat->ops->getsubmatrix)(mat,isrow,iscol,csize,cll,newmat);
5642:   PetscObjectStateIncrease((PetscObject)*newmat);
5643:   return(0);
5644: }

5648: /*@
5649:     MatGetSubMatrixRaw - Gets a single submatrix on the same number of processors
5650:                          as the original matrix.

5652:     Collective on Mat

5654:     Input Parameters:
5655: +   mat - the original matrix
5656: .   nrows - the number of rows this processor should obtain
5657: .   rows - rows this processor should obtain
5658: .   ncols - the number of columns for all processors you wish to keep
5659: .   cols - columns for all processors you wish to keep
5660: .   csize - number of columns "local" to this processor (does nothing for sequential 
5661:             matrices). This should match the result from VecGetLocalSize(x,...) if you 
5662:             plan to use the matrix in a A*x; alternatively, you can use PETSC_DECIDE
5663: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5665:     Output Parameter:
5666: .   newmat - the new submatrix, of the same type as the old

5668:     Level: advanced

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

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

5678:     Concepts: matrices^submatrices

5680: .seealso: MatGetSubMatrices(), ISAllGather()
5681: @*/
5682: PetscErrorCode  MatGetSubMatrixRaw(Mat mat,PetscInt nrows,const PetscInt rows[],PetscInt ncols,const PetscInt cols[],PetscInt csize,MatReuse cll,Mat *newmat)
5683: {
5684:   IS             isrow, iscol;

5694:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5695:   MatPreallocated(mat);
5696:   ISCreateGeneralWithArray(PETSC_COMM_SELF, nrows, (PetscInt *) rows, &isrow);
5697:   ISCreateGeneralWithArray(PETSC_COMM_SELF, ncols, (PetscInt *) cols, &iscol);
5698:   MatGetSubMatrix(mat, isrow, iscol, csize, cll, newmat);
5699:   ISDestroy(isrow);
5700:   ISDestroy(iscol);
5701:   return(0);
5702: }

5706: /*@
5707:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
5708:    used during the assembly process to store values that belong to 
5709:    other processors.

5711:    Not Collective

5713:    Input Parameters:
5714: +  mat   - the matrix
5715: .  size  - the initial size of the stash.
5716: -  bsize - the initial size of the block-stash(if used).

5718:    Options Database Keys:
5719: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
5720: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

5722:    Level: intermediate

5724:    Notes: 
5725:      The block-stash is used for values set with MatSetValuesBlocked() while
5726:      the stash is used for values set with MatSetValues()

5728:      Run with the option -info and look for output of the form
5729:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
5730:      to determine the appropriate value, MM, to use for size and 
5731:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
5732:      to determine the value, BMM to use for bsize

5734:    Concepts: stash^setting matrix size
5735:    Concepts: matrices^stash

5737: @*/
5738: PetscErrorCode  MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
5739: {

5745:   MatStashSetInitialSize_Private(&mat->stash,size);
5746:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
5747:   return(0);
5748: }

5752: /*@
5753:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of 
5754:      the matrix

5756:    Collective on Mat

5758:    Input Parameters:
5759: +  mat   - the matrix
5760: .  x,y - the vectors
5761: -  w - where the result is stored

5763:    Level: intermediate

5765:    Notes: 
5766:     w may be the same vector as y. 

5768:     This allows one to use either the restriction or interpolation (its transpose)
5769:     matrix to do the interpolation

5771:     Concepts: interpolation

5773: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

5775: @*/
5776: PetscErrorCode  MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
5777: {
5779:   PetscInt       M,N;

5787:   MatPreallocated(A);
5788:   MatGetSize(A,&M,&N);
5789:   if (N > M) {
5790:     MatMultTransposeAdd(A,x,y,w);
5791:   } else {
5792:     MatMultAdd(A,x,y,w);
5793:   }
5794:   return(0);
5795: }

5799: /*@
5800:    MatInterpolate - y = A*x or A'*x depending on the shape of 
5801:      the matrix

5803:    Collective on Mat

5805:    Input Parameters:
5806: +  mat   - the matrix
5807: -  x,y - the vectors

5809:    Level: intermediate

5811:    Notes: 
5812:     This allows one to use either the restriction or interpolation (its transpose)
5813:     matrix to do the interpolation

5815:    Concepts: matrices^interpolation

5817: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

5819: @*/
5820: PetscErrorCode  MatInterpolate(Mat A,Vec x,Vec y)
5821: {
5823:   PetscInt       M,N;

5830:   MatPreallocated(A);
5831:   MatGetSize(A,&M,&N);
5832:   if (N > M) {
5833:     MatMultTranspose(A,x,y);
5834:   } else {
5835:     MatMult(A,x,y);
5836:   }
5837:   return(0);
5838: }

5842: /*@
5843:    MatRestrict - y = A*x or A'*x

5845:    Collective on Mat

5847:    Input Parameters:
5848: +  mat   - the matrix
5849: -  x,y - the vectors

5851:    Level: intermediate

5853:    Notes: 
5854:     This allows one to use either the restriction or interpolation (its transpose)
5855:     matrix to do the restriction

5857:    Concepts: matrices^restriction

5859: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

5861: @*/
5862: PetscErrorCode  MatRestrict(Mat A,Vec x,Vec y)
5863: {
5865:   PetscInt       M,N;

5872:   MatPreallocated(A);

5874:   MatGetSize(A,&M,&N);
5875:   if (N > M) {
5876:     MatMult(A,x,y);
5877:   } else {
5878:     MatMultTranspose(A,x,y);
5879:   }
5880:   return(0);
5881: }

5885: /*@C
5886:    MatNullSpaceAttach - attaches a null space to a matrix.
5887:         This null space will be removed from the resulting vector whenever
5888:         MatMult() is called

5890:    Collective on Mat

5892:    Input Parameters:
5893: +  mat - the matrix
5894: -  nullsp - the null space object

5896:    Level: developer

5898:    Notes:
5899:       Overwrites any previous null space that may have been attached

5901:    Concepts: null space^attaching to matrix

5903: .seealso: MatCreate(), MatNullSpaceCreate()
5904: @*/
5905: PetscErrorCode  MatNullSpaceAttach(Mat mat,MatNullSpace nullsp)
5906: {

5913:   MatPreallocated(mat);
5914:   PetscObjectReference((PetscObject)nullsp);
5915:   if (mat->nullsp) { MatNullSpaceDestroy(mat->nullsp); }
5916:   mat->nullsp = nullsp;
5917:   return(0);
5918: }

5922: /*@  
5923:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

5925:    Collective on Mat

5927:    Input Parameters:
5928: +  mat - the matrix
5929: .  row - row/column permutation
5930: .  fill - expected fill factor >= 1.0
5931: -  level - level of fill, for ICC(k)

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

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

5941:    Level: developer

5943:    Concepts: matrices^incomplete Cholesky factorization
5944:    Concepts: Cholesky factorization

5946: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
5947: @*/
5948: PetscErrorCode  MatICCFactor(Mat mat,IS row,MatFactorInfo* info)
5949: {

5957:   if (mat->rmap.N != mat->cmap.N) SETERRQ(PETSC_ERR_ARG_WRONG,"matrix must be square");
5958:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5959:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5960:   if (!mat->ops->iccfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
5961:   MatPreallocated(mat);
5962:   (*mat->ops->iccfactor)(mat,row,info);
5963:   PetscObjectStateIncrease((PetscObject)mat);
5964:   return(0);
5965: }

5969: /*@ 
5970:    MatSetValuesAdic - Sets values computed with ADIC automatic differentiation into a matrix.

5972:    Not Collective

5974:    Input Parameters:
5975: +  mat - the matrix
5976: -  v - the values compute with ADIC

5978:    Level: developer

5980:    Notes:
5981:      Must call MatSetColoring() before using this routine. Also this matrix must already
5982:      have its nonzero pattern determined.

5984: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
5985:           MatSetValues(), MatSetColoring(), MatSetValuesAdifor()
5986: @*/
5987: PetscErrorCode  MatSetValuesAdic(Mat mat,void *v)
5988: {


5996:   if (!mat->assembled) {
5997:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
5998:   }
6000:   if (!mat->ops->setvaluesadic) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
6001:   (*mat->ops->setvaluesadic)(mat,v);
6003:   MatView_Private(mat);
6004:   PetscObjectStateIncrease((PetscObject)mat);
6005:   return(0);
6006: }


6011: /*@ 
6012:    MatSetColoring - Sets a coloring used by calls to MatSetValuesAdic()

6014:    Not Collective

6016:    Input Parameters:
6017: +  mat - the matrix
6018: -  coloring - the coloring

6020:    Level: developer

6022: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
6023:           MatSetValues(), MatSetValuesAdic()
6024: @*/
6025: PetscErrorCode  MatSetColoring(Mat mat,ISColoring coloring)
6026: {


6034:   if (!mat->assembled) {
6035:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
6036:   }
6037:   if (!mat->ops->setcoloring) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
6038:   (*mat->ops->setcoloring)(mat,coloring);
6039:   return(0);
6040: }

6044: /*@ 
6045:    MatSetValuesAdifor - Sets values computed with automatic differentiation into a matrix.

6047:    Not Collective

6049:    Input Parameters:
6050: +  mat - the matrix
6051: .  nl - leading dimension of v
6052: -  v - the values compute with ADIFOR

6054:    Level: developer

6056:    Notes:
6057:      Must call MatSetColoring() before using this routine. Also this matrix must already
6058:      have its nonzero pattern determined.

6060: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
6061:           MatSetValues(), MatSetColoring()
6062: @*/
6063: PetscErrorCode  MatSetValuesAdifor(Mat mat,PetscInt nl,void *v)
6064: {


6072:   if (!mat->assembled) {
6073:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
6074:   }
6076:   if (!mat->ops->setvaluesadifor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
6077:   (*mat->ops->setvaluesadifor)(mat,nl,v);
6079:   PetscObjectStateIncrease((PetscObject)mat);
6080:   return(0);
6081: }

6085: /*@ 
6086:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the 
6087:          ghosted ones.

6089:    Not Collective

6091:    Input Parameters:
6092: +  mat - the matrix
6093: -  diag = the diagonal values, including ghost ones

6095:    Level: developer

6097:    Notes: Works only for MPIAIJ and MPIBAIJ matrices
6098:       
6099: .seealso: MatDiagonalScale()
6100: @*/
6101: PetscErrorCode  MatDiagonalScaleLocal(Mat mat,Vec diag)
6102: {
6104:   PetscMPIInt    size;


6111:   if (!mat->assembled) {
6112:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
6113:   }
6115:   MPI_Comm_size(mat->comm,&size);
6116:   if (size == 1) {
6117:     PetscInt n,m;
6118:     VecGetSize(diag,&n);
6119:     MatGetSize(mat,0,&m);
6120:     if (m == n) {
6121:       MatDiagonalScale(mat,0,diag);
6122:     } else {
6123:       SETERRQ(PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
6124:     }
6125:   } else {
6126:     PetscErrorCode (*f)(Mat,Vec);
6127:     PetscObjectQueryFunction((PetscObject)mat,"MatDiagonalScaleLocal_C",(void (**)(void))&f);
6128:     if (f) {
6129:       (*f)(mat,diag);
6130:     } else {
6131:       SETERRQ(PETSC_ERR_SUP,"Only supported for MPIAIJ and MPIBAIJ parallel matrices");
6132:     }
6133:   }
6135:   PetscObjectStateIncrease((PetscObject)mat);
6136:   return(0);
6137: }

6141: /*@ 
6142:    MatGetInertia - Gets the inertia from a factored matrix

6144:    Collective on Mat

6146:    Input Parameter:
6147: .  mat - the matrix

6149:    Output Parameters:
6150: +   nneg - number of negative eigenvalues
6151: .   nzero - number of zero eigenvalues
6152: -   npos - number of positive eigenvalues

6154:    Level: advanced

6156:    Notes: Matrix must have been factored by MatCholeskyFactor()


6159: @*/
6160: PetscErrorCode  MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
6161: {

6167:   if (!mat->factor)    SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
6168:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
6169:   if (!mat->ops->getinertia) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
6170:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
6171:   return(0);
6172: }

6174: /* ----------------------------------------------------------------*/
6177: /*@
6178:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

6180:    Collective on Mat and Vecs

6182:    Input Parameters:
6183: +  mat - the factored matrix
6184: -  b - the right-hand-side vectors

6186:    Output Parameter:
6187: .  x - the result vectors

6189:    Notes:
6190:    The vectors b and x cannot be the same.  I.e., one cannot
6191:    call MatSolves(A,x,x).

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

6198:    Level: developer

6200:    Concepts: matrices^triangular solves

6202: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
6203: @*/
6204: PetscErrorCode  MatSolves(Mat mat,Vecs b,Vecs x)
6205: {

6211:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
6212:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
6213:   if (!mat->rmap.N && !mat->cmap.N) return(0);

6215:   if (!mat->ops->solves) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
6216:   MatPreallocated(mat);
6218:   (*mat->ops->solves)(mat,b,x);
6220:   return(0);
6221: }

6225: /*@
6226:    MatIsSymmetric - Test whether a matrix is symmetric

6228:    Collective on Mat

6230:    Input Parameter:
6231: +  A - the matrix to test
6232: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

6234:    Output Parameters:
6235: .  flg - the result

6237:    Level: intermediate

6239:    Concepts: matrix^symmetry

6241: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
6242: @*/
6243: PetscErrorCode  MatIsSymmetric(Mat A,PetscReal tol,PetscTruth *flg)
6244: {

6250:   if (!A->symmetric_set) {
6251:     if (!A->ops->issymmetric) {
6252:       MatType mattype;
6253:       MatGetType(A,&mattype);
6254:       SETERRQ1(PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
6255:     }
6256:     (*A->ops->issymmetric)(A,tol,&A->symmetric);
6257:     A->symmetric_set = PETSC_TRUE;
6258:     if (A->symmetric) {
6259:       A->structurally_symmetric_set = PETSC_TRUE;
6260:       A->structurally_symmetric     = PETSC_TRUE;
6261:     }
6262:   }
6263:   *flg = A->symmetric;
6264:   return(0);
6265: }

6269: /*@
6270:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

6272:    Collective on Mat

6274:    Input Parameter:
6275: .  A - the matrix to check

6277:    Output Parameters:
6278: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
6279: -  flg - the result

6281:    Level: advanced

6283:    Concepts: matrix^symmetry

6285:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
6286:          if you want it explicitly checked

6288: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
6289: @*/
6290: PetscErrorCode  MatIsSymmetricKnown(Mat A,PetscTruth *set,PetscTruth *flg)
6291: {
6296:   if (A->symmetric_set) {
6297:     *set = PETSC_TRUE;
6298:     *flg = A->symmetric;
6299:   } else {
6300:     *set = PETSC_FALSE;
6301:   }
6302:   return(0);
6303: }

6307: /*@
6308:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

6310:    Collective on Mat

6312:    Input Parameter:
6313: .  A - the matrix to check

6315:    Output Parameters:
6316: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
6317: -  flg - the result

6319:    Level: advanced

6321:    Concepts: matrix^symmetry

6323:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
6324:          if you want it explicitly checked

6326: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
6327: @*/
6328: PetscErrorCode  MatIsHermitianKnown(Mat A,PetscTruth *set,PetscTruth *flg)
6329: {
6334:   if (A->hermitian_set) {
6335:     *set = PETSC_TRUE;
6336:     *flg = A->hermitian;
6337:   } else {
6338:     *set = PETSC_FALSE;
6339:   }
6340:   return(0);
6341: }

6345: /*@
6346:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

6348:    Collective on Mat

6350:    Input Parameter:
6351: .  A - the matrix to test

6353:    Output Parameters:
6354: .  flg - the result

6356:    Level: intermediate

6358:    Concepts: matrix^symmetry

6360: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
6361: @*/
6362: PetscErrorCode  MatIsStructurallySymmetric(Mat A,PetscTruth *flg)
6363: {

6369:   if (!A->structurally_symmetric_set) {
6370:     if (!A->ops->isstructurallysymmetric) SETERRQ(PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
6371:     (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);
6372:     A->structurally_symmetric_set = PETSC_TRUE;
6373:   }
6374:   *flg = A->structurally_symmetric;
6375:   return(0);
6376: }

6380: /*@
6381:    MatIsHermitian - Test whether a matrix is Hermitian, i.e. it is the complex conjugate of its transpose.

6383:    Collective on Mat

6385:    Input Parameter:
6386: .  A - the matrix to test

6388:    Output Parameters:
6389: .  flg - the result

6391:    Level: intermediate

6393:    Concepts: matrix^symmetry

6395: .seealso: MatTranspose(), MatIsTranspose(), MatIsSymmetric(), MatIsStructurallySymmetric(), MatSetOption()
6396: @*/
6397: PetscErrorCode  MatIsHermitian(Mat A,PetscTruth *flg)
6398: {

6404:   if (!A->hermitian_set) {
6405:     if (!A->ops->ishermitian) SETERRQ(PETSC_ERR_SUP,"Matrix does not support checking for being Hermitian");
6406:     (*A->ops->ishermitian)(A,&A->hermitian);
6407:     A->hermitian_set = PETSC_TRUE;
6408:     if (A->hermitian) {
6409:       A->structurally_symmetric_set = PETSC_TRUE;
6410:       A->structurally_symmetric     = PETSC_TRUE;
6411:     }
6412:   }
6413:   *flg = A->hermitian;
6414:   return(0);
6415: }

6420: /*@ 
6421:    MatStashGetInfo - Gets how many values are currently in the vector stash, i.e. need
6422:        to be communicated to other processors during the MatAssemblyBegin/End() process

6424:     Not collective

6426:    Input Parameter:
6427: .   vec - the vector

6429:    Output Parameters:
6430: +   nstash   - the size of the stash
6431: .   reallocs - the number of additional mallocs incurred.
6432: .   bnstash   - the size of the block stash
6433: -   breallocs - the number of additional mallocs incurred.in the block stash
6434:  
6435:    Level: advanced

6437: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
6438:   
6439: @*/
6440: PetscErrorCode  MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
6441: {
6444:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
6445:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
6446:   return(0);
6447: }

6451: /*@
6452:    MatGetVecs - Get vector(s) compatible with the matrix, i.e. with the same 
6453:      parallel layout
6454:    
6455:    Collective on Mat

6457:    Input Parameter:
6458: .  mat - the matrix

6460:    Output Parameter:
6461: +   right - (optional) vector that the matrix can be multiplied against
6462: -   left - (optional) vector that the matrix vector product can be stored in

6464:   Level: advanced

6466: .seealso: MatCreate()
6467: @*/
6468: PetscErrorCode  MatGetVecs(Mat mat,Vec *right,Vec *left)
6469: {

6475:   MatPreallocated(mat);
6476:   if (mat->ops->getvecs) {
6477:     (*mat->ops->getvecs)(mat,right,left);
6478:   } else {
6479:     PetscMPIInt size;
6480:     MPI_Comm_size(mat->comm, &size);
6481:     if (right) {
6482:       VecCreate(mat->comm,right);
6483:       VecSetSizes(*right,mat->cmap.n,PETSC_DETERMINE);
6484:       if (size > 1) {VecSetType(*right,VECMPI);}
6485:       else {VecSetType(*right,VECSEQ);}
6486:     }
6487:     if (left) {
6488:       VecCreate(mat->comm,left);
6489:       VecSetSizes(*left,mat->rmap.n,PETSC_DETERMINE);
6490:       if (size > 1) {VecSetType(*left,VECMPI);}
6491:       else {VecSetType(*left,VECSEQ);}
6492:     }
6493:   }
6494:   if (right) {VecSetBlockSize(*right,mat->rmap.bs);}
6495:   if (left) {VecSetBlockSize(*left,mat->rmap.bs);}
6496:   if (mat->mapping) {
6497:     if (right) {VecSetLocalToGlobalMapping(*right,mat->mapping);}
6498:     if (left) {VecSetLocalToGlobalMapping(*left,mat->mapping);}
6499:   }
6500:   if (mat->bmapping) {
6501:     if (right) {VecSetLocalToGlobalMappingBlock(*right,mat->bmapping);}
6502:     if (left) {VecSetLocalToGlobalMappingBlock(*left,mat->bmapping);}
6503:   }
6504:   return(0);
6505: }

6509: /*@
6510:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
6511:      with default values.

6513:    Not Collective

6515:    Input Parameters:
6516: .    info - the MatFactorInfo data structure


6519:    Notes: The solvers are generally used through the KSP and PC objects, for example
6520:           PCLU, PCILU, PCCHOLESKY, PCICC

6522:    Level: developer

6524: .seealso: MatFactorInfo
6525: @*/

6527: PetscErrorCode  MatFactorInfoInitialize(MatFactorInfo *info)
6528: {

6532:   PetscMemzero(info,sizeof(MatFactorInfo));
6533:   return(0);
6534: }

6538: /*@
6539:    MatPtAP - Creates the matrix projection C = P^T * A * P

6541:    Collective on Mat

6543:    Input Parameters:
6544: +  A - the matrix
6545: .  P - the projection matrix
6546: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6547: -  fill - expected fill as ratio of nnz(C)/nnz(A) 

6549:    Output Parameters:
6550: .  C - the product matrix

6552:    Notes:
6553:    C will be created and must be destroyed by the user with MatDestroy().

6555:    This routine is currently only implemented for pairs of AIJ matrices and classes
6556:    which inherit from AIJ.  

6558:    Level: intermediate

6560: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult()
6561: @*/
6562: PetscErrorCode  MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
6563: {

6569:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6570:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6573:   MatPreallocated(P);
6574:   if (!P->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6575:   if (P->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6577:   if (P->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap.N,A->cmap.N);
6578:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be >= 1.0",fill);
6579:   MatPreallocated(A);

6582:   (*A->ops->ptap)(A,P,scall,fill,C);

6585:   return(0);
6586: }

6590: /*@
6591:    MatPtAPNumeric - Computes the matrix projection C = P^T * A * P

6593:    Collective on Mat

6595:    Input Parameters:
6596: +  A - the matrix
6597: -  P - the projection matrix

6599:    Output Parameters:
6600: .  C - the product matrix

6602:    Notes:
6603:    C must have been created by calling MatPtAPSymbolic and must be destroyed by
6604:    the user using MatDeatroy().

6606:    This routine is currently only implemented for pairs of AIJ matrices and classes
6607:    which inherit from AIJ.  C will be of type MATAIJ.

6609:    Level: intermediate

6611: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
6612: @*/
6613: PetscErrorCode  MatPtAPNumeric(Mat A,Mat P,Mat C)
6614: {

6620:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6621:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6624:   MatPreallocated(P);
6625:   if (!P->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6626:   if (P->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6629:   MatPreallocated(C);
6630:   if (C->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6631:   if (P->cmap.N!=C->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap.N,C->rmap.N);
6632:   if (P->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap.N,A->cmap.N);
6633:   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);
6634:   if (P->cmap.N!=C->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap.N,C->cmap.N);
6635:   MatPreallocated(A);

6638:   (*A->ops->ptapnumeric)(A,P,C);
6640:   return(0);
6641: }

6645: /*@
6646:    MatPtAPSymbolic - Creates the (i,j) structure of the matrix projection C = P^T * A * P

6648:    Collective on Mat

6650:    Input Parameters:
6651: +  A - the matrix
6652: -  P - the projection matrix

6654:    Output Parameters:
6655: .  C - the (i,j) structure of the product matrix

6657:    Notes:
6658:    C will be created and must be destroyed by the user with MatDestroy().

6660:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
6661:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
6662:    this (i,j) structure by calling MatPtAPNumeric().

6664:    Level: intermediate

6666: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
6667: @*/
6668: PetscErrorCode  MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
6669: {

6675:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6676:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6677:   if (fill <1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be >= 1.0",fill);
6680:   MatPreallocated(P);
6681:   if (!P->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6682:   if (P->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6685:   if (P->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap.N,A->cmap.N);
6686:   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);
6687:   MatPreallocated(A);
6689:   (*A->ops->ptapsymbolic)(A,P,fill,C);

6692:   MatSetBlockSize(*C,A->rmap.bs);

6694:   return(0);
6695: }

6699: /*@
6700:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

6702:    Collective on Mat

6704:    Input Parameters:
6705: +  A - the left matrix
6706: .  B - the right matrix
6707: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6708: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B))

6710:    Output Parameters:
6711: .  C - the product matrix

6713:    Notes:
6714:    C will be created and must be destroyed by the user with MatDestroy().
6715:    Unless scall is MAT_REUSE_MATRIX

6717:    If you have many matrices with the same non-zero structure to multiply, you 
6718:    should either 
6719: $   1) use MAT_REUSE_MATRIX in all calls but the first or
6720: $   2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed

6722:    Level: intermediate

6724: .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatPtAP()
6725: @*/
6726: PetscErrorCode  MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
6727: {
6729:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
6730:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
6731:   PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat *)=PETSC_NULL;

6736:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6737:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6740:   MatPreallocated(B);
6741:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6742:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6744:   if (B->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->cmap.N);
6745:   if (fill == PETSC_DEFAULT) fill = 2.0;
6746:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be >= 1.0",fill);
6747:   MatPreallocated(A);

6749:   fA = A->ops->matmult;
6750:   fB = B->ops->matmult;
6751:   if (fB == fA) {
6752:     if (!fB) SETERRQ1(PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",B->type_name);
6753:     mult = fB;
6754:   } else {
6755:     /* dispatch based on the type of A and B */
6756:     char  multname[256];
6757:     PetscStrcpy(multname,"MatMatMult_");
6758:     PetscStrcat(multname,A->type_name);
6759:     PetscStrcat(multname,"_");
6760:     PetscStrcat(multname,B->type_name);
6761:     PetscStrcat(multname,"_C"); /* e.g., multname = "MatMatMult_aij_dense_C" */
6762:     PetscObjectQueryFunction((PetscObject)B,multname,(void (**)(void))&mult);
6763:     if (!mult) SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMult requires A, %s, to be compatible with B, %s",A->type_name,B->type_name);
6764:   }
6766:   (*mult)(A,B,scall,fill,C);
6768:   return(0);
6769: }

6773: /*@
6774:    MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
6775:    of the matrix-matrix product C=A*B.  Call this routine before calling MatMatMultNumeric().

6777:    Collective on Mat

6779:    Input Parameters:
6780: +  A - the left matrix
6781: .  B - the right matrix
6782: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B))

6784:    Output Parameters:
6785: .  C - the matrix containing the ij structure of product matrix

6787:    Notes:
6788:    C will be created and must be destroyed by the user with MatDestroy().

6790:    This routine is currently implemented for 
6791:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
6792:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type MATDENSE.

6794:    Level: intermediate

6796: .seealso: MatMatMult(), MatMatMultNumeric()
6797: @*/
6798: PetscErrorCode  MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
6799: {
6801:   PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat *);
6802:   PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat *);
6803:   PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat *)=PETSC_NULL;

6808:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6809:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6813:   MatPreallocated(B);
6814:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6815:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6818:   if (B->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->cmap.N);
6819:   if (fill == PETSC_DEFAULT) fill = 2.0;
6820:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be > 1.0",fill);
6821:   MatPreallocated(A);
6822: 
6823:   Asymbolic = A->ops->matmultsymbolic;
6824:   Bsymbolic = B->ops->matmultsymbolic;
6825:   if (Asymbolic == Bsymbolic){
6826:     if (!Bsymbolic) SETERRQ1(PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",B->type_name);
6827:     symbolic = Bsymbolic;
6828:   } else { /* dispatch based on the type of A and B */
6829:     char  symbolicname[256];
6830:     PetscStrcpy(symbolicname,"MatMatMultSymbolic_");
6831:     PetscStrcat(symbolicname,A->type_name);
6832:     PetscStrcat(symbolicname,"_");
6833:     PetscStrcat(symbolicname,B->type_name);
6834:     PetscStrcat(symbolicname,"_C");
6835:     PetscObjectQueryFunction((PetscObject)B,symbolicname,(void (**)(void))&symbolic);
6836:     if (!symbolic) SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMultSymbolic requires A, %s, to be compatible with B, %s",A->type_name,B->type_name);
6837:   }
6839:   (*symbolic)(A,B,fill,C);
6841:   return(0);
6842: }

6846: /*@
6847:    MatMatMultNumeric - Performs the numeric matrix-matrix product.
6848:    Call this routine after first calling MatMatMultSymbolic().

6850:    Collective on Mat

6852:    Input Parameters:
6853: +  A - the left matrix
6854: -  B - the right matrix

6856:    Output Parameters:
6857: .  C - the product matrix, whose ij structure was defined from MatMatMultSymbolic().

6859:    Notes:
6860:    C must have been created with MatMatMultSymbolic.

6862:    This routine is currently implemented for 
6863:     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
6864:     - pairs of AIJ (A) and Dense (B) matrix, C will be of type MATDENSE.

6866:    Level: intermediate

6868: .seealso: MatMatMult(), MatMatMultSymbolic()
6869: @*/
6870: PetscErrorCode  MatMatMultNumeric(Mat A,Mat B,Mat C)
6871: {
6873:   PetscErrorCode (*Anumeric)(Mat,Mat,Mat);
6874:   PetscErrorCode (*Bnumeric)(Mat,Mat,Mat);
6875:   PetscErrorCode (*numeric)(Mat,Mat,Mat)=PETSC_NULL;

6880:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6881:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6885:   MatPreallocated(B);
6886:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6887:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6891:   MatPreallocated(C);
6892:   if (!C->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6893:   if (C->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

6895:   if (B->cmap.N!=C->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->cmap.N,C->cmap.N);
6896:   if (B->rmap.N!=A->cmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->cmap.N);
6897:   if (A->rmap.N!=C->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",A->rmap.N,C->rmap.N);
6898:   MatPreallocated(A);

6900:   Anumeric = A->ops->matmultnumeric;
6901:   Bnumeric = B->ops->matmultnumeric;
6902:   if (Anumeric == Bnumeric){
6903:     if (!Bnumeric) SETERRQ1(PETSC_ERR_SUP,"MatMatMultNumeric not supported for B of type %s",B->type_name);
6904:     numeric = Bnumeric;
6905:   } else {
6906:     char  numericname[256];
6907:     PetscStrcpy(numericname,"MatMatMultNumeric_");
6908:     PetscStrcat(numericname,A->type_name);
6909:     PetscStrcat(numericname,"_");
6910:     PetscStrcat(numericname,B->type_name);
6911:     PetscStrcat(numericname,"_C");
6912:     PetscObjectQueryFunction((PetscObject)B,numericname,(void (**)(void))&numeric);
6913:     if (!numeric)
6914:       SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMultNumeric requires A, %s, to be compatible with B, %s",A->type_name,B->type_name);
6915:   }
6917:   (*numeric)(A,B,C);
6919:   return(0);
6920: }

6924: /*@
6925:    MatMatMultTranspose - Performs Matrix-Matrix Multiplication C=A^T*B.

6927:    Collective on Mat

6929:    Input Parameters:
6930: +  A - the left matrix
6931: .  B - the right matrix
6932: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6933: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B))

6935:    Output Parameters:
6936: .  C - the product matrix

6938:    Notes:
6939:    C will be created and must be destroyed by the user with MatDestroy().

6941:    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
6942:    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.

6944:    Level: intermediate

6946: .seealso: MatMatMultTransposeSymbolic(), MatMatMultTransposeNumeric(), MatPtAP()
6947: @*/
6948: PetscErrorCode  MatMatMultTranspose(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
6949: {
6951:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
6952:   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);

6957:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6958:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6961:   MatPreallocated(B);
6962:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6963:   if (B->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6965:   if (B->rmap.N!=A->rmap.N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap.N,A->rmap.N);
6966:   if (fill < 1.0) SETERRQ1(PETSC_ERR_ARG_SIZ,"Expected fill=%G must be > 1.0",fill);
6967:   MatPreallocated(A);

6969:   fA = A->ops->matmulttranspose;
6970:   if (!fA) SETERRQ1(PETSC_ERR_SUP,"MatMatMultTranspose not supported for A of type %s",A->type_name);
6971:   fB = B->ops->matmulttranspose;
6972:   if (!fB) SETERRQ1(PETSC_ERR_SUP,"MatMatMultTranspose not supported for B of type %s",B->type_name);
6973:   if (fB!=fA) SETERRQ2(PETSC_ERR_ARG_INCOMP,"MatMatMultTranspose requires A, %s, to be compatible with B, %s",A->type_name,B->type_name);

6976:   (*A->ops->matmulttranspose)(A,B,scall,fill,C);
6978: 
6979:   return(0);
6980: }

6984: /*@C
6985:    MatGetRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators. 

6987:    Collective on Mat

6989:    Input Parameters:
6990: +  mat - the matrix
6991: .  nsubcomm - the number of subcommunicators (= number of redundant pareallel or sequential matrices)
6992: .  subcomm - MPI communicator split from the communicator where mat resides in
6993: .  mlocal_red - number of local rows of the redundant matrix
6994: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6996:    Output Parameter:
6997: .  matredundant - redundant matrix

6999:    Notes:
7000:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the 
7001:    original matrix has not changed from that last call to MatGetRedundantMatrix().

7003:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
7004:    calling it. 

7006:    Only MPIAIJ matrix is supported. 
7007:    
7008:    Level: advanced

7010:    Concepts: subcommunicator
7011:    Concepts: duplicate matrix

7013: .seealso: MatDestroy()
7014: @*/
7015: PetscErrorCode  MatGetRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,PetscInt mlocal_red,MatReuse reuse,Mat *matredundant)
7016: {

7021:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
7024:   }
7025:   if (!mat->ops->getredundantmatrix) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
7026:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7027:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7028:   MatPreallocated(mat);

7031:   (*mat->ops->getredundantmatrix)(mat,nsubcomm,subcomm,mlocal_red,reuse,matredundant);
7033:   return(0);
7034: }