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