Actual source code: matrix.c

  1: /*$Id: matrix.c,v 1.414 2001/09/28 18:57:28 balay Exp $*/

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

 7:  #include src/mat/matimpl.h
 8:  #include src/vec/vecimpl.h

 10: /* Logging support */
 11: int MAT_COOKIE;
 12: int MAT_Mult, MAT_MultMatrixFree, MAT_MultMultiple, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
 13: int MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_SolveMultiple, MAT_SolveAdd, MAT_SolveTranspose;
 14: int MAT_SolveTransposeAdd, MAT_Relax, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
 15: int MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
 16: int MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
 17: int MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetSubMatrices, MAT_GetColoring, MAT_GetOrdering;
 18: int MAT_IncreaseOverlap, MAT_Partitioning, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
 19: int MAT_FDColoringApply;

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

 26:    Not Collective

 28:    Input Parameters:
 29: +  mat - the matrix
 30: -  row - the row to get

 32:    Output Parameters:
 33: +  ncols -  the number of nonzeros in the row
 34: .  cols - if not NULL, the column numbers
 35: -  vals - if not NULL, the values

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

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

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

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

 52:    You can only have one call to MatGetRow() outstanding for a particular
 53:    matrix at a time, per processor. MatGetRow() can only obtained rows
 54:    associated with the given processor, it cannot get rows from the 
 55:    other processors; for that we suggest using MatGetSubMatrices(), then
 56:    MatGetRow() on the submatrix. The row indix passed to MatGetRows() 
 57:    is in the global number of rows.

 59:    Fortran Notes:
 60:    The calling sequence from Fortran is 
 61: .vb
 62:    MatGetRow(matrix,row,ncols,cols,values,ierr)
 63:          Mat     matrix (input)
 64:          integer row    (input)
 65:          integer ncols  (output)
 66:          integer cols(maxcols) (output)
 67:          double precision (or double complex) values(maxcols) output
 68: .ve
 69:    where maxcols >= maximum nonzeros in any row of the matrix.

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

 75:    Level: advanced

 77:    Concepts: matrices^row access

 79: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatGetSubmatrices(), MatGetDiagonal()
 80: @*/
 81: int MatGetRow(Mat mat,int row,int *ncols,int **cols,PetscScalar **vals)
 82: {
 83:   int   ierr;

 89:   MatPreallocated(mat);
 90:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
 91:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
 92:   if (!mat->ops->getrow) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
 93:   PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
 94:   (*mat->ops->getrow)(mat,row,ncols,cols,vals);
 95:   PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
 96:   return(0);
 97: }

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

102:    Not Collective

104:    Input Parameters:
105: +  mat - the matrix
106: .  row - the row to get
107: .  ncols, cols - the number of nonzeros and their columns
108: -  vals - if nonzero the column values

110:    Notes: 
111:    This routine should be called after you have finished examining the entries.

113:    Fortran Notes:
114:    The calling sequence from Fortran is 
115: .vb
116:    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
117:       Mat     matrix (input)
118:       integer row    (input)
119:       integer ncols  (output)
120:       integer cols(maxcols) (output)
121:       double precision (or double complex) values(maxcols) output
122: .ve
123:    Where maxcols >= maximum nonzeros in any row of the matrix. 

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

128:    Level: advanced

130: .seealso:  MatGetRow()
131: @*/
132: int MatRestoreRow(Mat mat,int row,int *ncols,int **cols,PetscScalar **vals)
133: {

139:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
140:   if (!mat->ops->restorerow) return(0);
141:   (*mat->ops->restorerow)(mat,row,ncols,cols,vals);
142:   return(0);
143: }

145: /*@C
146:    MatView - Visualizes a matrix object.

148:    Collective on Mat

150:    Input Parameters:
151: +  mat - the matrix
152: -  ptr - visualization context

154:   Notes:
155:   The available visualization contexts include
156: +    PETSC_VIEWER_STDOUT_SELF - standard output (default)
157: .    PETSC_VIEWER_STDOUT_WORLD - synchronized standard
158:         output where only the first processor opens
159:         the file.  All other processors send their 
160:         data to the first processor to print. 
161: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

163:    The user can open alternative visualization contexts with
164: +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
165: .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
166:          specified file; corresponding input uses MatLoad()
167: .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to 
168:          an X window display
169: -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
170:          Currently only the sequential dense and AIJ
171:          matrix types support the Socket viewer.

173:    The user can call PetscViewerSetFormat() to specify the output
174:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
175:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
176: +    PETSC_VIEWER_ASCII_DEFAULT - default, prints matrix contents
177: .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
178: .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
179: .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse 
180:          format common among all matrix types
181: .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific 
182:          format (which is in many cases the same as the default)
183: .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
184:          size and structure (not the matrix entries)
185: -    PETSC_VIEWER_ASCII_INFO_LONG - prints more detailed information about
186:          the matrix structure

188:    Level: beginner

190:    Concepts: matrices^viewing
191:    Concepts: matrices^plotting
192:    Concepts: matrices^printing

194: .seealso: PetscViewerSetFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(), 
195:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
196: @*/
197: int MatView(Mat mat,PetscViewer viewer)
198: {
199:   int               ierr,rows,cols;
200:   PetscTruth        isascii;
201:   char              *cstr;
202:   PetscViewerFormat format;

207:   MatPreallocated(mat);
208:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(mat->comm);
211:   if (!mat->assembled) SETERRQ(1,"Must call MatAssemblyBegin/End() before viewing matrix");

213:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&isascii);
214:   if (isascii) {
215:     PetscViewerGetFormat(viewer,&format);
216:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_LONG) {
217:       if (mat->prefix) {
218:         PetscViewerASCIIPrintf(viewer,"Matrix Object:(%s)n",mat->prefix);
219:       } else {
220:         PetscViewerASCIIPrintf(viewer,"Matrix Object:n");
221:       }
222:       PetscViewerASCIIPushTab(viewer);
223:       MatGetType(mat,&cstr);
224:       MatGetSize(mat,&rows,&cols);
225:       PetscViewerASCIIPrintf(viewer,"type=%s, rows=%d, cols=%dn",cstr,rows,cols);
226:       if (mat->ops->getinfo) {
227:         MatInfo info;
228:         MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
229:         PetscViewerASCIIPrintf(viewer,"total: nonzeros=%d, allocated nonzeros=%dn",
230:                           (int)info.nz_used,(int)info.nz_allocated);
231:       }
232:     }
233:   }
234:   if (mat->ops->view) {
235:     PetscViewerASCIIPushTab(viewer);
236:     (*mat->ops->view)(mat,viewer);
237:     PetscViewerASCIIPopTab(viewer);
238:   } else if (!isascii) {
239:     SETERRQ1(1,"Viewer type %s not supported",((PetscObject)viewer)->type_name);
240:   }
241:   if (isascii) {
242:     PetscViewerGetFormat(viewer,&format);
243:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_LONG) {
244:       PetscViewerASCIIPopTab(viewer);
245:     }
246:   }
247:   return(0);
248: }

250: /*@C
251:    MatScaleSystem - Scale a vector solution and right hand side to 
252:    match the scaling of a scaled matrix.
253:   
254:    Collective on Mat

256:    Input Parameter:
257: +  mat - the matrix
258: .  x - solution vector (or PETSC_NULL)
259: +  b - right hand side vector (or PETSC_NULL)


262:    Notes: 
263:    For AIJ, BAIJ, and BDiag matrix formats, the matrices are not 
264:    internally scaled, so this does nothing. For MPIROWBS it
265:    permutes and diagonally scales.

267:    The SLES methods automatically call this routine when required
268:    (via PCPreSolve()) so it is rarely used directly.

270:    Level: Developer            

272:    Concepts: matrices^scaling

274: .seealso: MatUseScaledForm(), MatUnScaleSystem()
275: @*/
276: int MatScaleSystem(Mat mat,Vec x,Vec b)
277: {

283:   MatPreallocated(mat);

287:   if (mat->ops->scalesystem) {
288:     (*mat->ops->scalesystem)(mat,x,b);
289:   }
290:   return(0);
291: }

293: /*@C
294:    MatUnScaleSystem - Unscales a vector solution and right hand side to 
295:    match the original scaling of a scaled matrix.
296:   
297:    Collective on Mat

299:    Input Parameter:
300: +  mat - the matrix
301: .  x - solution vector (or PETSC_NULL)
302: +  b - right hand side vector (or PETSC_NULL)


305:    Notes: 
306:    For AIJ, BAIJ, and BDiag matrix formats, the matrices are not 
307:    internally scaled, so this does nothing. For MPIROWBS it
308:    permutes and diagonally scales.

310:    The SLES methods automatically call this routine when required
311:    (via PCPreSolve()) so it is rarely used directly.

313:    Level: Developer            

315: .seealso: MatUseScaledForm(), MatScaleSystem()
316: @*/
317: int MatUnScaleSystem(Mat mat,Vec x,Vec b)
318: {

324:   MatPreallocated(mat);
327:   if (mat->ops->unscalesystem) {
328:     (*mat->ops->unscalesystem)(mat,x,b);
329:   }
330:   return(0);
331: }

333: /*@C
334:    MatUseScaledForm - For matrix storage formats that scale the 
335:    matrix (for example MPIRowBS matrices are diagonally scaled on
336:    assembly) indicates matrix operations (MatMult() etc) are 
337:    applied using the scaled matrix.
338:   
339:    Collective on Mat

341:    Input Parameter:
342: +  mat - the matrix
343: -  scaled - PETSC_TRUE for applying the scaled, PETSC_FALSE for 
344:             applying the original matrix

346:    Notes: 
347:    For scaled matrix formats, applying the original, unscaled matrix
348:    will be slightly more expensive

350:    Level: Developer            

352: .seealso: MatScaleSystem(), MatUnScaleSystem()
353: @*/
354: int MatUseScaledForm(Mat mat,PetscTruth scaled)
355: {

361:   MatPreallocated(mat);
362:   if (mat->ops->usescaledform) {
363:     (*mat->ops->usescaledform)(mat,scaled);
364:   }
365:   return(0);
366: }

368: /*@C
369:    MatDestroy - Frees space taken by a matrix.
370:   
371:    Collective on Mat

373:    Input Parameter:
374: .  A - the matrix

376:    Level: beginner

378: @*/
379: int MatDestroy(Mat A)
380: {

386:   MatPreallocated(A);
387:   if (--A->refct > 0) return(0);

389:   /* if memory was published with AMS then destroy it */
390:   PetscObjectDepublish(A);
391:   if (A->mapping) {
392:     ISLocalToGlobalMappingDestroy(A->mapping);
393:   }
394:   if (A->bmapping) {
395:     ISLocalToGlobalMappingDestroy(A->bmapping);
396:   }
397:   if (A->rmap) {
398:     PetscMapDestroy(A->rmap);
399:   }
400:   if (A->cmap) {
401:     PetscMapDestroy(A->cmap);
402:   }

404:   (*A->ops->destroy)(A);
405:   PetscLogObjectDestroy(A);
406:   PetscHeaderDestroy(A);
407:   return(0);
408: }

410: /*@
411:    MatValid - Checks whether a matrix object is valid.

413:    Collective on Mat

415:    Input Parameter:
416: .  m - the matrix to check 

418:    Output Parameter:
419:    flg - flag indicating matrix status, either
420:    PETSC_TRUE if matrix is valid, or PETSC_FALSE otherwise.

422:    Level: developer

424:    Concepts: matrices^validity
425: @*/
426: int MatValid(Mat m,PetscTruth *flg)
427: {
430:   if (!m)                           *flg = PETSC_FALSE;
431:   else if (m->cookie != MAT_COOKIE) *flg = PETSC_FALSE;
432:   else                              *flg = PETSC_TRUE;
433:   return(0);
434: }

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

441:    Not Collective

443:    Input Parameters:
444: +  mat - the matrix
445: .  v - a logically two-dimensional array of values
446: .  m, idxm - the number of rows and their global indices 
447: .  n, idxn - the number of columns and their global indices
448: -  addv - either ADD_VALUES or INSERT_VALUES, where
449:    ADD_VALUES adds values to any existing entries, and
450:    INSERT_VALUES replaces existing entries with new values

452:    Notes:
453:    By default the values, v, are row-oriented and unsorted.
454:    See MatSetOption() for other options.

456:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES 
457:    options cannot be mixed without intervening calls to the assembly
458:    routines.

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

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

468:    Efficiency Alert:
469:    The routine MatSetValuesBlocked() may offer much better efficiency
470:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

472:    Level: beginner

474:    Concepts: matrices^putting entries in

476: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
477: @*/
478: int MatSetValues(Mat mat,int m,int *idxm,int n,int *idxn,PetscScalar *v,InsertMode addv)
479: {

483:   if (!m || !n) return(0); /* no values to insert */
486:   MatPreallocated(mat);
490:   if (mat->insertmode == NOT_SET_VALUES) {
491:     mat->insertmode = addv;
492:   }
493: #if defined(PETSC_USE_BOPT_g)
494:   else if (mat->insertmode != addv) {
495:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
496:   }
497:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
498: #endif

500:   if (mat->assembled) {
501:     mat->was_assembled = PETSC_TRUE;
502:     mat->assembled     = PETSC_FALSE;
503:   }
504:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
505:   if (!mat->ops->setvalues) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
506:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
507:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
508:   return(0);
509: }

511: /*@C 
512:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
513:      Using structured grid indexing

515:    Not Collective

517:    Input Parameters:
518: +  mat - the matrix
519: .  v - a logically two-dimensional array of values
520: .  m - number of rows being entered
521: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
522: .  n - number of columns being entered
523: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered 
524: -  addv - either ADD_VALUES or INSERT_VALUES, where
525:    ADD_VALUES adds values to any existing entries, and
526:    INSERT_VALUES replaces existing entries with new values

528:    Notes:
529:    By default the values, v, are row-oriented and unsorted.
530:    See MatSetOption() for other options.

532:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES 
533:    options cannot be mixed without intervening calls to the assembly
534:    routines.

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

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

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

544:    In Fortran idxm and idxn should be declared as
545: $     MatStencil idxm(4,m),idxn(4,n)
546:    and the values inserted using
547: $    idxm(MatStencil_i,1) = i
548: $    idxm(MatStencil_j,1) = j
549: $    idxm(MatStencil_k,1) = k
550: $    idxm(MatStencil_c,1) = c
551:    etc

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

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

561:    Efficiency Alert:
562:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
563:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

565:    Level: beginner

567:    Concepts: matrices^putting entries in

569: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
570:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DAGetMatrix()
571: @*/
572: int MatSetValuesStencil(Mat mat,int m,MatStencil *idxm,int n,MatStencil *idxn,PetscScalar *v,InsertMode addv)
573: {
574:   int j,i,ierr,jdxm[128],jdxn[256],dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
575:   int *starts = mat->stencil.starts,*dxm = (int*)idxm,*dxn = (int*)idxn,sdim = dim - (1 - (int)mat->stencil.noc);

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

585:   if (m > 128) SETERRQ1(1,"Can only set 128 rows at a time; trying to set %d",m);
586:   if (n > 128) SETERRQ1(1,"Can only set 256 columns at a time; trying to set %d",n);

588:   for (i=0; i<m; i++) {
589:     for (j=0; j<3-sdim; j++) dxm++;
590:     tmp = *dxm++ - starts[0];
591:     for (j=0; j<dim-1; j++) {
592:       tmp = tmp*dims[j] + *dxm++ - starts[j+1];
593:     }
594:     if (mat->stencil.noc) dxm++;
595:     jdxm[i] = tmp;
596:   }
597:   for (i=0; i<n; i++) {
598:     for (j=0; j<3-sdim; j++) dxn++;
599:     tmp = *dxn++ - starts[0];
600:     for (j=0; j<dim-1; j++) {
601:       tmp = tmp*dims[j] + *dxn++ - starts[j+1];
602:     }
603:     if (mat->stencil.noc) dxn++;
604:     jdxn[i] = tmp;
605:   }
606:   MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
607:   return(0);
608: }

610: /*@ 
611:    MatSetStencil - Sets the grid information for setting values into a matrix via
612:         MatSetStencil()

614:    Not Collective

616:    Input Parameters:
617: +  mat - the matrix
618: .  dim - dimension of the grid 1,2, or 3
619: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
620: .  starts - starting point of ghost nodes on your processor in x, y, and z direction 
621: -  dof - number of degrees of freedom per node


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

627:    Level: beginner

629:    Concepts: matrices^putting entries in

631: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
632:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
633: @*/
634: int MatSetStencil(Mat mat,int dim,int *dims,int *starts,int dof)
635: {
636:   int i;


643:   mat->stencil.dim = dim + (dof > 1);
644:   for (i=0; i<dim; i++) {
645:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
646:     mat->stencil.starts[i] = starts[dim-i-1];
647:   }
648:   mat->stencil.dims[dim]   = dof;
649:   mat->stencil.starts[dim] = 0;
650:   mat->stencil.noc         = (PetscTruth)(dof == 1);
651:   return(0);
652: }

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

657:    Not Collective

659:    Input Parameters:
660: +  mat - the matrix
661: .  v - a logically two-dimensional array of values
662: .  m, idxm - the number of block rows and their global block indices 
663: .  n, idxn - the number of block columns and their global block indices
664: -  addv - either ADD_VALUES or INSERT_VALUES, where
665:    ADD_VALUES adds values to any existing entries, and
666:    INSERT_VALUES replaces existing entries with new values

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

672:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES 
673:    options cannot be mixed without intervening calls to the assembly
674:    routines.

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

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

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

690:    Restrictions:
691:    MatSetValuesBlocked() is currently supported only for the block AIJ
692:    matrix format (MATSEQBAIJ and MATMPIBAIJ, which are created via
693:    MatCreateSeqBAIJ() and MatCreateMPIBAIJ()).

695:    Level: intermediate

697:    Concepts: matrices^putting entries in blocked

699: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
700: @*/
701: int MatSetValuesBlocked(Mat mat,int m,int *idxm,int n,int *idxn,PetscScalar *v,InsertMode addv)
702: {

706:   if (!m || !n) return(0); /* no values to insert */
709:   MatPreallocated(mat);
713:   if (mat->insertmode == NOT_SET_VALUES) {
714:     mat->insertmode = addv;
715:   }
716: #if defined(PETSC_USE_BOPT_g) 
717:   else if (mat->insertmode != addv) {
718:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
719:   }
720:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
721: #endif

723:   if (mat->assembled) {
724:     mat->was_assembled = PETSC_TRUE;
725:     mat->assembled     = PETSC_FALSE;
726:   }
727:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
728:   if (!mat->ops->setvaluesblocked) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
729:   (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
730:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
731:   return(0);
732: }

734: /*MC
735:    MatSetValue - Set a single entry into a matrix.

737:    Synopsis:
738:    int MatSetValue(Mat m,int row,int col,PetscScalar value,InsertMode mode);

740:    Not collective

742:    Input Parameters:
743: +  m - the matrix
744: .  row - the row location of the entry
745: .  col - the column location of the entry
746: .  value - the value to insert
747: -  mode - either INSERT_VALUES or ADD_VALUES

749:    Notes: 
750:    For efficiency one should use MatSetValues() and set several or many
751:    values simultaneously if possible.

753:    Note that VecSetValue() does NOT return an error code (since this
754:    is checked internally).

756:    Level: beginner

758: .seealso: MatSetValues()
759: M*/

761: /*@ 
762:    MatGetValues - Gets a block of values from a matrix.

764:    Not Collective; currently only returns a local block

766:    Input Parameters:
767: +  mat - the matrix
768: .  v - a logically two-dimensional array for storing the values
769: .  m, idxm - the number of rows and their global indices 
770: -  n, idxn - the number of columns and their global indices

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

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

780:    MatGetValues() requires that the matrix has been assembled
781:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
782:    MatSetValues() and MatGetValues() CANNOT be made in succession
783:    without intermediate matrix assembly.

785:    Level: advanced

787:    Concepts: matrices^accessing values

789: .seealso: MatGetRow(), MatGetSubmatrices(), MatSetValues()
790: @*/
791: int MatGetValues(Mat mat,int m,int *idxm,int n,int *idxn,PetscScalar *v)
792: {

798:   MatPreallocated(mat);
802:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
803:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
804:   if (!mat->ops->getvalues) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

806:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
807:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
808:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
809:   return(0);
810: }

812: /*@
813:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
814:    the routine MatSetValuesLocal() to allow users to insert matrix entries
815:    using a local (per-processor) numbering.

817:    Not Collective

819:    Input Parameters:
820: +  x - the matrix
821: -  mapping - mapping created with ISLocalToGlobalMappingCreate() 
822:              or ISLocalToGlobalMappingCreateIS()

824:    Level: intermediate

826:    Concepts: matrices^local to global mapping
827:    Concepts: local to global mapping^for matrices

829: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
830: @*/
831: int MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping mapping)
832: {
837:   MatPreallocated(x);
839:   if (x->mapping) {
840:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Mapping already set for matrix");
841:   }

843:   if (x->ops->setlocaltoglobalmapping) {
844:     (*x->ops->setlocaltoglobalmapping)(x,mapping);
845:   } else {
846:     x->mapping = mapping;
847:     PetscObjectReference((PetscObject)mapping);
848:   }
849:   return(0);
850: }

852: /*@
853:    MatSetLocalToGlobalMappingBlock - Sets a local-to-global numbering for use
854:    by the routine MatSetValuesBlockedLocal() to allow users to insert matrix
855:    entries using a local (per-processor) numbering.

857:    Not Collective

859:    Input Parameters:
860: +  x - the matrix
861: -  mapping - mapping created with ISLocalToGlobalMappingCreate() or
862:              ISLocalToGlobalMappingCreateIS()

864:    Level: intermediate

866:    Concepts: matrices^local to global mapping blocked
867:    Concepts: local to global mapping^for matrices, blocked

869: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal(),
870:            MatSetValuesBlocked(), MatSetValuesLocal()
871: @*/
872: int MatSetLocalToGlobalMappingBlock(Mat x,ISLocalToGlobalMapping mapping)
873: {
878:   MatPreallocated(x);
880:   if (x->bmapping) {
881:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Mapping already set for matrix");
882:   }
883: 
884:   x->bmapping = mapping;
885:   PetscObjectReference((PetscObject)mapping);
886:   return(0);
887: }

889: /*@
890:    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
891:    using a local ordering of the nodes. 

893:    Not Collective

895:    Input Parameters:
896: +  x - the matrix
897: .  nrow, irow - number of rows and their local indices
898: .  ncol, icol - number of columns and their local indices
899: .  y -  a logically two-dimensional array of values
900: -  addv - either INSERT_VALUES or ADD_VALUES, where
901:    ADD_VALUES adds values to any existing entries, and
902:    INSERT_VALUES replaces existing entries with new values

904:    Notes:
905:    Before calling MatSetValuesLocal(), the user must first set the
906:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

908:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES 
909:    options cannot be mixed without intervening calls to the assembly
910:    routines.

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

915:    Level: intermediate

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

919: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
920:            MatSetValueLocal()
921: @*/
922: int MatSetValuesLocal(Mat mat,int nrow,int *irow,int ncol,int *icol,PetscScalar *y,InsertMode addv)
923: {
924:   int ierr,irowm[2048],icolm[2048];

929:   MatPreallocated(mat);

934:   if (mat->insertmode == NOT_SET_VALUES) {
935:     mat->insertmode = addv;
936:   }
937: #if defined(PETSC_USE_BOPT_g) 
938:   else if (mat->insertmode != addv) {
939:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
940:   }
941:   if (!mat->ops->setvalueslocal && (nrow > 2048 || ncol > 2048)) {
942:     SETERRQ2(PETSC_ERR_SUP,"Number column/row indices must be <= 2048: are %d %d",nrow,ncol);
943:   }
944:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
945: #endif

947:   if (mat->assembled) {
948:     mat->was_assembled = PETSC_TRUE;
949:     mat->assembled     = PETSC_FALSE;
950:   }
951:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
952:   if (!mat->ops->setvalueslocal) {
953:     ISLocalToGlobalMappingApply(mat->mapping,nrow,irow,irowm);
954:     ISLocalToGlobalMappingApply(mat->mapping,ncol,icol,icolm);
955:     (*mat->ops->setvalues)(mat,nrow,irowm,ncol,icolm,y,addv);
956:   } else {
957:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
958:   }
959:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
960:   return(0);
961: }

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

967:    Not Collective

969:    Input Parameters:
970: +  x - the matrix
971: .  nrow, irow - number of rows and their local indices
972: .  ncol, icol - number of columns and their local indices
973: .  y -  a logically two-dimensional array of values
974: -  addv - either INSERT_VALUES or ADD_VALUES, where
975:    ADD_VALUES adds values to any existing entries, and
976:    INSERT_VALUES replaces existing entries with new values

978:    Notes:
979:    Before calling MatSetValuesBlockedLocal(), the user must first set the
980:    local-to-global mapping by calling MatSetLocalToGlobalMappingBlock(),
981:    where the mapping MUST be set for matrix blocks, not for matrix elements.

983:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES 
984:    options cannot be mixed without intervening calls to the assembly
985:    routines.

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

990:    Level: intermediate

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

994: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesLocal(), MatSetLocalToGlobalMappingBlock(), MatSetValuesBlocked()
995: @*/
996: int MatSetValuesBlockedLocal(Mat mat,int nrow,int *irow,int ncol,int *icol,PetscScalar *y,InsertMode addv)
997: {
998:   int ierr,irowm[2048],icolm[2048];

1003:   MatPreallocated(mat);
1007:   if (mat->insertmode == NOT_SET_VALUES) {
1008:     mat->insertmode = addv;
1009:   }
1010: #if defined(PETSC_USE_BOPT_g) 
1011:   else if (mat->insertmode != addv) {
1012:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1013:   }
1014:   if (!mat->bmapping) {
1015:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Local to global never set with MatSetLocalToGlobalMappingBlock()");
1016:   }
1017:   if (nrow > 2048 || ncol > 2048) {
1018:     SETERRQ2(PETSC_ERR_SUP,"Number column/row indices must be <= 2048: are %d %d",nrow,ncol);
1019:   }
1020:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1021: #endif

1023:   if (mat->assembled) {
1024:     mat->was_assembled = PETSC_TRUE;
1025:     mat->assembled     = PETSC_FALSE;
1026:   }
1027:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1028:   ISLocalToGlobalMappingApply(mat->bmapping,nrow,irow,irowm);
1029:   ISLocalToGlobalMappingApply(mat->bmapping,ncol,icol,icolm);
1030:   (*mat->ops->setvaluesblocked)(mat,nrow,irowm,ncol,icolm,y,addv);
1031:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1032:   return(0);
1033: }

1035: /* --------------------------------------------------------*/
1036: /*@
1037:    MatMult - Computes the matrix-vector product, y = Ax.

1039:    Collective on Mat and Vec

1041:    Input Parameters:
1042: +  mat - the matrix
1043: -  x   - the vector to be multilplied

1045:    Output Parameters:
1046: .  y - the result

1048:    Notes:
1049:    The vectors x and y cannot be the same.  I.e., one cannot
1050:    call MatMult(A,y,y).

1052:    Level: beginner

1054:    Concepts: matrix-vector product

1056: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
1057: @*/
1058: int MatMult(Mat mat,Vec x,Vec y)
1059: {

1065:   MatPreallocated(mat);

1069:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1070:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1071:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1072: #ifndef PETSC_HAVE_CONSTRAINTS
1073:   if (mat->N != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
1074:   if (mat->M != y->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %d %d",mat->M,y->N);
1075:   if (mat->m != y->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %d %d",mat->m,y->n);
1076: #endif

1078:   if (mat->nullsp) {
1079:     MatNullSpaceRemove(mat->nullsp,x,&x);
1080:   }

1082:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
1083:   (*mat->ops->mult)(mat,x,y);
1084:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);

1086:   if (mat->nullsp) {
1087:     MatNullSpaceRemove(mat->nullsp,y,PETSC_NULL);
1088:   }
1089:   return(0);
1090: }

1092: /*@
1093:    MatMultTranspose - Computes matrix transpose times a vector.

1095:    Collective on Mat and Vec

1097:    Input Parameters:
1098: +  mat - the matrix
1099: -  x   - the vector to be multilplied

1101:    Output Parameters:
1102: .  y - the result

1104:    Notes:
1105:    The vectors x and y cannot be the same.  I.e., one cannot
1106:    call MatMultTranspose(A,y,y).

1108:    Level: beginner

1110:    Concepts: matrix vector product^transpose

1112: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd()
1113: @*/
1114: int MatMultTranspose(Mat mat,Vec x,Vec y)
1115: {

1121:   MatPreallocated(mat);

1125:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1126:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1127:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1128: #ifndef PETSC_HAVE_CONSTRAINTS
1129:   if (mat->M != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->M,x->N);
1130:   if (mat->N != y->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %d %d",mat->N,y->N);
1131: #endif

1133:   if (!mat->ops->multtranspose) SETERRQ(PETSC_ERR_SUP, "Operation not supported");
1134:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
1135:   if (!mat->ops->multtranspose) SETERRQ(PETSC_ERR_SUP,"This matrix type does not have a multiply tranpose defined");
1136:   (*mat->ops->multtranspose)(mat,x,y);
1137:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
1138:   return(0);
1139: }

1141: /*@
1142:     MatMultAdd -  Computes v3 = v2 + A * v1.

1144:     Collective on Mat and Vec

1146:     Input Parameters:
1147: +   mat - the matrix
1148: -   v1, v2 - the vectors

1150:     Output Parameters:
1151: .   v3 - the result

1153:     Notes:
1154:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
1155:     call MatMultAdd(A,v1,v2,v1).

1157:     Level: beginner

1159:     Concepts: matrix vector product^addition

1161: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
1162: @*/
1163: int MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
1164: {

1170:   MatPreallocated(mat);

1175:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1176:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1177:   if (mat->N != v1->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %d %d",mat->N,v1->N);
1178:   if (mat->M != v2->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %d %d",mat->M,v2->N);
1179:   if (mat->M != v3->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %d %d",mat->M,v3->N);
1180:   if (mat->m != v3->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: local dim %d %d",mat->m,v3->n);
1181:   if (mat->m != v2->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: local dim %d %d",mat->m,v2->n);
1182:   if (v1 == v3) SETERRQ(PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");

1184:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
1185:   (*mat->ops->multadd)(mat,v1,v2,v3);
1186:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
1187:   return(0);
1188: }

1190: /*@
1191:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

1193:    Collective on Mat and Vec

1195:    Input Parameters:
1196: +  mat - the matrix
1197: -  v1, v2 - the vectors

1199:    Output Parameters:
1200: .  v3 - the result

1202:    Notes:
1203:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
1204:    call MatMultTransposeAdd(A,v1,v2,v1).

1206:    Level: beginner

1208:    Concepts: matrix vector product^transpose and addition

1210: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
1211: @*/
1212: int MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
1213: {

1219:   MatPreallocated(mat);

1224:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1225:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1226:   if (!mat->ops->multtransposeadd) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1227:   if (v1 == v3) SETERRQ(PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
1228:   if (mat->M != v1->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %d %d",mat->M,v1->N);
1229:   if (mat->N != v2->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %d %d",mat->N,v2->N);
1230:   if (mat->N != v3->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %d %d",mat->N,v3->N);

1232:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
1233:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
1234:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
1235:   return(0);
1236: }

1238: /*@
1239:    MatMultConstrained - The inner multiplication routine for a
1240:    constrained matrix P^T A P.

1242:    Collective on Mat and Vec

1244:    Input Parameters:
1245: +  mat - the matrix
1246: -  x   - the vector to be multilplied

1248:    Output Parameters:
1249: .  y - the result

1251:    Notes:
1252:    The vectors x and y cannot be the same.  I.e., one cannot
1253:    call MatMult(A,y,y).

1255:    Level: beginner

1257: .keywords: matrix, multiply, matrix-vector product, constraint
1258: .seealso: MatMult(), MatMultTrans(), MatMultAdd(), MatMultTransAdd()
1259: @*/
1260: int MatMultConstrained(Mat mat,Vec x,Vec y)
1261: {

1267:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1268:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1269:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1270:   if (mat->N != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
1271:   if (mat->M != y->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %d %d",mat->M,y->N);
1272:   if (mat->m != y->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %d %d",mat->m,y->n);

1274:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
1275:   (*mat->ops->multconstrained)(mat,x,y);
1276:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);

1278:   return(0);
1279: }

1281: /*@
1282:    MatMultTransposeConstrained - The inner multiplication routine for a
1283:    constrained matrix P^T A^T P.

1285:    Collective on Mat and Vec

1287:    Input Parameters:
1288: +  mat - the matrix
1289: -  x   - the vector to be multilplied

1291:    Output Parameters:
1292: .  y - the result

1294:    Notes:
1295:    The vectors x and y cannot be the same.  I.e., one cannot
1296:    call MatMult(A,y,y).

1298:    Level: beginner

1300: .keywords: matrix, multiply, matrix-vector product, constraint
1301: .seealso: MatMult(), MatMultTrans(), MatMultAdd(), MatMultTransAdd()
1302: @*/
1303: int MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
1304: {

1310:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1311:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1312:   if (x == y) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
1313:   if (mat->M != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
1314:   if (mat->N != y->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %d %d",mat->M,y->N);

1316:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
1317:   (*mat->ops->multtransposeconstrained)(mat,x,y);
1318:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);

1320:   return(0);
1321: }
1322: /* ------------------------------------------------------------*/
1323: /*@C
1324:    MatGetInfo - Returns information about matrix storage (number of
1325:    nonzeros, memory, etc.).

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

1330:    Input Parameters:
1331: .  mat - the matrix

1333:    Output Parameters:
1334: +  flag - flag indicating the type of parameters to be returned
1335:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
1336:    MAT_GLOBAL_SUM - sum over all processors)
1337: -  info - matrix information context

1339:    Notes:
1340:    The MatInfo context contains a variety of matrix data, including
1341:    number of nonzeros allocated and used, number of mallocs during
1342:    matrix assembly, etc.  Additional information for factored matrices
1343:    is provided (such as the fill ratio, number of mallocs during
1344:    factorization, etc.).  Much of this info is printed to STDOUT
1345:    when using the runtime options 
1346: $       -log_info -mat_view_info

1348:    Example for C/C++ Users:
1349:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
1350:    data within the MatInfo context.  For example, 
1351: .vb
1352:       MatInfo info;
1353:       Mat     A;
1354:       double  mal, nz_a, nz_u;

1356:       MatGetInfo(A,MAT_LOCAL,&info);
1357:       mal  = info.mallocs;
1358:       nz_a = info.nz_allocated;
1359: .ve

1361:    Example for Fortran Users:
1362:    Fortran users should declare info as a double precision
1363:    array of dimension MAT_INFO_SIZE, and then extract the parameters
1364:    of interest.  See the file ${PETSC_DIR}/include/finclude/petscmat.h
1365:    a complete list of parameter names.
1366: .vb
1367:       double  precision info(MAT_INFO_SIZE)
1368:       double  precision mal, nz_a
1369:       Mat     A
1370:       integer ierr

1372:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
1373:       mal = info(MAT_INFO_MALLOCS)
1374:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
1375: .ve

1377:     Level: intermediate

1379:     Concepts: matrices^getting information on
1380:  
1381: @*/
1382: int MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
1383: {

1389:   MatPreallocated(mat);
1391:   if (!mat->ops->getinfo) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1392:   (*mat->ops->getinfo)(mat,flag,info);
1393:   return(0);
1394: }

1396: /* ----------------------------------------------------------*/
1397: /*@C  
1398:    MatILUDTFactor - Performs a drop tolerance ILU factorization.

1400:    Collective on Mat

1402:    Input Parameters:
1403: +  mat - the matrix
1404: .  info - information about the factorization to be done
1405: .  row - row permutation
1406: -  col - column permutation

1408:    Output Parameters:
1409: .  fact - the factored matrix

1411:    Level: developer

1413:    Notes:
1414:    Most users should employ the simplified SLES interface for linear solvers
1415:    instead of working directly with matrix algebra routines such as this.
1416:    See, e.g., SLESCreate().

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

1423:     Concepts: matrices^ILUDT factorization

1425: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatILUInfo
1426: @*/
1427: int MatILUDTFactor(Mat mat,MatILUInfo *info,IS row,IS col,Mat *fact)
1428: {

1434:   MatPreallocated(mat);
1436:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1437:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1438:   if (!mat->ops->iludtfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

1440:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
1441:   (*mat->ops->iludtfactor)(mat,info,row,col,fact);
1442:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);

1444:   return(0);
1445: }

1447: /*@  
1448:    MatLUFactor - Performs in-place LU factorization of matrix.

1450:    Collective on Mat

1452:    Input Parameters:
1453: +  mat - the matrix
1454: .  row - row permutation
1455: .  col - column permutation
1456: -  info - options for factorization, includes 
1457: $          fill - expected fill as ratio of original fill.
1458: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
1459: $                   Run with the option -log_info to determine an optimal value to use

1461:    Notes:
1462:    Most users should employ the simplified SLES interface for linear solvers
1463:    instead of working directly with matrix algebra routines such as this.
1464:    See, e.g., SLESCreate().

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

1469:    Level: developer

1471:    Concepts: matrices^LU factorization

1473: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
1474:           MatGetOrdering(), MatSetUnfactored(), MatLUInfo

1476: @*/
1477: int MatLUFactor(Mat mat,IS row,IS col,MatLUInfo *info)
1478: {

1484:   MatPreallocated(mat);
1485:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1486:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1487:   if (!mat->ops->lufactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

1489:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
1490:   (*mat->ops->lufactor)(mat,row,col,info);
1491:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
1492:   return(0);
1493: }

1495: /*@  
1496:    MatILUFactor - Performs in-place ILU factorization of matrix.

1498:    Collective on Mat

1500:    Input Parameters:
1501: +  mat - the matrix
1502: .  row - row permutation
1503: .  col - column permutation
1504: -  info - structure containing 
1505: $      levels - number of levels of fill.
1506: $      expected fill - as ratio of original fill.
1507: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
1508:                 missing diagonal entries)

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

1514:    Most users should employ the simplified SLES interface for linear solvers
1515:    instead of working directly with matrix algebra routines such as this.
1516:    See, e.g., SLESCreate().

1518:    Level: developer

1520:    Concepts: matrices^ILU factorization

1522: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatILUInfo
1523: @*/
1524: int MatILUFactor(Mat mat,IS row,IS col,MatILUInfo *info)
1525: {

1531:   MatPreallocated(mat);
1532:   if (mat->M != mat->N) SETERRQ(PETSC_ERR_ARG_WRONG,"matrix must be square");
1533:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1534:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1535:   if (!mat->ops->ilufactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

1537:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
1538:   (*mat->ops->ilufactor)(mat,row,col,info);
1539:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
1540:   return(0);
1541: }

1543: /*@  
1544:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
1545:    Call this routine before calling MatLUFactorNumeric().

1547:    Collective on Mat

1549:    Input Parameters:
1550: +  mat - the matrix
1551: .  row, col - row and column permutations
1552: -  info - options for factorization, includes 
1553: $          fill - expected fill as ratio of original fill.
1554: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
1555: $                   Run with the option -log_info to determine an optimal value to use

1557:    Output Parameter:
1558: .  fact - new matrix that has been symbolically factored

1560:    Notes:
1561:    See the users manual for additional information about
1562:    choosing the fill factor for better efficiency.

1564:    Most users should employ the simplified SLES interface for linear solvers
1565:    instead of working directly with matrix algebra routines such as this.
1566:    See, e.g., SLESCreate().

1568:    Level: developer

1570:    Concepts: matrices^LU symbolic factorization

1572: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatLUInfo
1573: @*/
1574: int MatLUFactorSymbolic(Mat mat,IS row,IS col,MatLUInfo *info,Mat *fact)
1575: {

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

1589:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
1590:   (*mat->ops->lufactorsymbolic)(mat,row,col,info,fact);
1591:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
1592:   return(0);
1593: }

1595: /*@  
1596:    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
1597:    Call this routine after first calling MatLUFactorSymbolic().

1599:    Collective on Mat

1601:    Input Parameters:
1602: +  mat - the matrix
1603: -  fact - the matrix generated for the factor, from MatLUFactorSymbolic()

1605:    Notes:
1606:    See MatLUFactor() for in-place factorization.  See 
1607:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.  

1609:    Most users should employ the simplified SLES interface for linear solvers
1610:    instead of working directly with matrix algebra routines such as this.
1611:    See, e.g., SLESCreate().

1613:    Level: developer

1615:    Concepts: matrices^LU numeric factorization

1617: .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
1618: @*/
1619: int MatLUFactorNumeric(Mat mat,Mat *fact)
1620: {
1621:   int        ierr;
1622:   PetscTruth flg;

1627:   MatPreallocated(mat);
1630:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1631:   if (mat->M != (*fact)->M || mat->N != (*fact)->N) {
1632:     SETERRQ4(PETSC_ERR_ARG_SIZ,"Mat mat,Mat *fact: global dimensions are different %d should = %d %d should = %d",
1633:             mat->M,(*fact)->M,mat->N,(*fact)->N);
1634:   }
1635:   if (!(*fact)->ops->lufactornumeric) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

1637:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,*fact,0,0);
1638:   (*(*fact)->ops->lufactornumeric)(mat,fact);
1639:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,*fact,0,0);
1640:   PetscOptionsHasName(PETSC_NULL,"-mat_view_draw",&flg);
1641:   if (flg) {
1642:     PetscOptionsHasName(PETSC_NULL,"-mat_view_contour",&flg);
1643:     if (flg) {
1644:       PetscViewerPushFormat(PETSC_VIEWER_DRAW_(mat->comm),PETSC_VIEWER_DRAW_CONTOUR);
1645:     }
1646:     MatView(*fact,PETSC_VIEWER_DRAW_(mat->comm));
1647:     PetscViewerFlush(PETSC_VIEWER_DRAW_(mat->comm));
1648:     if (flg) {
1649:       PetscViewerPopFormat(PETSC_VIEWER_DRAW_(mat->comm));
1650:     }
1651:   }
1652:   return(0);
1653: }

1655: /*@  
1656:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
1657:    symmetric matrix. 

1659:    Collective on Mat

1661:    Input Parameters:
1662: +  mat - the matrix
1663: .  perm - row and column permutations
1664: -  f - expected fill as ratio of original fill

1666:    Notes:
1667:    See MatLUFactor() for the nonsymmetric case.  See also
1668:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

1670:    Most users should employ the simplified SLES interface for linear solvers
1671:    instead of working directly with matrix algebra routines such as this.
1672:    See, e.g., SLESCreate().

1674:    Level: developer

1676:    Concepts: matrices^Cholesky factorization

1678: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
1679:           MatGetOrdering()

1681: @*/
1682: int MatCholeskyFactor(Mat mat,IS perm,PetscReal f)
1683: {

1689:   MatPreallocated(mat);
1691:   if (mat->M != mat->N) SETERRQ(PETSC_ERR_ARG_WRONG,"Matrix must be square");
1692:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1693:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1694:   if (!mat->ops->choleskyfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

1696:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
1697:   (*mat->ops->choleskyfactor)(mat,perm,f);
1698:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
1699:   return(0);
1700: }

1702: /*@  
1703:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
1704:    of a symmetric matrix. 

1706:    Collective on Mat

1708:    Input Parameters:
1709: +  mat - the matrix
1710: .  perm - row and column permutations
1711: -  f - expected fill as ratio of original

1713:    Output Parameter:
1714: .  fact - the factored matrix

1716:    Notes:
1717:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
1718:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

1720:    Most users should employ the simplified SLES interface for linear solvers
1721:    instead of working directly with matrix algebra routines such as this.
1722:    See, e.g., SLESCreate().

1724:    Level: developer

1726:    Concepts: matrices^Cholesky symbolic factorization

1728: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
1729:           MatGetOrdering()

1731: @*/
1732: int MatCholeskyFactorSymbolic(Mat mat,IS perm,PetscReal f,Mat *fact)
1733: {

1739:   MatPreallocated(mat);
1741:   if (mat->M != mat->N) SETERRQ(PETSC_ERR_ARG_WRONG,"Matrix must be square");
1742:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1743:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1744:   if (!mat->ops->choleskyfactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

1746:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
1747:   (*mat->ops->choleskyfactorsymbolic)(mat,perm,f,fact);
1748:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
1749:   return(0);
1750: }

1752: /*@  
1753:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
1754:    of a symmetric matrix. Call this routine after first calling
1755:    MatCholeskyFactorSymbolic().

1757:    Collective on Mat

1759:    Input Parameter:
1760: .  mat - the initial matrix

1762:    Output Parameter:
1763: .  fact - the factored matrix

1765:    Notes:
1766:    Most users should employ the simplified SLES interface for linear solvers
1767:    instead of working directly with matrix algebra routines such as this.
1768:    See, e.g., SLESCreate().

1770:    Level: developer

1772:    Concepts: matrices^Cholesky numeric factorization

1774: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
1775: @*/
1776: int MatCholeskyFactorNumeric(Mat mat,Mat *fact)
1777: {

1783:   MatPreallocated(mat);
1785:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1786:   if (!(*fact)->ops->choleskyfactornumeric) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1787:   if (mat->M != (*fact)->M || mat->N != (*fact)->N) {
1788:     SETERRQ4(PETSC_ERR_ARG_SIZ,"Mat mat,Mat *fact: global dim %d should = %d %d should = %d",
1789:             mat->M,(*fact)->M,mat->N,(*fact)->N);
1790:   }

1792:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,*fact,0,0);
1793:   (*(*fact)->ops->choleskyfactornumeric)(mat,fact);
1794:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,*fact,0,0);
1795:   return(0);
1796: }

1798: /* ----------------------------------------------------------------*/
1799: /*@
1800:    MatSolve - Solves A x = b, given a factored matrix.

1802:    Collective on Mat and Vec

1804:    Input Parameters:
1805: +  mat - the factored matrix
1806: -  b - the right-hand-side vector

1808:    Output Parameter:
1809: .  x - the result vector

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

1815:    Notes:
1816:    Most users should employ the simplified SLES interface for linear solvers
1817:    instead of working directly with matrix algebra routines such as this.
1818:    See, e.g., SLESCreate().

1820:    Level: developer

1822:    Concepts: matrices^triangular solves

1824: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
1825: @*/
1826: int MatSolve(Mat mat,Vec b,Vec x)
1827: {

1833:   MatPreallocated(mat);
1838:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
1839:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
1840:   if (mat->N != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
1841:   if (mat->M != b->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %d %d",mat->M,b->N);
1842:   if (mat->m != b->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %d %d",mat->m,b->n);
1843:   if (mat->M == 0 && mat->N == 0) return(0);

1845:   if (!mat->ops->solve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1846:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
1847:   (*mat->ops->solve)(mat,b,x);
1848:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
1849:   return(0);
1850: }

1852: /* @
1853:    MatForwardSolve - Solves L x = b, given a factored matrix, A = LU.

1855:    Collective on Mat and Vec

1857:    Input Parameters:
1858: +  mat - the factored matrix
1859: -  b - the right-hand-side vector

1861:    Output Parameter:
1862: .  x - the result vector

1864:    Notes:
1865:    MatSolve() should be used for most applications, as it performs
1866:    a forward solve followed by a backward solve.

1868:    The vectors b and x cannot be the same.  I.e., one cannot
1869:    call MatForwardSolve(A,x,x).

1871:    Most users should employ the simplified SLES interface for linear solvers
1872:    instead of working directly with matrix algebra routines such as this.
1873:    See, e.g., SLESCreate().

1875:    Level: developer

1877:    Concepts: matrices^forward solves

1879: .seealso: MatSolve(), MatBackwardSolve()
1880: @ */
1881: int MatForwardSolve(Mat mat,Vec b,Vec x)
1882: {

1888:   MatPreallocated(mat);
1893:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
1894:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
1895:   if (!mat->ops->forwardsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1896:   if (mat->N != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
1897:   if (mat->M != b->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %d %d",mat->M,b->N);
1898:   if (mat->m != b->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %d %d",mat->m,b->n);

1900:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
1901:   (*mat->ops->forwardsolve)(mat,b,x);
1902:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
1903:   return(0);
1904: }

1906: /* @
1907:    MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.

1909:    Collective on Mat and Vec

1911:    Input Parameters:
1912: +  mat - the factored matrix
1913: -  b - the right-hand-side vector

1915:    Output Parameter:
1916: .  x - the result vector

1918:    Notes:
1919:    MatSolve() should be used for most applications, as it performs
1920:    a forward solve followed by a backward solve.

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

1925:    Most users should employ the simplified SLES interface for linear solvers
1926:    instead of working directly with matrix algebra routines such as this.
1927:    See, e.g., SLESCreate().

1929:    Level: developer

1931:    Concepts: matrices^backward solves

1933: .seealso: MatSolve(), MatForwardSolve()
1934: @ */
1935: int MatBackwardSolve(Mat mat,Vec b,Vec x)
1936: {

1942:   MatPreallocated(mat);
1947:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
1948:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
1949:   if (!mat->ops->backwardsolve) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
1950:   if (mat->N != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
1951:   if (mat->M != b->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %d %d",mat->M,b->N);
1952:   if (mat->m != b->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %d %d",mat->m,b->n);

1954:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
1955:   (*mat->ops->backwardsolve)(mat,b,x);
1956:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
1957:   return(0);
1958: }

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

1963:    Collective on Mat and Vec

1965:    Input Parameters:
1966: +  mat - the factored matrix
1967: .  b - the right-hand-side vector
1968: -  y - the vector to be added to 

1970:    Output Parameter:
1971: .  x - the result vector

1973:    Notes:
1974:    The vectors b and x cannot be the same.  I.e., one cannot
1975:    call MatSolveAdd(A,x,y,x).

1977:    Most users should employ the simplified SLES interface for linear solvers
1978:    instead of working directly with matrix algebra routines such as this.
1979:    See, e.g., SLESCreate().

1981:    Level: developer

1983:    Concepts: matrices^triangular solves

1985: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
1986: @*/
1987: int MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
1988: {
1989:   PetscScalar one = 1.0;
1990:   Vec    tmp;
1991:   int    ierr;

1996:   MatPreallocated(mat);
2003:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2004:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2005:   if (mat->N != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
2006:   if (mat->M != b->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %d %d",mat->M,b->N);
2007:   if (mat->M != y->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %d %d",mat->M,y->N);
2008:   if (mat->m != b->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %d %d",mat->m,b->n);
2009:   if (x->n != y->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %d %d",x->n,y->n);

2011:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
2012:   if (mat->ops->solveadd)  {
2013:     (*mat->ops->solveadd)(mat,b,y,x);
2014:   } else {
2015:     /* do the solve then the add manually */
2016:     if (x != y) {
2017:       MatSolve(mat,b,x);
2018:       VecAXPY(&one,y,x);
2019:     } else {
2020:       VecDuplicate(x,&tmp);
2021:       PetscLogObjectParent(mat,tmp);
2022:       VecCopy(x,tmp);
2023:       MatSolve(mat,b,x);
2024:       VecAXPY(&one,tmp,x);
2025:       VecDestroy(tmp);
2026:     }
2027:   }
2028:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
2029:   return(0);
2030: }

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

2035:    Collective on Mat and Vec

2037:    Input Parameters:
2038: +  mat - the factored matrix
2039: -  b - the right-hand-side vector

2041:    Output Parameter:
2042: .  x - the result vector

2044:    Notes:
2045:    The vectors b and x cannot be the same.  I.e., one cannot
2046:    call MatSolveTranspose(A,x,x).

2048:    Most users should employ the simplified SLES interface for linear solvers
2049:    instead of working directly with matrix algebra routines such as this.
2050:    See, e.g., SLESCreate().

2052:    Level: developer

2054:    Concepts: matrices^triangular solves

2056: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
2057: @*/
2058: int MatSolveTranspose(Mat mat,Vec b,Vec x)
2059: {

2065:   MatPreallocated(mat);
2070:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2071:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2072:   if (!mat->ops->solvetranspose) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s",mat->type_name);
2073:   if (mat->M != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->M,x->N);
2074:   if (mat->N != b->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %d %d",mat->N,b->N);

2076:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
2077:   (*mat->ops->solvetranspose)(mat,b,x);
2078:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
2079:   return(0);
2080: }

2082: /*@
2083:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a 
2084:                       factored matrix. 

2086:    Collective on Mat and Vec

2088:    Input Parameters:
2089: +  mat - the factored matrix
2090: .  b - the right-hand-side vector
2091: -  y - the vector to be added to 

2093:    Output Parameter:
2094: .  x - the result vector

2096:    Notes:
2097:    The vectors b and x cannot be the same.  I.e., one cannot
2098:    call MatSolveTransposeAdd(A,x,y,x).

2100:    Most users should employ the simplified SLES interface for linear solvers
2101:    instead of working directly with matrix algebra routines such as this.
2102:    See, e.g., SLESCreate().

2104:    Level: developer

2106:    Concepts: matrices^triangular solves

2108: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
2109: @*/
2110: int MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
2111: {
2112:   PetscScalar one = 1.0;
2113:   int         ierr;
2114:   Vec         tmp;

2119:   MatPreallocated(mat);
2126:   if (x == b) SETERRQ(PETSC_ERR_ARG_IDN,"x and b must be different vectors");
2127:   if (!mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
2128:   if (mat->M != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->M,x->N);
2129:   if (mat->N != b->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %d %d",mat->N,b->N);
2130:   if (mat->N != y->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %d %d",mat->N,y->N);
2131:   if (x->n != y->n)   SETERRQ2(PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %d %d",x->n,y->n);

2133:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
2134:   if (mat->ops->solvetransposeadd) {
2135:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
2136:   } else {
2137:     /* do the solve then the add manually */
2138:     if (x != y) {
2139:       MatSolveTranspose(mat,b,x);
2140:       VecAXPY(&one,y,x);
2141:     } else {
2142:       VecDuplicate(x,&tmp);
2143:       PetscLogObjectParent(mat,tmp);
2144:       VecCopy(x,tmp);
2145:       MatSolveTranspose(mat,b,x);
2146:       VecAXPY(&one,tmp,x);
2147:       VecDestroy(tmp);
2148:     }
2149:   }
2150:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
2151:   return(0);
2152: }
2153: /* ----------------------------------------------------------------*/

2155: /*@
2156:    MatRelax - Computes one relaxation sweep.

2158:    Collective on Mat and Vec

2160:    Input Parameters:
2161: +  mat - the matrix
2162: .  b - the right hand side
2163: .  omega - the relaxation factor
2164: .  flag - flag indicating the type of SOR (see below)
2165: .  shift -  diagonal shift
2166: -  its - the number of iterations
2167: -  lits - the number of local iterations 

2169:    Output Parameters:
2170: .  x - the solution (can contain an initial guess)

2172:    SOR Flags:
2173: .     SOR_FORWARD_SWEEP - forward SOR
2174: .     SOR_BACKWARD_SWEEP - backward SOR
2175: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
2176: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR 
2177: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR 
2178: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
2179: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies 
2180:          upper/lower triangular part of matrix to
2181:          vector (with omega)
2182: .     SOR_ZERO_INITIAL_GUESS - zero initial guess

2184:    Notes:
2185:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
2186:    SOR_LOCAL_SYMMETRIC_SWEEP perform seperate independent smoothings
2187:    on each processor. 

2189:    Application programmers will not generally use MatRelax() directly,
2190:    but instead will employ the SLES/PC interface.

2192:    Notes for Advanced Users:
2193:    The flags are implemented as bitwise inclusive or operations.
2194:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
2195:    to specify a zero initial guess for SSOR.

2197:    Most users should employ the simplified SLES interface for linear solvers
2198:    instead of working directly with matrix algebra routines such as this.
2199:    See, e.g., SLESCreate().

2201:    Level: developer

2203:    Concepts: matrices^relaxation
2204:    Concepts: matrices^SOR
2205:    Concepts: matrices^Gauss-Seidel

2207: @*/
2208: int MatRelax(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,int its,int lits,Vec x)
2209: {

2215:   MatPreallocated(mat);
2220:   if (!mat->ops->relax) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2221:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2222:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2223:   if (mat->N != x->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %d %d",mat->N,x->N);
2224:   if (mat->M != b->N) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %d %d",mat->M,b->N);
2225:   if (mat->m != b->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %d %d",mat->m,b->n);

2227:   PetscLogEventBegin(MAT_Relax,mat,b,x,0);
2228:   ierr =(*mat->ops->relax)(mat,b,omega,flag,shift,its,lits,x);
2229:   PetscLogEventEnd(MAT_Relax,mat,b,x,0);
2230:   return(0);
2231: }

2233: /*
2234:       Default matrix copy routine.
2235: */
2236: int MatCopy_Basic(Mat A,Mat B,MatStructure str)
2237: {
2238:   int         ierr,i,rstart,rend,nz,*cwork;
2239:   PetscScalar *vwork;

2242:   MatZeroEntries(B);
2243:   MatGetOwnershipRange(A,&rstart,&rend);
2244:   for (i=rstart; i<rend; i++) {
2245:     MatGetRow(A,i,&nz,&cwork,&vwork);
2246:     MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
2247:     MatRestoreRow(A,i,&nz,&cwork,&vwork);
2248:   }
2249:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
2250:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
2251:   return(0);
2252: }

2254: /*@C  
2255:    MatCopy - Copys a matrix to another matrix.

2257:    Collective on Mat

2259:    Input Parameters:
2260: +  A - the matrix
2261: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

2263:    Output Parameter:
2264: .  B - where the copy is put

2266:    Notes:
2267:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the 
2268:    same nonzero pattern or the routine will crash.

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

2274:    Level: intermediate
2275:    
2276:    Concepts: matrices^copying

2278: .seealso: MatConvert()
2279: @*/
2280: int MatCopy(Mat A,Mat B,MatStructure str)
2281: {

2288:   MatPreallocated(A);
2290:   MatPreallocated(B);
2292:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2293:   if (A->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2294:   if (A->M != B->M || A->N != B->N) SETERRQ4(PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim (%d,%d) (%d,%d)",A->M,B->M,
2295:                                              A->N,B->N);

2297:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
2298:   if (A->ops->copy) {
2299:     (*A->ops->copy)(A,B,str);
2300:   } else { /* generic conversion */
2301:     MatCopy_Basic(A,B,str);
2302:   }
2303:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
2304:   return(0);
2305: }

2307:  #include petscsys.h
2308: PetscTruth MatConvertRegisterAllCalled = PETSC_FALSE;
2309: PetscFList MatConvertList              = 0;

2311: /*@C
2312:     MatConvertRegister - Allows one to register a routine that reads matrices
2313:         from a binary file for a particular matrix type.

2315:   Not Collective

2317:   Input Parameters:
2318: +   type - the type of matrix (defined in include/petscmat.h), for example, MATSEQAIJ.
2319: -   Converter - the function that reads the matrix from the binary file.

2321:   Level: developer

2323: .seealso: MatConvertRegisterAll(), MatConvert()

2325: @*/
2326: int MatConvertRegister(char *sname,char *path,char *name,int (*function)(Mat,MatType,Mat*))
2327: {
2328:   int  ierr;
2329:   char fullname[256];

2332:   PetscFListConcat(path,name,fullname);
2333:   PetscFListAdd(&MatConvertList,sname,fullname,(void (*)(void))function);
2334:   return(0);
2335: }

2337: /*@C  
2338:    MatConvert - Converts a matrix to another matrix, either of the same
2339:    or different type.

2341:    Collective on Mat

2343:    Input Parameters:
2344: +  mat - the matrix
2345: -  newtype - new matrix type.  Use MATSAME to create a new matrix of the
2346:    same type as the original matrix.

2348:    Output Parameter:
2349: .  M - pointer to place new matrix

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

2356:    Level: intermediate

2358:    Concepts: matrices^converting between storage formats

2360: .seealso: MatCopy(), MatDuplicate()
2361: @*/
2362: int MatConvert(Mat mat,MatType newtype,Mat *M)
2363: {
2364:   int        ierr;
2365:   PetscTruth sametype,issame,flg;
2366:   char       convname[256],mtype[256];

2371:   MatPreallocated(mat);
2373:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2374:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

2376:   PetscOptionsGetString(PETSC_NULL,"-matconvert_type",mtype,256,&flg);
2377:   if (flg) {
2378:     newtype = mtype;
2379:   }
2380:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
2381: 
2382:   PetscTypeCompare((PetscObject)mat,newtype,&sametype);
2383:   PetscStrcmp(newtype,"same",&issame);
2384:   if ((sametype || issame) && mat->ops->duplicate) {
2385:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
2386:   } else {
2387:     int (*conv)(Mat,MatType,Mat*);
2388:     if (!MatConvertRegisterAllCalled) {
2389:       MatConvertRegisterAll(PETSC_NULL);
2390:     }
2391:     PetscFListFind(mat->comm,MatConvertList,newtype,(void(**)(void))&conv);
2392:     if (conv) {
2393:       (*conv)(mat,newtype,M);
2394:     } else {
2395:       PetscStrcpy(convname,"MatConvert_");
2396:       PetscStrcat(convname,mat->type_name);
2397:       PetscStrcat(convname,"_");
2398:       PetscStrcat(convname,newtype);
2399:       PetscStrcat(convname,"_C");
2400:       PetscObjectQueryFunction((PetscObject)mat,convname,(void (**)(void))&conv);
2401:       if (conv) {
2402:         (*conv)(mat,newtype,M);
2403:       } else {
2404:         if (mat->ops->convert) {
2405:           (*mat->ops->convert)(mat,newtype,M);
2406:         } else {
2407:           MatConvert_Basic(mat,newtype,M);
2408:         }
2409:       }
2410:     }
2411:   }
2412:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
2413:   return(0);
2414: }


2417: /*@C  
2418:    MatDuplicate - Duplicates a matrix including the non-zero structure.

2420:    Collective on Mat

2422:    Input Parameters:
2423: +  mat - the matrix
2424: -  op - either MAT_DO_NOT_COPY_VALUES or MAT_COPY_VALUES, cause it to copy nonzero
2425:         values as well or not

2427:    Output Parameter:
2428: .  M - pointer to place new matrix

2430:    Level: intermediate

2432:    Concepts: matrices^duplicating

2434: .seealso: MatCopy(), MatConvert()
2435: @*/
2436: int MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
2437: {

2443:   MatPreallocated(mat);
2445:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2446:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

2448:   *M  = 0;
2449:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
2450:   if (!mat->ops->duplicate) {
2451:     SETERRQ(PETSC_ERR_SUP,"Not written for this matrix type");
2452:   }
2453:   (*mat->ops->duplicate)(mat,op,M);
2454:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
2455:   return(0);
2456: }

2458: /*@ 
2459:    MatGetDiagonal - Gets the diagonal of a matrix.

2461:    Collective on Mat and Vec

2463:    Input Parameters:
2464: +  mat - the matrix
2465: -  v - the vector for storing the diagonal

2467:    Output Parameter:
2468: .  v - the diagonal of the matrix

2470:    Notes:
2471:    For the SeqAIJ matrix format, this routine may also be called
2472:    on a LU factored matrix; in that case it routines the reciprocal of 
2473:    the diagonal entries in U. It returns the entries permuted by the 
2474:    row and column permutation used during the symbolic factorization.

2476:    Level: intermediate

2478:    Concepts: matrices^accessing diagonals

2480: .seealso: MatGetRow(), MatGetSubmatrices(), MatGetSubmatrix(), MatGetRowMax()
2481: @*/
2482: int MatGetDiagonal(Mat mat,Vec v)
2483: {

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

2495:   (*mat->ops->getdiagonal)(mat,v);
2496:   return(0);
2497: }

2499: /*@ 
2500:    MatGetRowMax - Gets the maximum value (in absolute value) of each
2501:         row of the matrix

2503:    Collective on Mat and Vec

2505:    Input Parameters:
2506: .  mat - the matrix

2508:    Output Parameter:
2509: .  v - the vector for storing the maximums

2511:    Level: intermediate

2513:    Concepts: matrices^getting row maximums

2515: .seealso: MatGetDiagonal(), MatGetSubmatrices(), MatGetSubmatrix()
2516: @*/
2517: int MatGetRowMax(Mat mat,Vec v)
2518: {

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

2530:   (*mat->ops->getrowmax)(mat,v);
2531:   return(0);
2532: }

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

2537:    Collective on Mat

2539:    Input Parameter:
2540: .  mat - the matrix to transpose

2542:    Output Parameters:
2543: .  B - the transpose (or pass in PETSC_NULL for an in-place transpose)

2545:    Level: intermediate

2547:    Concepts: matrices^transposing

2549: .seealso: MatMultTranspose(), MatMultTransposeAdd()
2550: @*/
2551: int MatTranspose(Mat mat,Mat *B)
2552: {

2558:   MatPreallocated(mat);
2559:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2560:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2561:   if (!mat->ops->transpose) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2562:   (*mat->ops->transpose)(mat,B);
2563:   return(0);
2564: }

2566: /*@C
2567:    MatPermute - Creates a new matrix with rows and columns permuted from the 
2568:    original.

2570:    Collective on Mat

2572:    Input Parameters:
2573: +  mat - the matrix to permute
2574: .  row - row permutation, each processor supplies only the permutation for its rows
2575: -  col - column permutation, each processor needs the entire column permutation, that is
2576:          this is the same size as the total number of columns in the matrix

2578:    Output Parameters:
2579: .  B - the permuted matrix

2581:    Level: advanced

2583:    Concepts: matrices^permuting

2585: .seealso: MatGetOrdering()
2586: @*/
2587: int MatPermute(Mat mat,IS row,IS col,Mat *B)
2588: {

2594:   MatPreallocated(mat);
2597:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2598:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2599:   if (!mat->ops->permute) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2600:   (*mat->ops->permute)(mat,row,col,B);
2601:   return(0);
2602: }

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

2608:   Collective on Mat

2610:   Input Parameters:
2611: + A    - The matrix to permute
2612: . band - The half-bandwidth of the sparsified matrix, or PETSC_DECIDE
2613: . frac - The half-bandwidth as a fraction of the total size, or 0.0
2614: . tol  - The drop tolerance
2615: . rowp - The row permutation
2616: - colp - The column permutation

2618:   Output Parameter:
2619: . B    - The permuted, sparsified matrix

2621:   Level: advanced

2623:   Note:
2624:   The default behavior (band = PETSC_DECIDE and frac = 0.0) is to
2625:   restrict the half-bandwidth of the resulting matrix to 5% of the
2626:   total matrix size.

2628: .keywords: matrix, permute, sparsify

2630: .seealso: MatGetOrdering(), MatPermute()
2631: @*/
2632: int MatPermuteSparsify(Mat A, int band, PetscReal frac, PetscReal tol, IS rowp, IS colp, Mat *B)
2633: {
2634:   IS           irowp, icolp;
2635:   int         *rows, *cols;
2636:   int          M, N, locRowStart, locRowEnd;
2637:   int          nz, newNz;
2638:   int         *cwork, *cnew;
2639:   PetscScalar *vwork, *vnew;
2640:   int          bw, size;
2641:   int          row, locRow, newRow, col, newCol;
2642:   int          ierr;

2648:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2649:   if (A->factor)     SETERRQ(PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2650:   if (!A->ops->permutesparsify) {
2651:     MatGetSize(A, &M, &N);
2652:     MatGetOwnershipRange(A, &locRowStart, &locRowEnd);
2653:     ISGetSize(rowp, &size);
2654:     if (size != M) SETERRQ2(PETSC_ERR_ARG_WRONG, "Wrong size %d for row permutation, should be %d", size, M);
2655:     ISGetSize(colp, &size);
2656:     if (size != N) SETERRQ2(PETSC_ERR_ARG_WRONG, "Wrong size %d for column permutation, should be %d", size, N);
2657:     ISInvertPermutation(rowp, 0, &irowp);
2658:     ISGetIndices(irowp, &rows);
2659:     ISInvertPermutation(colp, 0, &icolp);
2660:     ISGetIndices(icolp, &cols);
2661:     PetscMalloc(N * sizeof(int),         &cnew);
2662:     PetscMalloc(N * sizeof(PetscScalar), &vnew);

2664:     /* Setup bandwidth to include */
2665:     if (band == PETSC_DECIDE) {
2666:       if (frac <= 0.0)
2667:         bw = (int) (M * 0.05);
2668:       else
2669:         bw = (int) (M * frac);
2670:     } else {
2671:       if (band <= 0) SETERRQ(PETSC_ERR_ARG_WRONG, "Bandwidth must be a positive integer");
2672:       bw = band;
2673:     }

2675:     /* Put values into new matrix */
2676:     MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, B);
2677:     for(row = locRowStart, locRow = 0; row < locRowEnd; row++, locRow++) {
2678:       MatGetRow(A, row, &nz, &cwork, &vwork);
2679:       newRow   = rows[locRow]+locRowStart;
2680:       for(col = 0, newNz = 0; col < nz; col++) {
2681:         newCol = cols[cwork[col]];
2682:         if ((newCol >= newRow - bw) && (newCol < newRow + bw) && (PetscAbsScalar(vwork[col]) >= tol)) {
2683:           cnew[newNz] = newCol;
2684:           vnew[newNz] = vwork[col];
2685:           newNz++;
2686:         }
2687:       }
2688:       MatSetValues(*B, 1, &newRow, newNz, cnew, vnew, INSERT_VALUES);
2689:       MatRestoreRow(A, row, &nz, &cwork, &vwork);
2690:     }
2691:     PetscFree(cnew);
2692:     PetscFree(vnew);
2693:     MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY);
2694:     MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY);
2695:     ISRestoreIndices(irowp, &rows);
2696:     ISRestoreIndices(icolp, &cols);
2697:     ISDestroy(irowp);
2698:     ISDestroy(icolp);
2699:   } else {
2700:     (*A->ops->permutesparsify)(A, band, frac, tol, rowp, colp, B);
2701:   }
2702:   return(0);
2703: }

2705: /*@
2706:    MatEqual - Compares two matrices.

2708:    Collective on Mat

2710:    Input Parameters:
2711: +  A - the first matrix
2712: -  B - the second matrix

2714:    Output Parameter:
2715: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

2717:    Level: intermediate

2719:    Concepts: matrices^equality between
2720: @*/
2721: int MatEqual(Mat A,Mat B,PetscTruth *flg)
2722: {

2729:   MatPreallocated(A);
2731:   MatPreallocated(B);
2734:   if (!A->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2735:   if (!B->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2736:   if (A->M != B->M || A->N != B->N) SETERRQ4(PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %d %d %d %d",A->M,B->M,A->N,B->N);
2737:   if (!A->ops->equal) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",A->type_name);
2738:   (*A->ops->equal)(A,B,flg);
2739:   return(0);
2740: }

2742: /*@
2743:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
2744:    matrices that are stored as vectors.  Either of the two scaling
2745:    matrices can be PETSC_NULL.

2747:    Collective on Mat

2749:    Input Parameters:
2750: +  mat - the matrix to be scaled
2751: .  l - the left scaling vector (or PETSC_NULL)
2752: -  r - the right scaling vector (or PETSC_NULL)

2754:    Notes:
2755:    MatDiagonalScale() computes A = LAR, where
2756:    L = a diagonal matrix, R = a diagonal matrix

2758:    Level: intermediate

2760:    Concepts: matrices^diagonal scaling
2761:    Concepts: diagonal scaling of matrices

2763: .seealso: MatScale()
2764: @*/
2765: int MatDiagonalScale(Mat mat,Vec l,Vec r)
2766: {

2772:   MatPreallocated(mat);
2773:   if (!mat->ops->diagonalscale) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2776:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2777:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

2779:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
2780:   (*mat->ops->diagonalscale)(mat,l,r);
2781:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
2782:   return(0);
2783: }

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

2788:     Collective on Mat

2790:     Input Parameters:
2791: +   mat - the matrix to be scaled
2792: -   a  - the scaling value

2794:     Output Parameter:
2795: .   mat - the scaled matrix

2797:     Level: intermediate

2799:     Concepts: matrices^scaling all entries

2801: .seealso: MatDiagonalScale()
2802: @*/
2803: int MatScale(PetscScalar *a,Mat mat)
2804: {

2810:   MatPreallocated(mat);
2812:   if (!mat->ops->scale) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2813:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2814:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

2816:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
2817:   (*mat->ops->scale)(a,mat);
2818:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
2819:   return(0);
2820: }

2822: /*@ 
2823:    MatNorm - Calculates various norms of a matrix.

2825:    Collective on Mat

2827:    Input Parameters:
2828: +  mat - the matrix
2829: -  type - the type of norm, NORM_1, NORM_2, NORM_FROBENIUS, NORM_INFINITY

2831:    Output Parameters:
2832: .  nrm - the resulting norm 

2834:    Level: intermediate

2836:    Concepts: matrices^norm
2837:    Concepts: norm^of matrix
2838: @*/
2839: int MatNorm(Mat mat,NormType type,PetscReal *nrm)
2840: {

2846:   MatPreallocated(mat);

2849:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2850:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2851:   if (!mat->ops->norm) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
2852:   (*mat->ops->norm)(mat,type,nrm);
2853:   return(0);
2854: }

2856: /* 
2857:      This variable is used to prevent counting of MatAssemblyBegin() that
2858:    are called from within a MatAssemblyEnd().
2859: */
2860: static int MatAssemblyEnd_InUse = 0;
2861: /*@
2862:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
2863:    be called after completing all calls to MatSetValues().

2865:    Collective on Mat

2867:    Input Parameters:
2868: +  mat - the matrix 
2869: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
2870:  
2871:    Notes: 
2872:    MatSetValues() generally caches the values.  The matrix is ready to
2873:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
2874:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
2875:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
2876:    using the matrix.

2878:    Level: beginner

2880:    Concepts: matrices^assembling

2882: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
2883: @*/
2884: int MatAssemblyBegin(Mat mat,MatAssemblyType type)
2885: {

2891:   MatPreallocated(mat);
2892:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.nDid you forget to call MatSetUnfactored()?");
2893:   if (mat->assembled) {
2894:     mat->was_assembled = PETSC_TRUE;
2895:     mat->assembled     = PETSC_FALSE;
2896:   }
2897:   if (!MatAssemblyEnd_InUse) {
2898:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
2899:     if (mat->ops->assemblybegin){(*mat->ops->assemblybegin)(mat,type);}
2900:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
2901:   } else {
2902:     if (mat->ops->assemblybegin){(*mat->ops->assemblybegin)(mat,type);}
2903:   }
2904:   return(0);
2905: }

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

2911:    Collective on Mat

2913:    Input Parameter:
2914: .  mat - the matrix 

2916:    Output Parameter:
2917: .  assembled - PETSC_TRUE or PETSC_FALSE

2919:    Level: advanced

2921:    Concepts: matrices^assembled?

2923: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
2924: @*/
2925: int MatAssembled(Mat mat,PetscTruth *assembled)
2926: {
2930:   MatPreallocated(mat);
2931:   *assembled = mat->assembled;
2932:   return(0);
2933: }

2935: /*
2936:     Processes command line options to determine if/how a matrix
2937:   is to be viewed. Called by MatAssemblyEnd() and MatLoad().
2938: */
2939: int MatView_Private(Mat mat)
2940: {
2941:   int        ierr;
2942:   PetscTruth flg;

2945:   PetscOptionsHasName(mat->prefix,"-mat_view_info",&flg);
2946:   if (flg) {
2947:     PetscViewerPushFormat(PETSC_VIEWER_STDOUT_(mat->comm),PETSC_VIEWER_ASCII_INFO);
2948:     MatView(mat,PETSC_VIEWER_STDOUT_(mat->comm));
2949:     PetscViewerPopFormat(PETSC_VIEWER_STDOUT_(mat->comm));
2950:   }
2951:   PetscOptionsHasName(mat->prefix,"-mat_view_info_detailed",&flg);
2952:   if (flg) {
2953:     PetscViewerPushFormat(PETSC_VIEWER_STDOUT_(mat->comm),PETSC_VIEWER_ASCII_INFO_LONG);
2954:     MatView(mat,PETSC_VIEWER_STDOUT_(mat->comm));
2955:     PetscViewerPopFormat(PETSC_VIEWER_STDOUT_(mat->comm));
2956:   }
2957:   PetscOptionsHasName(mat->prefix,"-mat_view",&flg);
2958:   if (flg) {
2959:     MatView(mat,PETSC_VIEWER_STDOUT_(mat->comm));
2960:   }
2961:   PetscOptionsHasName(mat->prefix,"-mat_view_matlab",&flg);
2962:   if (flg) {
2963:     PetscViewerPushFormat(PETSC_VIEWER_STDOUT_(mat->comm),PETSC_VIEWER_ASCII_MATLAB);
2964:     MatView(mat,PETSC_VIEWER_STDOUT_(mat->comm));
2965:     PetscViewerPopFormat(PETSC_VIEWER_STDOUT_(mat->comm));
2966:   }
2967:   PetscOptionsHasName(mat->prefix,"-mat_view_draw",&flg);
2968:   if (flg) {
2969:     PetscOptionsHasName(mat->prefix,"-mat_view_contour",&flg);
2970:     if (flg) {
2971:       PetscViewerPushFormat(PETSC_VIEWER_DRAW_(mat->comm),PETSC_VIEWER_DRAW_CONTOUR);
2972:     }
2973:     MatView(mat,PETSC_VIEWER_DRAW_(mat->comm));
2974:     PetscViewerFlush(PETSC_VIEWER_DRAW_(mat->comm));
2975:     if (flg) {
2976:       PetscViewerPopFormat(PETSC_VIEWER_DRAW_(mat->comm));
2977:     }
2978:   }
2979:   PetscOptionsHasName(mat->prefix,"-mat_view_socket",&flg);
2980:   if (flg) {
2981:     MatView(mat,PETSC_VIEWER_SOCKET_(mat->comm));
2982:     PetscViewerFlush(PETSC_VIEWER_SOCKET_(mat->comm));
2983:   }
2984:   PetscOptionsHasName(mat->prefix,"-mat_view_binary",&flg);
2985:   if (flg) {
2986:     MatView(mat,PETSC_VIEWER_BINARY_(mat->comm));
2987:     PetscViewerFlush(PETSC_VIEWER_BINARY_(mat->comm));
2988:   }
2989:   return(0);
2990: }

2992: /*@
2993:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
2994:    be called after MatAssemblyBegin().

2996:    Collective on Mat

2998:    Input Parameters:
2999: +  mat - the matrix 
3000: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

3002:    Options Database Keys:
3003: +  -mat_view_info - Prints info on matrix at conclusion of MatEndAssembly()
3004: .  -mat_view_info_detailed - Prints more detailed info
3005: .  -mat_view - Prints matrix in ASCII format
3006: .  -mat_view_matlab - Prints matrix in Matlab format
3007: .  -mat_view_draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
3008: .  -display <name> - Sets display name (default is host)
3009: -  -draw_pause <sec> - Sets number of seconds to pause after display

3011:    Notes: 
3012:    MatSetValues() generally caches the values.  The matrix is ready to
3013:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
3014:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
3015:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
3016:    using the matrix.

3018:    Level: beginner

3020: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), MatView(), MatAssembled()
3021: @*/
3022: int MatAssemblyEnd(Mat mat,MatAssemblyType type)
3023: {
3024:   int        ierr;
3025:   static int inassm = 0;

3030:   MatPreallocated(mat);

3032:   inassm++;
3033:   MatAssemblyEnd_InUse++;
3034:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
3035:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
3036:     if (mat->ops->assemblyend) {
3037:       (*mat->ops->assemblyend)(mat,type);
3038:     }
3039:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
3040:   } else {
3041:     if (mat->ops->assemblyend) {
3042:       (*mat->ops->assemblyend)(mat,type);
3043:     }
3044:   }

3046:   /* Flush assembly is not a true assembly */
3047:   if (type != MAT_FLUSH_ASSEMBLY) {
3048:     mat->assembled  = PETSC_TRUE; mat->num_ass++;
3049:   }
3050:   mat->insertmode = NOT_SET_VALUES;
3051:   MatAssemblyEnd_InUse--;

3053:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
3054:     MatView_Private(mat);
3055:   }
3056:   inassm--;
3057:   return(0);
3058: }


3061: /*@
3062:    MatCompress - Tries to store the matrix in as little space as 
3063:    possible.  May fail if memory is already fully used, since it
3064:    tries to allocate new space.

3066:    Collective on Mat

3068:    Input Parameters:
3069: .  mat - the matrix 

3071:    Level: advanced

3073: @*/
3074: int MatCompress(Mat mat)
3075: {

3081:   MatPreallocated(mat);
3082:   if (mat->ops->compress) {(*mat->ops->compress)(mat);}
3083:   return(0);
3084: }

3086: /*@
3087:    MatSetOption - Sets a parameter option for a matrix. Some options
3088:    may be specific to certain storage formats.  Some options
3089:    determine how values will be inserted (or added). Sorted, 
3090:    row-oriented input will generally assemble the fastest. The default
3091:    is row-oriented, nonsorted input. 

3093:    Collective on Mat

3095:    Input Parameters:
3096: +  mat - the matrix 
3097: -  option - the option, one of those listed below (and possibly others),
3098:              e.g., MAT_ROWS_SORTED, MAT_NEW_NONZERO_LOCATION_ERR

3100:    Options Describing Matrix Structure:
3101: +    MAT_SYMMETRIC - symmetric in terms of both structure and value
3102: -    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure

3104:    Options For Use with MatSetValues():
3105:    Insert a logically dense subblock, which can be
3106: +    MAT_ROW_ORIENTED - row-oriented
3107: .    MAT_COLUMN_ORIENTED - column-oriented
3108: .    MAT_ROWS_SORTED - sorted by row
3109: .    MAT_ROWS_UNSORTED - not sorted by row
3110: .    MAT_COLUMNS_SORTED - sorted by column
3111: -    MAT_COLUMNS_UNSORTED - not sorted by column

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

3117:    When (re)assembling a matrix, we can restrict the input for
3118:    efficiency/debugging purposes.  These options include
3119: +    MAT_NO_NEW_NONZERO_LOCATIONS - additional insertions will not be
3120:         allowed if they generate a new nonzero
3121: .    MAT_YES_NEW_NONZERO_LOCATIONS - additional insertions will be allowed
3122: .    MAT_NO_NEW_DIAGONALS - additional insertions will not be allowed if
3123:          they generate a nonzero in a new diagonal (for block diagonal format only)
3124: .    MAT_YES_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
3125: .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
3126: .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
3127: -    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly

3129:    Notes:
3130:    Some options are relevant only for particular matrix types and
3131:    are thus ignored by others.  Other options are not supported by
3132:    certain matrix types and will generate an error message if set.

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

3138:    MAT_NO_NEW_NONZERO_LOCATIONS indicates that any add or insertion 
3139:    that would generate a new entry in the nonzero structure is instead
3140:    ignored.  Thus, if memory has not alredy been allocated for this particular 
3141:    data, then the insertion is ignored. For dense matrices, in which
3142:    the entire array is allocated, no entries are ever ignored. 

3144:    MAT_NEW_NONZERO_LOCATION_ERR indicates that any add or insertion 
3145:    that would generate a new entry in the nonzero structure instead produces 
3146:    an error. (Currently supported for AIJ and BAIJ formats only.)
3147:    This is a useful flag when using SAME_NONZERO_PATTERN in calling
3148:    SLESSetOperators() to ensure that the nonzero pattern truely does 
3149:    remain unchanged.

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

3156:    MAT_IGNORE_OFF_PROC_ENTRIES indicates entries destined for 
3157:    other processors should be dropped, rather than stashed.
3158:    This is useful if you know that the "owning" processor is also 
3159:    always generating the correct matrix entries, so that PETSc need
3160:    not transfer duplicate entries generated on another processor.
3161:    
3162:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
3163:    searches during matrix assembly. When this flag is set, the hash table
3164:    is created during the first Matrix Assembly. This hash table is
3165:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
3166:    to improve the searching of indices. MAT_NO_NEW_NONZERO_LOCATIONS flag 
3167:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
3168:    supported by MATMPIBAIJ format only.

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

3173:    MAT_IGNORE_ZERO_ENTRIES - when using ADD_VALUES for AIJ matrices this will stop
3174:    zero values from creating a zero location in the matrix

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

3179:    MAT_DO_NOT_USE_INODES - indicates not using inode version of the code - works
3180:    with AIJ and ROWBS matrix types

3182:    Level: intermediate

3184:    Concepts: matrices^setting options

3186: @*/
3187: int MatSetOption(Mat mat,MatOption op)
3188: {

3194:   MatPreallocated(mat);
3195:   switch (op) {
3196:   case MAT_SYMMETRIC:
3197:     mat->symmetric              = PETSC_TRUE;
3198:     mat->structurally_symmetric = PETSC_TRUE;
3199:     break;
3200:   case MAT_STRUCTURALLY_SYMMETRIC:
3201:     mat->structurally_symmetric = PETSC_TRUE;
3202:     break;
3203:   default:
3204:     if (mat->ops->setoption) {(*mat->ops->setoption)(mat,op);}
3205:     break;
3206:   }
3207:   return(0);
3208: }

3210: /*@
3211:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
3212:    this routine retains the old nonzero structure.

3214:    Collective on Mat

3216:    Input Parameters:
3217: .  mat - the matrix 

3219:    Level: intermediate

3221:    Concepts: matrices^zeroing

3223: .seealso: MatZeroRows()
3224: @*/
3225: int MatZeroEntries(Mat mat)
3226: {

3232:   MatPreallocated(mat);
3233:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3234:   if (!mat->ops->zeroentries) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

3236:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
3237:   (*mat->ops->zeroentries)(mat);
3238:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
3239:   return(0);
3240: }

3242: /*@C
3243:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
3244:    of a set of rows of a matrix.

3246:    Collective on Mat

3248:    Input Parameters:
3249: +  mat - the matrix
3250: .  is - index set of rows to remove
3251: -  diag - pointer to value put in all diagonals of eliminated rows.
3252:           Note that diag is not a pointer to an array, but merely a
3253:           pointer to a single value.

3255:    Notes:
3256:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
3257:    but does not release memory.  For the dense and block diagonal
3258:    formats this does not alter the nonzero structure.

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

3264:    The user can set a value in the diagonal entry (or for the AIJ and
3265:    row formats can optionally remove the main diagonal entry from the
3266:    nonzero structure as well, by passing a null pointer (PETSC_NULL 
3267:    in C or PETSC_NULL_SCALAR in Fortran) as the final argument).

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

3274:   
3275:    Level: intermediate

3277:    Concepts: matrices^zeroing rows

3279: .seealso: MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
3280: @*/
3281: int MatZeroRows(Mat mat,IS is,PetscScalar *diag)
3282: {

3288:   MatPreallocated(mat);
3291:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3292:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3293:   if (!mat->ops->zerorows) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);

3295:   (*mat->ops->zerorows)(mat,is,diag);
3296:   MatView_Private(mat);
3297:   return(0);
3298: }

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

3304:    Collective on Mat

3306:    Input Parameters:
3307: +  mat - the matrix
3308: .  is - index set of rows to remove
3309: -  diag - pointer to value put in all diagonals of eliminated rows.
3310:           Note that diag is not a pointer to an array, but merely a
3311:           pointer to a single value.

3313:    Notes:
3314:    Before calling MatZeroRowsLocal(), the user must first set the
3315:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

3317:    For the AIJ matrix formats this removes the old nonzero structure,
3318:    but does not release memory.  For the dense and block diagonal
3319:    formats this does not alter the nonzero structure.

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

3325:    The user can set a value in the diagonal entry (or for the AIJ and
3326:    row formats can optionally remove the main diagonal entry from the
3327:    nonzero structure as well, by passing a null pointer (PETSC_NULL
3328:    in C or PETSC_NULL_SCALAR in Fortran) as the final argument).

3330:    Level: intermediate

3332:    Concepts: matrices^zeroing

3334: .seealso: MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
3335: @*/
3336: int MatZeroRowsLocal(Mat mat,IS is,PetscScalar *diag)
3337: {
3339:   IS  newis;

3344:   MatPreallocated(mat);
3347:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3348:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

3350:   if (mat->ops->zerorowslocal) {
3351:     (*mat->ops->zerorowslocal)(mat,is,diag);
3352:   } else {
3353:     if (!mat->mapping) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
3354:     ISLocalToGlobalMappingApplyIS(mat->mapping,is,&newis);
3355:     (*mat->ops->zerorows)(mat,newis,diag);
3356:     ISDestroy(newis);
3357:   }
3358:   return(0);
3359: }

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

3364:    Not Collective

3366:    Input Parameter:
3367: .  mat - the matrix

3369:    Output Parameters:
3370: +  m - the number of global rows
3371: -  n - the number of global columns

3373:    Level: beginner

3375:    Concepts: matrices^size

3377: .seealso: MatGetLocalSize()
3378: @*/
3379: int MatGetSize(Mat mat,int *m,int* n)
3380: {
3383:   if (m) *m = mat->M;
3384:   if (n) *n = mat->N;
3385:   return(0);
3386: }

3388: /*@
3389:    MatGetLocalSize - Returns the number of rows and columns in a matrix
3390:    stored locally.  This information may be implementation dependent, so
3391:    use with care.

3393:    Not Collective

3395:    Input Parameters:
3396: .  mat - the matrix

3398:    Output Parameters:
3399: +  m - the number of local rows
3400: -  n - the number of local columns

3402:    Level: beginner

3404:    Concepts: matrices^local size

3406: .seealso: MatGetSize()
3407: @*/
3408: int MatGetLocalSize(Mat mat,int *m,int* n)
3409: {
3412:   if (m) *m = mat->m;
3413:   if (n) *n = mat->n;
3414:   return(0);
3415: }

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

3423:    Not Collective

3425:    Input Parameters:
3426: .  mat - the matrix

3428:    Output Parameters:
3429: +  m - the global index of the first local row
3430: -  n - one more than the global index of the last local row

3432:    Level: beginner

3434:    Concepts: matrices^row ownership
3435: @*/
3436: int MatGetOwnershipRange(Mat mat,int *m,int* n)
3437: {

3443:   MatPreallocated(mat);
3446:   PetscMapGetLocalRange(mat->rmap,m,n);
3447:   return(0);
3448: }

3450: /*@  
3451:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
3452:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric() 
3453:    to complete the factorization.

3455:    Collective on Mat

3457:    Input Parameters:
3458: +  mat - the matrix
3459: .  row - row permutation
3460: .  column - column permutation
3461: -  info - structure containing 
3462: $      levels - number of levels of fill.
3463: $      expected fill - as ratio of original fill.
3464: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3465:                 missing diagonal entries)

3467:    Output Parameters:
3468: .  fact - new matrix that has been symbolically factored

3470:    Notes:
3471:    See the users manual for additional information about
3472:    choosing the fill factor for better efficiency.

3474:    Most users should employ the simplified SLES interface for linear solvers
3475:    instead of working directly with matrix algebra routines such as this.
3476:    See, e.g., SLESCreate().

3478:    Level: developer

3480:   Concepts: matrices^symbolic LU factorization
3481:   Concepts: matrices^factorization
3482:   Concepts: LU^symbolic factorization

3484: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
3485:           MatGetOrdering(), MatILUInfo

3487: @*/
3488: int MatILUFactorSymbolic(Mat mat,IS row,IS col,MatILUInfo *info,Mat *fact)
3489: {

3495:   MatPreallocated(mat);
3499:   if (info && info->levels < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %d",(int)info->levels);
3500:   if (info && info->fill < 1.0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",info->fill);
3501:   if (!mat->ops->ilufactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic ILU",mat->type_name);
3502:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3503:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

3505:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
3506:   (*mat->ops->ilufactorsymbolic)(mat,row,col,info,fact);
3507:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
3508:   return(0);
3509: }

3511: /*@  
3512:    MatICCFactorSymbolic - Performs symbolic incomplete
3513:    Cholesky factorization for a symmetric matrix.  Use 
3514:    MatCholeskyFactorNumeric() to complete the factorization.

3516:    Collective on Mat

3518:    Input Parameters:
3519: +  mat - the matrix
3520: .  perm - row and column permutation
3521: .  fill - levels of fill
3522: -  f - expected fill as ratio of original fill

3524:    Output Parameter:
3525: .  fact - the factored matrix

3527:    Notes:
3528:    Currently only no-fill factorization is supported.

3530:    Most users should employ the simplified SLES interface for linear solvers
3531:    instead of working directly with matrix algebra routines such as this.
3532:    See, e.g., SLESCreate().

3534:    Level: developer

3536:   Concepts: matrices^symbolic incomplete Cholesky factorization
3537:   Concepts: matrices^factorization
3538:   Concepts: Cholsky^symbolic factorization

3540: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor()
3541: @*/
3542: int MatICCFactorSymbolic(Mat mat,IS perm,PetscReal f,int fill,Mat *fact)
3543: {

3549:   MatPreallocated(mat);
3552:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3553:   if (fill < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Fill negative %d",fill);
3554:   if (f < 1.0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",f);
3555:   if (!mat->ops->iccfactorsymbolic) SETERRQ1(PETSC_ERR_SUP,"Matrix type %s  symbolic ICC",mat->type_name);
3556:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");

3558:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
3559:   (*mat->ops->iccfactorsymbolic)(mat,perm,f,fill,fact);
3560:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
3561:   return(0);
3562: }

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

3570:    Not Collective

3572:    Input Parameter:
3573: .  mat - the matrix

3575:    Output Parameter:
3576: .  v - the location of the values


3579:    Fortran Note:
3580:    This routine is used differently from Fortran, e.g.,
3581: .vb
3582:         Mat         mat
3583:         PetscScalar mat_array(1)
3584:         PetscOffset i_mat
3585:         int         ierr
3586:         call MatGetArray(mat,mat_array,i_mat,ierr)

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

3592:         [... other code ...]
3593:         call MatRestoreArray(mat,mat_array,i_mat,ierr)
3594: .ve

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

3599:    Level: advanced

3601:    Concepts: matrices^access array

3603: .seealso: MatRestoreArray(), MatGetArrayF90()
3604: @*/
3605: int MatGetArray(Mat mat,PetscScalar **v)
3606: {

3612:   MatPreallocated(mat);
3614:   if (!mat->ops->getarray) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3615:   (*mat->ops->getarray)(mat,v);
3616:   return(0);
3617: }

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

3622:    Not Collective

3624:    Input Parameter:
3625: +  mat - the matrix
3626: -  v - the location of the values

3628:    Fortran Note:
3629:    This routine is used differently from Fortran, e.g.,
3630: .vb
3631:         Mat         mat
3632:         PetscScalar mat_array(1)
3633:         PetscOffset i_mat
3634:         int         ierr
3635:         call MatGetArray(mat,mat_array,i_mat,ierr)

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

3641:         [... other code ...]
3642:         call MatRestoreArray(mat,mat_array,i_mat,ierr)
3643: .ve

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

3648:    Level: advanced

3650: .seealso: MatGetArray(), MatRestoreArrayF90()
3651: @*/
3652: int MatRestoreArray(Mat mat,PetscScalar **v)
3653: {

3659:   MatPreallocated(mat);
3661:   if (!mat->ops->restorearray) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3662:   (*mat->ops->restorearray)(mat,v);
3663:   return(0);
3664: }

3666: /*@C
3667:    MatGetSubMatrices - Extracts several submatrices from a matrix. If submat
3668:    points to an array of valid matrices, they may be reused to store the new
3669:    submatrices.

3671:    Collective on Mat

3673:    Input Parameters:
3674: +  mat - the matrix
3675: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
3676: .  irow, icol - index sets of rows and columns to extract
3677: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

3679:    Output Parameter:
3680: .  submat - the array of submatrices

3682:    Notes:
3683:    MatGetSubMatrices() can extract only sequential submatrices
3684:    (from both sequential and parallel matrices). Use MatGetSubMatrix()
3685:    to extract a parallel submatrix.

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

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

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

3697:    This routine creates the matrices submat; you should NOT create them before
3698:    calling it.

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

3704:    Level: advanced

3706:    Concepts: matrices^accessing submatrices
3707:    Concepts: submatrices

3709: .seealso: MatDestroyMatrices(), MatGetSubMatrix(), MatGetRow(), MatGetDiagonal()
3710: @*/
3711: int MatGetSubMatrices(Mat mat,int n,IS *irow,IS *icol,MatReuse scall,Mat **submat)
3712: {
3713:   int        ierr;

3718:   MatPreallocated(mat);
3719:   if (!mat->ops->getsubmatrices) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3720:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");

3722:   PetscLogEventBegin(MAT_GetSubMatrices,mat,0,0,0);
3723:   (*mat->ops->getsubmatrices)(mat,n,irow,icol,scall,submat);
3724:   PetscLogEventEnd(MAT_GetSubMatrices,mat,0,0,0);
3725:   return(0);
3726: }

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

3731:    Collective on Mat

3733:    Input Parameters:
3734: +  n - the number of local matrices
3735: -  mat - the matrices

3737:    Level: advanced

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

3741: .seealso: MatGetSubMatrices()
3742: @*/
3743: int MatDestroyMatrices(int n,Mat **mat)
3744: {
3745:   int ierr,i;

3748:   if (n < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %d",n);
3750:   for (i=0; i<n; i++) {
3751:     MatDestroy((*mat)[i]);
3752:   }
3753:   /* memory is allocated even if n = 0 */
3754:   PetscFree(*mat);
3755:   return(0);
3756: }

3758: /*@
3759:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
3760:    replaces the index sets by larger ones that represent submatrices with
3761:    additional overlap.

3763:    Collective on Mat

3765:    Input Parameters:
3766: +  mat - the matrix
3767: .  n   - the number of index sets
3768: .  is  - the array of pointers to index sets
3769: -  ov  - the additional overlap requested

3771:    Level: developer

3773:    Concepts: overlap
3774:    Concepts: ASM^computing overlap

3776: .seealso: MatGetSubMatrices()
3777: @*/
3778: int MatIncreaseOverlap(Mat mat,int n,IS *is,int ov)
3779: {

3785:   MatPreallocated(mat);
3786:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3787:   if (mat->factor)     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

3789:   if (!ov) return(0);
3790:   if (!mat->ops->increaseoverlap) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3791:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
3792:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
3793:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
3794:   return(0);
3795: }

3797: /*@
3798:    MatPrintHelp - Prints all the options for the matrix.

3800:    Collective on Mat

3802:    Input Parameter:
3803: .  mat - the matrix 

3805:    Options Database Keys:
3806: +  -help - Prints matrix options
3807: -  -h - Prints matrix options

3809:    Level: developer

3811: .seealso: MatCreate(), MatCreateXXX()
3812: @*/
3813: int MatPrintHelp(Mat mat)
3814: {
3815:   static PetscTruth called = PETSC_FALSE;
3816:   int               ierr;
3817:   MPI_Comm          comm;

3822:   MatPreallocated(mat);

3824:   comm = mat->comm;
3825:   if (!called) {
3826:     (*PetscHelpPrintf)(comm,"General matrix options:n");
3827:     (*PetscHelpPrintf)(comm,"  -mat_view_info: view basic matrix info during MatAssemblyEnd()n");
3828:     (*PetscHelpPrintf)(comm,"  -mat_view_info_detailed: view detailed matrix info during MatAssemblyEnd()n");
3829:     (*PetscHelpPrintf)(comm,"  -mat_view_draw: draw nonzero matrix structure during MatAssemblyEnd()n");
3830:     (*PetscHelpPrintf)(comm,"      -draw_pause <sec>: set seconds of display pausen");
3831:     (*PetscHelpPrintf)(comm,"      -display <name>: set alternate displayn");
3832:     called = PETSC_TRUE;
3833:   }
3834:   if (mat->ops->printhelp) {
3835:     (*mat->ops->printhelp)(mat);
3836:   }
3837:   return(0);
3838: }

3840: /*@
3841:    MatGetBlockSize - Returns the matrix block size; useful especially for the
3842:    block row and block diagonal formats.
3843:    
3844:    Not Collective

3846:    Input Parameter:
3847: .  mat - the matrix

3849:    Output Parameter:
3850: .  bs - block size

3852:    Notes:
3853:    Block diagonal formats are MATSEQBDIAG, MATMPIBDIAG.
3854:    Block row formats are MATSEQBAIJ, MATMPIBAIJ

3856:    Level: intermediate

3858:    Concepts: matrices^block size

3860: .seealso: MatCreateSeqBAIJ(), MatCreateMPIBAIJ(), MatCreateSeqBDiag(), MatCreateMPIBDiag()
3861: @*/
3862: int MatGetBlockSize(Mat mat,int *bs)
3863: {

3869:   MatPreallocated(mat);
3871:   if (!mat->ops->getblocksize) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
3872:   (*mat->ops->getblocksize)(mat,bs);
3873:   return(0);
3874: }

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

3879:    Collective on Mat

3881:     Input Parameters:
3882: +   mat - the matrix
3883: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
3884: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
3885:                 symmetrized

3887:     Output Parameters:
3888: +   n - number of rows in the (possibly compressed) matrix
3889: .   ia - the row pointers
3890: .   ja - the column indices
3891: -   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

3893:     Level: developer

3895: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
3896: @*/
3897: int MatGetRowIJ(Mat mat,int shift,PetscTruth symmetric,int *n,int **ia,int** ja,PetscTruth *done)
3898: {

3904:   MatPreallocated(mat);
3908:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
3909:   else {
3910:     *done = PETSC_TRUE;
3911:     ierr  = (*mat->ops->getrowij)(mat,shift,symmetric,n,ia,ja,done);
3912:   }
3913:   return(0);
3914: }

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

3919:     Collective on Mat

3921:     Input Parameters:
3922: +   mat - the matrix
3923: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
3924: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
3925:                 symmetrized

3927:     Output Parameters:
3928: +   n - number of columns in the (possibly compressed) matrix
3929: .   ia - the column pointers
3930: .   ja - the row indices
3931: -   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

3933:     Level: developer

3935: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
3936: @*/
3937: int MatGetColumnIJ(Mat mat,int shift,PetscTruth symmetric,int *n,int **ia,int** ja,PetscTruth *done)
3938: {

3944:   MatPreallocated(mat);

3949:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
3950:   else {
3951:     *done = PETSC_TRUE;
3952:     ierr  = (*mat->ops->getcolumnij)(mat,shift,symmetric,n,ia,ja,done);
3953:   }
3954:   return(0);
3955: }

3957: /*@C
3958:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
3959:     MatGetRowIJ().

3961:     Collective on Mat

3963:     Input Parameters:
3964: +   mat - the matrix
3965: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
3966: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
3967:                 symmetrized

3969:     Output Parameters:
3970: +   n - size of (possibly compressed) matrix
3971: .   ia - the row pointers
3972: .   ja - the column indices
3973: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

3975:     Level: developer

3977: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
3978: @*/
3979: int MatRestoreRowIJ(Mat mat,int shift,PetscTruth symmetric,int *n,int **ia,int** ja,PetscTruth *done)
3980: {

3986:   MatPreallocated(mat);

3991:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
3992:   else {
3993:     *done = PETSC_TRUE;
3994:     ierr  = (*mat->ops->restorerowij)(mat,shift,symmetric,n,ia,ja,done);
3995:   }
3996:   return(0);
3997: }

3999: /*@C
4000:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
4001:     MatGetColumnIJ().

4003:     Collective on Mat

4005:     Input Parameters:
4006: +   mat - the matrix
4007: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
4008: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
4009:                 symmetrized

4011:     Output Parameters:
4012: +   n - size of (possibly compressed) matrix
4013: .   ia - the column pointers
4014: .   ja - the row indices
4015: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

4017:     Level: developer

4019: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
4020: @*/
4021: int MatRestoreColumnIJ(Mat mat,int shift,PetscTruth symmetric,int *n,int **ia,int** ja,PetscTruth *done)
4022: {

4028:   MatPreallocated(mat);

4033:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
4034:   else {
4035:     *done = PETSC_TRUE;
4036:     ierr  = (*mat->ops->restorecolumnij)(mat,shift,symmetric,n,ia,ja,done);
4037:   }
4038:   return(0);
4039: }

4041: /*@C
4042:     MatColoringPatch -Used inside matrix coloring routines that 
4043:     use MatGetRowIJ() and/or MatGetColumnIJ().

4045:     Collective on Mat

4047:     Input Parameters:
4048: +   mat - the matrix
4049: .   n   - number of colors
4050: -   colorarray - array indicating color for each column

4052:     Output Parameters:
4053: .   iscoloring - coloring generated using colorarray information

4055:     Level: developer

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

4059: @*/
4060: int MatColoringPatch(Mat mat,int n,int ncolors,int *colorarray,ISColoring *iscoloring)
4061: {

4067:   MatPreallocated(mat);

4070:   if (!mat->ops->coloringpatch){
4071:     ISColoringCreate(mat->comm,n,colorarray,iscoloring);
4072:   } else {
4073:     (*mat->ops->coloringpatch)(mat,n,ncolors,colorarray,iscoloring);
4074:   }
4075:   return(0);
4076: }


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

4082:    Collective on Mat

4084:    Input Parameter:
4085: .  mat - the factored matrix to be reset

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

4094:    Note that one can specify in-place ILU(0) factorization by calling 
4095: .vb
4096:      PCType(pc,PCILU);
4097:      PCILUSeUseInPlace(pc);
4098: .ve
4099:    or by using the options -pc_type ilu -pc_ilu_in_place

4101:    In-place factorization ILU(0) can also be used as a local
4102:    solver for the blocks within the block Jacobi or additive Schwarz
4103:    methods (runtime option: -sub_pc_ilu_in_place).  See the discussion 
4104:    of these preconditioners in the users manual for details on setting
4105:    local solver options.

4107:    Most users should employ the simplified SLES interface for linear solvers
4108:    instead of working directly with matrix algebra routines such as this.
4109:    See, e.g., SLESCreate().

4111:    Level: developer

4113: .seealso: PCILUSetUseInPlace(), PCLUSetUseInPlace()

4115:    Concepts: matrices^unfactored

4117: @*/
4118: int MatSetUnfactored(Mat mat)
4119: {

4125:   MatPreallocated(mat);
4126:   mat->factor = 0;
4127:   if (!mat->ops->setunfactored) return(0);
4128:   (*mat->ops->setunfactored)(mat);
4129:   return(0);
4130: }

4132: /*MC
4133:     MatGetArrayF90 - Accesses a matrix array from Fortran90.

4135:     Synopsis:
4136:     MatGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

4138:     Not collective

4140:     Input Parameter:
4141: .   x - matrix

4143:     Output Parameters:
4144: +   xx_v - the Fortran90 pointer to the array
4145: -   ierr - error code

4147:     Example of Usage: 
4148: .vb
4149:       PetscScalar, pointer xx_v(:)
4150:       ....
4151:       call MatGetArrayF90(x,xx_v,ierr)
4152:       a = xx_v(3)
4153:       call MatRestoreArrayF90(x,xx_v,ierr)
4154: .ve

4156:     Notes:
4157:     Not yet supported for all F90 compilers

4159:     Level: advanced

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

4163:     Concepts: matrices^accessing array

4165: M*/

4167: /*MC
4168:     MatRestoreArrayF90 - Restores a matrix array that has been
4169:     accessed with MatGetArrayF90().

4171:     Synopsis:
4172:     MatRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

4174:     Not collective

4176:     Input Parameters:
4177: +   x - matrix
4178: -   xx_v - the Fortran90 pointer to the array

4180:     Output Parameter:
4181: .   ierr - error code

4183:     Example of Usage: 
4184: .vb
4185:        PetscScalar, pointer xx_v(:)
4186:        ....
4187:        call MatGetArrayF90(x,xx_v,ierr)
4188:        a = xx_v(3)
4189:        call MatRestoreArrayF90(x,xx_v,ierr)
4190: .ve
4191:    
4192:     Notes:
4193:     Not yet supported for all F90 compilers

4195:     Level: advanced

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

4199: M*/


4202: /*@
4203:     MatGetSubMatrix - Gets a single submatrix on the same number of processors
4204:                       as the original matrix.

4206:     Collective on Mat

4208:     Input Parameters:
4209: +   mat - the original matrix
4210: .   isrow - rows this processor should obtain
4211: .   iscol - columns for all processors you wish to keep
4212: .   csize - number of columns "local" to this processor (does nothing for sequential 
4213:             matrices). This should match the result from VecGetLocalSize(x,...) if you 
4214:             plan to use the matrix in a A*x; alternatively, you can use PETSC_DECIDE
4215: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4217:     Output Parameter:
4218: .   newmat - the new submatrix, of the same type as the old

4220:     Level: advanced

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

4225:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
4226:    the MatGetSubMatrix() routine will create the newmat for you. Any additional calls
4227:    to this routine with a mat of the same nonzero structure will reuse the matrix
4228:    generated the first time.

4230:     Concepts: matrices^submatrices

4232: .seealso: MatGetSubMatrices(), ISAllGather()
4233: @*/
4234: int MatGetSubMatrix(Mat mat,IS isrow,IS iscol,int csize,MatReuse cll,Mat *newmat)
4235: {
4236:   int     ierr, size;
4237:   Mat     *local;

4241:   MatPreallocated(mat);
4242:   MPI_Comm_size(mat->comm,&size);

4244:   /* if original matrix is on just one processor then use submatrix generated */
4245:   if (!mat->ops->getsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
4246:     MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,&newmat);
4247:     return(0);
4248:   } else if (!mat->ops->getsubmatrix && size == 1) {
4249:     ierr    = MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&local);
4250:     *newmat = *local;
4251:     ierr    = PetscFree(local);
4252:     return(0);
4253:   }

4255:   if (!mat->ops->getsubmatrix) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4256:   (*mat->ops->getsubmatrix)(mat,isrow,iscol,csize,cll,newmat);
4257:   return(0);
4258: }

4260: /*@C
4261:    MatGetPetscMaps - Returns the maps associated with the matrix.

4263:    Not Collective

4265:    Input Parameter:
4266: .  mat - the matrix

4268:    Output Parameters:
4269: +  rmap - the row (right) map
4270: -  cmap - the column (left) map  

4272:    Level: developer

4274:    Concepts: maps^getting from matrix

4276: @*/
4277: int MatGetPetscMaps(Mat mat,PetscMap *rmap,PetscMap *cmap)
4278: {

4284:   MatPreallocated(mat);
4285:   (*mat->ops->getmaps)(mat,rmap,cmap);
4286:   return(0);
4287: }

4289: /*
4290:       Version that works for all PETSc matrices
4291: */
4292: int MatGetPetscMaps_Petsc(Mat mat,PetscMap *rmap,PetscMap *cmap)
4293: {
4295:   if (rmap) *rmap = mat->rmap;
4296:   if (cmap) *cmap = mat->cmap;
4297:   return(0);
4298: }

4300: /*@
4301:    MatSetStashInitialSize - sets the sizes of the matrix stash, that is
4302:    used during the assembly process to store values that belong to 
4303:    other processors.

4305:    Not Collective

4307:    Input Parameters:
4308: +  mat   - the matrix
4309: .  size  - the initial size of the stash.
4310: -  bsize - the initial size of the block-stash(if used).

4312:    Options Database Keys:
4313: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
4314: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

4316:    Level: intermediate

4318:    Notes: 
4319:      The block-stash is used for values set with VecSetValuesBlocked() while
4320:      the stash is used for values set with VecSetValues()

4322:      Run with the option -log_info and look for output of the form
4323:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
4324:      to determine the appropriate value, MM, to use for size and 
4325:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
4326:      to determine the value, BMM to use for bsize

4328:    Concepts: stash^setting matrix size
4329:    Concepts: matrices^stash

4331: @*/
4332: int MatSetStashInitialSize(Mat mat,int size, int bsize)
4333: {

4339:   MatPreallocated(mat);
4340:   MatStashSetInitialSize_Private(&mat->stash,size);
4341:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
4342:   return(0);
4343: }

4345: /*@
4346:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of 
4347:      the matrix

4349:    Collective on Mat

4351:    Input Parameters:
4352: +  mat   - the matrix
4353: .  x,y - the vectors
4354: -  w - where the result is stored

4356:    Level: intermediate

4358:    Notes: 
4359:     w may be the same vector as y. 

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

4364:     Concepts: interpolation

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

4368: @*/
4369: int MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
4370: {
4371:   int M,N,ierr;

4375:   MatPreallocated(A);
4376:   MatGetSize(A,&M,&N);
4377:   if (N > M) {
4378:     MatMultTransposeAdd(A,x,y,w);
4379:   } else {
4380:     MatMultAdd(A,x,y,w);
4381:   }
4382:   return(0);
4383: }

4385: /*@
4386:    MatInterpolate - y = A*x or A'*x depending on the shape of 
4387:      the matrix

4389:    Collective on Mat

4391:    Input Parameters:
4392: +  mat   - the matrix
4393: -  x,y - the vectors

4395:    Level: intermediate

4397:    Notes: 
4398:     This allows one to use either the restriction or interpolation (its transpose)
4399:     matrix to do the interpolation

4401:    Concepts: matrices^interpolation

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

4405: @*/
4406: int MatInterpolate(Mat A,Vec x,Vec y)
4407: {
4408:   int M,N,ierr;

4412:   MatPreallocated(A);
4413:   MatGetSize(A,&M,&N);
4414:   if (N > M) {
4415:     MatMultTranspose(A,x,y);
4416:   } else {
4417:     MatMult(A,x,y);
4418:   }
4419:   return(0);
4420: }

4422: /*@
4423:    MatRestrict - y = A*x or A'*x

4425:    Collective on Mat

4427:    Input Parameters:
4428: +  mat   - the matrix
4429: -  x,y - the vectors

4431:    Level: intermediate

4433:    Notes: 
4434:     This allows one to use either the restriction or interpolation (its transpose)
4435:     matrix to do the restriction

4437:    Concepts: matrices^restriction

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

4441: @*/
4442: int MatRestrict(Mat A,Vec x,Vec y)
4443: {
4444:   int M,N,ierr;

4448:   MatPreallocated(A);
4449:   MatGetSize(A,&M,&N);
4450:   if (N > M) {
4451:     MatMult(A,x,y);
4452:   } else {
4453:     MatMultTranspose(A,x,y);
4454:   }
4455:   return(0);
4456: }

4458: /*@C
4459:    MatNullSpaceAttach - attaches a null space to a matrix.
4460:         This null space will be removed from the resulting vector whenever
4461:         MatMult() is called

4463:    Collective on Mat

4465:    Input Parameters:
4466: +  mat - the matrix
4467: -  nullsp - the null space object

4469:    Level: developer

4471:    Notes:
4472:       Overwrites any previous null space that may have been attached

4474:    Concepts: null space^attaching to matrix

4476: .seealso: MatCreate(), MatNullSpaceCreate()
4477: @*/
4478: int MatNullSpaceAttach(Mat mat,MatNullSpace nullsp)
4479: {

4485:   MatPreallocated(mat);

4488:   if (mat->nullsp) {
4489:     MatNullSpaceDestroy(mat->nullsp);
4490:   }
4491:   mat->nullsp = nullsp;
4492:   PetscObjectReference((PetscObject)nullsp);
4493:   return(0);
4494: }

4496: /*@  
4497:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

4499:    Collective on Mat

4501:    Input Parameters:
4502: +  mat - the matrix
4503: .  row - row/column permutation
4504: .  fill - expected fill factor >= 1.0
4505: -  level - level of fill, for ICC(k)

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

4511:    Most users should employ the simplified SLES interface for linear solvers
4512:    instead of working directly with matrix algebra routines such as this.
4513:    See, e.g., SLESCreate().

4515:    Level: developer

4517:    Concepts: matrices^incomplete Cholesky factorization
4518:    Concepts: Cholesky factorization

4520: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
4521: @*/
4522: int MatICCFactor(Mat mat,IS row,PetscReal fill,int level)
4523: {

4529:   MatPreallocated(mat);
4530:   if (mat->M != mat->N) SETERRQ(PETSC_ERR_ARG_WRONG,"matrix must be square");
4531:   if (!mat->assembled) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4532:   if (mat->factor) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4533:   if (!mat->ops->iccfactor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4534:   (*mat->ops->iccfactor)(mat,row,fill,level);
4535:   return(0);
4536: }

4538: /*@ 
4539:    MatSetValuesAdic - Sets values computed with ADIC automatic differentiation into a matrix.

4541:    Not Collective

4543:    Input Parameters:
4544: +  mat - the matrix
4545: -  v - the values compute with ADIC

4547:    Level: developer

4549:    Notes:
4550:      Must call MatSetColoring() before using this routine. Also this matrix must already
4551:      have its nonzero pattern determined.

4553: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
4554:           MatSetValues(), MatSetColoring(), MatSetValuesAdifor()
4555: @*/
4556: int MatSetValuesAdic(Mat mat,void *v)
4557: {


4564:   if (!mat->assembled) {
4565:     SETERRQ(1,"Matrix must be already assembled");
4566:   }
4567:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
4568:   if (!mat->ops->setvaluesadic) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4569:   (*mat->ops->setvaluesadic)(mat,v);
4570:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
4571:   MatView_Private(mat);
4572:   return(0);
4573: }


4576: /*@ 
4577:    MatSetColoring - Sets a coloring used by calls to MatSetValuesAdic()

4579:    Not Collective

4581:    Input Parameters:
4582: +  mat - the matrix
4583: -  coloring - the coloring

4585:    Level: developer

4587: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
4588:           MatSetValues(), MatSetValuesAdic()
4589: @*/
4590: int MatSetColoring(Mat mat,ISColoring coloring)
4591: {


4598:   if (!mat->assembled) {
4599:     SETERRQ(1,"Matrix must be already assembled");
4600:   }
4601:   if (!mat->ops->setcoloring) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4602:   (*mat->ops->setcoloring)(mat,coloring);
4603:   return(0);
4604: }

4606: /*@ 
4607:    MatSetValuesAdifor - Sets values computed with automatic differentiation into a matrix.

4609:    Not Collective

4611:    Input Parameters:
4612: +  mat - the matrix
4613: .  nl - leading dimension of v
4614: -  v - the values compute with ADIFOR

4616:    Level: developer

4618:    Notes:
4619:      Must call MatSetColoring() before using this routine. Also this matrix must already
4620:      have its nonzero pattern determined.

4622: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
4623:           MatSetValues(), MatSetColoring()
4624: @*/
4625: int MatSetValuesAdifor(Mat mat,int nl,void *v)
4626: {


4633:   if (!mat->assembled) {
4634:     SETERRQ(1,"Matrix must be already assembled");
4635:   }
4636:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
4637:   if (!mat->ops->setvaluesadifor) SETERRQ1(PETSC_ERR_SUP,"Mat type %s",mat->type_name);
4638:   (*mat->ops->setvaluesadifor)(mat,nl,v);
4639:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
4640:   return(0);
4641: }