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