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