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