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