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