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