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