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