xref: /petsc/src/mat/interface/matrix.c (revision c783eb9e7d4443df2d00ad8bb41dd887df99e093)
1 
2 /*
3    This is where the abstract matrix operations are defined
4 */
5 
6 #include <petsc-private/matimpl.h>        /*I "petscmat.h" I*/
7 #include <petsc-private/vecimpl.h>
8 #include <petsc-private/isimpl.h>
9 
10 /* Logging support */
11 PetscClassId MAT_CLASSID;
12 PetscClassId MAT_COLORING_CLASSID;
13 PetscClassId MAT_FDCOLORING_CLASSID;
14 PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
15 
16 PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
17 PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve;
18 PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
19 PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
20 PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
21 PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_GetSubMatrices, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
22 PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
23 PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction;
24 PetscLogEvent MAT_TransposeColoringCreate;
25 PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
26 PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
27 PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
28 PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
29 PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
30 PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
31 PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_Transpose_SeqAIJ, MAT_GetBrowsOfAcols;
32 PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
33 PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
34 PetscLogEvent MAT_GetMultiProcBlock;
35 PetscLogEvent MAT_CUSPCopyToGPU, MAT_CUSPARSECopyToGPU, MAT_SetValuesBatch, MAT_SetValuesBatchI, MAT_SetValuesBatchII, MAT_SetValuesBatchIII, MAT_SetValuesBatchIV;
36 PetscLogEvent MAT_ViennaCLCopyToGPU;
37 PetscLogEvent MAT_Merge,MAT_Residual;
38 PetscLogEvent Mat_Coloring_Apply,Mat_Coloring_Comm,Mat_Coloring_Local,Mat_Coloring_ISCreate,Mat_Coloring_SetUp,Mat_Coloring_Weights;
39 
40 const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","MatFactorType","MAT_FACTOR_",0};
41 
42 #undef __FUNCT__
43 #define __FUNCT__ "MatSetRandom"
44 /*@
45    MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated it randomly selects appropriate locations
46 
47    Logically Collective on Vec
48 
49    Input Parameters:
50 +  x  - the vector
51 -  rctx - the random number context, formed by PetscRandomCreate(), or NULL and
52           it will create one internally.
53 
54    Output Parameter:
55 .  x  - the vector
56 
57    Example of Usage:
58 .vb
59      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
60      VecSetRandom(x,rctx);
61      PetscRandomDestroy(rctx);
62 .ve
63 
64    Level: intermediate
65 
66    Concepts: vector^setting to random
67    Concepts: random^vector
68 
69 .seealso: MatZeroEntries(), MatSetValues(), PetscRandomCreate(), PetscRandomDestroy()
70 @*/
71 PetscErrorCode  MatSetRandom(Mat x,PetscRandom rctx)
72 {
73   PetscErrorCode ierr;
74   PetscRandom    randObj = NULL;
75 
76   PetscFunctionBegin;
77   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
78   if (rctx) PetscValidHeaderSpecific(rctx,PETSC_RANDOM_CLASSID,2);
79   PetscValidType(x,1);
80 
81   if (!rctx) {
82     MPI_Comm comm;
83     ierr = PetscObjectGetComm((PetscObject)x,&comm);CHKERRQ(ierr);
84     ierr = PetscRandomCreate(comm,&randObj);CHKERRQ(ierr);
85     ierr = PetscRandomSetFromOptions(randObj);CHKERRQ(ierr);
86     rctx = randObj;
87   }
88 
89   ierr = PetscLogEventBegin(VEC_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
90   ierr = (*x->ops->setrandom)(x,rctx);CHKERRQ(ierr);
91   ierr = PetscLogEventEnd(VEC_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
92 
93   x->assembled = PETSC_TRUE;
94   ierr         = PetscRandomDestroy(&randObj);CHKERRQ(ierr);
95   PetscFunctionReturn(0);
96 }
97 
98 
99 #undef __FUNCT__
100 #define __FUNCT__ "MatFindNonzeroRows"
101 /*@
102       MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
103 
104   Input Parameter:
105 .    A  - the matrix
106 
107   Output Parameter:
108 .    keptrows - the rows that are not completely zero
109 
110   Level: intermediate
111 
112  @*/
113 PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
114 {
115   PetscErrorCode ierr;
116 
117   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
118   PetscValidType(mat,1);
119   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
120   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
121   if (!mat->ops->findnonzerorows) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not coded for this matrix type");
122   ierr = (*mat->ops->findnonzerorows)(mat,keptrows);CHKERRQ(ierr);
123   PetscFunctionReturn(0);
124 }
125 
126 #undef __FUNCT__
127 #define __FUNCT__ "MatGetDiagonalBlock"
128 /*@
129    MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
130 
131    Not Collective
132 
133    Input Parameters:
134 .   A - the matrix
135 
136    Output Parameters:
137 .   a - the diagonal part (which is a SEQUENTIAL matrix)
138 
139    Notes: see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.
140 
141    Level: advanced
142 
143 @*/
144 PetscErrorCode  MatGetDiagonalBlock(Mat A,Mat *a)
145 {
146   PetscErrorCode ierr,(*f)(Mat,Mat*);
147   PetscMPIInt    size;
148 
149   PetscFunctionBegin;
150   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
151   PetscValidType(A,1);
152   PetscValidPointer(a,3);
153   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
154   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRQ(ierr);
155   ierr = PetscObjectQueryFunction((PetscObject)A,"MatGetDiagonalBlock_C",&f);CHKERRQ(ierr);
156   if (f) {
157     ierr = (*f)(A,a);CHKERRQ(ierr);
158     PetscFunctionReturn(0);
159   } else if (size == 1) {
160     *a = A;
161   } else {
162     MatType mattype;
163     ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
164     SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix type %s does not support getting diagonal block",mattype);
165   }
166   PetscFunctionReturn(0);
167 }
168 
169 #undef __FUNCT__
170 #define __FUNCT__ "MatGetTrace"
171 /*@
172    MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
173 
174    Collective on Mat
175 
176    Input Parameters:
177 .  mat - the matrix
178 
179    Output Parameter:
180 .   trace - the sum of the diagonal entries
181 
182    Level: advanced
183 
184 @*/
185 PetscErrorCode  MatGetTrace(Mat mat,PetscScalar *trace)
186 {
187   PetscErrorCode ierr;
188   Vec            diag;
189 
190   PetscFunctionBegin;
191   ierr = MatCreateVecs(mat,&diag,NULL);CHKERRQ(ierr);
192   ierr = MatGetDiagonal(mat,diag);CHKERRQ(ierr);
193   ierr = VecSum(diag,trace);CHKERRQ(ierr);
194   ierr = VecDestroy(&diag);CHKERRQ(ierr);
195   PetscFunctionReturn(0);
196 }
197 
198 #undef __FUNCT__
199 #define __FUNCT__ "MatRealPart"
200 /*@
201    MatRealPart - Zeros out the imaginary part of the matrix
202 
203    Logically Collective on Mat
204 
205    Input Parameters:
206 .  mat - the matrix
207 
208    Level: advanced
209 
210 
211 .seealso: MatImaginaryPart()
212 @*/
213 PetscErrorCode  MatRealPart(Mat mat)
214 {
215   PetscErrorCode ierr;
216 
217   PetscFunctionBegin;
218   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
219   PetscValidType(mat,1);
220   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
221   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
222   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
223   MatCheckPreallocated(mat,1);
224   ierr = (*mat->ops->realpart)(mat);CHKERRQ(ierr);
225 #if defined(PETSC_HAVE_CUSP)
226   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
227     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
228   }
229 #endif
230 #if defined(PETSC_HAVE_VIENNACL)
231   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
232     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
233   }
234 #endif
235   PetscFunctionReturn(0);
236 }
237 
238 #undef __FUNCT__
239 #define __FUNCT__ "MatGetGhosts"
240 /*@C
241    MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix
242 
243    Collective on Mat
244 
245    Input Parameter:
246 .  mat - the matrix
247 
248    Output Parameters:
249 +   nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
250 -   ghosts - the global indices of the ghost points
251 
252    Notes: the nghosts and ghosts are suitable to pass into VecCreateGhost()
253 
254    Level: advanced
255 
256 @*/
257 PetscErrorCode  MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
258 {
259   PetscErrorCode ierr;
260 
261   PetscFunctionBegin;
262   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
263   PetscValidType(mat,1);
264   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
265   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
266   if (!mat->ops->getghosts) {
267     if (nghosts) *nghosts = 0;
268     if (ghosts) *ghosts = 0;
269   } else {
270     ierr = (*mat->ops->getghosts)(mat,nghosts,ghosts);CHKERRQ(ierr);
271   }
272   PetscFunctionReturn(0);
273 }
274 
275 
276 #undef __FUNCT__
277 #define __FUNCT__ "MatImaginaryPart"
278 /*@
279    MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
280 
281    Logically Collective on Mat
282 
283    Input Parameters:
284 .  mat - the matrix
285 
286    Level: advanced
287 
288 
289 .seealso: MatRealPart()
290 @*/
291 PetscErrorCode  MatImaginaryPart(Mat mat)
292 {
293   PetscErrorCode ierr;
294 
295   PetscFunctionBegin;
296   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
297   PetscValidType(mat,1);
298   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
299   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
300   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
301   MatCheckPreallocated(mat,1);
302   ierr = (*mat->ops->imaginarypart)(mat);CHKERRQ(ierr);
303 #if defined(PETSC_HAVE_CUSP)
304   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
305     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
306   }
307 #endif
308 #if defined(PETSC_HAVE_VIENNACL)
309   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
310     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
311   }
312 #endif
313   PetscFunctionReturn(0);
314 }
315 
316 #undef __FUNCT__
317 #define __FUNCT__ "MatMissingDiagonal"
318 /*@
319    MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)
320 
321    Collective on Mat
322 
323    Input Parameter:
324 .  mat - the matrix
325 
326    Output Parameters:
327 +  missing - is any diagonal missing
328 -  dd - first diagonal entry that is missing (optional)
329 
330    Level: advanced
331 
332 
333 .seealso: MatRealPart()
334 @*/
335 PetscErrorCode  MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
336 {
337   PetscErrorCode ierr;
338 
339   PetscFunctionBegin;
340   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
341   PetscValidType(mat,1);
342   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
343   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
344   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
345   ierr = (*mat->ops->missingdiagonal)(mat,missing,dd);CHKERRQ(ierr);
346   PetscFunctionReturn(0);
347 }
348 
349 #undef __FUNCT__
350 #define __FUNCT__ "MatGetRow"
351 /*@C
352    MatGetRow - Gets a row of a matrix.  You MUST call MatRestoreRow()
353    for each row that you get to ensure that your application does
354    not bleed memory.
355 
356    Not Collective
357 
358    Input Parameters:
359 +  mat - the matrix
360 -  row - the row to get
361 
362    Output Parameters:
363 +  ncols -  if not NULL, the number of nonzeros in the row
364 .  cols - if not NULL, the column numbers
365 -  vals - if not NULL, the values
366 
367    Notes:
368    This routine is provided for people who need to have direct access
369    to the structure of a matrix.  We hope that we provide enough
370    high-level matrix routines that few users will need it.
371 
372    MatGetRow() always returns 0-based column indices, regardless of
373    whether the internal representation is 0-based (default) or 1-based.
374 
375    For better efficiency, set cols and/or vals to NULL if you do
376    not wish to extract these quantities.
377 
378    The user can only examine the values extracted with MatGetRow();
379    the values cannot be altered.  To change the matrix entries, one
380    must use MatSetValues().
381 
382    You can only have one call to MatGetRow() outstanding for a particular
383    matrix at a time, per processor. MatGetRow() can only obtain rows
384    associated with the given processor, it cannot get rows from the
385    other processors; for that we suggest using MatGetSubMatrices(), then
386    MatGetRow() on the submatrix. The row indix passed to MatGetRows()
387    is in the global number of rows.
388 
389    Fortran Notes:
390    The calling sequence from Fortran is
391 .vb
392    MatGetRow(matrix,row,ncols,cols,values,ierr)
393          Mat     matrix (input)
394          integer row    (input)
395          integer ncols  (output)
396          integer cols(maxcols) (output)
397          double precision (or double complex) values(maxcols) output
398 .ve
399    where maxcols >= maximum nonzeros in any row of the matrix.
400 
401 
402    Caution:
403    Do not try to change the contents of the output arrays (cols and vals).
404    In some cases, this may corrupt the matrix.
405 
406    Level: advanced
407 
408    Concepts: matrices^row access
409 
410 .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatGetSubMatrices(), MatGetDiagonal()
411 @*/
412 PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
413 {
414   PetscErrorCode ierr;
415   PetscInt       incols;
416 
417   PetscFunctionBegin;
418   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
419   PetscValidType(mat,1);
420   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
421   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
422   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
423   MatCheckPreallocated(mat,1);
424   ierr = PetscLogEventBegin(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
425   ierr = (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);CHKERRQ(ierr);
426   if (ncols) *ncols = incols;
427   ierr = PetscLogEventEnd(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
428   PetscFunctionReturn(0);
429 }
430 
431 #undef __FUNCT__
432 #define __FUNCT__ "MatConjugate"
433 /*@
434    MatConjugate - replaces the matrix values with their complex conjugates
435 
436    Logically Collective on Mat
437 
438    Input Parameters:
439 .  mat - the matrix
440 
441    Level: advanced
442 
443 .seealso:  VecConjugate()
444 @*/
445 PetscErrorCode  MatConjugate(Mat mat)
446 {
447 #if defined(PETSC_USE_COMPLEX)
448   PetscErrorCode ierr;
449 
450   PetscFunctionBegin;
451   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
452   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
453   if (!mat->ops->conjugate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not provided for this matrix format, send email to petsc-maint@mcs.anl.gov");
454   ierr = (*mat->ops->conjugate)(mat);CHKERRQ(ierr);
455 #if defined(PETSC_HAVE_CUSP)
456   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
457     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
458   }
459 #endif
460 #if defined(PETSC_HAVE_VIENNACL)
461   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
462     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
463   }
464 #endif
465   PetscFunctionReturn(0);
466 #else
467   return 0;
468 #endif
469 }
470 
471 #undef __FUNCT__
472 #define __FUNCT__ "MatRestoreRow"
473 /*@C
474    MatRestoreRow - Frees any temporary space allocated by MatGetRow().
475 
476    Not Collective
477 
478    Input Parameters:
479 +  mat - the matrix
480 .  row - the row to get
481 .  ncols, cols - the number of nonzeros and their columns
482 -  vals - if nonzero the column values
483 
484    Notes:
485    This routine should be called after you have finished examining the entries.
486 
487    This routine zeros out ncols, cols, and vals. This is to prevent accidental
488    us of the array after it has been restored. If you pass NULL, it will
489    not zero the pointers.  Use of cols or vals after MatRestoreRow is invalid.
490 
491    Fortran Notes:
492    The calling sequence from Fortran is
493 .vb
494    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
495       Mat     matrix (input)
496       integer row    (input)
497       integer ncols  (output)
498       integer cols(maxcols) (output)
499       double precision (or double complex) values(maxcols) output
500 .ve
501    Where maxcols >= maximum nonzeros in any row of the matrix.
502 
503    In Fortran MatRestoreRow() MUST be called after MatGetRow()
504    before another call to MatGetRow() can be made.
505 
506    Level: advanced
507 
508 .seealso:  MatGetRow()
509 @*/
510 PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
511 {
512   PetscErrorCode ierr;
513 
514   PetscFunctionBegin;
515   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
516   if (ncols) PetscValidIntPointer(ncols,3);
517   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
518   if (!mat->ops->restorerow) PetscFunctionReturn(0);
519   ierr = (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);CHKERRQ(ierr);
520   if (ncols) *ncols = 0;
521   if (cols)  *cols = NULL;
522   if (vals)  *vals = NULL;
523   PetscFunctionReturn(0);
524 }
525 
526 #undef __FUNCT__
527 #define __FUNCT__ "MatGetRowUpperTriangular"
528 /*@
529    MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
530    You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.
531 
532    Not Collective
533 
534    Input Parameters:
535 +  mat - the matrix
536 
537    Notes:
538    The flag is to ensure that users are aware of MatGetRow() only provides the upper trianglular part of the row for the matrices in MATSBAIJ format.
539 
540    Level: advanced
541 
542    Concepts: matrices^row access
543 
544 .seealso: MatRestoreRowRowUpperTriangular()
545 @*/
546 PetscErrorCode  MatGetRowUpperTriangular(Mat mat)
547 {
548   PetscErrorCode ierr;
549 
550   PetscFunctionBegin;
551   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
552   PetscValidType(mat,1);
553   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
554   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
555   if (!mat->ops->getrowuppertriangular) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
556   MatCheckPreallocated(mat,1);
557   ierr = (*mat->ops->getrowuppertriangular)(mat);CHKERRQ(ierr);
558   PetscFunctionReturn(0);
559 }
560 
561 #undef __FUNCT__
562 #define __FUNCT__ "MatRestoreRowUpperTriangular"
563 /*@
564    MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.
565 
566    Not Collective
567 
568    Input Parameters:
569 +  mat - the matrix
570 
571    Notes:
572    This routine should be called after you have finished MatGetRow/MatRestoreRow().
573 
574 
575    Level: advanced
576 
577 .seealso:  MatGetRowUpperTriangular()
578 @*/
579 PetscErrorCode  MatRestoreRowUpperTriangular(Mat mat)
580 {
581   PetscErrorCode ierr;
582 
583   PetscFunctionBegin;
584   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
585   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
586   if (!mat->ops->restorerowuppertriangular) PetscFunctionReturn(0);
587   ierr = (*mat->ops->restorerowuppertriangular)(mat);CHKERRQ(ierr);
588   PetscFunctionReturn(0);
589 }
590 
591 #undef __FUNCT__
592 #define __FUNCT__ "MatSetOptionsPrefix"
593 /*@C
594    MatSetOptionsPrefix - Sets the prefix used for searching for all
595    Mat options in the database.
596 
597    Logically Collective on Mat
598 
599    Input Parameter:
600 +  A - the Mat context
601 -  prefix - the prefix to prepend to all option names
602 
603    Notes:
604    A hyphen (-) must NOT be given at the beginning of the prefix name.
605    The first character of all runtime options is AUTOMATICALLY the hyphen.
606 
607    Level: advanced
608 
609 .keywords: Mat, set, options, prefix, database
610 
611 .seealso: MatSetFromOptions()
612 @*/
613 PetscErrorCode  MatSetOptionsPrefix(Mat A,const char prefix[])
614 {
615   PetscErrorCode ierr;
616 
617   PetscFunctionBegin;
618   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
619   ierr = PetscObjectSetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
620   PetscFunctionReturn(0);
621 }
622 
623 #undef __FUNCT__
624 #define __FUNCT__ "MatAppendOptionsPrefix"
625 /*@C
626    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
627    Mat options in the database.
628 
629    Logically Collective on Mat
630 
631    Input Parameters:
632 +  A - the Mat context
633 -  prefix - the prefix to prepend to all option names
634 
635    Notes:
636    A hyphen (-) must NOT be given at the beginning of the prefix name.
637    The first character of all runtime options is AUTOMATICALLY the hyphen.
638 
639    Level: advanced
640 
641 .keywords: Mat, append, options, prefix, database
642 
643 .seealso: MatGetOptionsPrefix()
644 @*/
645 PetscErrorCode  MatAppendOptionsPrefix(Mat A,const char prefix[])
646 {
647   PetscErrorCode ierr;
648 
649   PetscFunctionBegin;
650   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
651   ierr = PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
652   PetscFunctionReturn(0);
653 }
654 
655 #undef __FUNCT__
656 #define __FUNCT__ "MatGetOptionsPrefix"
657 /*@C
658    MatGetOptionsPrefix - Sets the prefix used for searching for all
659    Mat options in the database.
660 
661    Not Collective
662 
663    Input Parameter:
664 .  A - the Mat context
665 
666    Output Parameter:
667 .  prefix - pointer to the prefix string used
668 
669    Notes: On the fortran side, the user should pass in a string 'prefix' of
670    sufficient length to hold the prefix.
671 
672    Level: advanced
673 
674 .keywords: Mat, get, options, prefix, database
675 
676 .seealso: MatAppendOptionsPrefix()
677 @*/
678 PetscErrorCode  MatGetOptionsPrefix(Mat A,const char *prefix[])
679 {
680   PetscErrorCode ierr;
681 
682   PetscFunctionBegin;
683   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
684   ierr = PetscObjectGetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
685   PetscFunctionReturn(0);
686 }
687 
688 #undef __FUNCT__
689 #define __FUNCT__ "MatSetUp"
690 /*@
691    MatSetUp - Sets up the internal matrix data structures for the later use.
692 
693    Collective on Mat
694 
695    Input Parameters:
696 .  A - the Mat context
697 
698    Notes:
699    If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.
700 
701    If a suitable preallocation routine is used, this function does not need to be called.
702 
703    See the Performance chapter of the PETSc users manual for how to preallocate matrices
704 
705    Level: beginner
706 
707 .keywords: Mat, setup
708 
709 .seealso: MatCreate(), MatDestroy()
710 @*/
711 PetscErrorCode  MatSetUp(Mat A)
712 {
713   PetscMPIInt    size;
714   PetscErrorCode ierr;
715 
716   PetscFunctionBegin;
717   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
718   if (!((PetscObject)A)->type_name) {
719     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);CHKERRQ(ierr);
720     if (size == 1) {
721       ierr = MatSetType(A, MATSEQAIJ);CHKERRQ(ierr);
722     } else {
723       ierr = MatSetType(A, MATMPIAIJ);CHKERRQ(ierr);
724     }
725   }
726   if (!A->preallocated && A->ops->setup) {
727     ierr = PetscInfo(A,"Warning not preallocating matrix storage\n");CHKERRQ(ierr);
728     ierr = (*A->ops->setup)(A);CHKERRQ(ierr);
729   }
730   A->preallocated = PETSC_TRUE;
731   PetscFunctionReturn(0);
732 }
733 
734 #if defined(PETSC_HAVE_SAWS)
735 #include <petscviewersaws.h>
736 #endif
737 #undef __FUNCT__
738 #define __FUNCT__ "MatView"
739 /*@C
740    MatView - Visualizes a matrix object.
741 
742    Collective on Mat
743 
744    Input Parameters:
745 +  mat - the matrix
746 -  viewer - visualization context
747 
748   Notes:
749   The available visualization contexts include
750 +    PETSC_VIEWER_STDOUT_SELF - standard output (default)
751 .    PETSC_VIEWER_STDOUT_WORLD - synchronized standard
752         output where only the first processor opens
753         the file.  All other processors send their
754         data to the first processor to print.
755 -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
756 
757    The user can open alternative visualization contexts with
758 +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
759 .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
760          specified file; corresponding input uses MatLoad()
761 .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
762          an X window display
763 -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
764          Currently only the sequential dense and AIJ
765          matrix types support the Socket viewer.
766 
767    The user can call PetscViewerSetFormat() to specify the output
768    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
769    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
770 +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
771 .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
772 .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
773 .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
774          format common among all matrix types
775 .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
776          format (which is in many cases the same as the default)
777 .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
778          size and structure (not the matrix entries)
779 .    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
780          the matrix structure
781 
782    Options Database Keys:
783 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
784 .  -mat_view ::ascii_info_detail - Prints more detailed info
785 .  -mat_view - Prints matrix in ASCII format
786 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
787 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
788 .  -display <name> - Sets display name (default is host)
789 .  -draw_pause <sec> - Sets number of seconds to pause after display
790 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: ch_matlab for details)
791 .  -viewer_socket_machine <machine> -
792 .  -viewer_socket_port <port> -
793 .  -mat_view binary - save matrix to file in binary format
794 -  -viewer_binary_filename <name> -
795    Level: beginner
796 
797    Notes: see the manual page for MatLoad() for the exact format of the binary file when the binary
798       viewer is used.
799 
800       See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
801       viewer is used.
802 
803       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure.
804       And then use the following mouse functions:
805           left mouse: zoom in
806           middle mouse: zoom out
807           right mouse: continue with the simulation
808 
809    Concepts: matrices^viewing
810    Concepts: matrices^plotting
811    Concepts: matrices^printing
812 
813 .seealso: PetscViewerSetFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
814           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
815 @*/
816 PetscErrorCode  MatView(Mat mat,PetscViewer viewer)
817 {
818   PetscErrorCode    ierr;
819   PetscInt          rows,cols,rbs,cbs;
820   PetscBool         iascii;
821   PetscViewerFormat format;
822 #if defined(PETSC_HAVE_SAWS)
823   PetscBool         isams;
824 #endif
825 
826   PetscFunctionBegin;
827   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
828   PetscValidType(mat,1);
829   if (!viewer) {
830     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);CHKERRQ(ierr);
831   }
832   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
833   PetscCheckSameComm(mat,1,viewer,2);
834   MatCheckPreallocated(mat,1);
835 
836   ierr = PetscLogEventBegin(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
837   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
838   ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
839   if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
840     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
841   }
842 
843 #if defined(PETSC_HAVE_SAWS)
844   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&isams);CHKERRQ(ierr);
845 #endif
846   if (iascii) {
847     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
848     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);CHKERRQ(ierr);
849     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
850       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
851       ierr = MatGetSize(mat,&rows,&cols);CHKERRQ(ierr);
852       ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
853       if (rbs != 1 || cbs != 1) {
854         if (rbs != cbs) {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs = %D\n",rows,cols,rbs,cbs);CHKERRQ(ierr);}
855         else            {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);CHKERRQ(ierr);}
856       } else {
857         ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);CHKERRQ(ierr);
858       }
859       if (mat->factortype) {
860         const MatSolverPackage solver;
861         ierr = MatFactorGetSolverPackage(mat,&solver);CHKERRQ(ierr);
862         ierr = PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);CHKERRQ(ierr);
863       }
864       if (mat->ops->getinfo) {
865         MatInfo info;
866         ierr = MatGetInfo(mat,MAT_GLOBAL_SUM,&info);CHKERRQ(ierr);
867         ierr = PetscViewerASCIIPrintf(viewer,"total: nonzeros=%g, allocated nonzeros=%g\n",info.nz_used,info.nz_allocated);CHKERRQ(ierr);
868         ierr = PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls =%D\n",(PetscInt)info.mallocs);CHKERRQ(ierr);
869       }
870       if (mat->nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached null space\n");CHKERRQ(ierr);}
871       if (mat->nearnullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");CHKERRQ(ierr);}
872     }
873 #if defined(PETSC_HAVE_SAWS)
874   } else if (isams) {
875     PetscMPIInt rank;
876 
877     ierr = PetscObjectName((PetscObject)mat);CHKERRQ(ierr);
878     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
879     if (!((PetscObject)mat)->amsmem && !rank) {
880       ierr = PetscObjectViewSAWs((PetscObject)mat,viewer);CHKERRQ(ierr);
881     }
882 #endif
883   }
884   if (mat->ops->view) {
885     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
886     ierr = (*mat->ops->view)(mat,viewer);CHKERRQ(ierr);
887     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
888   }
889   if (iascii) {
890     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
891     ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
892     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
893       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
894     }
895   }
896   ierr = PetscLogEventEnd(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
897   PetscFunctionReturn(0);
898 }
899 
900 #if defined(PETSC_USE_DEBUG)
901 #include <../src/sys/totalview/tv_data_display.h>
902 PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
903 {
904   TV_add_row("Local rows", "int", &mat->rmap->n);
905   TV_add_row("Local columns", "int", &mat->cmap->n);
906   TV_add_row("Global rows", "int", &mat->rmap->N);
907   TV_add_row("Global columns", "int", &mat->cmap->N);
908   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
909   return TV_format_OK;
910 }
911 #endif
912 
913 #undef __FUNCT__
914 #define __FUNCT__ "MatLoad"
915 /*@C
916    MatLoad - Loads a matrix that has been stored in binary format
917    with MatView().  The matrix format is determined from the options database.
918    Generates a parallel MPI matrix if the communicator has more than one
919    processor.  The default matrix type is AIJ.
920 
921    Collective on PetscViewer
922 
923    Input Parameters:
924 +  newmat - the newly loaded matrix, this needs to have been created with MatCreate()
925             or some related function before a call to MatLoad()
926 -  viewer - binary file viewer, created with PetscViewerBinaryOpen()
927 
928    Options Database Keys:
929    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
930    block size
931 .    -matload_block_size <bs>
932 
933    Level: beginner
934 
935    Notes:
936    If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
937    Mat before calling this routine if you wish to set it from the options database.
938 
939    MatLoad() automatically loads into the options database any options
940    given in the file filename.info where filename is the name of the file
941    that was passed to the PetscViewerBinaryOpen(). The options in the info
942    file will be ignored if you use the -viewer_binary_skip_info option.
943 
944    If the type or size of newmat is not set before a call to MatLoad, PETSc
945    sets the default matrix type AIJ and sets the local and global sizes.
946    If type and/or size is already set, then the same are used.
947 
948    In parallel, each processor can load a subset of rows (or the
949    entire matrix).  This routine is especially useful when a large
950    matrix is stored on disk and only part of it is desired on each
951    processor.  For example, a parallel solver may access only some of
952    the rows from each processor.  The algorithm used here reads
953    relatively small blocks of data rather than reading the entire
954    matrix and then subsetting it.
955 
956    Notes for advanced users:
957    Most users should not need to know the details of the binary storage
958    format, since MatLoad() and MatView() completely hide these details.
959    But for anyone who's interested, the standard binary matrix storage
960    format is
961 
962 $    int    MAT_FILE_CLASSID
963 $    int    number of rows
964 $    int    number of columns
965 $    int    total number of nonzeros
966 $    int    *number nonzeros in each row
967 $    int    *column indices of all nonzeros (starting index is zero)
968 $    PetscScalar *values of all nonzeros
969 
970    PETSc automatically does the byte swapping for
971 machines that store the bytes reversed, e.g.  DEC alpha, freebsd,
972 linux, Windows and the paragon; thus if you write your own binary
973 read/write routines you have to swap the bytes; see PetscBinaryRead()
974 and PetscBinaryWrite() to see how this may be done.
975 
976 .keywords: matrix, load, binary, input
977 
978 .seealso: PetscViewerBinaryOpen(), MatView(), VecLoad()
979 
980  @*/
981 PetscErrorCode  MatLoad(Mat newmat,PetscViewer viewer)
982 {
983   PetscErrorCode ierr;
984   PetscBool      isbinary,flg;
985 
986   PetscFunctionBegin;
987   PetscValidHeaderSpecific(newmat,MAT_CLASSID,1);
988   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
989   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
990   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
991 
992   if (!((PetscObject)newmat)->type_name) {
993     ierr = MatSetType(newmat,MATAIJ);CHKERRQ(ierr);
994   }
995 
996   if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
997   ierr = PetscLogEventBegin(MAT_Load,viewer,0,0,0);CHKERRQ(ierr);
998   ierr = (*newmat->ops->load)(newmat,viewer);CHKERRQ(ierr);
999   ierr = PetscLogEventEnd(MAT_Load,viewer,0,0,0);CHKERRQ(ierr);
1000 
1001   flg  = PETSC_FALSE;
1002   ierr = PetscOptionsGetBool(((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);CHKERRQ(ierr);
1003   if (flg) {
1004     ierr = MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
1005     ierr = MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);CHKERRQ(ierr);
1006   }
1007   flg  = PETSC_FALSE;
1008   ierr = PetscOptionsGetBool(((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);CHKERRQ(ierr);
1009   if (flg) {
1010     ierr = MatSetOption(newmat,MAT_SPD,PETSC_TRUE);CHKERRQ(ierr);
1011   }
1012   PetscFunctionReturn(0);
1013 }
1014 
1015 #undef __FUNCT__
1016 #define __FUNCT__ "MatDestroy_Redundant"
1017 PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1018 {
1019   PetscErrorCode ierr;
1020   Mat_Redundant  *redund = *redundant;
1021   PetscInt       i;
1022 
1023   PetscFunctionBegin;
1024   if (redund){
1025     if (redund->matseq) { /* via MatGetSubMatrices()  */
1026       ierr = ISDestroy(&redund->isrow);CHKERRQ(ierr);
1027       ierr = ISDestroy(&redund->iscol);CHKERRQ(ierr);
1028       ierr = MatDestroy(&redund->matseq[0]);CHKERRQ(ierr);
1029       ierr = PetscFree(redund->matseq);CHKERRQ(ierr);
1030     } else {
1031       ierr = PetscFree2(redund->send_rank,redund->recv_rank);CHKERRQ(ierr);
1032       ierr = PetscFree(redund->sbuf_j);CHKERRQ(ierr);
1033       ierr = PetscFree(redund->sbuf_a);CHKERRQ(ierr);
1034       for (i=0; i<redund->nrecvs; i++) {
1035         ierr = PetscFree(redund->rbuf_j[i]);CHKERRQ(ierr);
1036         ierr = PetscFree(redund->rbuf_a[i]);CHKERRQ(ierr);
1037       }
1038       ierr = PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);CHKERRQ(ierr);
1039     }
1040 
1041     if (redund->subcomm) {
1042       ierr = PetscCommDestroy(&redund->subcomm);CHKERRQ(ierr);
1043     }
1044     ierr = PetscFree(redund);CHKERRQ(ierr);
1045   }
1046   PetscFunctionReturn(0);
1047 }
1048 
1049 #undef __FUNCT__
1050 #define __FUNCT__ "MatDestroy"
1051 /*@
1052    MatDestroy - Frees space taken by a matrix.
1053 
1054    Collective on Mat
1055 
1056    Input Parameter:
1057 .  A - the matrix
1058 
1059    Level: beginner
1060 
1061 @*/
1062 PetscErrorCode  MatDestroy(Mat *A)
1063 {
1064   PetscErrorCode ierr;
1065 
1066   PetscFunctionBegin;
1067   if (!*A) PetscFunctionReturn(0);
1068   PetscValidHeaderSpecific(*A,MAT_CLASSID,1);
1069   if (--((PetscObject)(*A))->refct > 0) {*A = NULL; PetscFunctionReturn(0);}
1070 
1071   /* if memory was published with SAWs then destroy it */
1072   ierr = PetscObjectSAWsViewOff((PetscObject)*A);CHKERRQ(ierr);
1073   if ((*A)->ops->destroy) {
1074     ierr = (*(*A)->ops->destroy)(*A);CHKERRQ(ierr);
1075   }
1076   ierr = MatDestroy_Redundant(&(*A)->redundant);CHKERRQ(ierr);
1077   ierr = MatNullSpaceDestroy(&(*A)->nullsp);CHKERRQ(ierr);
1078   ierr = MatNullSpaceDestroy(&(*A)->nearnullsp);CHKERRQ(ierr);
1079   ierr = PetscLayoutDestroy(&(*A)->rmap);CHKERRQ(ierr);
1080   ierr = PetscLayoutDestroy(&(*A)->cmap);CHKERRQ(ierr);
1081   ierr = PetscHeaderDestroy(A);CHKERRQ(ierr);
1082   PetscFunctionReturn(0);
1083 }
1084 
1085 #undef __FUNCT__
1086 #define __FUNCT__ "MatSetValues"
1087 /*@
1088    MatSetValues - Inserts or adds a block of values into a matrix.
1089    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1090    MUST be called after all calls to MatSetValues() have been completed.
1091 
1092    Not Collective
1093 
1094    Input Parameters:
1095 +  mat - the matrix
1096 .  v - a logically two-dimensional array of values
1097 .  m, idxm - the number of rows and their global indices
1098 .  n, idxn - the number of columns and their global indices
1099 -  addv - either ADD_VALUES or INSERT_VALUES, where
1100    ADD_VALUES adds values to any existing entries, and
1101    INSERT_VALUES replaces existing entries with new values
1102 
1103    Notes:
1104    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1105       MatSetUp() before using this routine
1106 
1107    By default the values, v, are row-oriented. See MatSetOption() for other options.
1108 
1109    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1110    options cannot be mixed without intervening calls to the assembly
1111    routines.
1112 
1113    MatSetValues() uses 0-based row and column numbers in Fortran
1114    as well as in C.
1115 
1116    Negative indices may be passed in idxm and idxn, these rows and columns are
1117    simply ignored. This allows easily inserting element stiffness matrices
1118    with homogeneous Dirchlet boundary conditions that you don't want represented
1119    in the matrix.
1120 
1121    Efficiency Alert:
1122    The routine MatSetValuesBlocked() may offer much better efficiency
1123    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1124 
1125    Level: beginner
1126 
1127    Concepts: matrices^putting entries in
1128 
1129 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1130           InsertMode, INSERT_VALUES, ADD_VALUES
1131 @*/
1132 PetscErrorCode  MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1133 {
1134   PetscErrorCode ierr;
1135 #if defined(PETSC_USE_DEBUG)
1136   PetscInt       i,j;
1137 #endif
1138 
1139   PetscFunctionBeginHot;
1140   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1141   PetscValidType(mat,1);
1142   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1143   PetscValidIntPointer(idxm,3);
1144   PetscValidIntPointer(idxn,5);
1145   PetscValidScalarPointer(v,6);
1146   MatCheckPreallocated(mat,1);
1147   if (mat->insertmode == NOT_SET_VALUES) {
1148     mat->insertmode = addv;
1149   }
1150 #if defined(PETSC_USE_DEBUG)
1151   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1152   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1153   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1154 
1155   for (i=0; i<m; i++) {
1156     for (j=0; j<n; j++) {
1157       if (PetscIsInfOrNanScalar(v[i*n+j]))
1158 #if defined(PETSC_USE_COMPLEX)
1159         SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g+ig at matrix entry (%D,%D)",(double)PetscRealPart(v[i*n+j]),(double)PetscImaginaryPart(v[i*n+j]),idxm[i],idxn[j]);
1160 #else
1161       SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1162 #endif
1163     }
1164   }
1165 #endif
1166 
1167   if (mat->assembled) {
1168     mat->was_assembled = PETSC_TRUE;
1169     mat->assembled     = PETSC_FALSE;
1170   }
1171   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1172   ierr = (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);CHKERRQ(ierr);
1173   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1174 #if defined(PETSC_HAVE_CUSP)
1175   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1176     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1177   }
1178 #endif
1179 #if defined(PETSC_HAVE_VIENNACL)
1180   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1181     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1182   }
1183 #endif
1184   PetscFunctionReturn(0);
1185 }
1186 
1187 
1188 #undef __FUNCT__
1189 #define __FUNCT__ "MatSetValuesRowLocal"
1190 /*@
1191    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1192         values into a matrix
1193 
1194    Not Collective
1195 
1196    Input Parameters:
1197 +  mat - the matrix
1198 .  row - the (block) row to set
1199 -  v - a logically two-dimensional array of values
1200 
1201    Notes:
1202    By the values, v, are column-oriented (for the block version) and sorted
1203 
1204    All the nonzeros in the row must be provided
1205 
1206    The matrix must have previously had its column indices set
1207 
1208    The row must belong to this process
1209 
1210    Level: intermediate
1211 
1212    Concepts: matrices^putting entries in
1213 
1214 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1215           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1216 @*/
1217 PetscErrorCode  MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1218 {
1219   PetscErrorCode ierr;
1220   PetscInt       globalrow;
1221 
1222   PetscFunctionBegin;
1223   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1224   PetscValidType(mat,1);
1225   PetscValidScalarPointer(v,2);
1226   ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);CHKERRQ(ierr);
1227   ierr = MatSetValuesRow(mat,globalrow,v);CHKERRQ(ierr);
1228 #if defined(PETSC_HAVE_CUSP)
1229   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1230     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1231   }
1232 #endif
1233 #if defined(PETSC_HAVE_VIENNACL)
1234   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1235     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1236   }
1237 #endif
1238   PetscFunctionReturn(0);
1239 }
1240 
1241 #undef __FUNCT__
1242 #define __FUNCT__ "MatSetValuesRow"
1243 /*@
1244    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1245         values into a matrix
1246 
1247    Not Collective
1248 
1249    Input Parameters:
1250 +  mat - the matrix
1251 .  row - the (block) row to set
1252 -  v - a logically two-dimensional array of values
1253 
1254    Notes:
1255    The values, v, are column-oriented for the block version.
1256 
1257    All the nonzeros in the row must be provided
1258 
1259    THE MATRIX MUSAT HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1260 
1261    The row must belong to this process
1262 
1263    Level: advanced
1264 
1265    Concepts: matrices^putting entries in
1266 
1267 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1268           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1269 @*/
1270 PetscErrorCode  MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1271 {
1272   PetscErrorCode ierr;
1273 
1274   PetscFunctionBeginHot;
1275   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1276   PetscValidType(mat,1);
1277   MatCheckPreallocated(mat,1);
1278   PetscValidScalarPointer(v,2);
1279 #if defined(PETSC_USE_DEBUG)
1280   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1281   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1282 #endif
1283   mat->insertmode = INSERT_VALUES;
1284 
1285   if (mat->assembled) {
1286     mat->was_assembled = PETSC_TRUE;
1287     mat->assembled     = PETSC_FALSE;
1288   }
1289   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1290   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1291   ierr = (*mat->ops->setvaluesrow)(mat,row,v);CHKERRQ(ierr);
1292   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1293 #if defined(PETSC_HAVE_CUSP)
1294   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1295     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1296   }
1297 #endif
1298 #if defined(PETSC_HAVE_VIENNACL)
1299   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1300     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1301   }
1302 #endif
1303   PetscFunctionReturn(0);
1304 }
1305 
1306 #undef __FUNCT__
1307 #define __FUNCT__ "MatSetValuesStencil"
1308 /*@
1309    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1310      Using structured grid indexing
1311 
1312    Not Collective
1313 
1314    Input Parameters:
1315 +  mat - the matrix
1316 .  m - number of rows being entered
1317 .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1318 .  n - number of columns being entered
1319 .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1320 .  v - a logically two-dimensional array of values
1321 -  addv - either ADD_VALUES or INSERT_VALUES, where
1322    ADD_VALUES adds values to any existing entries, and
1323    INSERT_VALUES replaces existing entries with new values
1324 
1325    Notes:
1326    By default the values, v, are row-oriented.  See MatSetOption() for other options.
1327 
1328    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1329    options cannot be mixed without intervening calls to the assembly
1330    routines.
1331 
1332    The grid coordinates are across the entire grid, not just the local portion
1333 
1334    MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1335    as well as in C.
1336 
1337    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1338 
1339    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1340    or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1341 
1342    The columns and rows in the stencil passed in MUST be contained within the
1343    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1344    if you create a DMDA with an overlap of one grid level and on a particular process its first
1345    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1346    first i index you can use in your column and row indices in MatSetStencil() is 5.
1347 
1348    In Fortran idxm and idxn should be declared as
1349 $     MatStencil idxm(4,m),idxn(4,n)
1350    and the values inserted using
1351 $    idxm(MatStencil_i,1) = i
1352 $    idxm(MatStencil_j,1) = j
1353 $    idxm(MatStencil_k,1) = k
1354 $    idxm(MatStencil_c,1) = c
1355    etc
1356 
1357    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1358    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1359    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1360    DM_BOUNDARY_PERIODIC boundary type.
1361 
1362    For indices that don't mean anything for your case (like the k index when working in 2d) or the c index when you have
1363    a single value per point) you can skip filling those indices.
1364 
1365    Inspired by the structured grid interface to the HYPRE package
1366    (http://www.llnl.gov/CASC/hypre)
1367 
1368    Efficiency Alert:
1369    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1370    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1371 
1372    Level: beginner
1373 
1374    Concepts: matrices^putting entries in
1375 
1376 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1377           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1378 @*/
1379 PetscErrorCode  MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1380 {
1381   PetscErrorCode ierr;
1382   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1383   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1384   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1385 
1386   PetscFunctionBegin;
1387   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1388   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1389   PetscValidType(mat,1);
1390   PetscValidIntPointer(idxm,3);
1391   PetscValidIntPointer(idxn,5);
1392   PetscValidScalarPointer(v,6);
1393 
1394   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1395     jdxm = buf; jdxn = buf+m;
1396   } else {
1397     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1398     jdxm = bufm; jdxn = bufn;
1399   }
1400   for (i=0; i<m; i++) {
1401     for (j=0; j<3-sdim; j++) dxm++;
1402     tmp = *dxm++ - starts[0];
1403     for (j=0; j<dim-1; j++) {
1404       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1405       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1406     }
1407     if (mat->stencil.noc) dxm++;
1408     jdxm[i] = tmp;
1409   }
1410   for (i=0; i<n; i++) {
1411     for (j=0; j<3-sdim; j++) dxn++;
1412     tmp = *dxn++ - starts[0];
1413     for (j=0; j<dim-1; j++) {
1414       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1415       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1416     }
1417     if (mat->stencil.noc) dxn++;
1418     jdxn[i] = tmp;
1419   }
1420   ierr = MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1421   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1422   PetscFunctionReturn(0);
1423 }
1424 
1425 #undef __FUNCT__
1426 #define __FUNCT__ "MatSetValuesBlockedStencil"
1427 /*@
1428    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1429      Using structured grid indexing
1430 
1431    Not Collective
1432 
1433    Input Parameters:
1434 +  mat - the matrix
1435 .  m - number of rows being entered
1436 .  idxm - grid coordinates for matrix rows being entered
1437 .  n - number of columns being entered
1438 .  idxn - grid coordinates for matrix columns being entered
1439 .  v - a logically two-dimensional array of values
1440 -  addv - either ADD_VALUES or INSERT_VALUES, where
1441    ADD_VALUES adds values to any existing entries, and
1442    INSERT_VALUES replaces existing entries with new values
1443 
1444    Notes:
1445    By default the values, v, are row-oriented and unsorted.
1446    See MatSetOption() for other options.
1447 
1448    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1449    options cannot be mixed without intervening calls to the assembly
1450    routines.
1451 
1452    The grid coordinates are across the entire grid, not just the local portion
1453 
1454    MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1455    as well as in C.
1456 
1457    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1458 
1459    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1460    or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1461 
1462    The columns and rows in the stencil passed in MUST be contained within the
1463    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1464    if you create a DMDA with an overlap of one grid level and on a particular process its first
1465    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1466    first i index you can use in your column and row indices in MatSetStencil() is 5.
1467 
1468    In Fortran idxm and idxn should be declared as
1469 $     MatStencil idxm(4,m),idxn(4,n)
1470    and the values inserted using
1471 $    idxm(MatStencil_i,1) = i
1472 $    idxm(MatStencil_j,1) = j
1473 $    idxm(MatStencil_k,1) = k
1474    etc
1475 
1476    Negative indices may be passed in idxm and idxn, these rows and columns are
1477    simply ignored. This allows easily inserting element stiffness matrices
1478    with homogeneous Dirchlet boundary conditions that you don't want represented
1479    in the matrix.
1480 
1481    Inspired by the structured grid interface to the HYPRE package
1482    (http://www.llnl.gov/CASC/hypre)
1483 
1484    Level: beginner
1485 
1486    Concepts: matrices^putting entries in
1487 
1488 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1489           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1490           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1491 @*/
1492 PetscErrorCode  MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1493 {
1494   PetscErrorCode ierr;
1495   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1496   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1497   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1498 
1499   PetscFunctionBegin;
1500   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1501   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1502   PetscValidType(mat,1);
1503   PetscValidIntPointer(idxm,3);
1504   PetscValidIntPointer(idxn,5);
1505   PetscValidScalarPointer(v,6);
1506 
1507   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1508     jdxm = buf; jdxn = buf+m;
1509   } else {
1510     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1511     jdxm = bufm; jdxn = bufn;
1512   }
1513   for (i=0; i<m; i++) {
1514     for (j=0; j<3-sdim; j++) dxm++;
1515     tmp = *dxm++ - starts[0];
1516     for (j=0; j<sdim-1; j++) {
1517       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1518       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1519     }
1520     dxm++;
1521     jdxm[i] = tmp;
1522   }
1523   for (i=0; i<n; i++) {
1524     for (j=0; j<3-sdim; j++) dxn++;
1525     tmp = *dxn++ - starts[0];
1526     for (j=0; j<sdim-1; j++) {
1527       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1528       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1529     }
1530     dxn++;
1531     jdxn[i] = tmp;
1532   }
1533   ierr = MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1534   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1535 #if defined(PETSC_HAVE_CUSP)
1536   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1537     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1538   }
1539 #endif
1540 #if defined(PETSC_HAVE_VIENNACL)
1541   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1542     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1543   }
1544 #endif
1545   PetscFunctionReturn(0);
1546 }
1547 
1548 #undef __FUNCT__
1549 #define __FUNCT__ "MatSetStencil"
1550 /*@
1551    MatSetStencil - Sets the grid information for setting values into a matrix via
1552         MatSetValuesStencil()
1553 
1554    Not Collective
1555 
1556    Input Parameters:
1557 +  mat - the matrix
1558 .  dim - dimension of the grid 1, 2, or 3
1559 .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1560 .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1561 -  dof - number of degrees of freedom per node
1562 
1563 
1564    Inspired by the structured grid interface to the HYPRE package
1565    (www.llnl.gov/CASC/hyper)
1566 
1567    For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1568    user.
1569 
1570    Level: beginner
1571 
1572    Concepts: matrices^putting entries in
1573 
1574 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1575           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1576 @*/
1577 PetscErrorCode  MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1578 {
1579   PetscInt i;
1580 
1581   PetscFunctionBegin;
1582   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1583   PetscValidIntPointer(dims,3);
1584   PetscValidIntPointer(starts,4);
1585 
1586   mat->stencil.dim = dim + (dof > 1);
1587   for (i=0; i<dim; i++) {
1588     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1589     mat->stencil.starts[i] = starts[dim-i-1];
1590   }
1591   mat->stencil.dims[dim]   = dof;
1592   mat->stencil.starts[dim] = 0;
1593   mat->stencil.noc         = (PetscBool)(dof == 1);
1594   PetscFunctionReturn(0);
1595 }
1596 
1597 #undef __FUNCT__
1598 #define __FUNCT__ "MatSetValuesBlocked"
1599 /*@
1600    MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1601 
1602    Not Collective
1603 
1604    Input Parameters:
1605 +  mat - the matrix
1606 .  v - a logically two-dimensional array of values
1607 .  m, idxm - the number of block rows and their global block indices
1608 .  n, idxn - the number of block columns and their global block indices
1609 -  addv - either ADD_VALUES or INSERT_VALUES, where
1610    ADD_VALUES adds values to any existing entries, and
1611    INSERT_VALUES replaces existing entries with new values
1612 
1613    Notes:
1614    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1615    MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1616 
1617    The m and n count the NUMBER of blocks in the row direction and column direction,
1618    NOT the total number of rows/columns; for example, if the block size is 2 and
1619    you are passing in values for rows 2,3,4,5  then m would be 2 (not 4).
1620    The values in idxm would be 1 2; that is the first index for each block divided by
1621    the block size.
1622 
1623    Note that you must call MatSetBlockSize() when constructing this matrix (before
1624    preallocating it).
1625 
1626    By default the values, v, are row-oriented, so the layout of
1627    v is the same as for MatSetValues(). See MatSetOption() for other options.
1628 
1629    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1630    options cannot be mixed without intervening calls to the assembly
1631    routines.
1632 
1633    MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1634    as well as in C.
1635 
1636    Negative indices may be passed in idxm and idxn, these rows and columns are
1637    simply ignored. This allows easily inserting element stiffness matrices
1638    with homogeneous Dirchlet boundary conditions that you don't want represented
1639    in the matrix.
1640 
1641    Each time an entry is set within a sparse matrix via MatSetValues(),
1642    internal searching must be done to determine where to place the the
1643    data in the matrix storage space.  By instead inserting blocks of
1644    entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1645    reduced.
1646 
1647    Example:
1648 $   Suppose m=n=2 and block size(bs) = 2 The array is
1649 $
1650 $   1  2  | 3  4
1651 $   5  6  | 7  8
1652 $   - - - | - - -
1653 $   9  10 | 11 12
1654 $   13 14 | 15 16
1655 $
1656 $   v[] should be passed in like
1657 $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1658 $
1659 $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1660 $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1661 
1662    Level: intermediate
1663 
1664    Concepts: matrices^putting entries in blocked
1665 
1666 .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1667 @*/
1668 PetscErrorCode  MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1669 {
1670   PetscErrorCode ierr;
1671 
1672   PetscFunctionBeginHot;
1673   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1674   PetscValidType(mat,1);
1675   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1676   PetscValidIntPointer(idxm,3);
1677   PetscValidIntPointer(idxn,5);
1678   PetscValidScalarPointer(v,6);
1679   MatCheckPreallocated(mat,1);
1680   if (mat->insertmode == NOT_SET_VALUES) {
1681     mat->insertmode = addv;
1682   }
1683 #if defined(PETSC_USE_DEBUG)
1684   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1685   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1686   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1687 #endif
1688 
1689   if (mat->assembled) {
1690     mat->was_assembled = PETSC_TRUE;
1691     mat->assembled     = PETSC_FALSE;
1692   }
1693   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1694   if (mat->ops->setvaluesblocked) {
1695     ierr = (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);CHKERRQ(ierr);
1696   } else {
1697     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1698     PetscInt i,j,bs,cbs;
1699     ierr = MatGetBlockSizes(mat,&bs,&cbs);CHKERRQ(ierr);
1700     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1701       iidxm = buf; iidxn = buf + m*bs;
1702     } else {
1703       ierr  = PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);CHKERRQ(ierr);
1704       iidxm = bufr; iidxn = bufc;
1705     }
1706     for (i=0; i<m; i++) {
1707       for (j=0; j<bs; j++) {
1708         iidxm[i*bs+j] = bs*idxm[i] + j;
1709       }
1710     }
1711     for (i=0; i<n; i++) {
1712       for (j=0; j<cbs; j++) {
1713         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1714       }
1715     }
1716     ierr = MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);CHKERRQ(ierr);
1717     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
1718   }
1719   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1720 #if defined(PETSC_HAVE_CUSP)
1721   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
1722     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
1723   }
1724 #endif
1725 #if defined(PETSC_HAVE_VIENNACL)
1726   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
1727     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
1728   }
1729 #endif
1730   PetscFunctionReturn(0);
1731 }
1732 
1733 #undef __FUNCT__
1734 #define __FUNCT__ "MatGetValues"
1735 /*@
1736    MatGetValues - Gets a block of values from a matrix.
1737 
1738    Not Collective; currently only returns a local block
1739 
1740    Input Parameters:
1741 +  mat - the matrix
1742 .  v - a logically two-dimensional array for storing the values
1743 .  m, idxm - the number of rows and their global indices
1744 -  n, idxn - the number of columns and their global indices
1745 
1746    Notes:
1747    The user must allocate space (m*n PetscScalars) for the values, v.
1748    The values, v, are then returned in a row-oriented format,
1749    analogous to that used by default in MatSetValues().
1750 
1751    MatGetValues() uses 0-based row and column numbers in
1752    Fortran as well as in C.
1753 
1754    MatGetValues() requires that the matrix has been assembled
1755    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1756    MatSetValues() and MatGetValues() CANNOT be made in succession
1757    without intermediate matrix assembly.
1758 
1759    Negative row or column indices will be ignored and those locations in v[] will be
1760    left unchanged.
1761 
1762    Level: advanced
1763 
1764    Concepts: matrices^accessing values
1765 
1766 .seealso: MatGetRow(), MatGetSubMatrices(), MatSetValues()
1767 @*/
1768 PetscErrorCode  MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1769 {
1770   PetscErrorCode ierr;
1771 
1772   PetscFunctionBegin;
1773   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1774   PetscValidType(mat,1);
1775   if (!m || !n) PetscFunctionReturn(0);
1776   PetscValidIntPointer(idxm,3);
1777   PetscValidIntPointer(idxn,5);
1778   PetscValidScalarPointer(v,6);
1779   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1780   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1781   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1782   MatCheckPreallocated(mat,1);
1783 
1784   ierr = PetscLogEventBegin(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1785   ierr = (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);CHKERRQ(ierr);
1786   ierr = PetscLogEventEnd(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1787   PetscFunctionReturn(0);
1788 }
1789 
1790 #undef __FUNCT__
1791 #define __FUNCT__ "MatSetValuesBatch"
1792 /*@
1793   MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1794   the same size. Currently, this can only be called once and creates the given matrix.
1795 
1796   Not Collective
1797 
1798   Input Parameters:
1799 + mat - the matrix
1800 . nb - the number of blocks
1801 . bs - the number of rows (and columns) in each block
1802 . rows - a concatenation of the rows for each block
1803 - v - a concatenation of logically two-dimensional arrays of values
1804 
1805   Notes:
1806   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
1807 
1808   Level: advanced
1809 
1810   Concepts: matrices^putting entries in
1811 
1812 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1813           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1814 @*/
1815 PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1816 {
1817   PetscErrorCode ierr;
1818 
1819   PetscFunctionBegin;
1820   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1821   PetscValidType(mat,1);
1822   PetscValidScalarPointer(rows,4);
1823   PetscValidScalarPointer(v,5);
1824 #if defined(PETSC_USE_DEBUG)
1825   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1826 #endif
1827 
1828   ierr = PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
1829   if (mat->ops->setvaluesbatch) {
1830     ierr = (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);CHKERRQ(ierr);
1831   } else {
1832     PetscInt b;
1833     for (b = 0; b < nb; ++b) {
1834       ierr = MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);CHKERRQ(ierr);
1835     }
1836   }
1837   ierr = PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
1838   PetscFunctionReturn(0);
1839 }
1840 
1841 #undef __FUNCT__
1842 #define __FUNCT__ "MatSetLocalToGlobalMapping"
1843 /*@
1844    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1845    the routine MatSetValuesLocal() to allow users to insert matrix entries
1846    using a local (per-processor) numbering.
1847 
1848    Not Collective
1849 
1850    Input Parameters:
1851 +  x - the matrix
1852 .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
1853 - cmapping - column mapping
1854 
1855    Level: intermediate
1856 
1857    Concepts: matrices^local to global mapping
1858    Concepts: local to global mapping^for matrices
1859 
1860 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
1861 @*/
1862 PetscErrorCode  MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
1863 {
1864   PetscErrorCode ierr;
1865 
1866   PetscFunctionBegin;
1867   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
1868   PetscValidType(x,1);
1869   PetscValidHeaderSpecific(rmapping,IS_LTOGM_CLASSID,2);
1870   PetscValidHeaderSpecific(cmapping,IS_LTOGM_CLASSID,3);
1871 
1872   if (x->ops->setlocaltoglobalmapping) {
1873     ierr = (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);CHKERRQ(ierr);
1874   } else {
1875     ierr = PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);CHKERRQ(ierr);
1876     ierr = PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);CHKERRQ(ierr);
1877   }
1878   PetscFunctionReturn(0);
1879 }
1880 
1881 
1882 #undef __FUNCT__
1883 #define __FUNCT__ "MatGetLocalToGlobalMapping"
1884 /*@
1885    MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
1886 
1887    Not Collective
1888 
1889    Input Parameters:
1890 .  A - the matrix
1891 
1892    Output Parameters:
1893 + rmapping - row mapping
1894 - cmapping - column mapping
1895 
1896    Level: advanced
1897 
1898    Concepts: matrices^local to global mapping
1899    Concepts: local to global mapping^for matrices
1900 
1901 .seealso:  MatSetValuesLocal()
1902 @*/
1903 PetscErrorCode  MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
1904 {
1905   PetscFunctionBegin;
1906   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
1907   PetscValidType(A,1);
1908   if (rmapping) PetscValidPointer(rmapping,2);
1909   if (cmapping) PetscValidPointer(cmapping,3);
1910   if (rmapping) *rmapping = A->rmap->mapping;
1911   if (cmapping) *cmapping = A->cmap->mapping;
1912   PetscFunctionReturn(0);
1913 }
1914 
1915 #undef __FUNCT__
1916 #define __FUNCT__ "MatGetLayouts"
1917 /*@
1918    MatGetLayouts - Gets the PetscLayout objects for rows and columns
1919 
1920    Not Collective
1921 
1922    Input Parameters:
1923 .  A - the matrix
1924 
1925    Output Parameters:
1926 + rmap - row layout
1927 - cmap - column layout
1928 
1929    Level: advanced
1930 
1931 .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
1932 @*/
1933 PetscErrorCode  MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
1934 {
1935   PetscFunctionBegin;
1936   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
1937   PetscValidType(A,1);
1938   if (rmap) PetscValidPointer(rmap,2);
1939   if (cmap) PetscValidPointer(cmap,3);
1940   if (rmap) *rmap = A->rmap;
1941   if (cmap) *cmap = A->cmap;
1942   PetscFunctionReturn(0);
1943 }
1944 
1945 #undef __FUNCT__
1946 #define __FUNCT__ "MatSetValuesLocal"
1947 /*@
1948    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
1949    using a local ordering of the nodes.
1950 
1951    Not Collective
1952 
1953    Input Parameters:
1954 +  x - the matrix
1955 .  nrow, irow - number of rows and their local indices
1956 .  ncol, icol - number of columns and their local indices
1957 .  y -  a logically two-dimensional array of values
1958 -  addv - either INSERT_VALUES or ADD_VALUES, where
1959    ADD_VALUES adds values to any existing entries, and
1960    INSERT_VALUES replaces existing entries with new values
1961 
1962    Notes:
1963    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1964       MatSetUp() before using this routine
1965 
1966    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
1967 
1968    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
1969    options cannot be mixed without intervening calls to the assembly
1970    routines.
1971 
1972    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1973    MUST be called after all calls to MatSetValuesLocal() have been completed.
1974 
1975    Level: intermediate
1976 
1977    Concepts: matrices^putting entries in with local numbering
1978 
1979 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1980            MatSetValueLocal()
1981 @*/
1982 PetscErrorCode  MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
1983 {
1984   PetscErrorCode ierr;
1985 
1986   PetscFunctionBeginHot;
1987   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1988   PetscValidType(mat,1);
1989   MatCheckPreallocated(mat,1);
1990   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
1991   PetscValidIntPointer(irow,3);
1992   PetscValidIntPointer(icol,5);
1993   PetscValidScalarPointer(y,6);
1994   if (mat->insertmode == NOT_SET_VALUES) {
1995     mat->insertmode = addv;
1996   }
1997 #if defined(PETSC_USE_DEBUG)
1998   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1999   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2000   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2001 #endif
2002 
2003   if (mat->assembled) {
2004     mat->was_assembled = PETSC_TRUE;
2005     mat->assembled     = PETSC_FALSE;
2006   }
2007   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2008   if (mat->ops->setvalueslocal) {
2009     ierr = (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2010   } else {
2011     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2012     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2013       irowm = buf; icolm = buf+nrow;
2014     } else {
2015       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2016       irowm = bufr; icolm = bufc;
2017     }
2018     ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2019     ierr = ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2020     ierr = MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2021     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2022   }
2023   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2024 #if defined(PETSC_HAVE_CUSP)
2025   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
2026     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
2027   }
2028 #endif
2029 #if defined(PETSC_HAVE_VIENNACL)
2030   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
2031     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
2032   }
2033 #endif
2034   PetscFunctionReturn(0);
2035 }
2036 
2037 #undef __FUNCT__
2038 #define __FUNCT__ "MatSetValuesBlockedLocal"
2039 /*@
2040    MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2041    using a local ordering of the nodes a block at a time.
2042 
2043    Not Collective
2044 
2045    Input Parameters:
2046 +  x - the matrix
2047 .  nrow, irow - number of rows and their local indices
2048 .  ncol, icol - number of columns and their local indices
2049 .  y -  a logically two-dimensional array of values
2050 -  addv - either INSERT_VALUES or ADD_VALUES, where
2051    ADD_VALUES adds values to any existing entries, and
2052    INSERT_VALUES replaces existing entries with new values
2053 
2054    Notes:
2055    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2056       MatSetUp() before using this routine
2057 
2058    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2059       before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2060 
2061    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2062    options cannot be mixed without intervening calls to the assembly
2063    routines.
2064 
2065    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2066    MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2067 
2068    Level: intermediate
2069 
2070    Concepts: matrices^putting blocked values in with local numbering
2071 
2072 .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2073            MatSetValuesLocal(),  MatSetValuesBlocked()
2074 @*/
2075 PetscErrorCode  MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2076 {
2077   PetscErrorCode ierr;
2078 
2079   PetscFunctionBeginHot;
2080   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2081   PetscValidType(mat,1);
2082   MatCheckPreallocated(mat,1);
2083   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
2084   PetscValidIntPointer(irow,3);
2085   PetscValidIntPointer(icol,5);
2086   PetscValidScalarPointer(y,6);
2087   if (mat->insertmode == NOT_SET_VALUES) {
2088     mat->insertmode = addv;
2089   }
2090 #if defined(PETSC_USE_DEBUG)
2091   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2092   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2093   if (!mat->ops->setvaluesblockedlocal && !mat->ops->setvaluesblocked && !mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2094 #endif
2095 
2096   if (mat->assembled) {
2097     mat->was_assembled = PETSC_TRUE;
2098     mat->assembled     = PETSC_FALSE;
2099   }
2100   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2101   if (mat->ops->setvaluesblockedlocal) {
2102     ierr = (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2103   } else {
2104     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2105     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2106       irowm = buf; icolm = buf + nrow;
2107     } else {
2108       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2109       irowm = bufr; icolm = bufc;
2110     }
2111     ierr = ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2112     ierr = ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2113     ierr = MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2114     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2115   }
2116   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2117 #if defined(PETSC_HAVE_CUSP)
2118   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
2119     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
2120   }
2121 #endif
2122 #if defined(PETSC_HAVE_VIENNACL)
2123   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
2124     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
2125   }
2126 #endif
2127   PetscFunctionReturn(0);
2128 }
2129 
2130 #undef __FUNCT__
2131 #define __FUNCT__ "MatMultDiagonalBlock"
2132 /*@
2133    MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2134 
2135    Collective on Mat and Vec
2136 
2137    Input Parameters:
2138 +  mat - the matrix
2139 -  x   - the vector to be multiplied
2140 
2141    Output Parameters:
2142 .  y - the result
2143 
2144    Notes:
2145    The vectors x and y cannot be the same.  I.e., one cannot
2146    call MatMult(A,y,y).
2147 
2148    Level: developer
2149 
2150    Concepts: matrix-vector product
2151 
2152 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2153 @*/
2154 PetscErrorCode  MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2155 {
2156   PetscErrorCode ierr;
2157 
2158   PetscFunctionBegin;
2159   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2160   PetscValidType(mat,1);
2161   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2162   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2163 
2164   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2165   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2166   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2167   MatCheckPreallocated(mat,1);
2168 
2169   if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2170   ierr = (*mat->ops->multdiagonalblock)(mat,x,y);CHKERRQ(ierr);
2171   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2172   PetscFunctionReturn(0);
2173 }
2174 
2175 /* --------------------------------------------------------*/
2176 #undef __FUNCT__
2177 #define __FUNCT__ "MatMult"
2178 /*@
2179    MatMult - Computes the matrix-vector product, y = Ax.
2180 
2181    Neighbor-wise Collective on Mat and Vec
2182 
2183    Input Parameters:
2184 +  mat - the matrix
2185 -  x   - the vector to be multiplied
2186 
2187    Output Parameters:
2188 .  y - the result
2189 
2190    Notes:
2191    The vectors x and y cannot be the same.  I.e., one cannot
2192    call MatMult(A,y,y).
2193 
2194    Level: beginner
2195 
2196    Concepts: matrix-vector product
2197 
2198 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2199 @*/
2200 PetscErrorCode  MatMult(Mat mat,Vec x,Vec y)
2201 {
2202   PetscErrorCode ierr;
2203 
2204   PetscFunctionBegin;
2205   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2206   PetscValidType(mat,1);
2207   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2208   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2209   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2210   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2211   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2212 #if !defined(PETSC_HAVE_CONSTRAINTS)
2213   if (mat->cmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2214   if (mat->rmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2215   if (mat->rmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap->n,y->map->n);
2216 #endif
2217   ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);
2218   MatCheckPreallocated(mat,1);
2219 
2220   if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2221   ierr = PetscLogEventBegin(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2222   ierr = (*mat->ops->mult)(mat,x,y);CHKERRQ(ierr);
2223   ierr = PetscLogEventEnd(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2224   ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);
2225   PetscFunctionReturn(0);
2226 }
2227 
2228 #undef __FUNCT__
2229 #define __FUNCT__ "MatMultTranspose"
2230 /*@
2231    MatMultTranspose - Computes matrix transpose times a vector.
2232 
2233    Neighbor-wise Collective on Mat and Vec
2234 
2235    Input Parameters:
2236 +  mat - the matrix
2237 -  x   - the vector to be multilplied
2238 
2239    Output Parameters:
2240 .  y - the result
2241 
2242    Notes:
2243    The vectors x and y cannot be the same.  I.e., one cannot
2244    call MatMultTranspose(A,y,y).
2245 
2246    For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2247    use MatMultHermitianTranspose()
2248 
2249    Level: beginner
2250 
2251    Concepts: matrix vector product^transpose
2252 
2253 .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2254 @*/
2255 PetscErrorCode  MatMultTranspose(Mat mat,Vec x,Vec y)
2256 {
2257   PetscErrorCode ierr;
2258 
2259   PetscFunctionBegin;
2260   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2261   PetscValidType(mat,1);
2262   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2263   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2264 
2265   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2266   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2267   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2268 #if !defined(PETSC_HAVE_CONSTRAINTS)
2269   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2270   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2271 #endif
2272   ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);
2273   MatCheckPreallocated(mat,1);
2274 
2275   if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply tranpose defined");
2276   ierr = PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2277   ierr = (*mat->ops->multtranspose)(mat,x,y);CHKERRQ(ierr);
2278   ierr = PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2279   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2280   ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);
2281   PetscFunctionReturn(0);
2282 }
2283 
2284 #undef __FUNCT__
2285 #define __FUNCT__ "MatMultHermitianTranspose"
2286 /*@
2287    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2288 
2289    Neighbor-wise Collective on Mat and Vec
2290 
2291    Input Parameters:
2292 +  mat - the matrix
2293 -  x   - the vector to be multilplied
2294 
2295    Output Parameters:
2296 .  y - the result
2297 
2298    Notes:
2299    The vectors x and y cannot be the same.  I.e., one cannot
2300    call MatMultHermitianTranspose(A,y,y).
2301 
2302    Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2303 
2304    For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2305 
2306    Level: beginner
2307 
2308    Concepts: matrix vector product^transpose
2309 
2310 .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2311 @*/
2312 PetscErrorCode  MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2313 {
2314   PetscErrorCode ierr;
2315   Vec            w;
2316 
2317   PetscFunctionBegin;
2318   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2319   PetscValidType(mat,1);
2320   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2321   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2322 
2323   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2324   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2325   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2326 #if !defined(PETSC_HAVE_CONSTRAINTS)
2327   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2328   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2329 #endif
2330   MatCheckPreallocated(mat,1);
2331 
2332   ierr = PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2333   if (mat->ops->multhermitiantranspose) {
2334     ierr = (*mat->ops->multhermitiantranspose)(mat,x,y);CHKERRQ(ierr);
2335   } else {
2336     ierr = VecDuplicate(x,&w);CHKERRQ(ierr);
2337     ierr = VecCopy(x,w);CHKERRQ(ierr);
2338     ierr = VecConjugate(w);CHKERRQ(ierr);
2339     ierr = MatMultTranspose(mat,w,y);CHKERRQ(ierr);
2340     ierr = VecDestroy(&w);CHKERRQ(ierr);
2341     ierr = VecConjugate(y);CHKERRQ(ierr);
2342   }
2343   ierr = PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2344   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2345   PetscFunctionReturn(0);
2346 }
2347 
2348 #undef __FUNCT__
2349 #define __FUNCT__ "MatMultAdd"
2350 /*@
2351     MatMultAdd -  Computes v3 = v2 + A * v1.
2352 
2353     Neighbor-wise Collective on Mat and Vec
2354 
2355     Input Parameters:
2356 +   mat - the matrix
2357 -   v1, v2 - the vectors
2358 
2359     Output Parameters:
2360 .   v3 - the result
2361 
2362     Notes:
2363     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2364     call MatMultAdd(A,v1,v2,v1).
2365 
2366     Level: beginner
2367 
2368     Concepts: matrix vector product^addition
2369 
2370 .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2371 @*/
2372 PetscErrorCode  MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2373 {
2374   PetscErrorCode ierr;
2375 
2376   PetscFunctionBegin;
2377   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2378   PetscValidType(mat,1);
2379   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2380   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2381   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2382 
2383   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2384   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2385   if (mat->cmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->cmap->N,v1->map->N);
2386   /* if (mat->rmap->N != v2->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->rmap->N,v2->map->N);
2387      if (mat->rmap->N != v3->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->rmap->N,v3->map->N); */
2388   if (mat->rmap->n != v3->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: local dim %D %D",mat->rmap->n,v3->map->n);
2389   if (mat->rmap->n != v2->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: local dim %D %D",mat->rmap->n,v2->map->n);
2390   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2391   MatCheckPreallocated(mat,1);
2392 
2393   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2394   ierr = PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2395   ierr = (*mat->ops->multadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2396   ierr = PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2397   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2398   PetscFunctionReturn(0);
2399 }
2400 
2401 #undef __FUNCT__
2402 #define __FUNCT__ "MatMultTransposeAdd"
2403 /*@
2404    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2405 
2406    Neighbor-wise Collective on Mat and Vec
2407 
2408    Input Parameters:
2409 +  mat - the matrix
2410 -  v1, v2 - the vectors
2411 
2412    Output Parameters:
2413 .  v3 - the result
2414 
2415    Notes:
2416    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2417    call MatMultTransposeAdd(A,v1,v2,v1).
2418 
2419    Level: beginner
2420 
2421    Concepts: matrix vector product^transpose and addition
2422 
2423 .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2424 @*/
2425 PetscErrorCode  MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2426 {
2427   PetscErrorCode ierr;
2428 
2429   PetscFunctionBegin;
2430   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2431   PetscValidType(mat,1);
2432   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2433   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2434   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2435 
2436   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2437   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2438   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2439   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2440   if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2441   if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2442   if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2443   MatCheckPreallocated(mat,1);
2444 
2445   ierr = PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2446   ierr = (*mat->ops->multtransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2447   ierr = PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2448   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2449   PetscFunctionReturn(0);
2450 }
2451 
2452 #undef __FUNCT__
2453 #define __FUNCT__ "MatMultHermitianTransposeAdd"
2454 /*@
2455    MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2456 
2457    Neighbor-wise Collective on Mat and Vec
2458 
2459    Input Parameters:
2460 +  mat - the matrix
2461 -  v1, v2 - the vectors
2462 
2463    Output Parameters:
2464 .  v3 - the result
2465 
2466    Notes:
2467    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2468    call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2469 
2470    Level: beginner
2471 
2472    Concepts: matrix vector product^transpose and addition
2473 
2474 .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2475 @*/
2476 PetscErrorCode  MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2477 {
2478   PetscErrorCode ierr;
2479 
2480   PetscFunctionBegin;
2481   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2482   PetscValidType(mat,1);
2483   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2484   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2485   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2486 
2487   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2488   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2489   if (!mat->ops->multhermitiantransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2490   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2491   if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2492   if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2493   if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2494   MatCheckPreallocated(mat,1);
2495 
2496   ierr = PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2497   ierr = (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2498   ierr = PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2499   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2500   PetscFunctionReturn(0);
2501 }
2502 
2503 #undef __FUNCT__
2504 #define __FUNCT__ "MatMultConstrained"
2505 /*@
2506    MatMultConstrained - The inner multiplication routine for a
2507    constrained matrix P^T A P.
2508 
2509    Neighbor-wise Collective on Mat and Vec
2510 
2511    Input Parameters:
2512 +  mat - the matrix
2513 -  x   - the vector to be multilplied
2514 
2515    Output Parameters:
2516 .  y - the result
2517 
2518    Notes:
2519    The vectors x and y cannot be the same.  I.e., one cannot
2520    call MatMult(A,y,y).
2521 
2522    Level: beginner
2523 
2524 .keywords: matrix, multiply, matrix-vector product, constraint
2525 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2526 @*/
2527 PetscErrorCode  MatMultConstrained(Mat mat,Vec x,Vec y)
2528 {
2529   PetscErrorCode ierr;
2530 
2531   PetscFunctionBegin;
2532   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2533   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2534   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2535   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2536   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2537   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2538   if (mat->cmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2539   if (mat->rmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2540   if (mat->rmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap->n,y->map->n);
2541 
2542   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2543   ierr = (*mat->ops->multconstrained)(mat,x,y);CHKERRQ(ierr);
2544   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2545   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2546   PetscFunctionReturn(0);
2547 }
2548 
2549 #undef __FUNCT__
2550 #define __FUNCT__ "MatMultTransposeConstrained"
2551 /*@
2552    MatMultTransposeConstrained - The inner multiplication routine for a
2553    constrained matrix P^T A^T P.
2554 
2555    Neighbor-wise Collective on Mat and Vec
2556 
2557    Input Parameters:
2558 +  mat - the matrix
2559 -  x   - the vector to be multilplied
2560 
2561    Output Parameters:
2562 .  y - the result
2563 
2564    Notes:
2565    The vectors x and y cannot be the same.  I.e., one cannot
2566    call MatMult(A,y,y).
2567 
2568    Level: beginner
2569 
2570 .keywords: matrix, multiply, matrix-vector product, constraint
2571 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2572 @*/
2573 PetscErrorCode  MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2574 {
2575   PetscErrorCode ierr;
2576 
2577   PetscFunctionBegin;
2578   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2579   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2580   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2581   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2582   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2583   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2584   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2585   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2586 
2587   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2588   ierr = (*mat->ops->multtransposeconstrained)(mat,x,y);CHKERRQ(ierr);
2589   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2590   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2591   PetscFunctionReturn(0);
2592 }
2593 
2594 #undef __FUNCT__
2595 #define __FUNCT__ "MatGetFactorType"
2596 /*@C
2597    MatGetFactorType - gets the type of factorization it is
2598 
2599    Note Collective
2600    as the flag
2601 
2602    Input Parameters:
2603 .  mat - the matrix
2604 
2605    Output Parameters:
2606 .  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2607 
2608     Level: intermediate
2609 
2610 .seealso:    MatFactorType, MatGetFactor()
2611 @*/
2612 PetscErrorCode  MatGetFactorType(Mat mat,MatFactorType *t)
2613 {
2614   PetscFunctionBegin;
2615   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2616   PetscValidType(mat,1);
2617   *t = mat->factortype;
2618   PetscFunctionReturn(0);
2619 }
2620 
2621 /* ------------------------------------------------------------*/
2622 #undef __FUNCT__
2623 #define __FUNCT__ "MatGetInfo"
2624 /*@C
2625    MatGetInfo - Returns information about matrix storage (number of
2626    nonzeros, memory, etc.).
2627 
2628    Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2629 
2630    Input Parameters:
2631 .  mat - the matrix
2632 
2633    Output Parameters:
2634 +  flag - flag indicating the type of parameters to be returned
2635    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2636    MAT_GLOBAL_SUM - sum over all processors)
2637 -  info - matrix information context
2638 
2639    Notes:
2640    The MatInfo context contains a variety of matrix data, including
2641    number of nonzeros allocated and used, number of mallocs during
2642    matrix assembly, etc.  Additional information for factored matrices
2643    is provided (such as the fill ratio, number of mallocs during
2644    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2645    when using the runtime options
2646 $       -info -mat_view ::ascii_info
2647 
2648    Example for C/C++ Users:
2649    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2650    data within the MatInfo context.  For example,
2651 .vb
2652       MatInfo info;
2653       Mat     A;
2654       double  mal, nz_a, nz_u;
2655 
2656       MatGetInfo(A,MAT_LOCAL,&info);
2657       mal  = info.mallocs;
2658       nz_a = info.nz_allocated;
2659 .ve
2660 
2661    Example for Fortran Users:
2662    Fortran users should declare info as a double precision
2663    array of dimension MAT_INFO_SIZE, and then extract the parameters
2664    of interest.  See the file ${PETSC_DIR}/include/petsc-finclude/petscmat.h
2665    a complete list of parameter names.
2666 .vb
2667       double  precision info(MAT_INFO_SIZE)
2668       double  precision mal, nz_a
2669       Mat     A
2670       integer ierr
2671 
2672       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2673       mal = info(MAT_INFO_MALLOCS)
2674       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2675 .ve
2676 
2677     Level: intermediate
2678 
2679     Concepts: matrices^getting information on
2680 
2681     Developer Note: fortran interface is not autogenerated as the f90
2682     interface defintion cannot be generated correctly [due to MatInfo]
2683 
2684 .seealso: MatStashGetInfo()
2685 
2686 @*/
2687 PetscErrorCode  MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2688 {
2689   PetscErrorCode ierr;
2690 
2691   PetscFunctionBegin;
2692   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2693   PetscValidType(mat,1);
2694   PetscValidPointer(info,3);
2695   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2696   MatCheckPreallocated(mat,1);
2697   ierr = (*mat->ops->getinfo)(mat,flag,info);CHKERRQ(ierr);
2698   PetscFunctionReturn(0);
2699 }
2700 
2701 /* ----------------------------------------------------------*/
2702 
2703 #undef __FUNCT__
2704 #define __FUNCT__ "MatLUFactor"
2705 /*@C
2706    MatLUFactor - Performs in-place LU factorization of matrix.
2707 
2708    Collective on Mat
2709 
2710    Input Parameters:
2711 +  mat - the matrix
2712 .  row - row permutation
2713 .  col - column permutation
2714 -  info - options for factorization, includes
2715 $          fill - expected fill as ratio of original fill.
2716 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2717 $                   Run with the option -info to determine an optimal value to use
2718 
2719    Notes:
2720    Most users should employ the simplified KSP interface for linear solvers
2721    instead of working directly with matrix algebra routines such as this.
2722    See, e.g., KSPCreate().
2723 
2724    This changes the state of the matrix to a factored matrix; it cannot be used
2725    for example with MatSetValues() unless one first calls MatSetUnfactored().
2726 
2727    Level: developer
2728 
2729    Concepts: matrices^LU factorization
2730 
2731 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2732           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2733 
2734     Developer Note: fortran interface is not autogenerated as the f90
2735     interface defintion cannot be generated correctly [due to MatFactorInfo]
2736 
2737 @*/
2738 PetscErrorCode  MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2739 {
2740   PetscErrorCode ierr;
2741   MatFactorInfo  tinfo;
2742 
2743   PetscFunctionBegin;
2744   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2745   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2746   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2747   if (info) PetscValidPointer(info,4);
2748   PetscValidType(mat,1);
2749   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2750   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2751   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2752   MatCheckPreallocated(mat,1);
2753   if (!info) {
2754     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
2755     info = &tinfo;
2756   }
2757 
2758   ierr = PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2759   ierr = (*mat->ops->lufactor)(mat,row,col,info);CHKERRQ(ierr);
2760   ierr = PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2761   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
2762   PetscFunctionReturn(0);
2763 }
2764 
2765 #undef __FUNCT__
2766 #define __FUNCT__ "MatILUFactor"
2767 /*@C
2768    MatILUFactor - Performs in-place ILU factorization of matrix.
2769 
2770    Collective on Mat
2771 
2772    Input Parameters:
2773 +  mat - the matrix
2774 .  row - row permutation
2775 .  col - column permutation
2776 -  info - structure containing
2777 $      levels - number of levels of fill.
2778 $      expected fill - as ratio of original fill.
2779 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2780                 missing diagonal entries)
2781 
2782    Notes:
2783    Probably really in-place only when level of fill is zero, otherwise allocates
2784    new space to store factored matrix and deletes previous memory.
2785 
2786    Most users should employ the simplified KSP interface for linear solvers
2787    instead of working directly with matrix algebra routines such as this.
2788    See, e.g., KSPCreate().
2789 
2790    Level: developer
2791 
2792    Concepts: matrices^ILU factorization
2793 
2794 .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2795 
2796     Developer Note: fortran interface is not autogenerated as the f90
2797     interface defintion cannot be generated correctly [due to MatFactorInfo]
2798 
2799 @*/
2800 PetscErrorCode  MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2801 {
2802   PetscErrorCode ierr;
2803 
2804   PetscFunctionBegin;
2805   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2806   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2807   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2808   PetscValidPointer(info,4);
2809   PetscValidType(mat,1);
2810   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
2811   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2812   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2813   if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2814   MatCheckPreallocated(mat,1);
2815 
2816   ierr = PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
2817   ierr = (*mat->ops->ilufactor)(mat,row,col,info);CHKERRQ(ierr);
2818   ierr = PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
2819   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
2820   PetscFunctionReturn(0);
2821 }
2822 
2823 #undef __FUNCT__
2824 #define __FUNCT__ "MatLUFactorSymbolic"
2825 /*@C
2826    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2827    Call this routine before calling MatLUFactorNumeric().
2828 
2829    Collective on Mat
2830 
2831    Input Parameters:
2832 +  fact - the factor matrix obtained with MatGetFactor()
2833 .  mat - the matrix
2834 .  row, col - row and column permutations
2835 -  info - options for factorization, includes
2836 $          fill - expected fill as ratio of original fill.
2837 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2838 $                   Run with the option -info to determine an optimal value to use
2839 
2840 
2841    Notes: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
2842 
2843    Most users should employ the simplified KSP interface for linear solvers
2844    instead of working directly with matrix algebra routines such as this.
2845    See, e.g., KSPCreate().
2846 
2847    Level: developer
2848 
2849    Concepts: matrices^LU symbolic factorization
2850 
2851 .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2852 
2853     Developer Note: fortran interface is not autogenerated as the f90
2854     interface defintion cannot be generated correctly [due to MatFactorInfo]
2855 
2856 @*/
2857 PetscErrorCode  MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
2858 {
2859   PetscErrorCode ierr;
2860 
2861   PetscFunctionBegin;
2862   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2863   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2864   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2865   if (info) PetscValidPointer(info,4);
2866   PetscValidType(mat,1);
2867   PetscValidPointer(fact,5);
2868   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2869   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2870   if (!(fact)->ops->lufactorsymbolic) {
2871     const MatSolverPackage spackage;
2872     ierr = MatFactorGetSolverPackage(fact,&spackage);CHKERRQ(ierr);
2873     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
2874   }
2875   MatCheckPreallocated(mat,2);
2876 
2877   ierr = PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
2878   ierr = (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
2879   ierr = PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
2880   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
2881   PetscFunctionReturn(0);
2882 }
2883 
2884 #undef __FUNCT__
2885 #define __FUNCT__ "MatLUFactorNumeric"
2886 /*@C
2887    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
2888    Call this routine after first calling MatLUFactorSymbolic().
2889 
2890    Collective on Mat
2891 
2892    Input Parameters:
2893 +  fact - the factor matrix obtained with MatGetFactor()
2894 .  mat - the matrix
2895 -  info - options for factorization
2896 
2897    Notes:
2898    See MatLUFactor() for in-place factorization.  See
2899    MatCholeskyFactorNumeric() for the symmetric, positive definite case.
2900 
2901    Most users should employ the simplified KSP interface for linear solvers
2902    instead of working directly with matrix algebra routines such as this.
2903    See, e.g., KSPCreate().
2904 
2905    Level: developer
2906 
2907    Concepts: matrices^LU numeric factorization
2908 
2909 .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
2910 
2911     Developer Note: fortran interface is not autogenerated as the f90
2912     interface defintion cannot be generated correctly [due to MatFactorInfo]
2913 
2914 @*/
2915 PetscErrorCode  MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
2916 {
2917   PetscErrorCode ierr;
2918 
2919   PetscFunctionBegin;
2920   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2921   PetscValidType(mat,1);
2922   PetscValidPointer(fact,2);
2923   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
2924   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2925   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dimensions are different %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
2926 
2927   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
2928   MatCheckPreallocated(mat,2);
2929   ierr = PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
2930   ierr = (fact->ops->lufactornumeric)(fact,mat,info);CHKERRQ(ierr);
2931   ierr = PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
2932   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
2933   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
2934   PetscFunctionReturn(0);
2935 }
2936 
2937 #undef __FUNCT__
2938 #define __FUNCT__ "MatCholeskyFactor"
2939 /*@C
2940    MatCholeskyFactor - Performs in-place Cholesky factorization of a
2941    symmetric matrix.
2942 
2943    Collective on Mat
2944 
2945    Input Parameters:
2946 +  mat - the matrix
2947 .  perm - row and column permutations
2948 -  f - expected fill as ratio of original fill
2949 
2950    Notes:
2951    See MatLUFactor() for the nonsymmetric case.  See also
2952    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
2953 
2954    Most users should employ the simplified KSP interface for linear solvers
2955    instead of working directly with matrix algebra routines such as this.
2956    See, e.g., KSPCreate().
2957 
2958    Level: developer
2959 
2960    Concepts: matrices^Cholesky factorization
2961 
2962 .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
2963           MatGetOrdering()
2964 
2965     Developer Note: fortran interface is not autogenerated as the f90
2966     interface defintion cannot be generated correctly [due to MatFactorInfo]
2967 
2968 @*/
2969 PetscErrorCode  MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
2970 {
2971   PetscErrorCode ierr;
2972 
2973   PetscFunctionBegin;
2974   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2975   PetscValidType(mat,1);
2976   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
2977   if (info) PetscValidPointer(info,3);
2978   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
2979   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2980   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2981   if (!mat->ops->choleskyfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2982   MatCheckPreallocated(mat,1);
2983 
2984   ierr = PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
2985   ierr = (*mat->ops->choleskyfactor)(mat,perm,info);CHKERRQ(ierr);
2986   ierr = PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
2987   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
2988   PetscFunctionReturn(0);
2989 }
2990 
2991 #undef __FUNCT__
2992 #define __FUNCT__ "MatCholeskyFactorSymbolic"
2993 /*@C
2994    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
2995    of a symmetric matrix.
2996 
2997    Collective on Mat
2998 
2999    Input Parameters:
3000 +  fact - the factor matrix obtained with MatGetFactor()
3001 .  mat - the matrix
3002 .  perm - row and column permutations
3003 -  info - options for factorization, includes
3004 $          fill - expected fill as ratio of original fill.
3005 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3006 $                   Run with the option -info to determine an optimal value to use
3007 
3008    Notes:
3009    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3010    MatCholeskyFactor() and MatCholeskyFactorNumeric().
3011 
3012    Most users should employ the simplified KSP interface for linear solvers
3013    instead of working directly with matrix algebra routines such as this.
3014    See, e.g., KSPCreate().
3015 
3016    Level: developer
3017 
3018    Concepts: matrices^Cholesky symbolic factorization
3019 
3020 .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3021           MatGetOrdering()
3022 
3023     Developer Note: fortran interface is not autogenerated as the f90
3024     interface defintion cannot be generated correctly [due to MatFactorInfo]
3025 
3026 @*/
3027 PetscErrorCode  MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3028 {
3029   PetscErrorCode ierr;
3030 
3031   PetscFunctionBegin;
3032   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3033   PetscValidType(mat,1);
3034   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3035   if (info) PetscValidPointer(info,3);
3036   PetscValidPointer(fact,4);
3037   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3038   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3039   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3040   if (!(fact)->ops->choleskyfactorsymbolic) {
3041     const MatSolverPackage spackage;
3042     ierr = MatFactorGetSolverPackage(fact,&spackage);CHKERRQ(ierr);
3043     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3044   }
3045   MatCheckPreallocated(mat,2);
3046 
3047   ierr = PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3048   ierr = (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
3049   ierr = PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3050   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3051   PetscFunctionReturn(0);
3052 }
3053 
3054 #undef __FUNCT__
3055 #define __FUNCT__ "MatCholeskyFactorNumeric"
3056 /*@C
3057    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3058    of a symmetric matrix. Call this routine after first calling
3059    MatCholeskyFactorSymbolic().
3060 
3061    Collective on Mat
3062 
3063    Input Parameters:
3064 +  fact - the factor matrix obtained with MatGetFactor()
3065 .  mat - the initial matrix
3066 .  info - options for factorization
3067 -  fact - the symbolic factor of mat
3068 
3069 
3070    Notes:
3071    Most users should employ the simplified KSP interface for linear solvers
3072    instead of working directly with matrix algebra routines such as this.
3073    See, e.g., KSPCreate().
3074 
3075    Level: developer
3076 
3077    Concepts: matrices^Cholesky numeric factorization
3078 
3079 .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3080 
3081     Developer Note: fortran interface is not autogenerated as the f90
3082     interface defintion cannot be generated correctly [due to MatFactorInfo]
3083 
3084 @*/
3085 PetscErrorCode  MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3086 {
3087   PetscErrorCode ierr;
3088 
3089   PetscFunctionBegin;
3090   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3091   PetscValidType(mat,1);
3092   PetscValidPointer(fact,2);
3093   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
3094   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3095   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3096   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dim %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3097   MatCheckPreallocated(mat,2);
3098 
3099   ierr = PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3100   ierr = (fact->ops->choleskyfactornumeric)(fact,mat,info);CHKERRQ(ierr);
3101   ierr = PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3102   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3103   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3104   PetscFunctionReturn(0);
3105 }
3106 
3107 /* ----------------------------------------------------------------*/
3108 #undef __FUNCT__
3109 #define __FUNCT__ "MatSolve"
3110 /*@
3111    MatSolve - Solves A x = b, given a factored matrix.
3112 
3113    Neighbor-wise Collective on Mat and Vec
3114 
3115    Input Parameters:
3116 +  mat - the factored matrix
3117 -  b - the right-hand-side vector
3118 
3119    Output Parameter:
3120 .  x - the result vector
3121 
3122    Notes:
3123    The vectors b and x cannot be the same.  I.e., one cannot
3124    call MatSolve(A,x,x).
3125 
3126    Notes:
3127    Most users should employ the simplified KSP interface for linear solvers
3128    instead of working directly with matrix algebra routines such as this.
3129    See, e.g., KSPCreate().
3130 
3131    Level: developer
3132 
3133    Concepts: matrices^triangular solves
3134 
3135 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3136 @*/
3137 PetscErrorCode  MatSolve(Mat mat,Vec b,Vec x)
3138 {
3139   PetscErrorCode ierr;
3140 
3141   PetscFunctionBegin;
3142   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3143   PetscValidType(mat,1);
3144   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3145   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3146   PetscCheckSameComm(mat,1,b,2);
3147   PetscCheckSameComm(mat,1,x,3);
3148   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3149   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3150   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3151   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3152   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3153   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3154   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3155   MatCheckPreallocated(mat,1);
3156 
3157   ierr = PetscLogEventBegin(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3158   ierr = (*mat->ops->solve)(mat,b,x);CHKERRQ(ierr);
3159   ierr = PetscLogEventEnd(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3160   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3161   PetscFunctionReturn(0);
3162 }
3163 
3164 #undef __FUNCT__
3165 #define __FUNCT__ "MatMatSolve_Basic"
3166 PetscErrorCode  MatMatSolve_Basic(Mat A,Mat B,Mat X)
3167 {
3168   PetscErrorCode ierr;
3169   Vec            b,x;
3170   PetscInt       m,N,i;
3171   PetscScalar    *bb,*xx;
3172   PetscBool      flg;
3173 
3174   PetscFunctionBegin;
3175   ierr = PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQDENSE,MATMPIDENSE,NULL);CHKERRQ(ierr);
3176   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
3177   ierr = PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);CHKERRQ(ierr);
3178   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");
3179 
3180   ierr = MatDenseGetArray(B,&bb);CHKERRQ(ierr);
3181   ierr = MatDenseGetArray(X,&xx);CHKERRQ(ierr);
3182   ierr = MatGetLocalSize(B,&m,NULL);CHKERRQ(ierr);  /* number local rows */
3183   ierr = MatGetSize(B,NULL,&N);CHKERRQ(ierr);       /* total columns in dense matrix */
3184   ierr = MatCreateVecs(A,&x,&b);CHKERRQ(ierr);
3185   for (i=0; i<N; i++) {
3186     ierr = VecPlaceArray(b,bb + i*m);CHKERRQ(ierr);
3187     ierr = VecPlaceArray(x,xx + i*m);CHKERRQ(ierr);
3188     ierr = MatSolve(A,b,x);CHKERRQ(ierr);
3189     ierr = VecResetArray(x);CHKERRQ(ierr);
3190     ierr = VecResetArray(b);CHKERRQ(ierr);
3191   }
3192   ierr = VecDestroy(&b);CHKERRQ(ierr);
3193   ierr = VecDestroy(&x);CHKERRQ(ierr);
3194   ierr = MatDenseRestoreArray(B,&bb);CHKERRQ(ierr);
3195   ierr = MatDenseRestoreArray(X,&xx);CHKERRQ(ierr);
3196   PetscFunctionReturn(0);
3197 }
3198 
3199 #undef __FUNCT__
3200 #define __FUNCT__ "MatMatSolve"
3201 /*@
3202    MatMatSolve - Solves A X = B, given a factored matrix.
3203 
3204    Neighbor-wise Collective on Mat
3205 
3206    Input Parameters:
3207 +  mat - the factored matrix
3208 -  B - the right-hand-side matrix  (dense matrix)
3209 
3210    Output Parameter:
3211 .  X - the result matrix (dense matrix)
3212 
3213    Notes:
3214    The matrices b and x cannot be the same.  I.e., one cannot
3215    call MatMatSolve(A,x,x).
3216 
3217    Notes:
3218    Most users should usually employ the simplified KSP interface for linear solvers
3219    instead of working directly with matrix algebra routines such as this.
3220    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3221    at a time.
3222 
3223    When using SuperLU_Dist as a parallel solver PETSc will use the SuperLU_Dist functionality to solve multiple right hand sides simultaneously. For MUMPS
3224    it calls a separate solve for each right hand side since MUMPS does not yet support distributed right hand sides.
3225 
3226    Since the resulting matrix X must always be dense we do not support sparse representation of the matrix B.
3227 
3228    Level: developer
3229 
3230    Concepts: matrices^triangular solves
3231 
3232 .seealso: MatMatSolveAdd(), MatMatSolveTranspose(), MatMatSolveTransposeAdd(), MatLUFactor(), MatCholeskyFactor()
3233 @*/
3234 PetscErrorCode  MatMatSolve(Mat A,Mat B,Mat X)
3235 {
3236   PetscErrorCode ierr;
3237 
3238   PetscFunctionBegin;
3239   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3240   PetscValidType(A,1);
3241   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3242   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3243   PetscCheckSameComm(A,1,B,2);
3244   PetscCheckSameComm(A,1,X,3);
3245   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3246   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3247   if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3248   if (A->rmap->N != B->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap->N,B->rmap->N);
3249   if (A->rmap->n != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat A,Mat B: local dim %D %D",A->rmap->n,B->rmap->n);
3250   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3251   MatCheckPreallocated(A,1);
3252 
3253   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3254   if (!A->ops->matsolve) {
3255     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3256     ierr = MatMatSolve_Basic(A,B,X);CHKERRQ(ierr);
3257   } else {
3258     ierr = (*A->ops->matsolve)(A,B,X);CHKERRQ(ierr);
3259   }
3260   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3261   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3262   PetscFunctionReturn(0);
3263 }
3264 
3265 
3266 #undef __FUNCT__
3267 #define __FUNCT__ "MatForwardSolve"
3268 /*@
3269    MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3270                             U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3271 
3272    Neighbor-wise Collective on Mat and Vec
3273 
3274    Input Parameters:
3275 +  mat - the factored matrix
3276 -  b - the right-hand-side vector
3277 
3278    Output Parameter:
3279 .  x - the result vector
3280 
3281    Notes:
3282    MatSolve() should be used for most applications, as it performs
3283    a forward solve followed by a backward solve.
3284 
3285    The vectors b and x cannot be the same,  i.e., one cannot
3286    call MatForwardSolve(A,x,x).
3287 
3288    For matrix in seqsbaij format with block size larger than 1,
3289    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3290    MatForwardSolve() solves U^T*D y = b, and
3291    MatBackwardSolve() solves U x = y.
3292    Thus they do not provide a symmetric preconditioner.
3293 
3294    Most users should employ the simplified KSP interface for linear solvers
3295    instead of working directly with matrix algebra routines such as this.
3296    See, e.g., KSPCreate().
3297 
3298    Level: developer
3299 
3300    Concepts: matrices^forward solves
3301 
3302 .seealso: MatSolve(), MatBackwardSolve()
3303 @*/
3304 PetscErrorCode  MatForwardSolve(Mat mat,Vec b,Vec x)
3305 {
3306   PetscErrorCode ierr;
3307 
3308   PetscFunctionBegin;
3309   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3310   PetscValidType(mat,1);
3311   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3312   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3313   PetscCheckSameComm(mat,1,b,2);
3314   PetscCheckSameComm(mat,1,x,3);
3315   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3316   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3317   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3318   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3319   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3320   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3321   MatCheckPreallocated(mat,1);
3322   ierr = PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3323   ierr = (*mat->ops->forwardsolve)(mat,b,x);CHKERRQ(ierr);
3324   ierr = PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3325   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3326   PetscFunctionReturn(0);
3327 }
3328 
3329 #undef __FUNCT__
3330 #define __FUNCT__ "MatBackwardSolve"
3331 /*@
3332    MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3333                              D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3334 
3335    Neighbor-wise Collective on Mat and Vec
3336 
3337    Input Parameters:
3338 +  mat - the factored matrix
3339 -  b - the right-hand-side vector
3340 
3341    Output Parameter:
3342 .  x - the result vector
3343 
3344    Notes:
3345    MatSolve() should be used for most applications, as it performs
3346    a forward solve followed by a backward solve.
3347 
3348    The vectors b and x cannot be the same.  I.e., one cannot
3349    call MatBackwardSolve(A,x,x).
3350 
3351    For matrix in seqsbaij format with block size larger than 1,
3352    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3353    MatForwardSolve() solves U^T*D y = b, and
3354    MatBackwardSolve() solves U x = y.
3355    Thus they do not provide a symmetric preconditioner.
3356 
3357    Most users should employ the simplified KSP interface for linear solvers
3358    instead of working directly with matrix algebra routines such as this.
3359    See, e.g., KSPCreate().
3360 
3361    Level: developer
3362 
3363    Concepts: matrices^backward solves
3364 
3365 .seealso: MatSolve(), MatForwardSolve()
3366 @*/
3367 PetscErrorCode  MatBackwardSolve(Mat mat,Vec b,Vec x)
3368 {
3369   PetscErrorCode ierr;
3370 
3371   PetscFunctionBegin;
3372   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3373   PetscValidType(mat,1);
3374   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3375   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3376   PetscCheckSameComm(mat,1,b,2);
3377   PetscCheckSameComm(mat,1,x,3);
3378   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3379   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3380   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3381   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3382   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3383   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3384   MatCheckPreallocated(mat,1);
3385 
3386   ierr = PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3387   ierr = (*mat->ops->backwardsolve)(mat,b,x);CHKERRQ(ierr);
3388   ierr = PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3389   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3390   PetscFunctionReturn(0);
3391 }
3392 
3393 #undef __FUNCT__
3394 #define __FUNCT__ "MatSolveAdd"
3395 /*@
3396    MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3397 
3398    Neighbor-wise Collective on Mat and Vec
3399 
3400    Input Parameters:
3401 +  mat - the factored matrix
3402 .  b - the right-hand-side vector
3403 -  y - the vector to be added to
3404 
3405    Output Parameter:
3406 .  x - the result vector
3407 
3408    Notes:
3409    The vectors b and x cannot be the same.  I.e., one cannot
3410    call MatSolveAdd(A,x,y,x).
3411 
3412    Most users should employ the simplified KSP interface for linear solvers
3413    instead of working directly with matrix algebra routines such as this.
3414    See, e.g., KSPCreate().
3415 
3416    Level: developer
3417 
3418    Concepts: matrices^triangular solves
3419 
3420 .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3421 @*/
3422 PetscErrorCode  MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3423 {
3424   PetscScalar    one = 1.0;
3425   Vec            tmp;
3426   PetscErrorCode ierr;
3427 
3428   PetscFunctionBegin;
3429   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3430   PetscValidType(mat,1);
3431   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3432   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3433   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3434   PetscCheckSameComm(mat,1,b,2);
3435   PetscCheckSameComm(mat,1,y,2);
3436   PetscCheckSameComm(mat,1,x,3);
3437   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3438   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3439   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3440   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3441   if (mat->rmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
3442   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3443   if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
3444   MatCheckPreallocated(mat,1);
3445 
3446   ierr = PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3447   if (mat->ops->solveadd) {
3448     ierr = (*mat->ops->solveadd)(mat,b,y,x);CHKERRQ(ierr);
3449   } else {
3450     /* do the solve then the add manually */
3451     if (x != y) {
3452       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3453       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3454     } else {
3455       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3456       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3457       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3458       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3459       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3460       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3461     }
3462   }
3463   ierr = PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3464   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3465   PetscFunctionReturn(0);
3466 }
3467 
3468 #undef __FUNCT__
3469 #define __FUNCT__ "MatSolveTranspose"
3470 /*@
3471    MatSolveTranspose - Solves A' x = b, given a factored matrix.
3472 
3473    Neighbor-wise Collective on Mat and Vec
3474 
3475    Input Parameters:
3476 +  mat - the factored matrix
3477 -  b - the right-hand-side vector
3478 
3479    Output Parameter:
3480 .  x - the result vector
3481 
3482    Notes:
3483    The vectors b and x cannot be the same.  I.e., one cannot
3484    call MatSolveTranspose(A,x,x).
3485 
3486    Most users should employ the simplified KSP interface for linear solvers
3487    instead of working directly with matrix algebra routines such as this.
3488    See, e.g., KSPCreate().
3489 
3490    Level: developer
3491 
3492    Concepts: matrices^triangular solves
3493 
3494 .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3495 @*/
3496 PetscErrorCode  MatSolveTranspose(Mat mat,Vec b,Vec x)
3497 {
3498   PetscErrorCode ierr;
3499 
3500   PetscFunctionBegin;
3501   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3502   PetscValidType(mat,1);
3503   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3504   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3505   PetscCheckSameComm(mat,1,b,2);
3506   PetscCheckSameComm(mat,1,x,3);
3507   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3508   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3509   if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3510   if (mat->rmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
3511   if (mat->cmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap->N,b->map->N);
3512   MatCheckPreallocated(mat,1);
3513   ierr = PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3514   ierr = (*mat->ops->solvetranspose)(mat,b,x);CHKERRQ(ierr);
3515   ierr = PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3516   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3517   PetscFunctionReturn(0);
3518 }
3519 
3520 #undef __FUNCT__
3521 #define __FUNCT__ "MatSolveTransposeAdd"
3522 /*@
3523    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3524                       factored matrix.
3525 
3526    Neighbor-wise Collective on Mat and Vec
3527 
3528    Input Parameters:
3529 +  mat - the factored matrix
3530 .  b - the right-hand-side vector
3531 -  y - the vector to be added to
3532 
3533    Output Parameter:
3534 .  x - the result vector
3535 
3536    Notes:
3537    The vectors b and x cannot be the same.  I.e., one cannot
3538    call MatSolveTransposeAdd(A,x,y,x).
3539 
3540    Most users should employ the simplified KSP interface for linear solvers
3541    instead of working directly with matrix algebra routines such as this.
3542    See, e.g., KSPCreate().
3543 
3544    Level: developer
3545 
3546    Concepts: matrices^triangular solves
3547 
3548 .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3549 @*/
3550 PetscErrorCode  MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3551 {
3552   PetscScalar    one = 1.0;
3553   PetscErrorCode ierr;
3554   Vec            tmp;
3555 
3556   PetscFunctionBegin;
3557   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3558   PetscValidType(mat,1);
3559   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3560   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3561   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3562   PetscCheckSameComm(mat,1,b,2);
3563   PetscCheckSameComm(mat,1,y,3);
3564   PetscCheckSameComm(mat,1,x,4);
3565   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3566   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3567   if (mat->rmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
3568   if (mat->cmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap->N,b->map->N);
3569   if (mat->cmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
3570   if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
3571   MatCheckPreallocated(mat,1);
3572 
3573   ierr = PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3574   if (mat->ops->solvetransposeadd) {
3575     ierr = (*mat->ops->solvetransposeadd)(mat,b,y,x);CHKERRQ(ierr);
3576   } else {
3577     /* do the solve then the add manually */
3578     if (x != y) {
3579       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3580       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3581     } else {
3582       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3583       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3584       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3585       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3586       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3587       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3588     }
3589   }
3590   ierr = PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3591   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3592   PetscFunctionReturn(0);
3593 }
3594 /* ----------------------------------------------------------------*/
3595 
3596 #undef __FUNCT__
3597 #define __FUNCT__ "MatSOR"
3598 /*@
3599    MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3600 
3601    Neighbor-wise Collective on Mat and Vec
3602 
3603    Input Parameters:
3604 +  mat - the matrix
3605 .  b - the right hand side
3606 .  omega - the relaxation factor
3607 .  flag - flag indicating the type of SOR (see below)
3608 .  shift -  diagonal shift
3609 .  its - the number of iterations
3610 -  lits - the number of local iterations
3611 
3612    Output Parameters:
3613 .  x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3614 
3615    SOR Flags:
3616 .     SOR_FORWARD_SWEEP - forward SOR
3617 .     SOR_BACKWARD_SWEEP - backward SOR
3618 .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3619 .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3620 .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3621 .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3622 .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3623          upper/lower triangular part of matrix to
3624          vector (with omega)
3625 .     SOR_ZERO_INITIAL_GUESS - zero initial guess
3626 
3627    Notes:
3628    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3629    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3630    on each processor.
3631 
3632    Application programmers will not generally use MatSOR() directly,
3633    but instead will employ the KSP/PC interface.
3634 
3635    Notes: for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3636 
3637    Notes for Advanced Users:
3638    The flags are implemented as bitwise inclusive or operations.
3639    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3640    to specify a zero initial guess for SSOR.
3641 
3642    Most users should employ the simplified KSP interface for linear solvers
3643    instead of working directly with matrix algebra routines such as this.
3644    See, e.g., KSPCreate().
3645 
3646    Vectors x and b CANNOT be the same
3647 
3648    Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3649 
3650    Level: developer
3651 
3652    Concepts: matrices^relaxation
3653    Concepts: matrices^SOR
3654    Concepts: matrices^Gauss-Seidel
3655 
3656 @*/
3657 PetscErrorCode  MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3658 {
3659   PetscErrorCode ierr;
3660 
3661   PetscFunctionBegin;
3662   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3663   PetscValidType(mat,1);
3664   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3665   PetscValidHeaderSpecific(x,VEC_CLASSID,8);
3666   PetscCheckSameComm(mat,1,b,2);
3667   PetscCheckSameComm(mat,1,x,8);
3668   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3669   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3670   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3671   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3672   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3673   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3674   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3675   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3676   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
3677 
3678   MatCheckPreallocated(mat,1);
3679   ierr = PetscLogEventBegin(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
3680   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);CHKERRQ(ierr);
3681   ierr = PetscLogEventEnd(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
3682   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3683   PetscFunctionReturn(0);
3684 }
3685 
3686 #undef __FUNCT__
3687 #define __FUNCT__ "MatCopy_Basic"
3688 /*
3689       Default matrix copy routine.
3690 */
3691 PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3692 {
3693   PetscErrorCode    ierr;
3694   PetscInt          i,rstart = 0,rend = 0,nz;
3695   const PetscInt    *cwork;
3696   const PetscScalar *vwork;
3697 
3698   PetscFunctionBegin;
3699   if (B->assembled) {
3700     ierr = MatZeroEntries(B);CHKERRQ(ierr);
3701   }
3702   ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
3703   for (i=rstart; i<rend; i++) {
3704     ierr = MatGetRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
3705     ierr = MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);CHKERRQ(ierr);
3706     ierr = MatRestoreRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
3707   }
3708   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
3709   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
3710   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
3711   PetscFunctionReturn(0);
3712 }
3713 
3714 #undef __FUNCT__
3715 #define __FUNCT__ "MatCopy"
3716 /*@
3717    MatCopy - Copys a matrix to another matrix.
3718 
3719    Collective on Mat
3720 
3721    Input Parameters:
3722 +  A - the matrix
3723 -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
3724 
3725    Output Parameter:
3726 .  B - where the copy is put
3727 
3728    Notes:
3729    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3730    same nonzero pattern or the routine will crash.
3731 
3732    MatCopy() copies the matrix entries of a matrix to another existing
3733    matrix (after first zeroing the second matrix).  A related routine is
3734    MatConvert(), which first creates a new matrix and then copies the data.
3735 
3736    Level: intermediate
3737 
3738    Concepts: matrices^copying
3739 
3740 .seealso: MatConvert(), MatDuplicate()
3741 
3742 @*/
3743 PetscErrorCode  MatCopy(Mat A,Mat B,MatStructure str)
3744 {
3745   PetscErrorCode ierr;
3746   PetscInt       i;
3747 
3748   PetscFunctionBegin;
3749   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3750   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3751   PetscValidType(A,1);
3752   PetscValidType(B,2);
3753   PetscCheckSameComm(A,1,B,2);
3754   MatCheckPreallocated(B,2);
3755   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3756   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3757   if (A->rmap->N != B->rmap->N || A->cmap->N != B->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim (%D,%D) (%D,%D)",A->rmap->N,B->rmap->N,A->cmap->N,B->cmap->N);
3758   MatCheckPreallocated(A,1);
3759 
3760   ierr = PetscLogEventBegin(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
3761   if (A->ops->copy) {
3762     ierr = (*A->ops->copy)(A,B,str);CHKERRQ(ierr);
3763   } else { /* generic conversion */
3764     ierr = MatCopy_Basic(A,B,str);CHKERRQ(ierr);
3765   }
3766 
3767   B->stencil.dim = A->stencil.dim;
3768   B->stencil.noc = A->stencil.noc;
3769   for (i=0; i<=A->stencil.dim; i++) {
3770     B->stencil.dims[i]   = A->stencil.dims[i];
3771     B->stencil.starts[i] = A->stencil.starts[i];
3772   }
3773 
3774   ierr = PetscLogEventEnd(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
3775   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
3776   PetscFunctionReturn(0);
3777 }
3778 
3779 #undef __FUNCT__
3780 #define __FUNCT__ "MatConvert"
3781 /*@C
3782    MatConvert - Converts a matrix to another matrix, either of the same
3783    or different type.
3784 
3785    Collective on Mat
3786 
3787    Input Parameters:
3788 +  mat - the matrix
3789 .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
3790    same type as the original matrix.
3791 -  reuse - denotes if the destination matrix is to be created or reused.  Currently
3792    MAT_REUSE_MATRIX is only supported for inplace conversion, otherwise use
3793    MAT_INITIAL_MATRIX.
3794 
3795    Output Parameter:
3796 .  M - pointer to place new matrix
3797 
3798    Notes:
3799    MatConvert() first creates a new matrix and then copies the data from
3800    the first matrix.  A related routine is MatCopy(), which copies the matrix
3801    entries of one matrix to another already existing matrix context.
3802 
3803    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
3804    the MPI communicator of the generated matrix is always the same as the communicator
3805    of the input matrix.
3806 
3807    Level: intermediate
3808 
3809    Concepts: matrices^converting between storage formats
3810 
3811 .seealso: MatCopy(), MatDuplicate()
3812 @*/
3813 PetscErrorCode  MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
3814 {
3815   PetscErrorCode ierr;
3816   PetscBool      sametype,issame,flg;
3817   char           convname[256],mtype[256];
3818   Mat            B;
3819 
3820   PetscFunctionBegin;
3821   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3822   PetscValidType(mat,1);
3823   PetscValidPointer(M,3);
3824   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3825   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3826   MatCheckPreallocated(mat,1);
3827   ierr = MatSetOption(mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);CHKERRQ(ierr);
3828 
3829   ierr = PetscOptionsGetString(((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);CHKERRQ(ierr);
3830   if (flg) {
3831     newtype = mtype;
3832   }
3833   ierr = PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);CHKERRQ(ierr);
3834   ierr = PetscStrcmp(newtype,"same",&issame);CHKERRQ(ierr);
3835   if ((reuse == MAT_REUSE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_REUSE_MATRIX only supported for in-place conversion currently");
3836 
3837   if ((reuse == MAT_REUSE_MATRIX) && (issame || sametype)) PetscFunctionReturn(0);
3838 
3839   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
3840     ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
3841   } else {
3842     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
3843     const char     *prefix[3] = {"seq","mpi",""};
3844     PetscInt       i;
3845     /*
3846        Order of precedence:
3847        1) See if a specialized converter is known to the current matrix.
3848        2) See if a specialized converter is known to the desired matrix class.
3849        3) See if a good general converter is registered for the desired class
3850           (as of 6/27/03 only MATMPIADJ falls into this category).
3851        4) See if a good general converter is known for the current matrix.
3852        5) Use a really basic converter.
3853     */
3854 
3855     /* 1) See if a specialized converter is known to the current matrix and the desired class */
3856     for (i=0; i<3; i++) {
3857       ierr = PetscStrcpy(convname,"MatConvert_");CHKERRQ(ierr);
3858       ierr = PetscStrcat(convname,((PetscObject)mat)->type_name);CHKERRQ(ierr);
3859       ierr = PetscStrcat(convname,"_");CHKERRQ(ierr);
3860       ierr = PetscStrcat(convname,prefix[i]);CHKERRQ(ierr);
3861       ierr = PetscStrcat(convname,issame ? ((PetscObject)mat)->type_name : newtype);CHKERRQ(ierr);
3862       ierr = PetscStrcat(convname,"_C");CHKERRQ(ierr);
3863       ierr = PetscObjectQueryFunction((PetscObject)mat,convname,&conv);CHKERRQ(ierr);
3864       if (conv) goto foundconv;
3865     }
3866 
3867     /* 2)  See if a specialized converter is known to the desired matrix class. */
3868     ierr = MatCreate(PetscObjectComm((PetscObject)mat),&B);CHKERRQ(ierr);
3869     ierr = MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);CHKERRQ(ierr);
3870     ierr = MatSetType(B,newtype);CHKERRQ(ierr);
3871     for (i=0; i<3; i++) {
3872       ierr = PetscStrcpy(convname,"MatConvert_");CHKERRQ(ierr);
3873       ierr = PetscStrcat(convname,((PetscObject)mat)->type_name);CHKERRQ(ierr);
3874       ierr = PetscStrcat(convname,"_");CHKERRQ(ierr);
3875       ierr = PetscStrcat(convname,prefix[i]);CHKERRQ(ierr);
3876       ierr = PetscStrcat(convname,newtype);CHKERRQ(ierr);
3877       ierr = PetscStrcat(convname,"_C");CHKERRQ(ierr);
3878       ierr = PetscObjectQueryFunction((PetscObject)B,convname,&conv);CHKERRQ(ierr);
3879       if (conv) {
3880         ierr = MatDestroy(&B);CHKERRQ(ierr);
3881         goto foundconv;
3882       }
3883     }
3884 
3885     /* 3) See if a good general converter is registered for the desired class */
3886     conv = B->ops->convertfrom;
3887     ierr = MatDestroy(&B);CHKERRQ(ierr);
3888     if (conv) goto foundconv;
3889 
3890     /* 4) See if a good general converter is known for the current matrix */
3891     if (mat->ops->convert) {
3892       conv = mat->ops->convert;
3893     }
3894     if (conv) goto foundconv;
3895 
3896     /* 5) Use a really basic converter. */
3897     conv = MatConvert_Basic;
3898 
3899 foundconv:
3900     ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
3901     ierr = (*conv)(mat,newtype,reuse,M);CHKERRQ(ierr);
3902     ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
3903   }
3904   ierr = PetscObjectStateIncrease((PetscObject)*M);CHKERRQ(ierr);
3905 
3906   /* Copy Mat options */
3907   if (mat->symmetric) {ierr = MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);}
3908   if (mat->hermitian) {ierr = MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);}
3909   PetscFunctionReturn(0);
3910 }
3911 
3912 #undef __FUNCT__
3913 #define __FUNCT__ "MatFactorGetSolverPackage"
3914 /*@C
3915    MatFactorGetSolverPackage - Returns name of the package providing the factorization routines
3916 
3917    Not Collective
3918 
3919    Input Parameter:
3920 .  mat - the matrix, must be a factored matrix
3921 
3922    Output Parameter:
3923 .   type - the string name of the package (do not free this string)
3924 
3925    Notes:
3926       In Fortran you pass in a empty string and the package name will be copied into it.
3927     (Make sure the string is long enough)
3928 
3929    Level: intermediate
3930 
3931 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
3932 @*/
3933 PetscErrorCode  MatFactorGetSolverPackage(Mat mat, const MatSolverPackage *type)
3934 {
3935   PetscErrorCode ierr, (*conv)(Mat,const MatSolverPackage*);
3936 
3937   PetscFunctionBegin;
3938   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3939   PetscValidType(mat,1);
3940   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
3941   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverPackage_C",&conv);CHKERRQ(ierr);
3942   if (!conv) {
3943     *type = MATSOLVERPETSC;
3944   } else {
3945     ierr = (*conv)(mat,type);CHKERRQ(ierr);
3946   }
3947   PetscFunctionReturn(0);
3948 }
3949 
3950 typedef struct _MatSolverPackageForSpecifcType* MatSolverPackageForSpecifcType;
3951 struct _MatSolverPackageForSpecifcType {
3952   MatType                        mtype;
3953   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
3954   MatSolverPackageForSpecifcType next;
3955 };
3956 
3957 typedef struct _MatSolverPackageHolder* MatSolverPackageHolder;
3958 struct _MatSolverPackageHolder {
3959   char                           *name;
3960   MatSolverPackageForSpecifcType handlers;
3961   MatSolverPackageHolder         next;
3962 };
3963 
3964 static MatSolverPackageHolder MatSolverPackageHolders = NULL;
3965 
3966 #undef __FUNCT__
3967 #define __FUNCT__ "MatSolverPackageRegister"
3968 /*@C
3969    MatSolvePackageRegister - Registers a MatSolverPackage that works for a particular matrix type
3970 
3971    Input Parameters:
3972 +    package - name of the package, for example petsc or superlu
3973 .    mtype - the matrix type that works with this package
3974 .    ftype - the type of factorization supported by the package
3975 -    getfactor - routine that will create the factored matrix ready to be used
3976 
3977     Level: intermediate
3978 
3979 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
3980 @*/
3981 PetscErrorCode  MatSolverPackageRegister(const MatSolverPackage package,const MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
3982 {
3983   PetscErrorCode                 ierr;
3984   MatSolverPackageHolder         next = MatSolverPackageHolders,prev;
3985   PetscBool                      flg;
3986   MatSolverPackageForSpecifcType inext,iprev = NULL;
3987 
3988   PetscFunctionBegin;
3989   if (!MatSolverPackageHolders) {
3990     ierr = PetscNew(&MatSolverPackageHolders);CHKERRQ(ierr);
3991     ierr = PetscStrallocpy(package,&MatSolverPackageHolders->name);CHKERRQ(ierr);
3992     ierr = PetscNew(&MatSolverPackageHolders->handlers);CHKERRQ(ierr);
3993     ierr = PetscStrallocpy(mtype,(char **)&MatSolverPackageHolders->handlers->mtype);CHKERRQ(ierr);
3994     MatSolverPackageHolders->handlers->getfactor[(int)ftype-1] = getfactor;
3995     PetscFunctionReturn(0);
3996   }
3997   while (next) {
3998     ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
3999     if (flg) {
4000       inext = next->handlers;
4001       while (inext) {
4002         ierr = PetscStrcasecmp(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4003         if (flg) {
4004           inext->getfactor[(int)ftype-1] = getfactor;
4005           PetscFunctionReturn(0);
4006         }
4007         iprev = inext;
4008         inext = inext->next;
4009       }
4010       ierr = PetscNew(&iprev->next);CHKERRQ(ierr);
4011       ierr = PetscStrallocpy(mtype,(char **)&iprev->next->mtype);CHKERRQ(ierr);
4012       iprev->next->getfactor[(int)ftype-1] = getfactor;
4013       PetscFunctionReturn(0);
4014     }
4015     prev = next;
4016     next = next->next;
4017   }
4018   ierr = PetscNew(&prev->next);CHKERRQ(ierr);
4019   ierr = PetscStrallocpy(package,&prev->next->name);CHKERRQ(ierr);
4020   ierr = PetscNew(&prev->next->handlers);CHKERRQ(ierr);
4021   ierr = PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);CHKERRQ(ierr);
4022   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4023   PetscFunctionReturn(0);
4024 }
4025 
4026 #undef __FUNCT__
4027 #define __FUNCT__ "MatSolverPackageGet"
4028 /*@C
4029    MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4030 
4031    Input Parameters:
4032 +    package - name of the package, for example petsc or superlu
4033 .    ftype - the type of factorization supported by the package
4034 -    mtype - the matrix type that works with this package
4035 
4036    Output Parameters:
4037 +   foundpackage - PETSC_TRUE if the package was registered
4038 .   foundmtype - PETSC_TRUE if the package supports the requested mtype
4039 -   getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4040 
4041     Level: intermediate
4042 
4043 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4044 @*/
4045 PetscErrorCode  MatSolverPackageGet(const MatSolverPackage package,const MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4046 {
4047   PetscErrorCode                 ierr;
4048   MatSolverPackageHolder         next = MatSolverPackageHolders;
4049   PetscBool                      flg;
4050   MatSolverPackageForSpecifcType inext;
4051 
4052   PetscFunctionBegin;
4053   if (foundpackage) *foundpackage = PETSC_FALSE;
4054   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4055   if (getfactor)    *getfactor    = NULL;
4056   while (next) {
4057     ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4058     if (flg) {
4059       if (foundpackage) *foundpackage = PETSC_TRUE;
4060       inext = next->handlers;
4061       while (inext) {
4062         ierr = PetscStrcasecmp(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4063         if (flg) {
4064           if (foundmtype) *foundmtype = PETSC_TRUE;
4065           if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4066           PetscFunctionReturn(0);
4067         }
4068         inext = inext->next;
4069       }
4070     }
4071     next = next->next;
4072   }
4073   PetscFunctionReturn(0);
4074 }
4075 
4076 #undef __FUNCT__
4077 #define __FUNCT__ "MatSolverPackageDestroy"
4078 PetscErrorCode  MatSolverPackageDestroy(void)
4079 {
4080   PetscErrorCode                 ierr;
4081   MatSolverPackageHolder         next = MatSolverPackageHolders,prev;
4082   MatSolverPackageForSpecifcType inext,iprev;
4083 
4084   PetscFunctionBegin;
4085   while (next) {
4086     ierr = PetscFree(next->name);CHKERRQ(ierr);
4087     inext = next->handlers;
4088     while (inext) {
4089       ierr = PetscFree(inext->mtype);CHKERRQ(ierr);
4090       iprev = inext;
4091       inext = inext->next;
4092       ierr = PetscFree(iprev);CHKERRQ(ierr);
4093     }
4094     prev = next;
4095     next = next->next;
4096     ierr = PetscFree(prev);CHKERRQ(ierr);
4097   }
4098   MatSolverPackageHolders = NULL;
4099   PetscFunctionReturn(0);
4100 }
4101 
4102 #undef __FUNCT__
4103 #define __FUNCT__ "MatGetFactor"
4104 /*@C
4105    MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4106 
4107    Collective on Mat
4108 
4109    Input Parameters:
4110 +  mat - the matrix
4111 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4112 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4113 
4114    Output Parameters:
4115 .  f - the factor matrix used with MatXXFactorSymbolic() calls
4116 
4117    Notes:
4118       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4119      such as pastix, superlu, mumps etc.
4120 
4121       PETSc must have been ./configure to use the external solver, using the option --download-package
4122 
4123    Level: intermediate
4124 
4125 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4126 @*/
4127 PetscErrorCode  MatGetFactor(Mat mat, const MatSolverPackage type,MatFactorType ftype,Mat *f)
4128 {
4129   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4130   PetscBool      foundpackage,foundmtype;
4131 
4132   PetscFunctionBegin;
4133   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4134   PetscValidType(mat,1);
4135 
4136   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4137   MatCheckPreallocated(mat,1);
4138 
4139   ierr = MatSolverPackageGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);CHKERRQ(ierr);
4140   if (!foundpackage) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4141   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverPackage %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4142   if (!conv) SETERRQ3(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverPackage %s does not support factorization type %s for  matrix type %s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name);
4143 
4144   ierr = (*conv)(mat,ftype,f);CHKERRQ(ierr);
4145   PetscFunctionReturn(0);
4146 }
4147 
4148 #undef __FUNCT__
4149 #define __FUNCT__ "MatGetFactorAvailable"
4150 /*@C
4151    MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4152 
4153    Not Collective
4154 
4155    Input Parameters:
4156 +  mat - the matrix
4157 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4158 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4159 
4160    Output Parameter:
4161 .    flg - PETSC_TRUE if the factorization is available
4162 
4163    Notes:
4164       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4165      such as pastix, superlu, mumps etc.
4166 
4167       PETSc must have been ./configure to use the external solver, using the option --download-package
4168 
4169    Level: intermediate
4170 
4171 .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4172 @*/
4173 PetscErrorCode  MatGetFactorAvailable(Mat mat, const MatSolverPackage type,MatFactorType ftype,PetscBool  *flg)
4174 {
4175   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4176 
4177   PetscFunctionBegin;
4178   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4179   PetscValidType(mat,1);
4180 
4181   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4182   MatCheckPreallocated(mat,1);
4183 
4184   *flg = PETSC_FALSE;
4185   ierr = MatSolverPackageGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);CHKERRQ(ierr);
4186   if (gconv) {
4187     *flg = PETSC_TRUE;
4188   }
4189   PetscFunctionReturn(0);
4190 }
4191 
4192 #undef __FUNCT__
4193 #define __FUNCT__ "MatDuplicate"
4194 /*@
4195    MatDuplicate - Duplicates a matrix including the non-zero structure.
4196 
4197    Collective on Mat
4198 
4199    Input Parameters:
4200 +  mat - the matrix
4201 -  op - either MAT_DO_NOT_COPY_VALUES or MAT_COPY_VALUES, cause it to copy the numerical values in the matrix
4202         MAT_SHARE_NONZERO_PATTERN to share the nonzero patterns with the previous matrix and not copy them.
4203 
4204    Output Parameter:
4205 .  M - pointer to place new matrix
4206 
4207    Level: intermediate
4208 
4209    Concepts: matrices^duplicating
4210 
4211     Notes: You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4212 
4213 .seealso: MatCopy(), MatConvert()
4214 @*/
4215 PetscErrorCode  MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4216 {
4217   PetscErrorCode ierr;
4218   Mat            B;
4219   PetscInt       i;
4220 
4221   PetscFunctionBegin;
4222   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4223   PetscValidType(mat,1);
4224   PetscValidPointer(M,3);
4225   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4226   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4227   MatCheckPreallocated(mat,1);
4228 
4229   *M = 0;
4230   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4231   ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4232   ierr = (*mat->ops->duplicate)(mat,op,M);CHKERRQ(ierr);
4233   B    = *M;
4234 
4235   B->stencil.dim = mat->stencil.dim;
4236   B->stencil.noc = mat->stencil.noc;
4237   for (i=0; i<=mat->stencil.dim; i++) {
4238     B->stencil.dims[i]   = mat->stencil.dims[i];
4239     B->stencil.starts[i] = mat->stencil.starts[i];
4240   }
4241 
4242   B->nooffproczerorows = mat->nooffproczerorows;
4243   B->nooffprocentries  = mat->nooffprocentries;
4244 
4245   ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4246   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4247   PetscFunctionReturn(0);
4248 }
4249 
4250 #undef __FUNCT__
4251 #define __FUNCT__ "MatGetDiagonal"
4252 /*@
4253    MatGetDiagonal - Gets the diagonal of a matrix.
4254 
4255    Logically Collective on Mat and Vec
4256 
4257    Input Parameters:
4258 +  mat - the matrix
4259 -  v - the vector for storing the diagonal
4260 
4261    Output Parameter:
4262 .  v - the diagonal of the matrix
4263 
4264    Level: intermediate
4265 
4266    Note:
4267    Currently only correct in parallel for square matrices.
4268 
4269    Concepts: matrices^accessing diagonals
4270 
4271 .seealso: MatGetRow(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs()
4272 @*/
4273 PetscErrorCode  MatGetDiagonal(Mat mat,Vec v)
4274 {
4275   PetscErrorCode ierr;
4276 
4277   PetscFunctionBegin;
4278   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4279   PetscValidType(mat,1);
4280   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4281   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4282   if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4283   MatCheckPreallocated(mat,1);
4284 
4285   ierr = (*mat->ops->getdiagonal)(mat,v);CHKERRQ(ierr);
4286   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4287   PetscFunctionReturn(0);
4288 }
4289 
4290 #undef __FUNCT__
4291 #define __FUNCT__ "MatGetRowMin"
4292 /*@
4293    MatGetRowMin - Gets the minimum value (of the real part) of each
4294         row of the matrix
4295 
4296    Logically Collective on Mat and Vec
4297 
4298    Input Parameters:
4299 .  mat - the matrix
4300 
4301    Output Parameter:
4302 +  v - the vector for storing the maximums
4303 -  idx - the indices of the column found for each row (optional)
4304 
4305    Level: intermediate
4306 
4307    Notes: The result of this call are the same as if one converted the matrix to dense format
4308       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4309 
4310     This code is only implemented for a couple of matrix formats.
4311 
4312    Concepts: matrices^getting row maximums
4313 
4314 .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(),
4315           MatGetRowMax()
4316 @*/
4317 PetscErrorCode  MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4318 {
4319   PetscErrorCode ierr;
4320 
4321   PetscFunctionBegin;
4322   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4323   PetscValidType(mat,1);
4324   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4325   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4326   if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4327   MatCheckPreallocated(mat,1);
4328 
4329   ierr = (*mat->ops->getrowmin)(mat,v,idx);CHKERRQ(ierr);
4330   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4331   PetscFunctionReturn(0);
4332 }
4333 
4334 #undef __FUNCT__
4335 #define __FUNCT__ "MatGetRowMinAbs"
4336 /*@
4337    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4338         row of the matrix
4339 
4340    Logically Collective on Mat and Vec
4341 
4342    Input Parameters:
4343 .  mat - the matrix
4344 
4345    Output Parameter:
4346 +  v - the vector for storing the minimums
4347 -  idx - the indices of the column found for each row (or NULL if not needed)
4348 
4349    Level: intermediate
4350 
4351    Notes: if a row is completely empty or has only 0.0 values then the idx[] value for that
4352     row is 0 (the first column).
4353 
4354     This code is only implemented for a couple of matrix formats.
4355 
4356    Concepts: matrices^getting row maximums
4357 
4358 .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4359 @*/
4360 PetscErrorCode  MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4361 {
4362   PetscErrorCode ierr;
4363 
4364   PetscFunctionBegin;
4365   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4366   PetscValidType(mat,1);
4367   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4368   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4369   if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4370   MatCheckPreallocated(mat,1);
4371   if (idx) {ierr = PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));CHKERRQ(ierr);}
4372 
4373   ierr = (*mat->ops->getrowminabs)(mat,v,idx);CHKERRQ(ierr);
4374   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4375   PetscFunctionReturn(0);
4376 }
4377 
4378 #undef __FUNCT__
4379 #define __FUNCT__ "MatGetRowMax"
4380 /*@
4381    MatGetRowMax - Gets the maximum value (of the real part) of each
4382         row of the matrix
4383 
4384    Logically Collective on Mat and Vec
4385 
4386    Input Parameters:
4387 .  mat - the matrix
4388 
4389    Output Parameter:
4390 +  v - the vector for storing the maximums
4391 -  idx - the indices of the column found for each row (optional)
4392 
4393    Level: intermediate
4394 
4395    Notes: The result of this call are the same as if one converted the matrix to dense format
4396       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4397 
4398     This code is only implemented for a couple of matrix formats.
4399 
4400    Concepts: matrices^getting row maximums
4401 
4402 .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4403 @*/
4404 PetscErrorCode  MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4405 {
4406   PetscErrorCode ierr;
4407 
4408   PetscFunctionBegin;
4409   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4410   PetscValidType(mat,1);
4411   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4412   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4413   if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4414   MatCheckPreallocated(mat,1);
4415 
4416   ierr = (*mat->ops->getrowmax)(mat,v,idx);CHKERRQ(ierr);
4417   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4418   PetscFunctionReturn(0);
4419 }
4420 
4421 #undef __FUNCT__
4422 #define __FUNCT__ "MatGetRowMaxAbs"
4423 /*@
4424    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4425         row of the matrix
4426 
4427    Logically Collective on Mat and Vec
4428 
4429    Input Parameters:
4430 .  mat - the matrix
4431 
4432    Output Parameter:
4433 +  v - the vector for storing the maximums
4434 -  idx - the indices of the column found for each row (or NULL if not needed)
4435 
4436    Level: intermediate
4437 
4438    Notes: if a row is completely empty or has only 0.0 values then the idx[] value for that
4439     row is 0 (the first column).
4440 
4441     This code is only implemented for a couple of matrix formats.
4442 
4443    Concepts: matrices^getting row maximums
4444 
4445 .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
4446 @*/
4447 PetscErrorCode  MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4448 {
4449   PetscErrorCode ierr;
4450 
4451   PetscFunctionBegin;
4452   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4453   PetscValidType(mat,1);
4454   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4455   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4456   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4457   MatCheckPreallocated(mat,1);
4458   if (idx) {ierr = PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));CHKERRQ(ierr);}
4459 
4460   ierr = (*mat->ops->getrowmaxabs)(mat,v,idx);CHKERRQ(ierr);
4461   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4462   PetscFunctionReturn(0);
4463 }
4464 
4465 #undef __FUNCT__
4466 #define __FUNCT__ "MatGetRowSum"
4467 /*@
4468    MatGetRowSum - Gets the sum of each row of the matrix
4469 
4470    Logically Collective on Mat and Vec
4471 
4472    Input Parameters:
4473 .  mat - the matrix
4474 
4475    Output Parameter:
4476 .  v - the vector for storing the sum of rows
4477 
4478    Level: intermediate
4479 
4480    Notes: This code is slow since it is not currently specialized for different formats
4481 
4482    Concepts: matrices^getting row sums
4483 
4484 .seealso: MatGetDiagonal(), MatGetSubMatrices(), MatGetSubmatrix(), MatGetRowMax(), MatGetRowMin()
4485 @*/
4486 PetscErrorCode  MatGetRowSum(Mat mat, Vec v)
4487 {
4488   PetscInt       start = 0, end = 0, row;
4489   PetscScalar    *array;
4490   PetscErrorCode ierr;
4491 
4492   PetscFunctionBegin;
4493   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4494   PetscValidType(mat,1);
4495   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4496   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4497   MatCheckPreallocated(mat,1);
4498   ierr = MatGetOwnershipRange(mat, &start, &end);CHKERRQ(ierr);
4499   ierr = VecGetArray(v, &array);CHKERRQ(ierr);
4500   for (row = start; row < end; ++row) {
4501     PetscInt          ncols, col;
4502     const PetscInt    *cols;
4503     const PetscScalar *vals;
4504 
4505     array[row - start] = 0.0;
4506 
4507     ierr = MatGetRow(mat, row, &ncols, &cols, &vals);CHKERRQ(ierr);
4508     for (col = 0; col < ncols; col++) {
4509       array[row - start] += vals[col];
4510     }
4511     ierr = MatRestoreRow(mat, row, &ncols, &cols, &vals);CHKERRQ(ierr);
4512   }
4513   ierr = VecRestoreArray(v, &array);CHKERRQ(ierr);
4514   ierr = PetscObjectStateIncrease((PetscObject) v);CHKERRQ(ierr);
4515   PetscFunctionReturn(0);
4516 }
4517 
4518 #undef __FUNCT__
4519 #define __FUNCT__ "MatTranspose"
4520 /*@
4521    MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4522 
4523    Collective on Mat
4524 
4525    Input Parameter:
4526 +  mat - the matrix to transpose
4527 -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
4528 
4529    Output Parameters:
4530 .  B - the transpose
4531 
4532    Notes:
4533      If you  pass in &mat for B the transpose will be done in place, for example MatTranspose(mat,MAT_REUSE_MATRIX,&mat);
4534 
4535      Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4536 
4537    Level: intermediate
4538 
4539    Concepts: matrices^transposing
4540 
4541 .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4542 @*/
4543 PetscErrorCode  MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4544 {
4545   PetscErrorCode ierr;
4546 
4547   PetscFunctionBegin;
4548   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4549   PetscValidType(mat,1);
4550   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4551   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4552   if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4553   MatCheckPreallocated(mat,1);
4554 
4555   ierr = PetscLogEventBegin(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4556   ierr = (*mat->ops->transpose)(mat,reuse,B);CHKERRQ(ierr);
4557   ierr = PetscLogEventEnd(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4558   if (B) {ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);}
4559   PetscFunctionReturn(0);
4560 }
4561 
4562 #undef __FUNCT__
4563 #define __FUNCT__ "MatIsTranspose"
4564 /*@
4565    MatIsTranspose - Test whether a matrix is another one's transpose,
4566         or its own, in which case it tests symmetry.
4567 
4568    Collective on Mat
4569 
4570    Input Parameter:
4571 +  A - the matrix to test
4572 -  B - the matrix to test against, this can equal the first parameter
4573 
4574    Output Parameters:
4575 .  flg - the result
4576 
4577    Notes:
4578    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4579    has a running time of the order of the number of nonzeros; the parallel
4580    test involves parallel copies of the block-offdiagonal parts of the matrix.
4581 
4582    Level: intermediate
4583 
4584    Concepts: matrices^transposing, matrix^symmetry
4585 
4586 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4587 @*/
4588 PetscErrorCode  MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4589 {
4590   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4591 
4592   PetscFunctionBegin;
4593   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4594   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4595   PetscValidPointer(flg,3);
4596   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);CHKERRQ(ierr);
4597   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);CHKERRQ(ierr);
4598   *flg = PETSC_FALSE;
4599   if (f && g) {
4600     if (f == g) {
4601       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
4602     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4603   } else {
4604     MatType mattype;
4605     if (!f) {
4606       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
4607     } else {
4608       ierr = MatGetType(B,&mattype);CHKERRQ(ierr);
4609     }
4610     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4611   }
4612   PetscFunctionReturn(0);
4613 }
4614 
4615 #undef __FUNCT__
4616 #define __FUNCT__ "MatHermitianTranspose"
4617 /*@
4618    MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
4619 
4620    Collective on Mat
4621 
4622    Input Parameter:
4623 +  mat - the matrix to transpose and complex conjugate
4624 -  reuse - store the transpose matrix in the provided B
4625 
4626    Output Parameters:
4627 .  B - the Hermitian
4628 
4629    Notes:
4630      If you  pass in &mat for B the Hermitian will be done in place
4631 
4632    Level: intermediate
4633 
4634    Concepts: matrices^transposing, complex conjugatex
4635 
4636 .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4637 @*/
4638 PetscErrorCode  MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4639 {
4640   PetscErrorCode ierr;
4641 
4642   PetscFunctionBegin;
4643   ierr = MatTranspose(mat,reuse,B);CHKERRQ(ierr);
4644 #if defined(PETSC_USE_COMPLEX)
4645   ierr = MatConjugate(*B);CHKERRQ(ierr);
4646 #endif
4647   PetscFunctionReturn(0);
4648 }
4649 
4650 #undef __FUNCT__
4651 #define __FUNCT__ "MatIsHermitianTranspose"
4652 /*@
4653    MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
4654 
4655    Collective on Mat
4656 
4657    Input Parameter:
4658 +  A - the matrix to test
4659 -  B - the matrix to test against, this can equal the first parameter
4660 
4661    Output Parameters:
4662 .  flg - the result
4663 
4664    Notes:
4665    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4666    has a running time of the order of the number of nonzeros; the parallel
4667    test involves parallel copies of the block-offdiagonal parts of the matrix.
4668 
4669    Level: intermediate
4670 
4671    Concepts: matrices^transposing, matrix^symmetry
4672 
4673 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4674 @*/
4675 PetscErrorCode  MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4676 {
4677   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4678 
4679   PetscFunctionBegin;
4680   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4681   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4682   PetscValidPointer(flg,3);
4683   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);CHKERRQ(ierr);
4684   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);CHKERRQ(ierr);
4685   if (f && g) {
4686     if (f==g) {
4687       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
4688     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4689   }
4690   PetscFunctionReturn(0);
4691 }
4692 
4693 #undef __FUNCT__
4694 #define __FUNCT__ "MatPermute"
4695 /*@
4696    MatPermute - Creates a new matrix with rows and columns permuted from the
4697    original.
4698 
4699    Collective on Mat
4700 
4701    Input Parameters:
4702 +  mat - the matrix to permute
4703 .  row - row permutation, each processor supplies only the permutation for its rows
4704 -  col - column permutation, each processor supplies only the permutation for its columns
4705 
4706    Output Parameters:
4707 .  B - the permuted matrix
4708 
4709    Level: advanced
4710 
4711    Note:
4712    The index sets map from row/col of permuted matrix to row/col of original matrix.
4713    The index sets should be on the same communicator as Mat and have the same local sizes.
4714 
4715    Concepts: matrices^permuting
4716 
4717 .seealso: MatGetOrdering(), ISAllGather()
4718 
4719 @*/
4720 PetscErrorCode  MatPermute(Mat mat,IS row,IS col,Mat *B)
4721 {
4722   PetscErrorCode ierr;
4723 
4724   PetscFunctionBegin;
4725   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4726   PetscValidType(mat,1);
4727   PetscValidHeaderSpecific(row,IS_CLASSID,2);
4728   PetscValidHeaderSpecific(col,IS_CLASSID,3);
4729   PetscValidPointer(B,4);
4730   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4731   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4732   if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
4733   MatCheckPreallocated(mat,1);
4734 
4735   ierr = (*mat->ops->permute)(mat,row,col,B);CHKERRQ(ierr);
4736   ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);
4737   PetscFunctionReturn(0);
4738 }
4739 
4740 #undef __FUNCT__
4741 #define __FUNCT__ "MatEqual"
4742 /*@
4743    MatEqual - Compares two matrices.
4744 
4745    Collective on Mat
4746 
4747    Input Parameters:
4748 +  A - the first matrix
4749 -  B - the second matrix
4750 
4751    Output Parameter:
4752 .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
4753 
4754    Level: intermediate
4755 
4756    Concepts: matrices^equality between
4757 @*/
4758 PetscErrorCode  MatEqual(Mat A,Mat B,PetscBool  *flg)
4759 {
4760   PetscErrorCode ierr;
4761 
4762   PetscFunctionBegin;
4763   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4764   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4765   PetscValidType(A,1);
4766   PetscValidType(B,2);
4767   PetscValidIntPointer(flg,3);
4768   PetscCheckSameComm(A,1,B,2);
4769   MatCheckPreallocated(B,2);
4770   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4771   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4772   if (A->rmap->N != B->rmap->N || A->cmap->N != B->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D %D %D",A->rmap->N,B->rmap->N,A->cmap->N,B->cmap->N);
4773   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
4774   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
4775   if (A->ops->equal != B->ops->equal) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"A is type: %s\nB is type: %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
4776   MatCheckPreallocated(A,1);
4777 
4778   ierr = (*A->ops->equal)(A,B,flg);CHKERRQ(ierr);
4779   PetscFunctionReturn(0);
4780 }
4781 
4782 #undef __FUNCT__
4783 #define __FUNCT__ "MatDiagonalScale"
4784 /*@
4785    MatDiagonalScale - Scales a matrix on the left and right by diagonal
4786    matrices that are stored as vectors.  Either of the two scaling
4787    matrices can be NULL.
4788 
4789    Collective on Mat
4790 
4791    Input Parameters:
4792 +  mat - the matrix to be scaled
4793 .  l - the left scaling vector (or NULL)
4794 -  r - the right scaling vector (or NULL)
4795 
4796    Notes:
4797    MatDiagonalScale() computes A = LAR, where
4798    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
4799    The L scales the rows of the matrix, the R scales the columns of the matrix.
4800 
4801    Level: intermediate
4802 
4803    Concepts: matrices^diagonal scaling
4804    Concepts: diagonal scaling of matrices
4805 
4806 .seealso: MatScale()
4807 @*/
4808 PetscErrorCode  MatDiagonalScale(Mat mat,Vec l,Vec r)
4809 {
4810   PetscErrorCode ierr;
4811 
4812   PetscFunctionBegin;
4813   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4814   PetscValidType(mat,1);
4815   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4816   if (l) {PetscValidHeaderSpecific(l,VEC_CLASSID,2);PetscCheckSameComm(mat,1,l,2);}
4817   if (r) {PetscValidHeaderSpecific(r,VEC_CLASSID,3);PetscCheckSameComm(mat,1,r,3);}
4818   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4819   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4820   MatCheckPreallocated(mat,1);
4821 
4822   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
4823   ierr = (*mat->ops->diagonalscale)(mat,l,r);CHKERRQ(ierr);
4824   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
4825   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
4826 #if defined(PETSC_HAVE_CUSP)
4827   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
4828     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
4829   }
4830 #endif
4831 #if defined(PETSC_HAVE_VIENNACL)
4832   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
4833     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
4834   }
4835 #endif
4836   PetscFunctionReturn(0);
4837 }
4838 
4839 #undef __FUNCT__
4840 #define __FUNCT__ "MatScale"
4841 /*@
4842     MatScale - Scales all elements of a matrix by a given number.
4843 
4844     Logically Collective on Mat
4845 
4846     Input Parameters:
4847 +   mat - the matrix to be scaled
4848 -   a  - the scaling value
4849 
4850     Output Parameter:
4851 .   mat - the scaled matrix
4852 
4853     Level: intermediate
4854 
4855     Concepts: matrices^scaling all entries
4856 
4857 .seealso: MatDiagonalScale()
4858 @*/
4859 PetscErrorCode  MatScale(Mat mat,PetscScalar a)
4860 {
4861   PetscErrorCode ierr;
4862 
4863   PetscFunctionBegin;
4864   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4865   PetscValidType(mat,1);
4866   if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4867   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4868   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4869   PetscValidLogicalCollectiveScalar(mat,a,2);
4870   MatCheckPreallocated(mat,1);
4871 
4872   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
4873   if (a != (PetscScalar)1.0) {
4874     ierr = (*mat->ops->scale)(mat,a);CHKERRQ(ierr);
4875     ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
4876   }
4877   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
4878 #if defined(PETSC_HAVE_CUSP)
4879   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
4880     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
4881   }
4882 #endif
4883 #if defined(PETSC_HAVE_VIENNACL)
4884   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
4885     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
4886   }
4887 #endif
4888   PetscFunctionReturn(0);
4889 }
4890 
4891 #undef __FUNCT__
4892 #define __FUNCT__ "MatNorm"
4893 /*@
4894    MatNorm - Calculates various norms of a matrix.
4895 
4896    Collective on Mat
4897 
4898    Input Parameters:
4899 +  mat - the matrix
4900 -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
4901 
4902    Output Parameters:
4903 .  nrm - the resulting norm
4904 
4905    Level: intermediate
4906 
4907    Concepts: matrices^norm
4908    Concepts: norm^of matrix
4909 @*/
4910 PetscErrorCode  MatNorm(Mat mat,NormType type,PetscReal *nrm)
4911 {
4912   PetscErrorCode ierr;
4913 
4914   PetscFunctionBegin;
4915   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4916   PetscValidType(mat,1);
4917   PetscValidScalarPointer(nrm,3);
4918 
4919   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4920   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4921   if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4922   MatCheckPreallocated(mat,1);
4923 
4924   ierr = (*mat->ops->norm)(mat,type,nrm);CHKERRQ(ierr);
4925   PetscFunctionReturn(0);
4926 }
4927 
4928 /*
4929      This variable is used to prevent counting of MatAssemblyBegin() that
4930    are called from within a MatAssemblyEnd().
4931 */
4932 static PetscInt MatAssemblyEnd_InUse = 0;
4933 #undef __FUNCT__
4934 #define __FUNCT__ "MatAssemblyBegin"
4935 /*@
4936    MatAssemblyBegin - Begins assembling the matrix.  This routine should
4937    be called after completing all calls to MatSetValues().
4938 
4939    Collective on Mat
4940 
4941    Input Parameters:
4942 +  mat - the matrix
4943 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
4944 
4945    Notes:
4946    MatSetValues() generally caches the values.  The matrix is ready to
4947    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
4948    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
4949    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
4950    using the matrix.
4951 
4952    ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
4953    same flag of MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY for all processes. Thus you CANNOT locally change from ADD_VALUES to INSERT_VALUES, that is
4954    a global collective operation requring all processes that share the matrix.
4955 
4956    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
4957    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
4958    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
4959 
4960    Level: beginner
4961 
4962    Concepts: matrices^assembling
4963 
4964 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
4965 @*/
4966 PetscErrorCode  MatAssemblyBegin(Mat mat,MatAssemblyType type)
4967 {
4968   PetscErrorCode ierr;
4969 
4970   PetscFunctionBegin;
4971   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4972   PetscValidType(mat,1);
4973   MatCheckPreallocated(mat,1);
4974   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
4975   if (mat->assembled) {
4976     mat->was_assembled = PETSC_TRUE;
4977     mat->assembled     = PETSC_FALSE;
4978   }
4979   if (!MatAssemblyEnd_InUse) {
4980     ierr = PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
4981     if (mat->ops->assemblybegin) {ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);}
4982     ierr = PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
4983   } else if (mat->ops->assemblybegin) {
4984     ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);
4985   }
4986   PetscFunctionReturn(0);
4987 }
4988 
4989 #undef __FUNCT__
4990 #define __FUNCT__ "MatAssembled"
4991 /*@
4992    MatAssembled - Indicates if a matrix has been assembled and is ready for
4993      use; for example, in matrix-vector product.
4994 
4995    Not Collective
4996 
4997    Input Parameter:
4998 .  mat - the matrix
4999 
5000    Output Parameter:
5001 .  assembled - PETSC_TRUE or PETSC_FALSE
5002 
5003    Level: advanced
5004 
5005    Concepts: matrices^assembled?
5006 
5007 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5008 @*/
5009 PetscErrorCode  MatAssembled(Mat mat,PetscBool  *assembled)
5010 {
5011   PetscFunctionBegin;
5012   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5013   PetscValidType(mat,1);
5014   PetscValidPointer(assembled,2);
5015   *assembled = mat->assembled;
5016   PetscFunctionReturn(0);
5017 }
5018 
5019 #undef __FUNCT__
5020 #define __FUNCT__ "MatAssemblyEnd"
5021 /*@
5022    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5023    be called after MatAssemblyBegin().
5024 
5025    Collective on Mat
5026 
5027    Input Parameters:
5028 +  mat - the matrix
5029 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5030 
5031    Options Database Keys:
5032 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5033 .  -mat_view ::ascii_info_detail - Prints more detailed info
5034 .  -mat_view - Prints matrix in ASCII format
5035 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5036 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5037 .  -display <name> - Sets display name (default is host)
5038 .  -draw_pause <sec> - Sets number of seconds to pause after display
5039 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab )
5040 .  -viewer_socket_machine <machine>
5041 .  -viewer_socket_port <port>
5042 .  -mat_view binary - save matrix to file in binary format
5043 -  -viewer_binary_filename <name>
5044 
5045    Notes:
5046    MatSetValues() generally caches the values.  The matrix is ready to
5047    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5048    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5049    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5050    using the matrix.
5051 
5052    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5053    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5054    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5055 
5056    Level: beginner
5057 
5058 .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5059 @*/
5060 PetscErrorCode  MatAssemblyEnd(Mat mat,MatAssemblyType type)
5061 {
5062   PetscErrorCode  ierr;
5063   static PetscInt inassm = 0;
5064   PetscBool       flg    = PETSC_FALSE;
5065 
5066   PetscFunctionBegin;
5067   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5068   PetscValidType(mat,1);
5069 
5070   inassm++;
5071   MatAssemblyEnd_InUse++;
5072   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5073     ierr = PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5074     if (mat->ops->assemblyend) {
5075       ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5076     }
5077     ierr = PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5078   } else if (mat->ops->assemblyend) {
5079     ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5080   }
5081 
5082   /* Flush assembly is not a true assembly */
5083   if (type != MAT_FLUSH_ASSEMBLY) {
5084     mat->assembled = PETSC_TRUE; mat->num_ass++;
5085   }
5086   mat->insertmode = NOT_SET_VALUES;
5087   MatAssemblyEnd_InUse--;
5088   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5089   if (!mat->symmetric_eternal) {
5090     mat->symmetric_set              = PETSC_FALSE;
5091     mat->hermitian_set              = PETSC_FALSE;
5092     mat->structurally_symmetric_set = PETSC_FALSE;
5093   }
5094 #if defined(PETSC_HAVE_CUSP)
5095   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5096     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5097   }
5098 #endif
5099 #if defined(PETSC_HAVE_VIENNACL)
5100   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5101     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5102   }
5103 #endif
5104   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5105     ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5106 
5107     if (mat->checksymmetryonassembly) {
5108       ierr = MatIsSymmetric(mat,mat->checksymmetrytol,&flg);CHKERRQ(ierr);
5109       if (flg) {
5110         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5111       } else {
5112         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5113       }
5114     }
5115     if (mat->nullsp && mat->checknullspaceonassembly) {
5116       ierr = MatNullSpaceTest(mat->nullsp,mat,NULL);CHKERRQ(ierr);
5117     }
5118   }
5119   inassm--;
5120   PetscFunctionReturn(0);
5121 }
5122 
5123 #undef __FUNCT__
5124 #define __FUNCT__ "MatSetOption"
5125 /*@
5126    MatSetOption - Sets a parameter option for a matrix. Some options
5127    may be specific to certain storage formats.  Some options
5128    determine how values will be inserted (or added). Sorted,
5129    row-oriented input will generally assemble the fastest. The default
5130    is row-oriented.
5131 
5132    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5133 
5134    Input Parameters:
5135 +  mat - the matrix
5136 .  option - the option, one of those listed below (and possibly others),
5137 -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5138 
5139   Options Describing Matrix Structure:
5140 +    MAT_SPD - symmetric positive definite
5141 .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5142 .    MAT_HERMITIAN - transpose is the complex conjugation
5143 .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5144 -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5145                             you set to be kept with all future use of the matrix
5146                             including after MatAssemblyBegin/End() which could
5147                             potentially change the symmetry structure, i.e. you
5148                             KNOW the matrix will ALWAYS have the property you set.
5149 
5150 
5151    Options For Use with MatSetValues():
5152    Insert a logically dense subblock, which can be
5153 .    MAT_ROW_ORIENTED - row-oriented (default)
5154 
5155    Note these options reflect the data you pass in with MatSetValues(); it has
5156    nothing to do with how the data is stored internally in the matrix
5157    data structure.
5158 
5159    When (re)assembling a matrix, we can restrict the input for
5160    efficiency/debugging purposes.  These options include:
5161 +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5162 .    MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5163 .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5164 .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5165 .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5166 +    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5167         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5168         performance for very large process counts.
5169 
5170    Notes:
5171    Some options are relevant only for particular matrix types and
5172    are thus ignored by others.  Other options are not supported by
5173    certain matrix types and will generate an error message if set.
5174 
5175    If using a Fortran 77 module to compute a matrix, one may need to
5176    use the column-oriented option (or convert to the row-oriented
5177    format).
5178 
5179    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5180    that would generate a new entry in the nonzero structure is instead
5181    ignored.  Thus, if memory has not alredy been allocated for this particular
5182    data, then the insertion is ignored. For dense matrices, in which
5183    the entire array is allocated, no entries are ever ignored.
5184    Set after the first MatAssemblyEnd()
5185 
5186    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5187    that would generate a new entry in the nonzero structure instead produces
5188    an error. (Currently supported for AIJ and BAIJ formats only.)
5189 
5190    MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5191    that would generate a new entry that has not been preallocated will
5192    instead produce an error. (Currently supported for AIJ and BAIJ formats
5193    only.) This is a useful flag when debugging matrix memory preallocation.
5194 
5195    MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5196    other processors should be dropped, rather than stashed.
5197    This is useful if you know that the "owning" processor is also
5198    always generating the correct matrix entries, so that PETSc need
5199    not transfer duplicate entries generated on another processor.
5200 
5201    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5202    searches during matrix assembly. When this flag is set, the hash table
5203    is created during the first Matrix Assembly. This hash table is
5204    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5205    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5206    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5207    supported by MATMPIBAIJ format only.
5208 
5209    MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5210    are kept in the nonzero structure
5211 
5212    MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5213    a zero location in the matrix
5214 
5215    MAT_USE_INODES - indicates using inode version of the code - works with AIJ and
5216    ROWBS matrix types
5217 
5218    MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5219         zero row routines and thus improves performance for very large process counts.
5220 
5221    MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5222         part of the matrix (since they should match the upper triangular part).
5223 
5224    Notes: Can only be called after MatSetSizes() and MatSetType() have been set.
5225 
5226    Level: intermediate
5227 
5228    Concepts: matrices^setting options
5229 
5230 .seealso:  MatOption, Mat
5231 
5232 @*/
5233 PetscErrorCode  MatSetOption(Mat mat,MatOption op,PetscBool flg)
5234 {
5235   PetscErrorCode ierr;
5236 
5237   PetscFunctionBegin;
5238   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5239   PetscValidType(mat,1);
5240   if (op > 0) {
5241     PetscValidLogicalCollectiveEnum(mat,op,2);
5242     PetscValidLogicalCollectiveBool(mat,flg,3);
5243   }
5244 
5245   if (((int) op) <= MAT_OPTION_MIN || ((int) op) >= MAT_OPTION_MAX) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Options %d is out of range",(int)op);
5246   if (!((PetscObject)mat)->type_name) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_TYPENOTSET,"Cannot set options until type and size have been set, see MatSetType() and MatSetSizes()");
5247 
5248   switch (op) {
5249   case MAT_NO_OFF_PROC_ENTRIES:
5250     mat->nooffprocentries = flg;
5251     PetscFunctionReturn(0);
5252     break;
5253   case MAT_NO_OFF_PROC_ZERO_ROWS:
5254     mat->nooffproczerorows = flg;
5255     PetscFunctionReturn(0);
5256     break;
5257   case MAT_SPD:
5258     mat->spd_set = PETSC_TRUE;
5259     mat->spd     = flg;
5260     if (flg) {
5261       mat->symmetric                  = PETSC_TRUE;
5262       mat->structurally_symmetric     = PETSC_TRUE;
5263       mat->symmetric_set              = PETSC_TRUE;
5264       mat->structurally_symmetric_set = PETSC_TRUE;
5265     }
5266     break;
5267   case MAT_SYMMETRIC:
5268     mat->symmetric = flg;
5269     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5270     mat->symmetric_set              = PETSC_TRUE;
5271     mat->structurally_symmetric_set = flg;
5272     break;
5273   case MAT_HERMITIAN:
5274     mat->hermitian = flg;
5275     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5276     mat->hermitian_set              = PETSC_TRUE;
5277     mat->structurally_symmetric_set = flg;
5278     break;
5279   case MAT_STRUCTURALLY_SYMMETRIC:
5280     mat->structurally_symmetric     = flg;
5281     mat->structurally_symmetric_set = PETSC_TRUE;
5282     break;
5283   case MAT_SYMMETRY_ETERNAL:
5284     mat->symmetric_eternal = flg;
5285     break;
5286   default:
5287     break;
5288   }
5289   if (mat->ops->setoption) {
5290     ierr = (*mat->ops->setoption)(mat,op,flg);CHKERRQ(ierr);
5291   }
5292   PetscFunctionReturn(0);
5293 }
5294 
5295 #undef __FUNCT__
5296 #define __FUNCT__ "MatZeroEntries"
5297 /*@
5298    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5299    this routine retains the old nonzero structure.
5300 
5301    Logically Collective on Mat
5302 
5303    Input Parameters:
5304 .  mat - the matrix
5305 
5306    Level: intermediate
5307 
5308    Notes: If the matrix was not preallocated then a default, likely poor preallocation will be set in the matrix, so this should be called after the preallocation phase.
5309    See the Performance chapter of the users manual for information on preallocating matrices.
5310 
5311    Concepts: matrices^zeroing
5312 
5313 .seealso: MatZeroRows()
5314 @*/
5315 PetscErrorCode  MatZeroEntries(Mat mat)
5316 {
5317   PetscErrorCode ierr;
5318 
5319   PetscFunctionBegin;
5320   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5321   PetscValidType(mat,1);
5322   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5323   if (mat->insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for matrices where you have set values but not yet assembled");
5324   if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5325   MatCheckPreallocated(mat,1);
5326 
5327   ierr = PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5328   ierr = (*mat->ops->zeroentries)(mat);CHKERRQ(ierr);
5329   ierr = PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5330   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5331 #if defined(PETSC_HAVE_CUSP)
5332   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5333     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5334   }
5335 #endif
5336 #if defined(PETSC_HAVE_VIENNACL)
5337   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5338     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5339   }
5340 #endif
5341   PetscFunctionReturn(0);
5342 }
5343 
5344 #undef __FUNCT__
5345 #define __FUNCT__ "MatZeroRowsColumns"
5346 /*@C
5347    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5348    of a set of rows and columns of a matrix.
5349 
5350    Collective on Mat
5351 
5352    Input Parameters:
5353 +  mat - the matrix
5354 .  numRows - the number of rows to remove
5355 .  rows - the global row indices
5356 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5357 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5358 -  b - optional vector of right hand side, that will be adjusted by provided solution
5359 
5360    Notes:
5361    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5362 
5363    The user can set a value in the diagonal entry (or for the AIJ and
5364    row formats can optionally remove the main diagonal entry from the
5365    nonzero structure as well, by passing 0.0 as the final argument).
5366 
5367    For the parallel case, all processes that share the matrix (i.e.,
5368    those in the communicator used for matrix creation) MUST call this
5369    routine, regardless of whether any rows being zeroed are owned by
5370    them.
5371 
5372    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5373    list only rows local to itself).
5374 
5375    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5376 
5377    Level: intermediate
5378 
5379    Concepts: matrices^zeroing rows
5380 
5381 .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(), MatZeroRowsColumnsIS()
5382 @*/
5383 PetscErrorCode  MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5384 {
5385   PetscErrorCode ierr;
5386 
5387   PetscFunctionBegin;
5388   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5389   PetscValidType(mat,1);
5390   if (numRows) PetscValidIntPointer(rows,3);
5391   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5392   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5393   if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5394   MatCheckPreallocated(mat,1);
5395 
5396   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5397   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5398   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5399 #if defined(PETSC_HAVE_CUSP)
5400   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5401     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5402   }
5403 #endif
5404 #if defined(PETSC_HAVE_VIENNACL)
5405   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5406     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5407   }
5408 #endif
5409   PetscFunctionReturn(0);
5410 }
5411 
5412 #undef __FUNCT__
5413 #define __FUNCT__ "MatZeroRowsColumnsIS"
5414 /*@C
5415    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5416    of a set of rows and columns of a matrix.
5417 
5418    Collective on Mat
5419 
5420    Input Parameters:
5421 +  mat - the matrix
5422 .  is - the rows to zero
5423 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5424 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5425 -  b - optional vector of right hand side, that will be adjusted by provided solution
5426 
5427    Notes:
5428    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5429 
5430    The user can set a value in the diagonal entry (or for the AIJ and
5431    row formats can optionally remove the main diagonal entry from the
5432    nonzero structure as well, by passing 0.0 as the final argument).
5433 
5434    For the parallel case, all processes that share the matrix (i.e.,
5435    those in the communicator used for matrix creation) MUST call this
5436    routine, regardless of whether any rows being zeroed are owned by
5437    them.
5438 
5439    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5440    list only rows local to itself).
5441 
5442    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5443 
5444    Level: intermediate
5445 
5446    Concepts: matrices^zeroing rows
5447 
5448 .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(), MatZeroRowsColumns()
5449 @*/
5450 PetscErrorCode  MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5451 {
5452   PetscErrorCode ierr;
5453   PetscInt       numRows;
5454   const PetscInt *rows;
5455 
5456   PetscFunctionBegin;
5457   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5458   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5459   PetscValidType(mat,1);
5460   PetscValidType(is,2);
5461   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5462   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5463   ierr = MatZeroRowsColumns(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5464   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5465   PetscFunctionReturn(0);
5466 }
5467 
5468 #undef __FUNCT__
5469 #define __FUNCT__ "MatZeroRows"
5470 /*@C
5471    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5472    of a set of rows of a matrix.
5473 
5474    Collective on Mat
5475 
5476    Input Parameters:
5477 +  mat - the matrix
5478 .  numRows - the number of rows to remove
5479 .  rows - the global row indices
5480 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5481 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5482 -  b - optional vector of right hand side, that will be adjusted by provided solution
5483 
5484    Notes:
5485    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5486    but does not release memory.  For the dense and block diagonal
5487    formats this does not alter the nonzero structure.
5488 
5489    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5490    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5491    merely zeroed.
5492 
5493    The user can set a value in the diagonal entry (or for the AIJ and
5494    row formats can optionally remove the main diagonal entry from the
5495    nonzero structure as well, by passing 0.0 as the final argument).
5496 
5497    For the parallel case, all processes that share the matrix (i.e.,
5498    those in the communicator used for matrix creation) MUST call this
5499    routine, regardless of whether any rows being zeroed are owned by
5500    them.
5501 
5502    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5503    list only rows local to itself).
5504 
5505    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5506    owns that are to be zeroed. This saves a global synchronization in the implementation.
5507 
5508    Level: intermediate
5509 
5510    Concepts: matrices^zeroing rows
5511 
5512 .seealso: MatZeroRowsIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5513 @*/
5514 PetscErrorCode  MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5515 {
5516   PetscErrorCode ierr;
5517 
5518   PetscFunctionBegin;
5519   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5520   PetscValidType(mat,1);
5521   if (numRows) PetscValidIntPointer(rows,3);
5522   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5523   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5524   if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5525   MatCheckPreallocated(mat,1);
5526 
5527   ierr = (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5528   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5529   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5530 #if defined(PETSC_HAVE_CUSP)
5531   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5532     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5533   }
5534 #endif
5535 #if defined(PETSC_HAVE_VIENNACL)
5536   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5537     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5538   }
5539 #endif
5540   PetscFunctionReturn(0);
5541 }
5542 
5543 #undef __FUNCT__
5544 #define __FUNCT__ "MatZeroRowsIS"
5545 /*@C
5546    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5547    of a set of rows of a matrix.
5548 
5549    Collective on Mat
5550 
5551    Input Parameters:
5552 +  mat - the matrix
5553 .  is - index set of rows to remove
5554 .  diag - value put in all diagonals of eliminated rows
5555 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5556 -  b - optional vector of right hand side, that will be adjusted by provided solution
5557 
5558    Notes:
5559    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5560    but does not release memory.  For the dense and block diagonal
5561    formats this does not alter the nonzero structure.
5562 
5563    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5564    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5565    merely zeroed.
5566 
5567    The user can set a value in the diagonal entry (or for the AIJ and
5568    row formats can optionally remove the main diagonal entry from the
5569    nonzero structure as well, by passing 0.0 as the final argument).
5570 
5571    For the parallel case, all processes that share the matrix (i.e.,
5572    those in the communicator used for matrix creation) MUST call this
5573    routine, regardless of whether any rows being zeroed are owned by
5574    them.
5575 
5576    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5577    list only rows local to itself).
5578 
5579    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5580    owns that are to be zeroed. This saves a global synchronization in the implementation.
5581 
5582    Level: intermediate
5583 
5584    Concepts: matrices^zeroing rows
5585 
5586 .seealso: MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5587 @*/
5588 PetscErrorCode  MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5589 {
5590   PetscInt       numRows;
5591   const PetscInt *rows;
5592   PetscErrorCode ierr;
5593 
5594   PetscFunctionBegin;
5595   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5596   PetscValidType(mat,1);
5597   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5598   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5599   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5600   ierr = MatZeroRows(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5601   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5602   PetscFunctionReturn(0);
5603 }
5604 
5605 #undef __FUNCT__
5606 #define __FUNCT__ "MatZeroRowsStencil"
5607 /*@C
5608    MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5609    of a set of rows of a matrix. These rows must be local to the process.
5610 
5611    Collective on Mat
5612 
5613    Input Parameters:
5614 +  mat - the matrix
5615 .  numRows - the number of rows to remove
5616 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5617 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5618 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5619 -  b - optional vector of right hand side, that will be adjusted by provided solution
5620 
5621    Notes:
5622    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5623    but does not release memory.  For the dense and block diagonal
5624    formats this does not alter the nonzero structure.
5625 
5626    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5627    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5628    merely zeroed.
5629 
5630    The user can set a value in the diagonal entry (or for the AIJ and
5631    row formats can optionally remove the main diagonal entry from the
5632    nonzero structure as well, by passing 0.0 as the final argument).
5633 
5634    For the parallel case, all processes that share the matrix (i.e.,
5635    those in the communicator used for matrix creation) MUST call this
5636    routine, regardless of whether any rows being zeroed are owned by
5637    them.
5638 
5639    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5640    list only rows local to itself).
5641 
5642    The grid coordinates are across the entire grid, not just the local portion
5643 
5644    In Fortran idxm and idxn should be declared as
5645 $     MatStencil idxm(4,m)
5646    and the values inserted using
5647 $    idxm(MatStencil_i,1) = i
5648 $    idxm(MatStencil_j,1) = j
5649 $    idxm(MatStencil_k,1) = k
5650 $    idxm(MatStencil_c,1) = c
5651    etc
5652 
5653    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5654    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5655    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5656    DM_BOUNDARY_PERIODIC boundary type.
5657 
5658    For indices that don't mean anything for your case (like the k index when working in 2d) or the c index when you have
5659    a single value per point) you can skip filling those indices.
5660 
5661    Level: intermediate
5662 
5663    Concepts: matrices^zeroing rows
5664 
5665 .seealso: MatZeroRows(), MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5666 @*/
5667 PetscErrorCode  MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5668 {
5669   PetscInt       dim     = mat->stencil.dim;
5670   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5671   PetscInt       *dims   = mat->stencil.dims+1;
5672   PetscInt       *starts = mat->stencil.starts;
5673   PetscInt       *dxm    = (PetscInt*) rows;
5674   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
5675   PetscErrorCode ierr;
5676 
5677   PetscFunctionBegin;
5678   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5679   PetscValidType(mat,1);
5680   if (numRows) PetscValidIntPointer(rows,3);
5681 
5682   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
5683   for (i = 0; i < numRows; ++i) {
5684     /* Skip unused dimensions (they are ordered k, j, i, c) */
5685     for (j = 0; j < 3-sdim; ++j) dxm++;
5686     /* Local index in X dir */
5687     tmp = *dxm++ - starts[0];
5688     /* Loop over remaining dimensions */
5689     for (j = 0; j < dim-1; ++j) {
5690       /* If nonlocal, set index to be negative */
5691       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5692       /* Update local index */
5693       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5694     }
5695     /* Skip component slot if necessary */
5696     if (mat->stencil.noc) dxm++;
5697     /* Local row number */
5698     if (tmp >= 0) {
5699       jdxm[numNewRows++] = tmp;
5700     }
5701   }
5702   ierr = MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
5703   ierr = PetscFree(jdxm);CHKERRQ(ierr);
5704   PetscFunctionReturn(0);
5705 }
5706 
5707 #undef __FUNCT__
5708 #define __FUNCT__ "MatZeroRowsColumnsStencil"
5709 /*@C
5710    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
5711    of a set of rows and columns of a matrix.
5712 
5713    Collective on Mat
5714 
5715    Input Parameters:
5716 +  mat - the matrix
5717 .  numRows - the number of rows/columns to remove
5718 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5719 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5720 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5721 -  b - optional vector of right hand side, that will be adjusted by provided solution
5722 
5723    Notes:
5724    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5725    but does not release memory.  For the dense and block diagonal
5726    formats this does not alter the nonzero structure.
5727 
5728    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5729    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5730    merely zeroed.
5731 
5732    The user can set a value in the diagonal entry (or for the AIJ and
5733    row formats can optionally remove the main diagonal entry from the
5734    nonzero structure as well, by passing 0.0 as the final argument).
5735 
5736    For the parallel case, all processes that share the matrix (i.e.,
5737    those in the communicator used for matrix creation) MUST call this
5738    routine, regardless of whether any rows being zeroed are owned by
5739    them.
5740 
5741    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5742    list only rows local to itself, but the row/column numbers are given in local numbering).
5743 
5744    The grid coordinates are across the entire grid, not just the local portion
5745 
5746    In Fortran idxm and idxn should be declared as
5747 $     MatStencil idxm(4,m)
5748    and the values inserted using
5749 $    idxm(MatStencil_i,1) = i
5750 $    idxm(MatStencil_j,1) = j
5751 $    idxm(MatStencil_k,1) = k
5752 $    idxm(MatStencil_c,1) = c
5753    etc
5754 
5755    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5756    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5757    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5758    DM_BOUNDARY_PERIODIC boundary type.
5759 
5760    For indices that don't mean anything for your case (like the k index when working in 2d) or the c index when you have
5761    a single value per point) you can skip filling those indices.
5762 
5763    Level: intermediate
5764 
5765    Concepts: matrices^zeroing rows
5766 
5767 .seealso: MatZeroRows(), MatZeroRowsIS(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption()
5768 @*/
5769 PetscErrorCode  MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5770 {
5771   PetscInt       dim     = mat->stencil.dim;
5772   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5773   PetscInt       *dims   = mat->stencil.dims+1;
5774   PetscInt       *starts = mat->stencil.starts;
5775   PetscInt       *dxm    = (PetscInt*) rows;
5776   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
5777   PetscErrorCode ierr;
5778 
5779   PetscFunctionBegin;
5780   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5781   PetscValidType(mat,1);
5782   if (numRows) PetscValidIntPointer(rows,3);
5783 
5784   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
5785   for (i = 0; i < numRows; ++i) {
5786     /* Skip unused dimensions (they are ordered k, j, i, c) */
5787     for (j = 0; j < 3-sdim; ++j) dxm++;
5788     /* Local index in X dir */
5789     tmp = *dxm++ - starts[0];
5790     /* Loop over remaining dimensions */
5791     for (j = 0; j < dim-1; ++j) {
5792       /* If nonlocal, set index to be negative */
5793       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5794       /* Update local index */
5795       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5796     }
5797     /* Skip component slot if necessary */
5798     if (mat->stencil.noc) dxm++;
5799     /* Local row number */
5800     if (tmp >= 0) {
5801       jdxm[numNewRows++] = tmp;
5802     }
5803   }
5804   ierr = MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
5805   ierr = PetscFree(jdxm);CHKERRQ(ierr);
5806   PetscFunctionReturn(0);
5807 }
5808 
5809 #undef __FUNCT__
5810 #define __FUNCT__ "MatZeroRowsLocal"
5811 /*@C
5812    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
5813    of a set of rows of a matrix; using local numbering of rows.
5814 
5815    Collective on Mat
5816 
5817    Input Parameters:
5818 +  mat - the matrix
5819 .  numRows - the number of rows to remove
5820 .  rows - the global row indices
5821 .  diag - value put in all diagonals of eliminated rows
5822 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5823 -  b - optional vector of right hand side, that will be adjusted by provided solution
5824 
5825    Notes:
5826    Before calling MatZeroRowsLocal(), the user must first set the
5827    local-to-global mapping by calling MatSetLocalToGlobalMapping().
5828 
5829    For the AIJ matrix formats this removes the old nonzero structure,
5830    but does not release memory.  For the dense and block diagonal
5831    formats this does not alter the nonzero structure.
5832 
5833    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5834    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5835    merely zeroed.
5836 
5837    The user can set a value in the diagonal entry (or for the AIJ and
5838    row formats can optionally remove the main diagonal entry from the
5839    nonzero structure as well, by passing 0.0 as the final argument).
5840 
5841    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5842    owns that are to be zeroed. This saves a global synchronization in the implementation.
5843 
5844    Level: intermediate
5845 
5846    Concepts: matrices^zeroing
5847 
5848 .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5849 @*/
5850 PetscErrorCode  MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5851 {
5852   PetscErrorCode ierr;
5853 
5854   PetscFunctionBegin;
5855   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5856   PetscValidType(mat,1);
5857   if (numRows) PetscValidIntPointer(rows,3);
5858   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5859   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5860   MatCheckPreallocated(mat,1);
5861 
5862   if (mat->ops->zerorowslocal) {
5863     ierr = (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5864   } else {
5865     IS             is, newis;
5866     const PetscInt *newRows;
5867 
5868     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
5869     ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
5870     ierr = ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);CHKERRQ(ierr);
5871     ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
5872     ierr = (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
5873     ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
5874     ierr = ISDestroy(&newis);CHKERRQ(ierr);
5875     ierr = ISDestroy(&is);CHKERRQ(ierr);
5876   }
5877   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5878 #if defined(PETSC_HAVE_CUSP)
5879   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
5880     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
5881   }
5882 #endif
5883 #if defined(PETSC_HAVE_VIENNACL)
5884   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
5885     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
5886   }
5887 #endif
5888   PetscFunctionReturn(0);
5889 }
5890 
5891 #undef __FUNCT__
5892 #define __FUNCT__ "MatZeroRowsLocalIS"
5893 /*@C
5894    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
5895    of a set of rows of a matrix; using local numbering of rows.
5896 
5897    Collective on Mat
5898 
5899    Input Parameters:
5900 +  mat - the matrix
5901 .  is - index set of rows to remove
5902 .  diag - value put in all diagonals of eliminated rows
5903 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5904 -  b - optional vector of right hand side, that will be adjusted by provided solution
5905 
5906    Notes:
5907    Before calling MatZeroRowsLocalIS(), the user must first set the
5908    local-to-global mapping by calling MatSetLocalToGlobalMapping().
5909 
5910    For the AIJ matrix formats this removes the old nonzero structure,
5911    but does not release memory.  For the dense and block diagonal
5912    formats this does not alter the nonzero structure.
5913 
5914    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5915    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5916    merely zeroed.
5917 
5918    The user can set a value in the diagonal entry (or for the AIJ and
5919    row formats can optionally remove the main diagonal entry from the
5920    nonzero structure as well, by passing 0.0 as the final argument).
5921 
5922    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5923    owns that are to be zeroed. This saves a global synchronization in the implementation.
5924 
5925    Level: intermediate
5926 
5927    Concepts: matrices^zeroing
5928 
5929 .seealso: MatZeroRows(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5930 @*/
5931 PetscErrorCode  MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5932 {
5933   PetscErrorCode ierr;
5934   PetscInt       numRows;
5935   const PetscInt *rows;
5936 
5937   PetscFunctionBegin;
5938   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5939   PetscValidType(mat,1);
5940   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5941   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5942   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5943   MatCheckPreallocated(mat,1);
5944 
5945   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5946   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5947   ierr = MatZeroRowsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5948   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5949   PetscFunctionReturn(0);
5950 }
5951 
5952 #undef __FUNCT__
5953 #define __FUNCT__ "MatZeroRowsColumnsLocal"
5954 /*@C
5955    MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
5956    of a set of rows and columns of a matrix; using local numbering of rows.
5957 
5958    Collective on Mat
5959 
5960    Input Parameters:
5961 +  mat - the matrix
5962 .  numRows - the number of rows to remove
5963 .  rows - the global row indices
5964 .  diag - value put in all diagonals of eliminated rows
5965 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5966 -  b - optional vector of right hand side, that will be adjusted by provided solution
5967 
5968    Notes:
5969    Before calling MatZeroRowsColumnsLocal(), the user must first set the
5970    local-to-global mapping by calling MatSetLocalToGlobalMapping().
5971 
5972    The user can set a value in the diagonal entry (or for the AIJ and
5973    row formats can optionally remove the main diagonal entry from the
5974    nonzero structure as well, by passing 0.0 as the final argument).
5975 
5976    Level: intermediate
5977 
5978    Concepts: matrices^zeroing
5979 
5980 .seealso: MatZeroRows(), MatZeroRowsLocalIS(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
5981 @*/
5982 PetscErrorCode  MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5983 {
5984   PetscErrorCode ierr;
5985   IS             is, newis;
5986   const PetscInt *newRows;
5987 
5988   PetscFunctionBegin;
5989   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5990   PetscValidType(mat,1);
5991   if (numRows) PetscValidIntPointer(rows,3);
5992   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5993   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5994   MatCheckPreallocated(mat,1);
5995 
5996   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
5997   ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
5998   ierr = ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);CHKERRQ(ierr);
5999   ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6000   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6001   ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6002   ierr = ISDestroy(&newis);CHKERRQ(ierr);
6003   ierr = ISDestroy(&is);CHKERRQ(ierr);
6004   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6005 #if defined(PETSC_HAVE_CUSP)
6006   if (mat->valid_GPU_matrix != PETSC_CUSP_UNALLOCATED) {
6007     mat->valid_GPU_matrix = PETSC_CUSP_CPU;
6008   }
6009 #endif
6010 #if defined(PETSC_HAVE_VIENNACL)
6011   if (mat->valid_GPU_matrix != PETSC_VIENNACL_UNALLOCATED) {
6012     mat->valid_GPU_matrix = PETSC_VIENNACL_CPU;
6013   }
6014 #endif
6015   PetscFunctionReturn(0);
6016 }
6017 
6018 #undef __FUNCT__
6019 #define __FUNCT__ "MatZeroRowsColumnsLocalIS"
6020 /*@C
6021    MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6022    of a set of rows and columns of a matrix; using local numbering of rows.
6023 
6024    Collective on Mat
6025 
6026    Input Parameters:
6027 +  mat - the matrix
6028 .  is - index set of rows to remove
6029 .  diag - value put in all diagonals of eliminated rows
6030 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6031 -  b - optional vector of right hand side, that will be adjusted by provided solution
6032 
6033    Notes:
6034    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6035    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6036 
6037    The user can set a value in the diagonal entry (or for the AIJ and
6038    row formats can optionally remove the main diagonal entry from the
6039    nonzero structure as well, by passing 0.0 as the final argument).
6040 
6041    Level: intermediate
6042 
6043    Concepts: matrices^zeroing
6044 
6045 .seealso: MatZeroRows(), MatZeroRowsLocal(), MatZeroEntries(), MatZeroRows(), MatSetLocalToGlobalMapping
6046 @*/
6047 PetscErrorCode  MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6048 {
6049   PetscErrorCode ierr;
6050   PetscInt       numRows;
6051   const PetscInt *rows;
6052 
6053   PetscFunctionBegin;
6054   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6055   PetscValidType(mat,1);
6056   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6057   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6058   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6059   MatCheckPreallocated(mat,1);
6060 
6061   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6062   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6063   ierr = MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6064   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6065   PetscFunctionReturn(0);
6066 }
6067 
6068 #undef __FUNCT__
6069 #define __FUNCT__ "MatGetSize"
6070 /*@
6071    MatGetSize - Returns the numbers of rows and columns in a matrix.
6072 
6073    Not Collective
6074 
6075    Input Parameter:
6076 .  mat - the matrix
6077 
6078    Output Parameters:
6079 +  m - the number of global rows
6080 -  n - the number of global columns
6081 
6082    Note: both output parameters can be NULL on input.
6083 
6084    Level: beginner
6085 
6086    Concepts: matrices^size
6087 
6088 .seealso: MatGetLocalSize()
6089 @*/
6090 PetscErrorCode  MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6091 {
6092   PetscFunctionBegin;
6093   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6094   if (m) *m = mat->rmap->N;
6095   if (n) *n = mat->cmap->N;
6096   PetscFunctionReturn(0);
6097 }
6098 
6099 #undef __FUNCT__
6100 #define __FUNCT__ "MatGetLocalSize"
6101 /*@
6102    MatGetLocalSize - Returns the number of rows and columns in a matrix
6103    stored locally.  This information may be implementation dependent, so
6104    use with care.
6105 
6106    Not Collective
6107 
6108    Input Parameters:
6109 .  mat - the matrix
6110 
6111    Output Parameters:
6112 +  m - the number of local rows
6113 -  n - the number of local columns
6114 
6115    Note: both output parameters can be NULL on input.
6116 
6117    Level: beginner
6118 
6119    Concepts: matrices^local size
6120 
6121 .seealso: MatGetSize()
6122 @*/
6123 PetscErrorCode  MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6124 {
6125   PetscFunctionBegin;
6126   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6127   if (m) PetscValidIntPointer(m,2);
6128   if (n) PetscValidIntPointer(n,3);
6129   if (m) *m = mat->rmap->n;
6130   if (n) *n = mat->cmap->n;
6131   PetscFunctionReturn(0);
6132 }
6133 
6134 #undef __FUNCT__
6135 #define __FUNCT__ "MatGetOwnershipRangeColumn"
6136 /*@
6137    MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6138    this processor. (The columns of the "diagonal block")
6139 
6140    Not Collective, unless matrix has not been allocated, then collective on Mat
6141 
6142    Input Parameters:
6143 .  mat - the matrix
6144 
6145    Output Parameters:
6146 +  m - the global index of the first local column
6147 -  n - one more than the global index of the last local column
6148 
6149    Notes: both output parameters can be NULL on input.
6150 
6151    Level: developer
6152 
6153    Concepts: matrices^column ownership
6154 
6155 .seealso:  MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6156 
6157 @*/
6158 PetscErrorCode  MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6159 {
6160   PetscFunctionBegin;
6161   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6162   PetscValidType(mat,1);
6163   if (m) PetscValidIntPointer(m,2);
6164   if (n) PetscValidIntPointer(n,3);
6165   MatCheckPreallocated(mat,1);
6166   if (m) *m = mat->cmap->rstart;
6167   if (n) *n = mat->cmap->rend;
6168   PetscFunctionReturn(0);
6169 }
6170 
6171 #undef __FUNCT__
6172 #define __FUNCT__ "MatGetOwnershipRange"
6173 /*@
6174    MatGetOwnershipRange - Returns the range of matrix rows owned by
6175    this processor, assuming that the matrix is laid out with the first
6176    n1 rows on the first processor, the next n2 rows on the second, etc.
6177    For certain parallel layouts this range may not be well defined.
6178 
6179    Not Collective
6180 
6181    Input Parameters:
6182 .  mat - the matrix
6183 
6184    Output Parameters:
6185 +  m - the global index of the first local row
6186 -  n - one more than the global index of the last local row
6187 
6188    Note: Both output parameters can be NULL on input.
6189 $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6190 $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6191 $  and then MPI_Scan() to calculate prefix sums of the local sizes.
6192 
6193    Level: beginner
6194 
6195    Concepts: matrices^row ownership
6196 
6197 .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6198 
6199 @*/
6200 PetscErrorCode  MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6201 {
6202   PetscFunctionBegin;
6203   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6204   PetscValidType(mat,1);
6205   if (m) PetscValidIntPointer(m,2);
6206   if (n) PetscValidIntPointer(n,3);
6207   MatCheckPreallocated(mat,1);
6208   if (m) *m = mat->rmap->rstart;
6209   if (n) *n = mat->rmap->rend;
6210   PetscFunctionReturn(0);
6211 }
6212 
6213 #undef __FUNCT__
6214 #define __FUNCT__ "MatGetOwnershipRanges"
6215 /*@C
6216    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6217    each process
6218 
6219    Not Collective, unless matrix has not been allocated, then collective on Mat
6220 
6221    Input Parameters:
6222 .  mat - the matrix
6223 
6224    Output Parameters:
6225 .  ranges - start of each processors portion plus one more then the total length at the end
6226 
6227    Level: beginner
6228 
6229    Concepts: matrices^row ownership
6230 
6231 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6232 
6233 @*/
6234 PetscErrorCode  MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6235 {
6236   PetscErrorCode ierr;
6237 
6238   PetscFunctionBegin;
6239   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6240   PetscValidType(mat,1);
6241   MatCheckPreallocated(mat,1);
6242   ierr = PetscLayoutGetRanges(mat->rmap,ranges);CHKERRQ(ierr);
6243   PetscFunctionReturn(0);
6244 }
6245 
6246 #undef __FUNCT__
6247 #define __FUNCT__ "MatGetOwnershipRangesColumn"
6248 /*@C
6249    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6250    this processor. (The columns of the "diagonal blocks" for each process)
6251 
6252    Not Collective, unless matrix has not been allocated, then collective on Mat
6253 
6254    Input Parameters:
6255 .  mat - the matrix
6256 
6257    Output Parameters:
6258 .  ranges - start of each processors portion plus one more then the total length at the end
6259 
6260    Level: beginner
6261 
6262    Concepts: matrices^column ownership
6263 
6264 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6265 
6266 @*/
6267 PetscErrorCode  MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6268 {
6269   PetscErrorCode ierr;
6270 
6271   PetscFunctionBegin;
6272   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6273   PetscValidType(mat,1);
6274   MatCheckPreallocated(mat,1);
6275   ierr = PetscLayoutGetRanges(mat->cmap,ranges);CHKERRQ(ierr);
6276   PetscFunctionReturn(0);
6277 }
6278 
6279 #undef __FUNCT__
6280 #define __FUNCT__ "MatGetOwnershipIS"
6281 /*@C
6282    MatGetOwnershipIS - Get row and column ownership as index sets
6283 
6284    Not Collective
6285 
6286    Input Arguments:
6287 .  A - matrix of type Elemental
6288 
6289    Output Arguments:
6290 +  rows - rows in which this process owns elements
6291 .  cols - columns in which this process owns elements
6292 
6293    Level: intermediate
6294 
6295 .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL, MatSetValues()
6296 @*/
6297 PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6298 {
6299   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6300 
6301   PetscFunctionBegin;
6302   MatCheckPreallocated(A,1);
6303   ierr = PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);CHKERRQ(ierr);
6304   if (f) {
6305     ierr = (*f)(A,rows,cols);CHKERRQ(ierr);
6306   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6307     if (rows) {ierr = ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);CHKERRQ(ierr);}
6308     if (cols) {ierr = ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);CHKERRQ(ierr);}
6309   }
6310   PetscFunctionReturn(0);
6311 }
6312 
6313 #undef __FUNCT__
6314 #define __FUNCT__ "MatILUFactorSymbolic"
6315 /*@C
6316    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6317    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6318    to complete the factorization.
6319 
6320    Collective on Mat
6321 
6322    Input Parameters:
6323 +  mat - the matrix
6324 .  row - row permutation
6325 .  column - column permutation
6326 -  info - structure containing
6327 $      levels - number of levels of fill.
6328 $      expected fill - as ratio of original fill.
6329 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6330                 missing diagonal entries)
6331 
6332    Output Parameters:
6333 .  fact - new matrix that has been symbolically factored
6334 
6335    Notes: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6336 
6337    Most users should employ the simplified KSP interface for linear solvers
6338    instead of working directly with matrix algebra routines such as this.
6339    See, e.g., KSPCreate().
6340 
6341    Level: developer
6342 
6343   Concepts: matrices^symbolic LU factorization
6344   Concepts: matrices^factorization
6345   Concepts: LU^symbolic factorization
6346 
6347 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6348           MatGetOrdering(), MatFactorInfo
6349 
6350     Developer Note: fortran interface is not autogenerated as the f90
6351     interface defintion cannot be generated correctly [due to MatFactorInfo]
6352 
6353 @*/
6354 PetscErrorCode  MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6355 {
6356   PetscErrorCode ierr;
6357 
6358   PetscFunctionBegin;
6359   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6360   PetscValidType(mat,1);
6361   PetscValidHeaderSpecific(row,IS_CLASSID,2);
6362   PetscValidHeaderSpecific(col,IS_CLASSID,3);
6363   PetscValidPointer(info,4);
6364   PetscValidPointer(fact,5);
6365   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6366   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6367   if (!(fact)->ops->ilufactorsymbolic) {
6368     const MatSolverPackage spackage;
6369     ierr = MatFactorGetSolverPackage(fact,&spackage);CHKERRQ(ierr);
6370     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6371   }
6372   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6373   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6374   MatCheckPreallocated(mat,2);
6375 
6376   ierr = PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6377   ierr = (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
6378   ierr = PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6379   PetscFunctionReturn(0);
6380 }
6381 
6382 #undef __FUNCT__
6383 #define __FUNCT__ "MatICCFactorSymbolic"
6384 /*@C
6385    MatICCFactorSymbolic - Performs symbolic incomplete
6386    Cholesky factorization for a symmetric matrix.  Use
6387    MatCholeskyFactorNumeric() to complete the factorization.
6388 
6389    Collective on Mat
6390 
6391    Input Parameters:
6392 +  mat - the matrix
6393 .  perm - row and column permutation
6394 -  info - structure containing
6395 $      levels - number of levels of fill.
6396 $      expected fill - as ratio of original fill.
6397 
6398    Output Parameter:
6399 .  fact - the factored matrix
6400 
6401    Notes:
6402    Most users should employ the KSP interface for linear solvers
6403    instead of working directly with matrix algebra routines such as this.
6404    See, e.g., KSPCreate().
6405 
6406    Level: developer
6407 
6408   Concepts: matrices^symbolic incomplete Cholesky factorization
6409   Concepts: matrices^factorization
6410   Concepts: Cholsky^symbolic factorization
6411 
6412 .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6413 
6414     Developer Note: fortran interface is not autogenerated as the f90
6415     interface defintion cannot be generated correctly [due to MatFactorInfo]
6416 
6417 @*/
6418 PetscErrorCode  MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6419 {
6420   PetscErrorCode ierr;
6421 
6422   PetscFunctionBegin;
6423   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6424   PetscValidType(mat,1);
6425   PetscValidHeaderSpecific(perm,IS_CLASSID,2);
6426   PetscValidPointer(info,3);
6427   PetscValidPointer(fact,4);
6428   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6429   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6430   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6431   if (!(fact)->ops->iccfactorsymbolic) {
6432     const MatSolverPackage spackage;
6433     ierr = MatFactorGetSolverPackage(fact,&spackage);CHKERRQ(ierr);
6434     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6435   }
6436   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6437   MatCheckPreallocated(mat,2);
6438 
6439   ierr = PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6440   ierr = (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
6441   ierr = PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6442   PetscFunctionReturn(0);
6443 }
6444 
6445 #undef __FUNCT__
6446 #define __FUNCT__ "MatGetSubMatrices"
6447 /*@C
6448    MatGetSubMatrices - Extracts several submatrices from a matrix. If submat
6449    points to an array of valid matrices, they may be reused to store the new
6450    submatrices.
6451 
6452    Collective on Mat
6453 
6454    Input Parameters:
6455 +  mat - the matrix
6456 .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6457 .  irow, icol - index sets of rows and columns to extract (must be sorted)
6458 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6459 
6460    Output Parameter:
6461 .  submat - the array of submatrices
6462 
6463    Notes:
6464    MatGetSubMatrices() can extract ONLY sequential submatrices
6465    (from both sequential and parallel matrices). Use MatGetSubMatrix()
6466    to extract a parallel submatrix.
6467 
6468    Currently both row and column indices must be sorted to guarantee
6469    correctness with all matrix types.
6470 
6471    When extracting submatrices from a parallel matrix, each processor can
6472    form a different submatrix by setting the rows and columns of its
6473    individual index sets according to the local submatrix desired.
6474 
6475    When finished using the submatrices, the user should destroy
6476    them with MatDestroyMatrices().
6477 
6478    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6479    original matrix has not changed from that last call to MatGetSubMatrices().
6480 
6481    This routine creates the matrices in submat; you should NOT create them before
6482    calling it. It also allocates the array of matrix pointers submat.
6483 
6484    For BAIJ matrices the index sets must respect the block structure, that is if they
6485    request one row/column in a block, they must request all rows/columns that are in
6486    that block. For example, if the block size is 2 you cannot request just row 0 and
6487    column 0.
6488 
6489    Fortran Note:
6490    The Fortran interface is slightly different from that given below; it
6491    requires one to pass in  as submat a Mat (integer) array of size at least m.
6492 
6493    Level: advanced
6494 
6495    Concepts: matrices^accessing submatrices
6496    Concepts: submatrices
6497 
6498 .seealso: MatDestroyMatrices(), MatGetSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6499 @*/
6500 PetscErrorCode  MatGetSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6501 {
6502   PetscErrorCode ierr;
6503   PetscInt       i;
6504   PetscBool      eq;
6505 
6506   PetscFunctionBegin;
6507   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6508   PetscValidType(mat,1);
6509   if (n) {
6510     PetscValidPointer(irow,3);
6511     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6512     PetscValidPointer(icol,4);
6513     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6514   }
6515   PetscValidPointer(submat,6);
6516   if (n && scall == MAT_REUSE_MATRIX) {
6517     PetscValidPointer(*submat,6);
6518     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6519   }
6520   if (!mat->ops->getsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6521   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6522   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6523   MatCheckPreallocated(mat,1);
6524 
6525   ierr = PetscLogEventBegin(MAT_GetSubMatrices,mat,0,0,0);CHKERRQ(ierr);
6526   ierr = (*mat->ops->getsubmatrices)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6527   ierr = PetscLogEventEnd(MAT_GetSubMatrices,mat,0,0,0);CHKERRQ(ierr);
6528   for (i=0; i<n; i++) {
6529     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6530     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6531       ierr = ISEqual(irow[i],icol[i],&eq);CHKERRQ(ierr);
6532       if (eq) {
6533         if (mat->symmetric) {
6534           ierr = MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6535         } else if (mat->hermitian) {
6536           ierr = MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
6537         } else if (mat->structurally_symmetric) {
6538           ierr = MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6539         }
6540       }
6541     }
6542   }
6543   PetscFunctionReturn(0);
6544 }
6545 
6546 #undef __FUNCT__
6547 #define __FUNCT__ "MatGetSubMatricesParallel"
6548 PetscErrorCode  MatGetSubMatricesParallel(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6549 {
6550   PetscErrorCode ierr;
6551   PetscInt       i;
6552   PetscBool      eq;
6553 
6554   PetscFunctionBegin;
6555   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6556   PetscValidType(mat,1);
6557   if (n) {
6558     PetscValidPointer(irow,3);
6559     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6560     PetscValidPointer(icol,4);
6561     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6562   }
6563   PetscValidPointer(submat,6);
6564   if (n && scall == MAT_REUSE_MATRIX) {
6565     PetscValidPointer(*submat,6);
6566     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6567   }
6568   if (!mat->ops->getsubmatricesparallel) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6569   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6570   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6571   MatCheckPreallocated(mat,1);
6572 
6573   ierr = PetscLogEventBegin(MAT_GetSubMatrices,mat,0,0,0);CHKERRQ(ierr);
6574   ierr = (*mat->ops->getsubmatricesparallel)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6575   ierr = PetscLogEventEnd(MAT_GetSubMatrices,mat,0,0,0);CHKERRQ(ierr);
6576   for (i=0; i<n; i++) {
6577     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6578       ierr = ISEqual(irow[i],icol[i],&eq);CHKERRQ(ierr);
6579       if (eq) {
6580         if (mat->symmetric) {
6581           ierr = MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6582         } else if (mat->hermitian) {
6583           ierr = MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
6584         } else if (mat->structurally_symmetric) {
6585           ierr = MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6586         }
6587       }
6588     }
6589   }
6590   PetscFunctionReturn(0);
6591 }
6592 
6593 #undef __FUNCT__
6594 #define __FUNCT__ "MatDestroyMatrices"
6595 /*@C
6596    MatDestroyMatrices - Destroys a set of matrices obtained with MatGetSubMatrices().
6597 
6598    Collective on Mat
6599 
6600    Input Parameters:
6601 +  n - the number of local matrices
6602 -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6603                        sequence of MatGetSubMatrices())
6604 
6605    Level: advanced
6606 
6607     Notes: Frees not only the matrices, but also the array that contains the matrices
6608            In Fortran will not free the array.
6609 
6610 .seealso: MatGetSubMatrices()
6611 @*/
6612 PetscErrorCode  MatDestroyMatrices(PetscInt n,Mat *mat[])
6613 {
6614   PetscErrorCode ierr;
6615   PetscInt       i;
6616 
6617   PetscFunctionBegin;
6618   if (!*mat) PetscFunctionReturn(0);
6619   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6620   PetscValidPointer(mat,2);
6621   for (i=0; i<n; i++) {
6622     ierr = MatDestroy(&(*mat)[i]);CHKERRQ(ierr);
6623   }
6624   /* memory is allocated even if n = 0 */
6625   ierr = PetscFree(*mat);CHKERRQ(ierr);
6626   *mat = NULL;
6627   PetscFunctionReturn(0);
6628 }
6629 
6630 #undef __FUNCT__
6631 #define __FUNCT__ "MatGetSeqNonzeroStructure"
6632 /*@C
6633    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
6634 
6635    Collective on Mat
6636 
6637    Input Parameters:
6638 .  mat - the matrix
6639 
6640    Output Parameter:
6641 .  matstruct - the sequential matrix with the nonzero structure of mat
6642 
6643   Level: intermediate
6644 
6645 .seealso: MatDestroySeqNonzeroStructure(), MatGetSubMatrices(), MatDestroyMatrices()
6646 @*/
6647 PetscErrorCode  MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6648 {
6649   PetscErrorCode ierr;
6650 
6651   PetscFunctionBegin;
6652   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6653   PetscValidPointer(matstruct,2);
6654 
6655   PetscValidType(mat,1);
6656   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6657   MatCheckPreallocated(mat,1);
6658 
6659   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6660   ierr = PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
6661   ierr = (*mat->ops->getseqnonzerostructure)(mat,matstruct);CHKERRQ(ierr);
6662   ierr = PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
6663   PetscFunctionReturn(0);
6664 }
6665 
6666 #undef __FUNCT__
6667 #define __FUNCT__ "MatDestroySeqNonzeroStructure"
6668 /*@C
6669    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
6670 
6671    Collective on Mat
6672 
6673    Input Parameters:
6674 .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6675                        sequence of MatGetSequentialNonzeroStructure())
6676 
6677    Level: advanced
6678 
6679     Notes: Frees not only the matrices, but also the array that contains the matrices
6680 
6681 .seealso: MatGetSeqNonzeroStructure()
6682 @*/
6683 PetscErrorCode  MatDestroySeqNonzeroStructure(Mat *mat)
6684 {
6685   PetscErrorCode ierr;
6686 
6687   PetscFunctionBegin;
6688   PetscValidPointer(mat,1);
6689   ierr = MatDestroy(mat);CHKERRQ(ierr);
6690   PetscFunctionReturn(0);
6691 }
6692 
6693 #undef __FUNCT__
6694 #define __FUNCT__ "MatIncreaseOverlap"
6695 /*@
6696    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6697    replaces the index sets by larger ones that represent submatrices with
6698    additional overlap.
6699 
6700    Collective on Mat
6701 
6702    Input Parameters:
6703 +  mat - the matrix
6704 .  n   - the number of index sets
6705 .  is  - the array of index sets (these index sets will changed during the call)
6706 -  ov  - the additional overlap requested
6707 
6708    Level: developer
6709 
6710    Concepts: overlap
6711    Concepts: ASM^computing overlap
6712 
6713 .seealso: MatGetSubMatrices()
6714 @*/
6715 PetscErrorCode  MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6716 {
6717   PetscErrorCode ierr;
6718 
6719   PetscFunctionBegin;
6720   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6721   PetscValidType(mat,1);
6722   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6723   if (n) {
6724     PetscValidPointer(is,3);
6725     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
6726   }
6727   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6728   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6729   MatCheckPreallocated(mat,1);
6730 
6731   if (!ov) PetscFunctionReturn(0);
6732   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6733   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
6734   ierr = (*mat->ops->increaseoverlap)(mat,n,is,ov);CHKERRQ(ierr);
6735   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
6736   PetscFunctionReturn(0);
6737 }
6738 
6739 #undef __FUNCT__
6740 #define __FUNCT__ "MatGetBlockSize"
6741 /*@
6742    MatGetBlockSize - Returns the matrix block size.
6743 
6744    Not Collective
6745 
6746    Input Parameter:
6747 .  mat - the matrix
6748 
6749    Output Parameter:
6750 .  bs - block size
6751 
6752    Notes:
6753     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6754 
6755    If the block size has not been set yet this routine returns 1.
6756 
6757    Level: intermediate
6758 
6759    Concepts: matrices^block size
6760 
6761 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
6762 @*/
6763 PetscErrorCode  MatGetBlockSize(Mat mat,PetscInt *bs)
6764 {
6765   PetscFunctionBegin;
6766   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6767   PetscValidIntPointer(bs,2);
6768   *bs = PetscAbs(mat->rmap->bs);
6769   PetscFunctionReturn(0);
6770 }
6771 
6772 #undef __FUNCT__
6773 #define __FUNCT__ "MatGetBlockSizes"
6774 /*@
6775    MatGetBlockSizes - Returns the matrix block row and column sizes.
6776 
6777    Not Collective
6778 
6779    Input Parameter:
6780 .  mat - the matrix
6781 
6782    Output Parameter:
6783 .  rbs - row block size
6784 .  cbs - coumn block size
6785 
6786    Notes:
6787     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6788     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
6789 
6790    If a block size has not been set yet this routine returns 1.
6791 
6792    Level: intermediate
6793 
6794    Concepts: matrices^block size
6795 
6796 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
6797 @*/
6798 PetscErrorCode  MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
6799 {
6800   PetscFunctionBegin;
6801   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6802   if (rbs) PetscValidIntPointer(rbs,2);
6803   if (cbs) PetscValidIntPointer(cbs,3);
6804   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
6805   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
6806   PetscFunctionReturn(0);
6807 }
6808 
6809 #undef __FUNCT__
6810 #define __FUNCT__ "MatSetBlockSize"
6811 /*@
6812    MatSetBlockSize - Sets the matrix block size.
6813 
6814    Logically Collective on Mat
6815 
6816    Input Parameters:
6817 +  mat - the matrix
6818 -  bs - block size
6819 
6820    Notes:
6821     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6822 
6823      This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later
6824 
6825    Level: intermediate
6826 
6827    Concepts: matrices^block size
6828 
6829 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
6830 @*/
6831 PetscErrorCode  MatSetBlockSize(Mat mat,PetscInt bs)
6832 {
6833   PetscErrorCode ierr;
6834 
6835   PetscFunctionBegin;
6836   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6837   PetscValidLogicalCollectiveInt(mat,bs,2);
6838   ierr = PetscLayoutSetBlockSize(mat->rmap,bs);CHKERRQ(ierr);
6839   ierr = PetscLayoutSetBlockSize(mat->cmap,bs);CHKERRQ(ierr);
6840   PetscFunctionReturn(0);
6841 }
6842 
6843 #undef __FUNCT__
6844 #define __FUNCT__ "MatSetBlockSizes"
6845 /*@
6846    MatSetBlockSizes - Sets the matrix block row and column sizes.
6847 
6848    Logically Collective on Mat
6849 
6850    Input Parameters:
6851 +  mat - the matrix
6852 -  rbs - row block size
6853 -  cbs - column block size
6854 
6855    Notes:
6856     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
6857     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
6858 
6859     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later
6860 
6861     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
6862 
6863    Level: intermediate
6864 
6865    Concepts: matrices^block size
6866 
6867 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
6868 @*/
6869 PetscErrorCode  MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
6870 {
6871   PetscErrorCode ierr;
6872 
6873   PetscFunctionBegin;
6874   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6875   PetscValidLogicalCollectiveInt(mat,rbs,2);
6876   PetscValidLogicalCollectiveInt(mat,cbs,3);
6877   ierr = PetscLayoutSetBlockSize(mat->rmap,rbs);CHKERRQ(ierr);
6878   ierr = PetscLayoutSetBlockSize(mat->cmap,cbs);CHKERRQ(ierr);
6879   PetscFunctionReturn(0);
6880 }
6881 
6882 #undef __FUNCT__
6883 #define __FUNCT__ "MatSetBlockSizesFromMats"
6884 /*@
6885    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
6886 
6887    Logically Collective on Mat
6888 
6889    Input Parameters:
6890 +  mat - the matrix
6891 .  fromRow - matrix from which to copy row block size
6892 -  fromCol - matrix from which to copy column block size (can be same as fromRow)
6893 
6894    Level: developer
6895 
6896    Concepts: matrices^block size
6897 
6898 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
6899 @*/
6900 PetscErrorCode  MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
6901 {
6902   PetscErrorCode ierr;
6903 
6904   PetscFunctionBegin;
6905   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6906   PetscValidHeaderSpecific(fromRow,MAT_CLASSID,2);
6907   PetscValidHeaderSpecific(fromCol,MAT_CLASSID,3);
6908   if (fromRow->rmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);CHKERRQ(ierr);}
6909   if (fromCol->cmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);CHKERRQ(ierr);}
6910   PetscFunctionReturn(0);
6911 }
6912 
6913 #undef __FUNCT__
6914 #define __FUNCT__ "MatResidual"
6915 /*@
6916    MatResidual - Default routine to calculate the residual.
6917 
6918    Collective on Mat and Vec
6919 
6920    Input Parameters:
6921 +  mat - the matrix
6922 .  b   - the right-hand-side
6923 -  x   - the approximate solution
6924 
6925    Output Parameter:
6926 .  r - location to store the residual
6927 
6928    Level: developer
6929 
6930 .keywords: MG, default, multigrid, residual
6931 
6932 .seealso: PCMGSetResidual()
6933 @*/
6934 PetscErrorCode  MatResidual(Mat mat,Vec b,Vec x,Vec r)
6935 {
6936   PetscErrorCode ierr;
6937 
6938   PetscFunctionBegin;
6939   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6940   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
6941   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
6942   PetscValidHeaderSpecific(r,VEC_CLASSID,4);
6943   PetscValidType(mat,1);
6944   MatCheckPreallocated(mat,1);
6945   ierr  = PetscLogEventBegin(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
6946   if (!mat->ops->residual) {
6947     ierr = MatMult(mat,x,r);CHKERRQ(ierr);
6948     ierr = VecAYPX(r,-1.0,b);CHKERRQ(ierr);
6949   } else {
6950     ierr  = (*mat->ops->residual)(mat,b,x,r);CHKERRQ(ierr);
6951   }
6952   ierr  = PetscLogEventEnd(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
6953   PetscFunctionReturn(0);
6954 }
6955 
6956 #undef __FUNCT__
6957 #define __FUNCT__ "MatGetRowIJ"
6958 /*@C
6959     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
6960 
6961    Collective on Mat
6962 
6963     Input Parameters:
6964 +   mat - the matrix
6965 .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
6966 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
6967 -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
6968                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
6969                  always used.
6970 
6971     Output Parameters:
6972 +   n - number of rows in the (possibly compressed) matrix
6973 .   ia - the row pointers [of length n+1]
6974 .   ja - the column indices
6975 -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
6976            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
6977 
6978     Level: developer
6979 
6980     Notes: You CANNOT change any of the ia[] or ja[] values.
6981 
6982            Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values
6983 
6984     Fortran Node
6985 
6986            In Fortran use
6987 $           PetscInt ia(1), ja(1)
6988 $           PetscOffset iia, jja
6989 $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
6990 $
6991 $          or
6992 $
6993 $           PetscScalar, pointer :: xx_v(:)
6994 $    call  MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
6995 
6996 
6997        Acess the ith and jth entries via ia(iia + i) and ja(jja + j)
6998 
6999 .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7000 @*/
7001 PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7002 {
7003   PetscErrorCode ierr;
7004 
7005   PetscFunctionBegin;
7006   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7007   PetscValidType(mat,1);
7008   PetscValidIntPointer(n,4);
7009   if (ia) PetscValidIntPointer(ia,5);
7010   if (ja) PetscValidIntPointer(ja,6);
7011   PetscValidIntPointer(done,7);
7012   MatCheckPreallocated(mat,1);
7013   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7014   else {
7015     *done = PETSC_TRUE;
7016     ierr  = PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7017     ierr  = (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7018     ierr  = PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7019   }
7020   PetscFunctionReturn(0);
7021 }
7022 
7023 #undef __FUNCT__
7024 #define __FUNCT__ "MatGetColumnIJ"
7025 /*@C
7026     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7027 
7028     Collective on Mat
7029 
7030     Input Parameters:
7031 +   mat - the matrix
7032 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7033 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7034                 symmetrized
7035 .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7036                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7037                  always used.
7038 .   n - number of columns in the (possibly compressed) matrix
7039 .   ia - the column pointers
7040 -   ja - the row indices
7041 
7042     Output Parameters:
7043 .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7044 
7045     Note:
7046     This routine zeros out n, ia, and ja. This is to prevent accidental
7047     us of the array after it has been restored. If you pass NULL, it will
7048     not zero the pointers.  Use of ia or ja after MatRestoreColumnIJ() is invalid.
7049 
7050     Level: developer
7051 
7052 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7053 @*/
7054 PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7055 {
7056   PetscErrorCode ierr;
7057 
7058   PetscFunctionBegin;
7059   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7060   PetscValidType(mat,1);
7061   PetscValidIntPointer(n,4);
7062   if (ia) PetscValidIntPointer(ia,5);
7063   if (ja) PetscValidIntPointer(ja,6);
7064   PetscValidIntPointer(done,7);
7065   MatCheckPreallocated(mat,1);
7066   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7067   else {
7068     *done = PETSC_TRUE;
7069     ierr  = (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7070   }
7071   PetscFunctionReturn(0);
7072 }
7073 
7074 #undef __FUNCT__
7075 #define __FUNCT__ "MatRestoreRowIJ"
7076 /*@C
7077     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7078     MatGetRowIJ().
7079 
7080     Collective on Mat
7081 
7082     Input Parameters:
7083 +   mat - the matrix
7084 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7085 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7086                 symmetrized
7087 .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7088                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7089                  always used.
7090 .   n - size of (possibly compressed) matrix
7091 .   ia - the row pointers
7092 -   ja - the column indices
7093 
7094     Output Parameters:
7095 .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7096 
7097     Note:
7098     This routine zeros out n, ia, and ja. This is to prevent accidental
7099     us of the array after it has been restored. If you pass NULL, it will
7100     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.
7101 
7102     Level: developer
7103 
7104 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7105 @*/
7106 PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7107 {
7108   PetscErrorCode ierr;
7109 
7110   PetscFunctionBegin;
7111   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7112   PetscValidType(mat,1);
7113   if (ia) PetscValidIntPointer(ia,5);
7114   if (ja) PetscValidIntPointer(ja,6);
7115   PetscValidIntPointer(done,7);
7116   MatCheckPreallocated(mat,1);
7117 
7118   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7119   else {
7120     *done = PETSC_TRUE;
7121     ierr  = (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7122     if (n)  *n = 0;
7123     if (ia) *ia = NULL;
7124     if (ja) *ja = NULL;
7125   }
7126   PetscFunctionReturn(0);
7127 }
7128 
7129 #undef __FUNCT__
7130 #define __FUNCT__ "MatRestoreColumnIJ"
7131 /*@C
7132     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7133     MatGetColumnIJ().
7134 
7135     Collective on Mat
7136 
7137     Input Parameters:
7138 +   mat - the matrix
7139 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7140 -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7141                 symmetrized
7142 -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7143                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7144                  always used.
7145 
7146     Output Parameters:
7147 +   n - size of (possibly compressed) matrix
7148 .   ia - the column pointers
7149 .   ja - the row indices
7150 -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7151 
7152     Level: developer
7153 
7154 .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7155 @*/
7156 PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7157 {
7158   PetscErrorCode ierr;
7159 
7160   PetscFunctionBegin;
7161   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7162   PetscValidType(mat,1);
7163   if (ia) PetscValidIntPointer(ia,5);
7164   if (ja) PetscValidIntPointer(ja,6);
7165   PetscValidIntPointer(done,7);
7166   MatCheckPreallocated(mat,1);
7167 
7168   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7169   else {
7170     *done = PETSC_TRUE;
7171     ierr  = (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7172     if (n)  *n = 0;
7173     if (ia) *ia = NULL;
7174     if (ja) *ja = NULL;
7175   }
7176   PetscFunctionReturn(0);
7177 }
7178 
7179 #undef __FUNCT__
7180 #define __FUNCT__ "MatColoringPatch"
7181 /*@C
7182     MatColoringPatch -Used inside matrix coloring routines that
7183     use MatGetRowIJ() and/or MatGetColumnIJ().
7184 
7185     Collective on Mat
7186 
7187     Input Parameters:
7188 +   mat - the matrix
7189 .   ncolors - max color value
7190 .   n   - number of entries in colorarray
7191 -   colorarray - array indicating color for each column
7192 
7193     Output Parameters:
7194 .   iscoloring - coloring generated using colorarray information
7195 
7196     Level: developer
7197 
7198 .seealso: MatGetRowIJ(), MatGetColumnIJ()
7199 
7200 @*/
7201 PetscErrorCode  MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7202 {
7203   PetscErrorCode ierr;
7204 
7205   PetscFunctionBegin;
7206   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7207   PetscValidType(mat,1);
7208   PetscValidIntPointer(colorarray,4);
7209   PetscValidPointer(iscoloring,5);
7210   MatCheckPreallocated(mat,1);
7211 
7212   if (!mat->ops->coloringpatch) {
7213     ierr = ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);CHKERRQ(ierr);
7214   } else {
7215     ierr = (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);CHKERRQ(ierr);
7216   }
7217   PetscFunctionReturn(0);
7218 }
7219 
7220 
7221 #undef __FUNCT__
7222 #define __FUNCT__ "MatSetUnfactored"
7223 /*@
7224    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7225 
7226    Logically Collective on Mat
7227 
7228    Input Parameter:
7229 .  mat - the factored matrix to be reset
7230 
7231    Notes:
7232    This routine should be used only with factored matrices formed by in-place
7233    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7234    format).  This option can save memory, for example, when solving nonlinear
7235    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7236    ILU(0) preconditioner.
7237 
7238    Note that one can specify in-place ILU(0) factorization by calling
7239 .vb
7240      PCType(pc,PCILU);
7241      PCFactorSeUseInPlace(pc);
7242 .ve
7243    or by using the options -pc_type ilu -pc_factor_in_place
7244 
7245    In-place factorization ILU(0) can also be used as a local
7246    solver for the blocks within the block Jacobi or additive Schwarz
7247    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7248    for details on setting local solver options.
7249 
7250    Most users should employ the simplified KSP interface for linear solvers
7251    instead of working directly with matrix algebra routines such as this.
7252    See, e.g., KSPCreate().
7253 
7254    Level: developer
7255 
7256 .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7257 
7258    Concepts: matrices^unfactored
7259 
7260 @*/
7261 PetscErrorCode  MatSetUnfactored(Mat mat)
7262 {
7263   PetscErrorCode ierr;
7264 
7265   PetscFunctionBegin;
7266   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7267   PetscValidType(mat,1);
7268   MatCheckPreallocated(mat,1);
7269   mat->factortype = MAT_FACTOR_NONE;
7270   if (!mat->ops->setunfactored) PetscFunctionReturn(0);
7271   ierr = (*mat->ops->setunfactored)(mat);CHKERRQ(ierr);
7272   PetscFunctionReturn(0);
7273 }
7274 
7275 /*MC
7276     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7277 
7278     Synopsis:
7279     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7280 
7281     Not collective
7282 
7283     Input Parameter:
7284 .   x - matrix
7285 
7286     Output Parameters:
7287 +   xx_v - the Fortran90 pointer to the array
7288 -   ierr - error code
7289 
7290     Example of Usage:
7291 .vb
7292       PetscScalar, pointer xx_v(:,:)
7293       ....
7294       call MatDenseGetArrayF90(x,xx_v,ierr)
7295       a = xx_v(3)
7296       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7297 .ve
7298 
7299     Level: advanced
7300 
7301 .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7302 
7303     Concepts: matrices^accessing array
7304 
7305 M*/
7306 
7307 /*MC
7308     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7309     accessed with MatDenseGetArrayF90().
7310 
7311     Synopsis:
7312     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7313 
7314     Not collective
7315 
7316     Input Parameters:
7317 +   x - matrix
7318 -   xx_v - the Fortran90 pointer to the array
7319 
7320     Output Parameter:
7321 .   ierr - error code
7322 
7323     Example of Usage:
7324 .vb
7325        PetscScalar, pointer xx_v(:)
7326        ....
7327        call MatDenseGetArrayF90(x,xx_v,ierr)
7328        a = xx_v(3)
7329        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7330 .ve
7331 
7332     Level: advanced
7333 
7334 .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7335 
7336 M*/
7337 
7338 
7339 /*MC
7340     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7341 
7342     Synopsis:
7343     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7344 
7345     Not collective
7346 
7347     Input Parameter:
7348 .   x - matrix
7349 
7350     Output Parameters:
7351 +   xx_v - the Fortran90 pointer to the array
7352 -   ierr - error code
7353 
7354     Example of Usage:
7355 .vb
7356       PetscScalar, pointer xx_v(:,:)
7357       ....
7358       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7359       a = xx_v(3)
7360       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7361 .ve
7362 
7363     Level: advanced
7364 
7365 .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7366 
7367     Concepts: matrices^accessing array
7368 
7369 M*/
7370 
7371 /*MC
7372     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7373     accessed with MatSeqAIJGetArrayF90().
7374 
7375     Synopsis:
7376     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7377 
7378     Not collective
7379 
7380     Input Parameters:
7381 +   x - matrix
7382 -   xx_v - the Fortran90 pointer to the array
7383 
7384     Output Parameter:
7385 .   ierr - error code
7386 
7387     Example of Usage:
7388 .vb
7389        PetscScalar, pointer xx_v(:)
7390        ....
7391        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7392        a = xx_v(3)
7393        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7394 .ve
7395 
7396     Level: advanced
7397 
7398 .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7399 
7400 M*/
7401 
7402 
7403 #undef __FUNCT__
7404 #define __FUNCT__ "MatGetSubMatrix"
7405 /*@
7406     MatGetSubMatrix - Gets a single submatrix on the same number of processors
7407                       as the original matrix.
7408 
7409     Collective on Mat
7410 
7411     Input Parameters:
7412 +   mat - the original matrix
7413 .   isrow - parallel IS containing the rows this processor should obtain
7414 .   iscol - parallel IS containing all columns you wish to keep. Each process should list the columns that will be in IT's "diagonal part" in the new matrix.
7415 -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7416 
7417     Output Parameter:
7418 .   newmat - the new submatrix, of the same type as the old
7419 
7420     Level: advanced
7421 
7422     Notes:
7423     The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7424 
7425     The rows in isrow will be sorted into the same order as the original matrix on each process.
7426 
7427       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7428    the MatGetSubMatrix() routine will create the newmat for you. Any additional calls
7429    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7430    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7431    you are finished using it.
7432 
7433     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7434     the input matrix.
7435 
7436     If iscol is NULL then all columns are obtained (not supported in Fortran).
7437 
7438    Example usage:
7439    Consider the following 8x8 matrix with 34 non-zero values, that is
7440    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7441    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7442    as follows:
7443 
7444 .vb
7445             1  2  0  |  0  3  0  |  0  4
7446     Proc0   0  5  6  |  7  0  0  |  8  0
7447             9  0 10  | 11  0  0  | 12  0
7448     -------------------------------------
7449            13  0 14  | 15 16 17  |  0  0
7450     Proc1   0 18  0  | 19 20 21  |  0  0
7451             0  0  0  | 22 23  0  | 24  0
7452     -------------------------------------
7453     Proc2  25 26 27  |  0  0 28  | 29  0
7454            30  0  0  | 31 32 33  |  0 34
7455 .ve
7456 
7457     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is
7458 
7459 .vb
7460             2  0  |  0  3  0  |  0
7461     Proc0   5  6  |  7  0  0  |  8
7462     -------------------------------
7463     Proc1  18  0  | 19 20 21  |  0
7464     -------------------------------
7465     Proc2  26 27  |  0  0 28  | 29
7466             0  0  | 31 32 33  |  0
7467 .ve
7468 
7469 
7470     Concepts: matrices^submatrices
7471 
7472 .seealso: MatGetSubMatrices()
7473 @*/
7474 PetscErrorCode  MatGetSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7475 {
7476   PetscErrorCode ierr;
7477   PetscMPIInt    size;
7478   Mat            *local;
7479   IS             iscoltmp;
7480 
7481   PetscFunctionBegin;
7482   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7483   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
7484   if (iscol) PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
7485   PetscValidPointer(newmat,5);
7486   if (cll == MAT_REUSE_MATRIX) PetscValidHeaderSpecific(*newmat,MAT_CLASSID,5);
7487   PetscValidType(mat,1);
7488   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7489   MatCheckPreallocated(mat,1);
7490   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
7491 
7492   if (!iscol) {
7493     ierr = ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);CHKERRQ(ierr);
7494   } else {
7495     iscoltmp = iscol;
7496   }
7497 
7498   /* if original matrix is on just one processor then use submatrix generated */
7499   if (mat->ops->getsubmatrices && !mat->ops->getsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7500     ierr = MatGetSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);CHKERRQ(ierr);
7501     if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
7502     PetscFunctionReturn(0);
7503   } else if (mat->ops->getsubmatrices && !mat->ops->getsubmatrix && size == 1) {
7504     ierr    = MatGetSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);CHKERRQ(ierr);
7505     *newmat = *local;
7506     ierr    = PetscFree(local);CHKERRQ(ierr);
7507     if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
7508     PetscFunctionReturn(0);
7509   } else if (!mat->ops->getsubmatrix) {
7510     /* Create a new matrix type that implements the operation using the full matrix */
7511     switch (cll) {
7512     case MAT_INITIAL_MATRIX:
7513       ierr = MatCreateSubMatrix(mat,isrow,iscoltmp,newmat);CHKERRQ(ierr);
7514       break;
7515     case MAT_REUSE_MATRIX:
7516       ierr = MatSubMatrixUpdate(*newmat,mat,isrow,iscoltmp);CHKERRQ(ierr);
7517       break;
7518     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7519     }
7520     if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
7521     PetscFunctionReturn(0);
7522   }
7523 
7524   if (!mat->ops->getsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7525   ierr = (*mat->ops->getsubmatrix)(mat,isrow,iscoltmp,cll,newmat);CHKERRQ(ierr);
7526   if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
7527   if (*newmat && cll == MAT_INITIAL_MATRIX) {ierr = PetscObjectStateIncrease((PetscObject)*newmat);CHKERRQ(ierr);}
7528   PetscFunctionReturn(0);
7529 }
7530 
7531 #undef __FUNCT__
7532 #define __FUNCT__ "MatStashSetInitialSize"
7533 /*@
7534    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7535    used during the assembly process to store values that belong to
7536    other processors.
7537 
7538    Not Collective
7539 
7540    Input Parameters:
7541 +  mat   - the matrix
7542 .  size  - the initial size of the stash.
7543 -  bsize - the initial size of the block-stash(if used).
7544 
7545    Options Database Keys:
7546 +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7547 -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>
7548 
7549    Level: intermediate
7550 
7551    Notes:
7552      The block-stash is used for values set with MatSetValuesBlocked() while
7553      the stash is used for values set with MatSetValues()
7554 
7555      Run with the option -info and look for output of the form
7556      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7557      to determine the appropriate value, MM, to use for size and
7558      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7559      to determine the value, BMM to use for bsize
7560 
7561    Concepts: stash^setting matrix size
7562    Concepts: matrices^stash
7563 
7564 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
7565 
7566 @*/
7567 PetscErrorCode  MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7568 {
7569   PetscErrorCode ierr;
7570 
7571   PetscFunctionBegin;
7572   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7573   PetscValidType(mat,1);
7574   ierr = MatStashSetInitialSize_Private(&mat->stash,size);CHKERRQ(ierr);
7575   ierr = MatStashSetInitialSize_Private(&mat->bstash,bsize);CHKERRQ(ierr);
7576   PetscFunctionReturn(0);
7577 }
7578 
7579 #undef __FUNCT__
7580 #define __FUNCT__ "MatInterpolateAdd"
7581 /*@
7582    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7583      the matrix
7584 
7585    Neighbor-wise Collective on Mat
7586 
7587    Input Parameters:
7588 +  mat   - the matrix
7589 .  x,y - the vectors
7590 -  w - where the result is stored
7591 
7592    Level: intermediate
7593 
7594    Notes:
7595     w may be the same vector as y.
7596 
7597     This allows one to use either the restriction or interpolation (its transpose)
7598     matrix to do the interpolation
7599 
7600     Concepts: interpolation
7601 
7602 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
7603 
7604 @*/
7605 PetscErrorCode  MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
7606 {
7607   PetscErrorCode ierr;
7608   PetscInt       M,N,Ny;
7609 
7610   PetscFunctionBegin;
7611   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
7612   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
7613   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
7614   PetscValidHeaderSpecific(w,VEC_CLASSID,4);
7615   PetscValidType(A,1);
7616   MatCheckPreallocated(A,1);
7617   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
7618   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
7619   if (M == Ny) {
7620     ierr = MatMultAdd(A,x,y,w);CHKERRQ(ierr);
7621   } else {
7622     ierr = MatMultTransposeAdd(A,x,y,w);CHKERRQ(ierr);
7623   }
7624   PetscFunctionReturn(0);
7625 }
7626 
7627 #undef __FUNCT__
7628 #define __FUNCT__ "MatInterpolate"
7629 /*@
7630    MatInterpolate - y = A*x or A'*x depending on the shape of
7631      the matrix
7632 
7633    Neighbor-wise Collective on Mat
7634 
7635    Input Parameters:
7636 +  mat   - the matrix
7637 -  x,y - the vectors
7638 
7639    Level: intermediate
7640 
7641    Notes:
7642     This allows one to use either the restriction or interpolation (its transpose)
7643     matrix to do the interpolation
7644 
7645    Concepts: matrices^interpolation
7646 
7647 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
7648 
7649 @*/
7650 PetscErrorCode  MatInterpolate(Mat A,Vec x,Vec y)
7651 {
7652   PetscErrorCode ierr;
7653   PetscInt       M,N,Ny;
7654 
7655   PetscFunctionBegin;
7656   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
7657   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
7658   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
7659   PetscValidType(A,1);
7660   MatCheckPreallocated(A,1);
7661   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
7662   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
7663   if (M == Ny) {
7664     ierr = MatMult(A,x,y);CHKERRQ(ierr);
7665   } else {
7666     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
7667   }
7668   PetscFunctionReturn(0);
7669 }
7670 
7671 #undef __FUNCT__
7672 #define __FUNCT__ "MatRestrict"
7673 /*@
7674    MatRestrict - y = A*x or A'*x
7675 
7676    Neighbor-wise Collective on Mat
7677 
7678    Input Parameters:
7679 +  mat   - the matrix
7680 -  x,y - the vectors
7681 
7682    Level: intermediate
7683 
7684    Notes:
7685     This allows one to use either the restriction or interpolation (its transpose)
7686     matrix to do the restriction
7687 
7688    Concepts: matrices^restriction
7689 
7690 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
7691 
7692 @*/
7693 PetscErrorCode  MatRestrict(Mat A,Vec x,Vec y)
7694 {
7695   PetscErrorCode ierr;
7696   PetscInt       M,N,Ny;
7697 
7698   PetscFunctionBegin;
7699   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
7700   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
7701   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
7702   PetscValidType(A,1);
7703   MatCheckPreallocated(A,1);
7704 
7705   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
7706   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
7707   if (M == Ny) {
7708     ierr = MatMult(A,x,y);CHKERRQ(ierr);
7709   } else {
7710     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
7711   }
7712   PetscFunctionReturn(0);
7713 }
7714 
7715 #undef __FUNCT__
7716 #define __FUNCT__ "MatGetNullSpace"
7717 /*@
7718    MatGetNullSpace - retrieves the null space to a matrix.
7719 
7720    Logically Collective on Mat and MatNullSpace
7721 
7722    Input Parameters:
7723 +  mat - the matrix
7724 -  nullsp - the null space object
7725 
7726    Level: developer
7727 
7728    Notes:
7729       This null space is used by solvers. Overwrites any previous null space that may have been attached
7730 
7731    Concepts: null space^attaching to matrix
7732 
7733 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace()
7734 @*/
7735 PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
7736 {
7737   PetscFunctionBegin;
7738   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7739   PetscValidType(mat,1);
7740   PetscValidPointer(nullsp,2);
7741   *nullsp = mat->nullsp;
7742   PetscFunctionReturn(0);
7743 }
7744 
7745 #undef __FUNCT__
7746 #define __FUNCT__ "MatSetNullSpace"
7747 /*@
7748    MatSetNullSpace - attaches a null space to a matrix.
7749         This null space will be removed from the resulting vector whenever
7750         MatMult() is called
7751 
7752    Logically Collective on Mat and MatNullSpace
7753 
7754    Input Parameters:
7755 +  mat - the matrix
7756 -  nullsp - the null space object
7757 
7758    Level: advanced
7759 
7760    Notes:
7761       This null space is used by solvers. Overwrites any previous null space that may have been attached
7762 
7763    Concepts: null space^attaching to matrix
7764 
7765 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace()
7766 @*/
7767 PetscErrorCode  MatSetNullSpace(Mat mat,MatNullSpace nullsp)
7768 {
7769   PetscErrorCode ierr;
7770 
7771   PetscFunctionBegin;
7772   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7773   PetscValidType(mat,1);
7774   PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
7775   MatCheckPreallocated(mat,1);
7776   ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);
7777   ierr = MatNullSpaceDestroy(&mat->nullsp);CHKERRQ(ierr);
7778 
7779   mat->nullsp = nullsp;
7780   PetscFunctionReturn(0);
7781 }
7782 
7783 #undef __FUNCT__
7784 #define __FUNCT__ "MatSetNearNullSpace"
7785 /*@
7786    MatSetNearNullSpace - attaches a null space to a matrix.
7787         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
7788 
7789    Logically Collective on Mat and MatNullSpace
7790 
7791    Input Parameters:
7792 +  mat - the matrix
7793 -  nullsp - the null space object
7794 
7795    Level: advanced
7796 
7797    Notes:
7798       Overwrites any previous near null space that may have been attached
7799 
7800    Concepts: null space^attaching to matrix
7801 
7802 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace()
7803 @*/
7804 PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
7805 {
7806   PetscErrorCode ierr;
7807 
7808   PetscFunctionBegin;
7809   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7810   PetscValidType(mat,1);
7811   PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
7812   MatCheckPreallocated(mat,1);
7813   ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);
7814   ierr = MatNullSpaceDestroy(&mat->nearnullsp);CHKERRQ(ierr);
7815 
7816   mat->nearnullsp = nullsp;
7817   PetscFunctionReturn(0);
7818 }
7819 
7820 #undef __FUNCT__
7821 #define __FUNCT__ "MatGetNearNullSpace"
7822 /*@
7823    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()
7824 
7825    Not Collective
7826 
7827    Input Parameters:
7828 .  mat - the matrix
7829 
7830    Output Parameters:
7831 .  nullsp - the null space object, NULL if not set
7832 
7833    Level: developer
7834 
7835    Concepts: null space^attaching to matrix
7836 
7837 .seealso: MatSetNearNullSpace(), MatGetNullSpace()
7838 @*/
7839 PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
7840 {
7841   PetscFunctionBegin;
7842   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7843   PetscValidType(mat,1);
7844   PetscValidPointer(nullsp,2);
7845   MatCheckPreallocated(mat,1);
7846   *nullsp = mat->nearnullsp;
7847   PetscFunctionReturn(0);
7848 }
7849 
7850 #undef __FUNCT__
7851 #define __FUNCT__ "MatICCFactor"
7852 /*@C
7853    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
7854 
7855    Collective on Mat
7856 
7857    Input Parameters:
7858 +  mat - the matrix
7859 .  row - row/column permutation
7860 .  fill - expected fill factor >= 1.0
7861 -  level - level of fill, for ICC(k)
7862 
7863    Notes:
7864    Probably really in-place only when level of fill is zero, otherwise allocates
7865    new space to store factored matrix and deletes previous memory.
7866 
7867    Most users should employ the simplified KSP interface for linear solvers
7868    instead of working directly with matrix algebra routines such as this.
7869    See, e.g., KSPCreate().
7870 
7871    Level: developer
7872 
7873    Concepts: matrices^incomplete Cholesky factorization
7874    Concepts: Cholesky factorization
7875 
7876 .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
7877 
7878     Developer Note: fortran interface is not autogenerated as the f90
7879     interface defintion cannot be generated correctly [due to MatFactorInfo]
7880 
7881 @*/
7882 PetscErrorCode  MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
7883 {
7884   PetscErrorCode ierr;
7885 
7886   PetscFunctionBegin;
7887   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7888   PetscValidType(mat,1);
7889   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
7890   PetscValidPointer(info,3);
7891   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
7892   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7893   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7894   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7895   MatCheckPreallocated(mat,1);
7896   ierr = (*mat->ops->iccfactor)(mat,row,info);CHKERRQ(ierr);
7897   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
7898   PetscFunctionReturn(0);
7899 }
7900 
7901 #undef __FUNCT__
7902 #define __FUNCT__ "MatSetValuesAdifor"
7903 /*@
7904    MatSetValuesAdifor - Sets values computed with automatic differentiation into a matrix.
7905 
7906    Not Collective
7907 
7908    Input Parameters:
7909 +  mat - the matrix
7910 .  nl - leading dimension of v
7911 -  v - the values compute with ADIFOR
7912 
7913    Level: developer
7914 
7915    Notes:
7916      Must call MatSetColoring() before using this routine. Also this matrix must already
7917      have its nonzero pattern determined.
7918 
7919 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
7920           MatSetValues(), MatSetColoring()
7921 @*/
7922 PetscErrorCode  MatSetValuesAdifor(Mat mat,PetscInt nl,void *v)
7923 {
7924   PetscErrorCode ierr;
7925 
7926   PetscFunctionBegin;
7927   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7928   PetscValidType(mat,1);
7929   PetscValidPointer(v,3);
7930 
7931   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
7932   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
7933   if (!mat->ops->setvaluesadifor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7934   ierr = (*mat->ops->setvaluesadifor)(mat,nl,v);CHKERRQ(ierr);
7935   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
7936   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
7937   PetscFunctionReturn(0);
7938 }
7939 
7940 #undef __FUNCT__
7941 #define __FUNCT__ "MatDiagonalScaleLocal"
7942 /*@
7943    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
7944          ghosted ones.
7945 
7946    Not Collective
7947 
7948    Input Parameters:
7949 +  mat - the matrix
7950 -  diag = the diagonal values, including ghost ones
7951 
7952    Level: developer
7953 
7954    Notes: Works only for MPIAIJ and MPIBAIJ matrices
7955 
7956 .seealso: MatDiagonalScale()
7957 @*/
7958 PetscErrorCode  MatDiagonalScaleLocal(Mat mat,Vec diag)
7959 {
7960   PetscErrorCode ierr;
7961   PetscMPIInt    size;
7962 
7963   PetscFunctionBegin;
7964   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7965   PetscValidHeaderSpecific(diag,VEC_CLASSID,2);
7966   PetscValidType(mat,1);
7967 
7968   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
7969   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
7970   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
7971   if (size == 1) {
7972     PetscInt n,m;
7973     ierr = VecGetSize(diag,&n);CHKERRQ(ierr);
7974     ierr = MatGetSize(mat,0,&m);CHKERRQ(ierr);
7975     if (m == n) {
7976       ierr = MatDiagonalScale(mat,0,diag);CHKERRQ(ierr);
7977     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
7978   } else {
7979     ierr = PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));CHKERRQ(ierr);
7980   }
7981   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
7982   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
7983   PetscFunctionReturn(0);
7984 }
7985 
7986 #undef __FUNCT__
7987 #define __FUNCT__ "MatGetInertia"
7988 /*@
7989    MatGetInertia - Gets the inertia from a factored matrix
7990 
7991    Collective on Mat
7992 
7993    Input Parameter:
7994 .  mat - the matrix
7995 
7996    Output Parameters:
7997 +   nneg - number of negative eigenvalues
7998 .   nzero - number of zero eigenvalues
7999 -   npos - number of positive eigenvalues
8000 
8001    Level: advanced
8002 
8003    Notes: Matrix must have been factored by MatCholeskyFactor()
8004 
8005 
8006 @*/
8007 PetscErrorCode  MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8008 {
8009   PetscErrorCode ierr;
8010 
8011   PetscFunctionBegin;
8012   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8013   PetscValidType(mat,1);
8014   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8015   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8016   if (!mat->ops->getinertia) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8017   ierr = (*mat->ops->getinertia)(mat,nneg,nzero,npos);CHKERRQ(ierr);
8018   PetscFunctionReturn(0);
8019 }
8020 
8021 /* ----------------------------------------------------------------*/
8022 #undef __FUNCT__
8023 #define __FUNCT__ "MatSolves"
8024 /*@C
8025    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8026 
8027    Neighbor-wise Collective on Mat and Vecs
8028 
8029    Input Parameters:
8030 +  mat - the factored matrix
8031 -  b - the right-hand-side vectors
8032 
8033    Output Parameter:
8034 .  x - the result vectors
8035 
8036    Notes:
8037    The vectors b and x cannot be the same.  I.e., one cannot
8038    call MatSolves(A,x,x).
8039 
8040    Notes:
8041    Most users should employ the simplified KSP interface for linear solvers
8042    instead of working directly with matrix algebra routines such as this.
8043    See, e.g., KSPCreate().
8044 
8045    Level: developer
8046 
8047    Concepts: matrices^triangular solves
8048 
8049 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8050 @*/
8051 PetscErrorCode  MatSolves(Mat mat,Vecs b,Vecs x)
8052 {
8053   PetscErrorCode ierr;
8054 
8055   PetscFunctionBegin;
8056   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8057   PetscValidType(mat,1);
8058   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8059   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8060   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
8061 
8062   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8063   MatCheckPreallocated(mat,1);
8064   ierr = PetscLogEventBegin(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8065   ierr = (*mat->ops->solves)(mat,b,x);CHKERRQ(ierr);
8066   ierr = PetscLogEventEnd(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8067   PetscFunctionReturn(0);
8068 }
8069 
8070 #undef __FUNCT__
8071 #define __FUNCT__ "MatIsSymmetric"
8072 /*@
8073    MatIsSymmetric - Test whether a matrix is symmetric
8074 
8075    Collective on Mat
8076 
8077    Input Parameter:
8078 +  A - the matrix to test
8079 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8080 
8081    Output Parameters:
8082 .  flg - the result
8083 
8084    Notes: For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8085 
8086    Level: intermediate
8087 
8088    Concepts: matrix^symmetry
8089 
8090 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8091 @*/
8092 PetscErrorCode  MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8093 {
8094   PetscErrorCode ierr;
8095 
8096   PetscFunctionBegin;
8097   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8098   PetscValidPointer(flg,2);
8099 
8100   if (!A->symmetric_set) {
8101     if (!A->ops->issymmetric) {
8102       MatType mattype;
8103       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8104       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8105     }
8106     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8107     if (!tol) {
8108       A->symmetric_set = PETSC_TRUE;
8109       A->symmetric     = *flg;
8110       if (A->symmetric) {
8111         A->structurally_symmetric_set = PETSC_TRUE;
8112         A->structurally_symmetric     = PETSC_TRUE;
8113       }
8114     }
8115   } else if (A->symmetric) {
8116     *flg = PETSC_TRUE;
8117   } else if (!tol) {
8118     *flg = PETSC_FALSE;
8119   } else {
8120     if (!A->ops->issymmetric) {
8121       MatType mattype;
8122       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8123       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8124     }
8125     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8126   }
8127   PetscFunctionReturn(0);
8128 }
8129 
8130 #undef __FUNCT__
8131 #define __FUNCT__ "MatIsHermitian"
8132 /*@
8133    MatIsHermitian - Test whether a matrix is Hermitian
8134 
8135    Collective on Mat
8136 
8137    Input Parameter:
8138 +  A - the matrix to test
8139 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8140 
8141    Output Parameters:
8142 .  flg - the result
8143 
8144    Level: intermediate
8145 
8146    Concepts: matrix^symmetry
8147 
8148 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8149           MatIsSymmetricKnown(), MatIsSymmetric()
8150 @*/
8151 PetscErrorCode  MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8152 {
8153   PetscErrorCode ierr;
8154 
8155   PetscFunctionBegin;
8156   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8157   PetscValidPointer(flg,2);
8158 
8159   if (!A->hermitian_set) {
8160     if (!A->ops->ishermitian) {
8161       MatType mattype;
8162       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8163       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8164     }
8165     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8166     if (!tol) {
8167       A->hermitian_set = PETSC_TRUE;
8168       A->hermitian     = *flg;
8169       if (A->hermitian) {
8170         A->structurally_symmetric_set = PETSC_TRUE;
8171         A->structurally_symmetric     = PETSC_TRUE;
8172       }
8173     }
8174   } else if (A->hermitian) {
8175     *flg = PETSC_TRUE;
8176   } else if (!tol) {
8177     *flg = PETSC_FALSE;
8178   } else {
8179     if (!A->ops->ishermitian) {
8180       MatType mattype;
8181       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8182       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8183     }
8184     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8185   }
8186   PetscFunctionReturn(0);
8187 }
8188 
8189 #undef __FUNCT__
8190 #define __FUNCT__ "MatIsSymmetricKnown"
8191 /*@
8192    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8193 
8194    Not Collective
8195 
8196    Input Parameter:
8197 .  A - the matrix to check
8198 
8199    Output Parameters:
8200 +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8201 -  flg - the result
8202 
8203    Level: advanced
8204 
8205    Concepts: matrix^symmetry
8206 
8207    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8208          if you want it explicitly checked
8209 
8210 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8211 @*/
8212 PetscErrorCode  MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8213 {
8214   PetscFunctionBegin;
8215   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8216   PetscValidPointer(set,2);
8217   PetscValidPointer(flg,3);
8218   if (A->symmetric_set) {
8219     *set = PETSC_TRUE;
8220     *flg = A->symmetric;
8221   } else {
8222     *set = PETSC_FALSE;
8223   }
8224   PetscFunctionReturn(0);
8225 }
8226 
8227 #undef __FUNCT__
8228 #define __FUNCT__ "MatIsHermitianKnown"
8229 /*@
8230    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8231 
8232    Not Collective
8233 
8234    Input Parameter:
8235 .  A - the matrix to check
8236 
8237    Output Parameters:
8238 +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8239 -  flg - the result
8240 
8241    Level: advanced
8242 
8243    Concepts: matrix^symmetry
8244 
8245    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8246          if you want it explicitly checked
8247 
8248 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8249 @*/
8250 PetscErrorCode  MatIsHermitianKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8251 {
8252   PetscFunctionBegin;
8253   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8254   PetscValidPointer(set,2);
8255   PetscValidPointer(flg,3);
8256   if (A->hermitian_set) {
8257     *set = PETSC_TRUE;
8258     *flg = A->hermitian;
8259   } else {
8260     *set = PETSC_FALSE;
8261   }
8262   PetscFunctionReturn(0);
8263 }
8264 
8265 #undef __FUNCT__
8266 #define __FUNCT__ "MatIsStructurallySymmetric"
8267 /*@
8268    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8269 
8270    Collective on Mat
8271 
8272    Input Parameter:
8273 .  A - the matrix to test
8274 
8275    Output Parameters:
8276 .  flg - the result
8277 
8278    Level: intermediate
8279 
8280    Concepts: matrix^symmetry
8281 
8282 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8283 @*/
8284 PetscErrorCode  MatIsStructurallySymmetric(Mat A,PetscBool  *flg)
8285 {
8286   PetscErrorCode ierr;
8287 
8288   PetscFunctionBegin;
8289   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8290   PetscValidPointer(flg,2);
8291   if (!A->structurally_symmetric_set) {
8292     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8293     ierr = (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);CHKERRQ(ierr);
8294 
8295     A->structurally_symmetric_set = PETSC_TRUE;
8296   }
8297   *flg = A->structurally_symmetric;
8298   PetscFunctionReturn(0);
8299 }
8300 
8301 #undef __FUNCT__
8302 #define __FUNCT__ "MatStashGetInfo"
8303 extern PetscErrorCode MatStashGetInfo_Private(MatStash*,PetscInt*,PetscInt*);
8304 /*@
8305    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8306        to be communicated to other processors during the MatAssemblyBegin/End() process
8307 
8308     Not collective
8309 
8310    Input Parameter:
8311 .   vec - the vector
8312 
8313    Output Parameters:
8314 +   nstash   - the size of the stash
8315 .   reallocs - the number of additional mallocs incurred.
8316 .   bnstash   - the size of the block stash
8317 -   breallocs - the number of additional mallocs incurred.in the block stash
8318 
8319    Level: advanced
8320 
8321 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8322 
8323 @*/
8324 PetscErrorCode  MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8325 {
8326   PetscErrorCode ierr;
8327 
8328   PetscFunctionBegin;
8329   ierr = MatStashGetInfo_Private(&mat->stash,nstash,reallocs);CHKERRQ(ierr);
8330   ierr = MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);CHKERRQ(ierr);
8331   PetscFunctionReturn(0);
8332 }
8333 
8334 #undef __FUNCT__
8335 #define __FUNCT__ "MatCreateVecs"
8336 /*@C
8337    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8338      parallel layout
8339 
8340    Collective on Mat
8341 
8342    Input Parameter:
8343 .  mat - the matrix
8344 
8345    Output Parameter:
8346 +   right - (optional) vector that the matrix can be multiplied against
8347 -   left - (optional) vector that the matrix vector product can be stored in
8348 
8349    Notes:
8350     The blocksize of the returned vectors is determined by the row and column block sizes set with MatSetBlockSizes() or the single blocksize (same for both) set by MatSetBlockSize().
8351 
8352   Notes: These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8353 
8354   Level: advanced
8355 
8356 .seealso: MatCreate(), VecDestroy()
8357 @*/
8358 PetscErrorCode  MatCreateVecs(Mat mat,Vec *right,Vec *left)
8359 {
8360   PetscErrorCode ierr;
8361 
8362   PetscFunctionBegin;
8363   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8364   PetscValidType(mat,1);
8365   MatCheckPreallocated(mat,1);
8366   if (mat->ops->getvecs) {
8367     ierr = (*mat->ops->getvecs)(mat,right,left);CHKERRQ(ierr);
8368   } else {
8369     PetscMPIInt size;
8370     PetscInt    rbs,cbs;
8371     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size);CHKERRQ(ierr);
8372     ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
8373     if (right) {
8374       ierr = VecCreate(PetscObjectComm((PetscObject)mat),right);CHKERRQ(ierr);
8375       ierr = VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8376       ierr = VecSetBlockSize(*right,cbs);CHKERRQ(ierr);
8377       ierr = VecSetType(*right,VECSTANDARD);CHKERRQ(ierr);
8378       ierr = PetscLayoutReference(mat->cmap,&(*right)->map);CHKERRQ(ierr);
8379     }
8380     if (left) {
8381       ierr = VecCreate(PetscObjectComm((PetscObject)mat),left);CHKERRQ(ierr);
8382       ierr = VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8383       ierr = VecSetBlockSize(*left,rbs);CHKERRQ(ierr);
8384       ierr = VecSetType(*left,VECSTANDARD);CHKERRQ(ierr);
8385       ierr = PetscLayoutReference(mat->rmap,&(*left)->map);CHKERRQ(ierr);
8386     }
8387   }
8388   PetscFunctionReturn(0);
8389 }
8390 
8391 #undef __FUNCT__
8392 #define __FUNCT__ "MatFactorInfoInitialize"
8393 /*@C
8394    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8395      with default values.
8396 
8397    Not Collective
8398 
8399    Input Parameters:
8400 .    info - the MatFactorInfo data structure
8401 
8402 
8403    Notes: The solvers are generally used through the KSP and PC objects, for example
8404           PCLU, PCILU, PCCHOLESKY, PCICC
8405 
8406    Level: developer
8407 
8408 .seealso: MatFactorInfo
8409 
8410     Developer Note: fortran interface is not autogenerated as the f90
8411     interface defintion cannot be generated correctly [due to MatFactorInfo]
8412 
8413 @*/
8414 
8415 PetscErrorCode  MatFactorInfoInitialize(MatFactorInfo *info)
8416 {
8417   PetscErrorCode ierr;
8418 
8419   PetscFunctionBegin;
8420   ierr = PetscMemzero(info,sizeof(MatFactorInfo));CHKERRQ(ierr);
8421   PetscFunctionReturn(0);
8422 }
8423 
8424 #undef __FUNCT__
8425 #define __FUNCT__ "MatPtAP"
8426 /*@
8427    MatPtAP - Creates the matrix product C = P^T * A * P
8428 
8429    Neighbor-wise Collective on Mat
8430 
8431    Input Parameters:
8432 +  A - the matrix
8433 .  P - the projection matrix
8434 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8435 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P))
8436 
8437    Output Parameters:
8438 .  C - the product matrix
8439 
8440    Notes:
8441    C will be created and must be destroyed by the user with MatDestroy().
8442 
8443    This routine is currently only implemented for pairs of AIJ matrices and classes
8444    which inherit from AIJ.
8445 
8446    Level: intermediate
8447 
8448 .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
8449 @*/
8450 PetscErrorCode  MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
8451 {
8452   PetscErrorCode ierr;
8453   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
8454   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
8455   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
8456   PetscBool      viatranspose=PETSC_FALSE,viamatmatmatmult=PETSC_FALSE;
8457 
8458   PetscFunctionBegin;
8459   ierr = PetscOptionsGetBool(((PetscObject)A)->prefix,"-matptap_viatranspose",&viatranspose,NULL);CHKERRQ(ierr);
8460   ierr = PetscOptionsGetBool(((PetscObject)A)->prefix,"-matptap_viamatmatmatmult",&viamatmatmatmult,NULL);CHKERRQ(ierr);
8461 
8462   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8463   PetscValidType(A,1);
8464   MatCheckPreallocated(A,1);
8465   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8466   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8467   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
8468   PetscValidType(P,2);
8469   MatCheckPreallocated(P,2);
8470   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8471   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8472 
8473   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
8474   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8475 
8476   if (scall == MAT_REUSE_MATRIX) {
8477     PetscValidPointer(*C,5);
8478     PetscValidHeaderSpecific(*C,MAT_CLASSID,5);
8479     if (viatranspose || viamatmatmatmult) {
8480       Mat Pt;
8481       ierr = MatTranspose(P,MAT_INITIAL_MATRIX,&Pt);CHKERRQ(ierr);
8482       if (viamatmatmatmult) {
8483         ierr = MatMatMatMult(Pt,A,P,scall,fill,C);CHKERRQ(ierr);
8484       } else {
8485         Mat AP;
8486         ierr = MatMatMult(A,P,MAT_INITIAL_MATRIX,fill,&AP);CHKERRQ(ierr);
8487         ierr = MatMatMult(Pt,AP,scall,fill,C);CHKERRQ(ierr);
8488         ierr = MatDestroy(&AP);CHKERRQ(ierr);
8489       }
8490       ierr = MatDestroy(&Pt);CHKERRQ(ierr);
8491     } else {
8492       ierr = PetscLogEventBegin(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
8493       ierr = PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
8494       ierr = (*(*C)->ops->ptapnumeric)(A,P,*C);CHKERRQ(ierr);
8495       ierr = PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
8496       ierr = PetscLogEventEnd(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
8497     }
8498     PetscFunctionReturn(0);
8499   }
8500 
8501   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
8502   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8503 
8504   fA = A->ops->ptap;
8505   fP = P->ops->ptap;
8506   if (fP == fA) {
8507     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatPtAP not supported for A of type %s",((PetscObject)A)->type_name);
8508     ptap = fA;
8509   } else {
8510     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
8511     char ptapname[256];
8512     ierr = PetscStrcpy(ptapname,"MatPtAP_");CHKERRQ(ierr);
8513     ierr = PetscStrcat(ptapname,((PetscObject)A)->type_name);CHKERRQ(ierr);
8514     ierr = PetscStrcat(ptapname,"_");CHKERRQ(ierr);
8515     ierr = PetscStrcat(ptapname,((PetscObject)P)->type_name);CHKERRQ(ierr);
8516     ierr = PetscStrcat(ptapname,"_C");CHKERRQ(ierr); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
8517     ierr = PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);CHKERRQ(ierr);
8518     if (!ptap) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatPtAP requires A, %s, to be compatible with P, %s",((PetscObject)A)->type_name,((PetscObject)P)->type_name);
8519   }
8520 
8521   if (viatranspose || viamatmatmatmult) {
8522     Mat Pt;
8523     ierr = MatTranspose(P,MAT_INITIAL_MATRIX,&Pt);CHKERRQ(ierr);
8524     if (viamatmatmatmult) {
8525       ierr = MatMatMatMult(Pt,A,P,scall,fill,C);CHKERRQ(ierr);
8526       ierr = PetscInfo(*C,"MatPtAP via MatMatMatMult\n");CHKERRQ(ierr);
8527     } else {
8528       Mat AP;
8529       ierr = MatMatMult(A,P,MAT_INITIAL_MATRIX,fill,&AP);CHKERRQ(ierr);
8530       ierr = MatMatMult(Pt,AP,scall,fill,C);CHKERRQ(ierr);
8531       ierr = MatDestroy(&AP);CHKERRQ(ierr);
8532       ierr = PetscInfo(*C,"MatPtAP via MatTranspose and MatMatMult\n");CHKERRQ(ierr);
8533     }
8534     ierr = MatDestroy(&Pt);CHKERRQ(ierr);
8535   } else {
8536     ierr = PetscLogEventBegin(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
8537     ierr = (*ptap)(A,P,scall,fill,C);CHKERRQ(ierr);
8538     ierr = PetscLogEventEnd(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
8539   }
8540   PetscFunctionReturn(0);
8541 }
8542 
8543 #undef __FUNCT__
8544 #define __FUNCT__ "MatPtAPNumeric"
8545 /*@
8546    MatPtAPNumeric - Computes the matrix product C = P^T * A * P
8547 
8548    Neighbor-wise Collective on Mat
8549 
8550    Input Parameters:
8551 +  A - the matrix
8552 -  P - the projection matrix
8553 
8554    Output Parameters:
8555 .  C - the product matrix
8556 
8557    Notes:
8558    C must have been created by calling MatPtAPSymbolic and must be destroyed by
8559    the user using MatDeatroy().
8560 
8561    This routine is currently only implemented for pairs of AIJ matrices and classes
8562    which inherit from AIJ.  C will be of type MATAIJ.
8563 
8564    Level: intermediate
8565 
8566 .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
8567 @*/
8568 PetscErrorCode  MatPtAPNumeric(Mat A,Mat P,Mat C)
8569 {
8570   PetscErrorCode ierr;
8571 
8572   PetscFunctionBegin;
8573   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8574   PetscValidType(A,1);
8575   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8576   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8577   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
8578   PetscValidType(P,2);
8579   MatCheckPreallocated(P,2);
8580   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8581   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8582   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
8583   PetscValidType(C,3);
8584   MatCheckPreallocated(C,3);
8585   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8586   if (P->cmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->rmap->N);
8587   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
8588   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8589   if (P->cmap->N!=C->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->cmap->N);
8590   MatCheckPreallocated(A,1);
8591 
8592   ierr = PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
8593   ierr = (*C->ops->ptapnumeric)(A,P,C);CHKERRQ(ierr);
8594   ierr = PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
8595   PetscFunctionReturn(0);
8596 }
8597 
8598 #undef __FUNCT__
8599 #define __FUNCT__ "MatPtAPSymbolic"
8600 /*@
8601    MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P
8602 
8603    Neighbor-wise Collective on Mat
8604 
8605    Input Parameters:
8606 +  A - the matrix
8607 -  P - the projection matrix
8608 
8609    Output Parameters:
8610 .  C - the (i,j) structure of the product matrix
8611 
8612    Notes:
8613    C will be created and must be destroyed by the user with MatDestroy().
8614 
8615    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
8616    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
8617    this (i,j) structure by calling MatPtAPNumeric().
8618 
8619    Level: intermediate
8620 
8621 .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
8622 @*/
8623 PetscErrorCode  MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
8624 {
8625   PetscErrorCode ierr;
8626 
8627   PetscFunctionBegin;
8628   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8629   PetscValidType(A,1);
8630   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8631   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8632   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8633   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
8634   PetscValidType(P,2);
8635   MatCheckPreallocated(P,2);
8636   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8637   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8638   PetscValidPointer(C,3);
8639 
8640   if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
8641   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8642   MatCheckPreallocated(A,1);
8643   ierr = PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);CHKERRQ(ierr);
8644   ierr = (*A->ops->ptapsymbolic)(A,P,fill,C);CHKERRQ(ierr);
8645   ierr = PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);CHKERRQ(ierr);
8646 
8647   /* ierr = MatSetBlockSize(*C,A->rmap->bs);CHKERRQ(ierr); NO! this is not always true -ma */
8648   PetscFunctionReturn(0);
8649 }
8650 
8651 #undef __FUNCT__
8652 #define __FUNCT__ "MatRARt"
8653 /*@
8654    MatRARt - Creates the matrix product C = R * A * R^T
8655 
8656    Neighbor-wise Collective on Mat
8657 
8658    Input Parameters:
8659 +  A - the matrix
8660 .  R - the projection matrix
8661 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8662 -  fill - expected fill as ratio of nnz(C)/nnz(A)
8663 
8664    Output Parameters:
8665 .  C - the product matrix
8666 
8667    Notes:
8668    C will be created and must be destroyed by the user with MatDestroy().
8669 
8670    This routine is currently only implemented for pairs of AIJ matrices and classes
8671    which inherit from AIJ.
8672 
8673    Level: intermediate
8674 
8675 .seealso: MatRARtSymbolic(), MatRARtNumeric(), MatMatMult(), MatPtAP()
8676 @*/
8677 PetscErrorCode  MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
8678 {
8679   PetscErrorCode ierr;
8680 
8681   PetscFunctionBegin;
8682   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8683   PetscValidType(A,1);
8684   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8685   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8686   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
8687   PetscValidType(R,2);
8688   MatCheckPreallocated(R,2);
8689   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8690   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8691   PetscValidPointer(C,3);
8692   if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)R),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
8693   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8694   MatCheckPreallocated(A,1);
8695 
8696   if (!A->ops->rart) {
8697     MatType mattype;
8698     ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8699     SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type <%s> does not support RARt",mattype);
8700   }
8701   ierr = PetscLogEventBegin(MAT_RARt,A,R,0,0);CHKERRQ(ierr);
8702   ierr = (*A->ops->rart)(A,R,scall,fill,C);CHKERRQ(ierr);
8703   ierr = PetscLogEventEnd(MAT_RARt,A,R,0,0);CHKERRQ(ierr);
8704   PetscFunctionReturn(0);
8705 }
8706 
8707 #undef __FUNCT__
8708 #define __FUNCT__ "MatRARtNumeric"
8709 /*@
8710    MatRARtNumeric - Computes the matrix product C = R * A * R^T
8711 
8712    Neighbor-wise Collective on Mat
8713 
8714    Input Parameters:
8715 +  A - the matrix
8716 -  R - the projection matrix
8717 
8718    Output Parameters:
8719 .  C - the product matrix
8720 
8721    Notes:
8722    C must have been created by calling MatRARtSymbolic and must be destroyed by
8723    the user using MatDeatroy().
8724 
8725    This routine is currently only implemented for pairs of AIJ matrices and classes
8726    which inherit from AIJ.  C will be of type MATAIJ.
8727 
8728    Level: intermediate
8729 
8730 .seealso: MatRARt(), MatRARtSymbolic(), MatMatMultNumeric()
8731 @*/
8732 PetscErrorCode  MatRARtNumeric(Mat A,Mat R,Mat C)
8733 {
8734   PetscErrorCode ierr;
8735 
8736   PetscFunctionBegin;
8737   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8738   PetscValidType(A,1);
8739   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8740   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8741   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
8742   PetscValidType(R,2);
8743   MatCheckPreallocated(R,2);
8744   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8745   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8746   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
8747   PetscValidType(C,3);
8748   MatCheckPreallocated(C,3);
8749   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8750   if (R->rmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->rmap->N,C->rmap->N);
8751   if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
8752   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8753   if (R->rmap->N!=C->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->rmap->N,C->cmap->N);
8754   MatCheckPreallocated(A,1);
8755 
8756   ierr = PetscLogEventBegin(MAT_RARtNumeric,A,R,0,0);CHKERRQ(ierr);
8757   ierr = (*A->ops->rartnumeric)(A,R,C);CHKERRQ(ierr);
8758   ierr = PetscLogEventEnd(MAT_RARtNumeric,A,R,0,0);CHKERRQ(ierr);
8759   PetscFunctionReturn(0);
8760 }
8761 
8762 #undef __FUNCT__
8763 #define __FUNCT__ "MatRARtSymbolic"
8764 /*@
8765    MatRARtSymbolic - Creates the (i,j) structure of the matrix product C = R * A * R^T
8766 
8767    Neighbor-wise Collective on Mat
8768 
8769    Input Parameters:
8770 +  A - the matrix
8771 -  R - the projection matrix
8772 
8773    Output Parameters:
8774 .  C - the (i,j) structure of the product matrix
8775 
8776    Notes:
8777    C will be created and must be destroyed by the user with MatDestroy().
8778 
8779    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
8780    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
8781    this (i,j) structure by calling MatRARtNumeric().
8782 
8783    Level: intermediate
8784 
8785 .seealso: MatRARt(), MatRARtNumeric(), MatMatMultSymbolic()
8786 @*/
8787 PetscErrorCode  MatRARtSymbolic(Mat A,Mat R,PetscReal fill,Mat *C)
8788 {
8789   PetscErrorCode ierr;
8790 
8791   PetscFunctionBegin;
8792   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8793   PetscValidType(A,1);
8794   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8795   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8796   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8797   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
8798   PetscValidType(R,2);
8799   MatCheckPreallocated(R,2);
8800   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8801   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8802   PetscValidPointer(C,3);
8803 
8804   if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
8805   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
8806   MatCheckPreallocated(A,1);
8807   ierr = PetscLogEventBegin(MAT_RARtSymbolic,A,R,0,0);CHKERRQ(ierr);
8808   ierr = (*A->ops->rartsymbolic)(A,R,fill,C);CHKERRQ(ierr);
8809   ierr = PetscLogEventEnd(MAT_RARtSymbolic,A,R,0,0);CHKERRQ(ierr);
8810 
8811   ierr = MatSetBlockSizes(*C,PetscAbs(R->rmap->bs),PetscAbs(R->rmap->bs));CHKERRQ(ierr);
8812   PetscFunctionReturn(0);
8813 }
8814 
8815 #undef __FUNCT__
8816 #define __FUNCT__ "MatMatMult"
8817 /*@
8818    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
8819 
8820    Neighbor-wise Collective on Mat
8821 
8822    Input Parameters:
8823 +  A - the left matrix
8824 .  B - the right matrix
8825 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8826 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
8827           if the result is a dense matrix this is irrelevent
8828 
8829    Output Parameters:
8830 .  C - the product matrix
8831 
8832    Notes:
8833    Unless scall is MAT_REUSE_MATRIX C will be created.
8834 
8835    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
8836 
8837    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
8838    actually needed.
8839 
8840    If you have many matrices with the same non-zero structure to multiply, you
8841    should either
8842 $   1) use MAT_REUSE_MATRIX in all calls but the first or
8843 $   2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed
8844 
8845    Level: intermediate
8846 
8847 .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatTransposeMatMult(),  MatMatTransposeMult(), MatPtAP()
8848 @*/
8849 PetscErrorCode  MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
8850 {
8851   PetscErrorCode ierr;
8852   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
8853   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
8854   PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
8855 
8856   PetscFunctionBegin;
8857   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8858   PetscValidType(A,1);
8859   MatCheckPreallocated(A,1);
8860   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8861   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8862   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
8863   PetscValidType(B,2);
8864   MatCheckPreallocated(B,2);
8865   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8866   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8867   PetscValidPointer(C,3);
8868   if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
8869   if (scall == MAT_REUSE_MATRIX) {
8870     PetscValidPointer(*C,5);
8871     PetscValidHeaderSpecific(*C,MAT_CLASSID,5);
8872     ierr = PetscLogEventBegin(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
8873     ierr = PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
8874     ierr = (*(*C)->ops->matmultnumeric)(A,B,*C);CHKERRQ(ierr);
8875     ierr = PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
8876     ierr = PetscLogEventEnd(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
8877     PetscFunctionReturn(0);
8878   }
8879   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
8880   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
8881 
8882   fA = A->ops->matmult;
8883   fB = B->ops->matmult;
8884   if (fB == fA) {
8885     if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",((PetscObject)B)->type_name);
8886     mult = fB;
8887   } else {
8888     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
8889     char multname[256];
8890     ierr = PetscStrcpy(multname,"MatMatMult_");CHKERRQ(ierr);
8891     ierr = PetscStrcat(multname,((PetscObject)A)->type_name);CHKERRQ(ierr);
8892     ierr = PetscStrcat(multname,"_");CHKERRQ(ierr);
8893     ierr = PetscStrcat(multname,((PetscObject)B)->type_name);CHKERRQ(ierr);
8894     ierr = PetscStrcat(multname,"_C");CHKERRQ(ierr); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
8895     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&mult);CHKERRQ(ierr);
8896     if (!mult) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
8897   }
8898   ierr = PetscLogEventBegin(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
8899   ierr = (*mult)(A,B,scall,fill,C);CHKERRQ(ierr);
8900   ierr = PetscLogEventEnd(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
8901   PetscFunctionReturn(0);
8902 }
8903 
8904 #undef __FUNCT__
8905 #define __FUNCT__ "MatMatMultSymbolic"
8906 /*@
8907    MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
8908    of the matrix-matrix product C=A*B.  Call this routine before calling MatMatMultNumeric().
8909 
8910    Neighbor-wise Collective on Mat
8911 
8912    Input Parameters:
8913 +  A - the left matrix
8914 .  B - the right matrix
8915 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate,
8916       if C is a dense matrix this is irrelevent
8917 
8918    Output Parameters:
8919 .  C - the product matrix
8920 
8921    Notes:
8922    Unless scall is MAT_REUSE_MATRIX C will be created.
8923 
8924    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
8925    actually needed.
8926 
8927    This routine is currently implemented for
8928     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type AIJ
8929     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
8930     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
8931 
8932    Level: intermediate
8933 
8934    Developers Note: There are ways to estimate the number of nonzeros in the resulting product, see for example, http://arxiv.org/abs/1006.4173
8935      We should incorporate them into PETSc.
8936 
8937 .seealso: MatMatMult(), MatMatMultNumeric()
8938 @*/
8939 PetscErrorCode  MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
8940 {
8941   PetscErrorCode ierr;
8942   PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat*);
8943   PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat*);
8944   PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat*)=NULL;
8945 
8946   PetscFunctionBegin;
8947   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8948   PetscValidType(A,1);
8949   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8950   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8951 
8952   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
8953   PetscValidType(B,2);
8954   MatCheckPreallocated(B,2);
8955   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8956   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8957   PetscValidPointer(C,3);
8958 
8959   if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
8960   if (fill == PETSC_DEFAULT) fill = 2.0;
8961   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
8962   MatCheckPreallocated(A,1);
8963 
8964   Asymbolic = A->ops->matmultsymbolic;
8965   Bsymbolic = B->ops->matmultsymbolic;
8966   if (Asymbolic == Bsymbolic) {
8967     if (!Bsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
8968     symbolic = Bsymbolic;
8969   } else { /* dispatch based on the type of A and B */
8970     char symbolicname[256];
8971     ierr = PetscStrcpy(symbolicname,"MatMatMultSymbolic_");CHKERRQ(ierr);
8972     ierr = PetscStrcat(symbolicname,((PetscObject)A)->type_name);CHKERRQ(ierr);
8973     ierr = PetscStrcat(symbolicname,"_");CHKERRQ(ierr);
8974     ierr = PetscStrcat(symbolicname,((PetscObject)B)->type_name);CHKERRQ(ierr);
8975     ierr = PetscStrcat(symbolicname,"_C");CHKERRQ(ierr);
8976     ierr = PetscObjectQueryFunction((PetscObject)B,symbolicname,&symbolic);CHKERRQ(ierr);
8977     if (!symbolic) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMultSymbolic requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
8978   }
8979   ierr = PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
8980   ierr = (*symbolic)(A,B,fill,C);CHKERRQ(ierr);
8981   ierr = PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
8982   PetscFunctionReturn(0);
8983 }
8984 
8985 #undef __FUNCT__
8986 #define __FUNCT__ "MatMatMultNumeric"
8987 /*@
8988    MatMatMultNumeric - Performs the numeric matrix-matrix product.
8989    Call this routine after first calling MatMatMultSymbolic().
8990 
8991    Neighbor-wise Collective on Mat
8992 
8993    Input Parameters:
8994 +  A - the left matrix
8995 -  B - the right matrix
8996 
8997    Output Parameters:
8998 .  C - the product matrix, which was created by from MatMatMultSymbolic() or a call to MatMatMult().
8999 
9000    Notes:
9001    C must have been created with MatMatMultSymbolic().
9002 
9003    This routine is currently implemented for
9004     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
9005     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9006     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9007 
9008    Level: intermediate
9009 
9010 .seealso: MatMatMult(), MatMatMultSymbolic()
9011 @*/
9012 PetscErrorCode  MatMatMultNumeric(Mat A,Mat B,Mat C)
9013 {
9014   PetscErrorCode ierr;
9015 
9016   PetscFunctionBegin;
9017   ierr = MatMatMult(A,B,MAT_REUSE_MATRIX,0.0,&C);CHKERRQ(ierr);
9018   PetscFunctionReturn(0);
9019 }
9020 
9021 #undef __FUNCT__
9022 #define __FUNCT__ "MatMatTransposeMult"
9023 /*@
9024    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9025 
9026    Neighbor-wise Collective on Mat
9027 
9028    Input Parameters:
9029 +  A - the left matrix
9030 .  B - the right matrix
9031 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9032 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9033 
9034    Output Parameters:
9035 .  C - the product matrix
9036 
9037    Notes:
9038    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9039 
9040    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9041 
9042   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9043    actually needed.
9044 
9045    This routine is currently only implemented for pairs of SeqAIJ matrices.  C will be of type MATSEQAIJ.
9046 
9047    Level: intermediate
9048 
9049 .seealso: MatMatTransposeMultSymbolic(), MatMatTransposeMultNumeric(), MatMatMult(), MatTransposeMatMult() MatPtAP()
9050 @*/
9051 PetscErrorCode  MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9052 {
9053   PetscErrorCode ierr;
9054   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9055   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9056 
9057   PetscFunctionBegin;
9058   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9059   PetscValidType(A,1);
9060   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9061   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9062   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9063   PetscValidType(B,2);
9064   MatCheckPreallocated(B,2);
9065   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9066   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9067   PetscValidPointer(C,3);
9068   if (B->cmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, AN %D != BN %D",A->cmap->N,B->cmap->N);
9069   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9070   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9071   MatCheckPreallocated(A,1);
9072 
9073   fA = A->ops->mattransposemult;
9074   if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for A of type %s",((PetscObject)A)->type_name);
9075   fB = B->ops->mattransposemult;
9076   if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for B of type %s",((PetscObject)B)->type_name);
9077   if (fB!=fA) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatTransposeMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9078 
9079   ierr = PetscLogEventBegin(MAT_MatTransposeMult,A,B,0,0);CHKERRQ(ierr);
9080   if (scall == MAT_INITIAL_MATRIX) {
9081     ierr = PetscLogEventBegin(MAT_MatTransposeMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9082     ierr = (*A->ops->mattransposemultsymbolic)(A,B,fill,C);CHKERRQ(ierr);
9083     ierr = PetscLogEventEnd(MAT_MatTransposeMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9084   }
9085   ierr = PetscLogEventBegin(MAT_MatTransposeMultNumeric,A,B,0,0);CHKERRQ(ierr);
9086   ierr = (*A->ops->mattransposemultnumeric)(A,B,*C);CHKERRQ(ierr);
9087   ierr = PetscLogEventEnd(MAT_MatTransposeMultNumeric,A,B,0,0);CHKERRQ(ierr);
9088   ierr = PetscLogEventEnd(MAT_MatTransposeMult,A,B,0,0);CHKERRQ(ierr);
9089   PetscFunctionReturn(0);
9090 }
9091 
9092 #undef __FUNCT__
9093 #define __FUNCT__ "MatTransposeMatMult"
9094 /*@
9095    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
9096 
9097    Neighbor-wise Collective on Mat
9098 
9099    Input Parameters:
9100 +  A - the left matrix
9101 .  B - the right matrix
9102 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9103 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9104 
9105    Output Parameters:
9106 .  C - the product matrix
9107 
9108    Notes:
9109    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9110 
9111    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9112 
9113   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9114    actually needed.
9115 
9116    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9117    which inherit from SeqAIJ.  C will be of same type as the input matrices.
9118 
9119    Level: intermediate
9120 
9121 .seealso: MatTransposeMatMultSymbolic(), MatTransposeMatMultNumeric(), MatMatMult(), MatMatTransposeMult(), MatPtAP()
9122 @*/
9123 PetscErrorCode  MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9124 {
9125   PetscErrorCode ierr;
9126   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9127   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9128   PetscErrorCode (*transposematmult)(Mat,Mat,MatReuse,PetscReal,Mat*) = NULL;
9129 
9130   PetscFunctionBegin;
9131   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9132   PetscValidType(A,1);
9133   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9134   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9135   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9136   PetscValidType(B,2);
9137   MatCheckPreallocated(B,2);
9138   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9139   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9140   PetscValidPointer(C,3);
9141   if (B->rmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->rmap->N);
9142   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9143   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9144   MatCheckPreallocated(A,1);
9145 
9146   fA = A->ops->transposematmult;
9147   fB = B->ops->transposematmult;
9148   if (fB==fA) {
9149     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatTransposeMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9150     transposematmult = fA;
9151   } else {
9152     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9153     char multname[256];
9154     ierr = PetscStrcpy(multname,"MatTransposeMatMult_");CHKERRQ(ierr);
9155     ierr = PetscStrcat(multname,((PetscObject)A)->type_name);CHKERRQ(ierr);
9156     ierr = PetscStrcat(multname,"_");CHKERRQ(ierr);
9157     ierr = PetscStrcat(multname,((PetscObject)B)->type_name);CHKERRQ(ierr);
9158     ierr = PetscStrcat(multname,"_C");CHKERRQ(ierr); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9159     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&transposematmult);CHKERRQ(ierr);
9160     if (!transposematmult) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatTransposeMatMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9161   }
9162   ierr = PetscLogEventBegin(MAT_TransposeMatMult,A,B,0,0);CHKERRQ(ierr);
9163   ierr = (*transposematmult)(A,B,scall,fill,C);CHKERRQ(ierr);
9164   ierr = PetscLogEventEnd(MAT_TransposeMatMult,A,B,0,0);CHKERRQ(ierr);
9165   PetscFunctionReturn(0);
9166 }
9167 
9168 #undef __FUNCT__
9169 #define __FUNCT__ "MatMatMatMult"
9170 /*@
9171    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
9172 
9173    Neighbor-wise Collective on Mat
9174 
9175    Input Parameters:
9176 +  A - the left matrix
9177 .  B - the middle matrix
9178 .  C - the right matrix
9179 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9180 -  fill - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use PETSC_DEFAULT if you do not have a good estimate
9181           if the result is a dense matrix this is irrelevent
9182 
9183    Output Parameters:
9184 .  D - the product matrix
9185 
9186    Notes:
9187    Unless scall is MAT_REUSE_MATRIX D will be created.
9188 
9189    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
9190 
9191    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9192    actually needed.
9193 
9194    If you have many matrices with the same non-zero structure to multiply, you
9195    should either
9196 $   1) use MAT_REUSE_MATRIX in all calls but the first or
9197 $   2) call MatMatMatMultSymbolic() once and then MatMatMatMultNumeric() for each product needed
9198 
9199    Level: intermediate
9200 
9201 .seealso: MatMatMult, MatPtAP()
9202 @*/
9203 PetscErrorCode  MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9204 {
9205   PetscErrorCode ierr;
9206   PetscErrorCode (*fA)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9207   PetscErrorCode (*fB)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9208   PetscErrorCode (*fC)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9209   PetscErrorCode (*mult)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9210 
9211   PetscFunctionBegin;
9212   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9213   PetscValidType(A,1);
9214   MatCheckPreallocated(A,1);
9215   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9216   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9217   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9218   PetscValidType(B,2);
9219   MatCheckPreallocated(B,2);
9220   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9221   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9222   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
9223   PetscValidPointer(C,3);
9224   MatCheckPreallocated(C,3);
9225   if (!C->assembled) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9226   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9227   if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
9228   if (C->rmap->N!=B->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",C->rmap->N,B->cmap->N);
9229   if (scall == MAT_REUSE_MATRIX) {
9230     PetscValidPointer(*D,6);
9231     PetscValidHeaderSpecific(*D,MAT_CLASSID,6);
9232     ierr = PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9233     ierr = (*(*D)->ops->matmatmult)(A,B,C,scall,fill,D);CHKERRQ(ierr);
9234     ierr = PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9235     PetscFunctionReturn(0);
9236   }
9237   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9238   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9239 
9240   fA = A->ops->matmatmult;
9241   fB = B->ops->matmatmult;
9242   fC = C->ops->matmatmult;
9243   if (fA == fB && fA == fC) {
9244     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9245     mult = fA;
9246   } else {
9247     /* dispatch based on the type of A, B and C from their PetscObject's PetscFunctionLists. */
9248     char multname[256];
9249     ierr = PetscStrcpy(multname,"MatMatMatMult_");CHKERRQ(ierr);
9250     ierr = PetscStrcat(multname,((PetscObject)A)->type_name);CHKERRQ(ierr);
9251     ierr = PetscStrcat(multname,"_");CHKERRQ(ierr);
9252     ierr = PetscStrcat(multname,((PetscObject)B)->type_name);CHKERRQ(ierr);
9253     ierr = PetscStrcat(multname,"_");CHKERRQ(ierr);
9254     ierr = PetscStrcat(multname,((PetscObject)C)->type_name);CHKERRQ(ierr);
9255     ierr = PetscStrcat(multname,"_C");CHKERRQ(ierr);
9256     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&mult);CHKERRQ(ierr);
9257     if (!mult) SETERRQ3(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMatMult requires A, %s, to be compatible with B, %s, C, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name,((PetscObject)C)->type_name);
9258   }
9259   ierr = PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9260   ierr = (*mult)(A,B,C,scall,fill,D);CHKERRQ(ierr);
9261   ierr = PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9262   PetscFunctionReturn(0);
9263 }
9264 
9265 #undef __FUNCT__
9266 #define __FUNCT__ "MatCreateRedundantMatrix"
9267 /*@C
9268    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
9269 
9270    Collective on Mat
9271 
9272    Input Parameters:
9273 +  mat - the matrix
9274 .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9275 .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9276 -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9277 
9278    Output Parameter:
9279 .  matredundant - redundant matrix
9280 
9281    Notes:
9282    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9283    original matrix has not changed from that last call to MatCreateRedundantMatrix().
9284 
9285    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9286    calling it.
9287 
9288    Level: advanced
9289 
9290    Concepts: subcommunicator
9291    Concepts: duplicate matrix
9292 
9293 .seealso: MatDestroy()
9294 @*/
9295 PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9296 {
9297   PetscErrorCode ierr;
9298   MPI_Comm       comm;
9299   PetscMPIInt    size;
9300   PetscInt       mloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9301   Mat_Redundant  *redund=NULL;
9302   PetscSubcomm   psubcomm=NULL;
9303   MPI_Comm       subcomm_in=subcomm;
9304   Mat            *matseq;
9305   IS             isrow,iscol;
9306   PetscBool      newsubcomm=PETSC_FALSE;
9307 
9308   PetscFunctionBegin;
9309   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
9310   if (size == 1 || nsubcomm == 1) {
9311     if (reuse == MAT_INITIAL_MATRIX) {
9312       ierr = MatDuplicate(mat,MAT_COPY_VALUES,matredundant);CHKERRQ(ierr);
9313     } else {
9314       ierr = MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
9315     }
9316     PetscFunctionReturn(0);
9317   }
9318 
9319   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9320   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9321     PetscValidPointer(*matredundant,5);
9322     PetscValidHeaderSpecific(*matredundant,MAT_CLASSID,5);
9323   }
9324   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9325   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9326   MatCheckPreallocated(mat,1);
9327 
9328   ierr = PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
9329   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9330     /* create psubcomm, then get subcomm */
9331     ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
9332     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
9333     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
9334 
9335     ierr = PetscSubcommCreate(comm,&psubcomm);CHKERRQ(ierr);
9336     ierr = PetscSubcommSetNumber(psubcomm,nsubcomm);CHKERRQ(ierr);
9337     ierr = PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);CHKERRQ(ierr);
9338     ierr = PetscSubcommSetFromOptions(psubcomm);CHKERRQ(ierr);
9339     ierr = PetscCommDuplicate(psubcomm->comm,&subcomm,NULL);CHKERRQ(ierr);
9340     newsubcomm = PETSC_TRUE;
9341     ierr = PetscSubcommDestroy(&psubcomm);CHKERRQ(ierr);
9342   }
9343 
9344   /* get isrow, iscol and a local sequential matrix matseq[0] */
9345   if (reuse == MAT_INITIAL_MATRIX) {
9346     mloc_sub = PETSC_DECIDE;
9347     if (bs < 1) {
9348       ierr = PetscSplitOwnership(subcomm,&mloc_sub,&M);CHKERRQ(ierr);
9349     } else {
9350       ierr = PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);CHKERRQ(ierr);
9351     }
9352     ierr = MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);CHKERRQ(ierr);
9353     rstart = rend - mloc_sub;
9354     ierr = ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);CHKERRQ(ierr);
9355     ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);CHKERRQ(ierr);
9356   } else { /* reuse == MAT_REUSE_MATRIX */
9357     /* retrieve subcomm */
9358     ierr = PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);CHKERRQ(ierr);
9359     redund = (*matredundant)->redundant;
9360     isrow  = redund->isrow;
9361     iscol  = redund->iscol;
9362     matseq = redund->matseq;
9363   }
9364   ierr = MatGetSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);CHKERRQ(ierr);
9365 
9366   /* get matredundant over subcomm */
9367   if (reuse == MAT_INITIAL_MATRIX) {
9368     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],mloc_sub,reuse,matredundant);CHKERRQ(ierr);
9369 
9370     /* create a supporting struct and attach it to C for reuse */
9371     ierr = PetscNewLog(*matredundant,&redund);CHKERRQ(ierr);
9372     (*matredundant)->redundant = redund;
9373     redund->isrow              = isrow;
9374     redund->iscol              = iscol;
9375     redund->matseq             = matseq;
9376     if (newsubcomm) {
9377       redund->subcomm          = subcomm;
9378     } else {
9379       redund->subcomm          = MPI_COMM_NULL;
9380     }
9381   } else {
9382     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);CHKERRQ(ierr);
9383   }
9384   ierr = PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
9385   PetscFunctionReturn(0);
9386 }
9387 
9388 #undef __FUNCT__
9389 #define __FUNCT__ "MatGetMultiProcBlock"
9390 /*@C
9391    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
9392    a given 'mat' object. Each submatrix can span multiple procs.
9393 
9394    Collective on Mat
9395 
9396    Input Parameters:
9397 +  mat - the matrix
9398 .  subcomm - the subcommunicator obtained by com_split(comm)
9399 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9400 
9401    Output Parameter:
9402 .  subMat - 'parallel submatrices each spans a given subcomm
9403 
9404   Notes:
9405   The submatrix partition across processors is dictated by 'subComm' a
9406   communicator obtained by com_split(comm). The comm_split
9407   is not restriced to be grouped with consecutive original ranks.
9408 
9409   Due the comm_split() usage, the parallel layout of the submatrices
9410   map directly to the layout of the original matrix [wrt the local
9411   row,col partitioning]. So the original 'DiagonalMat' naturally maps
9412   into the 'DiagonalMat' of the subMat, hence it is used directly from
9413   the subMat. However the offDiagMat looses some columns - and this is
9414   reconstructed with MatSetValues()
9415 
9416   Level: advanced
9417 
9418   Concepts: subcommunicator
9419   Concepts: submatrices
9420 
9421 .seealso: MatGetSubMatrices()
9422 @*/
9423 PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
9424 {
9425   PetscErrorCode ierr;
9426   PetscMPIInt    commsize,subCommSize;
9427 
9428   PetscFunctionBegin;
9429   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);CHKERRQ(ierr);
9430   ierr = MPI_Comm_size(subComm,&subCommSize);CHKERRQ(ierr);
9431   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
9432 
9433   ierr = PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
9434   ierr = (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);CHKERRQ(ierr);
9435   ierr = PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
9436   PetscFunctionReturn(0);
9437 }
9438 
9439 #undef __FUNCT__
9440 #define __FUNCT__ "MatGetLocalSubMatrix"
9441 /*@
9442    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
9443 
9444    Not Collective
9445 
9446    Input Arguments:
9447    mat - matrix to extract local submatrix from
9448    isrow - local row indices for submatrix
9449    iscol - local column indices for submatrix
9450 
9451    Output Arguments:
9452    submat - the submatrix
9453 
9454    Level: intermediate
9455 
9456    Notes:
9457    The submat should be returned with MatRestoreLocalSubMatrix().
9458 
9459    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
9460    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
9461 
9462    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
9463    MatSetValuesBlockedLocal() will also be implemented.
9464 
9465 .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef()
9466 @*/
9467 PetscErrorCode  MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9468 {
9469   PetscErrorCode ierr;
9470 
9471   PetscFunctionBegin;
9472   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9473   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
9474   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
9475   PetscCheckSameComm(isrow,2,iscol,3);
9476   PetscValidPointer(submat,4);
9477 
9478   if (mat->ops->getlocalsubmatrix) {
9479     ierr = (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
9480   } else {
9481     ierr = MatCreateLocalRef(mat,isrow,iscol,submat);CHKERRQ(ierr);
9482   }
9483   PetscFunctionReturn(0);
9484 }
9485 
9486 #undef __FUNCT__
9487 #define __FUNCT__ "MatRestoreLocalSubMatrix"
9488 /*@
9489    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
9490 
9491    Not Collective
9492 
9493    Input Arguments:
9494    mat - matrix to extract local submatrix from
9495    isrow - local row indices for submatrix
9496    iscol - local column indices for submatrix
9497    submat - the submatrix
9498 
9499    Level: intermediate
9500 
9501 .seealso: MatGetLocalSubMatrix()
9502 @*/
9503 PetscErrorCode  MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9504 {
9505   PetscErrorCode ierr;
9506 
9507   PetscFunctionBegin;
9508   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9509   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
9510   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
9511   PetscCheckSameComm(isrow,2,iscol,3);
9512   PetscValidPointer(submat,4);
9513   if (*submat) {
9514     PetscValidHeaderSpecific(*submat,MAT_CLASSID,4);
9515   }
9516 
9517   if (mat->ops->restorelocalsubmatrix) {
9518     ierr = (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
9519   } else {
9520     ierr = MatDestroy(submat);CHKERRQ(ierr);
9521   }
9522   *submat = NULL;
9523   PetscFunctionReturn(0);
9524 }
9525 
9526 /* --------------------------------------------------------*/
9527 #undef __FUNCT__
9528 #define __FUNCT__ "MatFindZeroDiagonals"
9529 /*@
9530    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no entry in the matrix
9531 
9532    Collective on Mat
9533 
9534    Input Parameter:
9535 .  mat - the matrix
9536 
9537    Output Parameter:
9538 .  is - if any rows have zero diagonals this contains the list of them
9539 
9540    Level: developer
9541 
9542    Concepts: matrix-vector product
9543 
9544 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9545 @*/
9546 PetscErrorCode  MatFindZeroDiagonals(Mat mat,IS *is)
9547 {
9548   PetscErrorCode ierr;
9549 
9550   PetscFunctionBegin;
9551   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9552   PetscValidType(mat,1);
9553   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9554   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9555 
9556   if (!mat->ops->findzerodiagonals) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find zero diagonals defined");
9557   ierr = (*mat->ops->findzerodiagonals)(mat,is);CHKERRQ(ierr);
9558   PetscFunctionReturn(0);
9559 }
9560 
9561 #undef __FUNCT__
9562 #define __FUNCT__ "MatFindOffBlockDiagonalEntries"
9563 /*@
9564    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
9565 
9566    Collective on Mat
9567 
9568    Input Parameter:
9569 .  mat - the matrix
9570 
9571    Output Parameter:
9572 .  is - contains the list of rows with off block diagonal entries
9573 
9574    Level: developer
9575 
9576    Concepts: matrix-vector product
9577 
9578 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9579 @*/
9580 PetscErrorCode  MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
9581 {
9582   PetscErrorCode ierr;
9583 
9584   PetscFunctionBegin;
9585   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9586   PetscValidType(mat,1);
9587   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9588   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9589 
9590   if (!mat->ops->findoffblockdiagonalentries) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find off block diagonal entries defined");
9591   ierr = (*mat->ops->findoffblockdiagonalentries)(mat,is);CHKERRQ(ierr);
9592   PetscFunctionReturn(0);
9593 }
9594 
9595 #undef __FUNCT__
9596 #define __FUNCT__ "MatInvertBlockDiagonal"
9597 /*@C
9598   MatInvertBlockDiagonal - Inverts the block diagonal entries.
9599 
9600   Collective on Mat
9601 
9602   Input Parameters:
9603 . mat - the matrix
9604 
9605   Output Parameters:
9606 . values - the block inverses in column major order (FORTRAN-like)
9607 
9608    Note:
9609    This routine is not available from Fortran.
9610 
9611   Level: advanced
9612 @*/
9613 PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
9614 {
9615   PetscErrorCode ierr;
9616 
9617   PetscFunctionBegin;
9618   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9619   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9620   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9621   if (!mat->ops->invertblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
9622   ierr = (*mat->ops->invertblockdiagonal)(mat,values);CHKERRQ(ierr);
9623   PetscFunctionReturn(0);
9624 }
9625 
9626 #undef __FUNCT__
9627 #define __FUNCT__ "MatTransposeColoringDestroy"
9628 /*@C
9629     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
9630     via MatTransposeColoringCreate().
9631 
9632     Collective on MatTransposeColoring
9633 
9634     Input Parameter:
9635 .   c - coloring context
9636 
9637     Level: intermediate
9638 
9639 .seealso: MatTransposeColoringCreate()
9640 @*/
9641 PetscErrorCode  MatTransposeColoringDestroy(MatTransposeColoring *c)
9642 {
9643   PetscErrorCode       ierr;
9644   MatTransposeColoring matcolor=*c;
9645 
9646   PetscFunctionBegin;
9647   if (!matcolor) PetscFunctionReturn(0);
9648   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; PetscFunctionReturn(0);}
9649 
9650   ierr = PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);CHKERRQ(ierr);
9651   ierr = PetscFree(matcolor->rows);CHKERRQ(ierr);
9652   ierr = PetscFree(matcolor->den2sp);CHKERRQ(ierr);
9653   ierr = PetscFree(matcolor->colorforcol);CHKERRQ(ierr);
9654   ierr = PetscFree(matcolor->columns);CHKERRQ(ierr);
9655   if (matcolor->brows>0) {
9656     ierr = PetscFree(matcolor->lstart);CHKERRQ(ierr);
9657   }
9658   ierr = PetscHeaderDestroy(c);CHKERRQ(ierr);
9659   PetscFunctionReturn(0);
9660 }
9661 
9662 #undef __FUNCT__
9663 #define __FUNCT__ "MatTransColoringApplySpToDen"
9664 /*@C
9665     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
9666     a MatTransposeColoring context has been created, computes a dense B^T by Apply
9667     MatTransposeColoring to sparse B.
9668 
9669     Collective on MatTransposeColoring
9670 
9671     Input Parameters:
9672 +   B - sparse matrix B
9673 .   Btdense - symbolic dense matrix B^T
9674 -   coloring - coloring context created with MatTransposeColoringCreate()
9675 
9676     Output Parameter:
9677 .   Btdense - dense matrix B^T
9678 
9679     Options Database Keys:
9680 +    -mat_transpose_coloring_view - Activates basic viewing or coloring
9681 .    -mat_transpose_coloring_view_draw - Activates drawing of coloring
9682 -    -mat_transpose_coloring_view_info - Activates viewing of coloring info
9683 
9684     Level: intermediate
9685 
9686 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy()
9687 
9688 .keywords: coloring
9689 @*/
9690 PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
9691 {
9692   PetscErrorCode ierr;
9693 
9694   PetscFunctionBegin;
9695   PetscValidHeaderSpecific(B,MAT_CLASSID,1);
9696   PetscValidHeaderSpecific(Btdense,MAT_CLASSID,2);
9697   PetscValidHeaderSpecific(coloring,MAT_TRANSPOSECOLORING_CLASSID,3);
9698 
9699   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
9700   ierr = (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);CHKERRQ(ierr);
9701   PetscFunctionReturn(0);
9702 }
9703 
9704 #undef __FUNCT__
9705 #define __FUNCT__ "MatTransColoringApplyDenToSp"
9706 /*@C
9707     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
9708     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
9709     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
9710     Csp from Cden.
9711 
9712     Collective on MatTransposeColoring
9713 
9714     Input Parameters:
9715 +   coloring - coloring context created with MatTransposeColoringCreate()
9716 -   Cden - matrix product of a sparse matrix and a dense matrix Btdense
9717 
9718     Output Parameter:
9719 .   Csp - sparse matrix
9720 
9721     Options Database Keys:
9722 +    -mat_multtranspose_coloring_view - Activates basic viewing or coloring
9723 .    -mat_multtranspose_coloring_view_draw - Activates drawing of coloring
9724 -    -mat_multtranspose_coloring_view_info - Activates viewing of coloring info
9725 
9726     Level: intermediate
9727 
9728 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
9729 
9730 .keywords: coloring
9731 @*/
9732 PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
9733 {
9734   PetscErrorCode ierr;
9735 
9736   PetscFunctionBegin;
9737   PetscValidHeaderSpecific(matcoloring,MAT_TRANSPOSECOLORING_CLASSID,1);
9738   PetscValidHeaderSpecific(Cden,MAT_CLASSID,2);
9739   PetscValidHeaderSpecific(Csp,MAT_CLASSID,3);
9740 
9741   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
9742   ierr = (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);CHKERRQ(ierr);
9743   PetscFunctionReturn(0);
9744 }
9745 
9746 #undef __FUNCT__
9747 #define __FUNCT__ "MatTransposeColoringCreate"
9748 /*@C
9749    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
9750 
9751    Collective on Mat
9752 
9753    Input Parameters:
9754 +  mat - the matrix product C
9755 -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
9756 
9757     Output Parameter:
9758 .   color - the new coloring context
9759 
9760     Level: intermediate
9761 
9762 .seealso: MatTransposeColoringDestroy(), MatTransposeColoringSetFromOptions(), MatTransColoringApplySpToDen(),
9763            MatTransColoringApplyDenToSp(), MatTransposeColoringView(),
9764 @*/
9765 PetscErrorCode  MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
9766 {
9767   MatTransposeColoring c;
9768   MPI_Comm             comm;
9769   PetscErrorCode       ierr;
9770 
9771   PetscFunctionBegin;
9772   ierr = PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
9773   ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
9774   ierr = PetscHeaderCreate(c,_p_MatTransposeColoring,int,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,0);CHKERRQ(ierr);
9775 
9776   c->ctype = iscoloring->ctype;
9777   if (mat->ops->transposecoloringcreate) {
9778     ierr = (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);CHKERRQ(ierr);
9779   } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for this matrix type");
9780 
9781   *color = c;
9782   ierr   = PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
9783   PetscFunctionReturn(0);
9784 }
9785 
9786 #undef __FUNCT__
9787 #define __FUNCT__ "MatGetNonzeroState"
9788 /*@
9789       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
9790         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
9791         same, otherwise it will be larger
9792 
9793      Not Collective
9794 
9795   Input Parameter:
9796 .    A  - the matrix
9797 
9798   Output Parameter:
9799 .    state - the current state
9800 
9801   Notes: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
9802          different matrices
9803 
9804   Level: intermediate
9805 
9806 @*/
9807 PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
9808 {
9809   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9810   *state = mat->nonzerostate;
9811   PetscFunctionReturn(0);
9812 }
9813 
9814 #undef __FUNCT__
9815 #define __FUNCT__ "MatCreateMPIMatConcatenateSeqMat"
9816 /*@
9817       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
9818                  matrices from each processor
9819 
9820     Collective on MPI_Comm
9821 
9822    Input Parameters:
9823 +    comm - the communicators the parallel matrix will live on
9824 .    seqmat - the input sequential matrices
9825 .    n - number of local columns (or PETSC_DECIDE)
9826 -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9827 
9828    Output Parameter:
9829 .    mpimat - the parallel matrix generated
9830 
9831     Level: advanced
9832 
9833    Notes: The number of columns of the matrix in EACH processor MUST be the same.
9834 
9835 @*/
9836 PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
9837 {
9838   PetscErrorCode ierr;
9839   PetscMPIInt    size;
9840 
9841   PetscFunctionBegin;
9842   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
9843   if (size == 1) {
9844     if (reuse == MAT_INITIAL_MATRIX) {
9845       ierr = MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);CHKERRQ(ierr);
9846     } else {
9847       ierr = MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
9848     }
9849     PetscFunctionReturn(0);
9850   }
9851 
9852   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
9853   ierr = PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
9854   ierr = (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);CHKERRQ(ierr);
9855   ierr = PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
9856   PetscFunctionReturn(0);
9857 }
9858