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