xref: /petsc/src/mat/interface/matrix.c (revision 4e278199b78715991f5c71ebbd945c1489263e6c)
1 /*
2    This is where the abstract matrix operations are defined
3 */
4 
5 #include <petsc/private/matimpl.h>        /*I "petscmat.h" I*/
6 #include <petsc/private/isimpl.h>
7 #include <petsc/private/vecimpl.h>
8 
9 /* Logging support */
10 PetscClassId MAT_CLASSID;
11 PetscClassId MAT_COLORING_CLASSID;
12 PetscClassId MAT_FDCOLORING_CLASSID;
13 PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
14 
15 PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
16 PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve,MAT_MatTrSolve;
17 PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
18 PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
19 PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
20 PetscLogEvent MAT_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 
44 const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","QR","MatFactorType","MAT_FACTOR_",NULL};
45 
46 /*@
47    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,
48                   for sparse matrices that already have locations it fills the locations with random numbers
49 
50    Logically Collective on Mat
51 
52    Input Parameters:
53 +  x  - the matrix
54 -  rctx - the random number context, formed by PetscRandomCreate(), or NULL and
55           it will create one internally.
56 
57    Output Parameter:
58 .  x  - the matrix
59 
60    Example of Usage:
61 .vb
62      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
63      MatSetRandom(x,rctx);
64      PetscRandomDestroy(rctx);
65 .ve
66 
67    Level: intermediate
68 
69 .seealso: MatZeroEntries(), MatSetValues(), PetscRandomCreate(), PetscRandomDestroy()
70 @*/
71 PetscErrorCode MatSetRandom(Mat x,PetscRandom rctx)
72 {
73   PetscErrorCode ierr;
74   PetscRandom    randObj = NULL;
75 
76   PetscFunctionBegin;
77   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
78   if (rctx) PetscValidHeaderSpecific(rctx,PETSC_RANDOM_CLASSID,2);
79   PetscValidType(x,1);
80 
81   if (!x->ops->setrandom) SETERRQ1(PetscObjectComm((PetscObject)x),PETSC_ERR_SUP,"Mat type %s",((PetscObject)x)->type_name);
82 
83   if (!rctx) {
84     MPI_Comm comm;
85     ierr = PetscObjectGetComm((PetscObject)x,&comm);CHKERRQ(ierr);
86     ierr = PetscRandomCreate(comm,&randObj);CHKERRQ(ierr);
87     ierr = PetscRandomSetFromOptions(randObj);CHKERRQ(ierr);
88     rctx = randObj;
89   }
90 
91   ierr = PetscLogEventBegin(MAT_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
92   ierr = (*x->ops->setrandom)(x,rctx);CHKERRQ(ierr);
93   ierr = PetscLogEventEnd(MAT_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
94 
95   ierr = MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
96   ierr = MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
97   ierr = PetscRandomDestroy(&randObj);CHKERRQ(ierr);
98   PetscFunctionReturn(0);
99 }
100 
101 /*@
102    MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
103 
104    Logically Collective on Mat
105 
106    Input Parameters:
107 .  mat - the factored matrix
108 
109    Output Parameter:
110 +  pivot - the pivot value computed
111 -  row - the row that the zero pivot occurred. Note that this row must be interpreted carefully due to row reorderings and which processes
112          the share the matrix
113 
114    Level: advanced
115 
116    Notes:
117     This routine does not work for factorizations done with external packages.
118 
119     This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT
120 
121     This can be called on non-factored matrices that come from, for example, matrices used in SOR.
122 
123 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
124 @*/
125 PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat,PetscReal *pivot,PetscInt *row)
126 {
127   PetscFunctionBegin;
128   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
129   *pivot = mat->factorerror_zeropivot_value;
130   *row   = mat->factorerror_zeropivot_row;
131   PetscFunctionReturn(0);
132 }
133 
134 /*@
135    MatFactorGetError - gets the error code from a factorization
136 
137    Logically Collective on Mat
138 
139    Input Parameters:
140 .  mat - the factored matrix
141 
142    Output Parameter:
143 .  err  - the error code
144 
145    Level: advanced
146 
147    Notes:
148     This can be called on non-factored matrices that come from, for example, matrices used in SOR.
149 
150 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
151 @*/
152 PetscErrorCode MatFactorGetError(Mat mat,MatFactorError *err)
153 {
154   PetscFunctionBegin;
155   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
156   *err = mat->factorerrortype;
157   PetscFunctionReturn(0);
158 }
159 
160 /*@
161    MatFactorClearError - clears the error code in a factorization
162 
163    Logically Collective on Mat
164 
165    Input Parameter:
166 .  mat - the factored matrix
167 
168    Level: developer
169 
170    Notes:
171     This can be called on non-factored matrices that come from, for example, matrices used in SOR.
172 
173 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic(), MatFactorGetError(), MatFactorGetErrorZeroPivot()
174 @*/
175 PetscErrorCode MatFactorClearError(Mat mat)
176 {
177   PetscFunctionBegin;
178   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
179   mat->factorerrortype             = MAT_FACTOR_NOERROR;
180   mat->factorerror_zeropivot_value = 0.0;
181   mat->factorerror_zeropivot_row   = 0;
182   PetscFunctionReturn(0);
183 }
184 
185 PETSC_INTERN PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat,PetscBool cols,PetscReal tol,IS *nonzero)
186 {
187   PetscErrorCode    ierr;
188   Vec               r,l;
189   const PetscScalar *al;
190   PetscInt          i,nz,gnz,N,n;
191 
192   PetscFunctionBegin;
193   ierr = MatCreateVecs(mat,&r,&l);CHKERRQ(ierr);
194   if (!cols) { /* nonzero rows */
195     ierr = MatGetSize(mat,&N,NULL);CHKERRQ(ierr);
196     ierr = MatGetLocalSize(mat,&n,NULL);CHKERRQ(ierr);
197     ierr = VecSet(l,0.0);CHKERRQ(ierr);
198     ierr = VecSetRandom(r,NULL);CHKERRQ(ierr);
199     ierr = MatMult(mat,r,l);CHKERRQ(ierr);
200     ierr = VecGetArrayRead(l,&al);CHKERRQ(ierr);
201   } else { /* nonzero columns */
202     ierr = MatGetSize(mat,NULL,&N);CHKERRQ(ierr);
203     ierr = MatGetLocalSize(mat,NULL,&n);CHKERRQ(ierr);
204     ierr = VecSet(r,0.0);CHKERRQ(ierr);
205     ierr = VecSetRandom(l,NULL);CHKERRQ(ierr);
206     ierr = MatMultTranspose(mat,l,r);CHKERRQ(ierr);
207     ierr = VecGetArrayRead(r,&al);CHKERRQ(ierr);
208   }
209   if (tol <= 0.0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nz++; }
210   else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nz++; }
211   ierr = MPIU_Allreduce(&nz,&gnz,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)mat));CHKERRMPI(ierr);
212   if (gnz != N) {
213     PetscInt *nzr;
214     ierr = PetscMalloc1(nz,&nzr);CHKERRQ(ierr);
215     if (nz) {
216       if (tol < 0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nzr[nz++] = i; }
217       else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i; }
218     }
219     ierr = ISCreateGeneral(PetscObjectComm((PetscObject)mat),nz,nzr,PETSC_OWN_POINTER,nonzero);CHKERRQ(ierr);
220   } else *nonzero = NULL;
221   if (!cols) { /* nonzero rows */
222     ierr = VecRestoreArrayRead(l,&al);CHKERRQ(ierr);
223   } else {
224     ierr = VecRestoreArrayRead(r,&al);CHKERRQ(ierr);
225   }
226   ierr = VecDestroy(&l);CHKERRQ(ierr);
227   ierr = VecDestroy(&r);CHKERRQ(ierr);
228   PetscFunctionReturn(0);
229 }
230 
231 /*@
232       MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
233 
234   Input Parameter:
235 .    A  - the matrix
236 
237   Output Parameter:
238 .    keptrows - the rows that are not completely zero
239 
240   Notes:
241     keptrows is set to NULL if all rows are nonzero.
242 
243   Level: intermediate
244 
245  @*/
246 PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
247 {
248   PetscErrorCode ierr;
249 
250   PetscFunctionBegin;
251   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
252   PetscValidType(mat,1);
253   PetscValidPointer(keptrows,2);
254   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
255   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
256   if (!mat->ops->findnonzerorows) {
257     ierr = MatFindNonzeroRowsOrCols_Basic(mat,PETSC_FALSE,0.0,keptrows);CHKERRQ(ierr);
258   } else {
259     ierr = (*mat->ops->findnonzerorows)(mat,keptrows);CHKERRQ(ierr);
260   }
261   PetscFunctionReturn(0);
262 }
263 
264 /*@
265       MatFindZeroRows - Locate all rows that are completely zero in the matrix
266 
267   Input Parameter:
268 .    A  - the matrix
269 
270   Output Parameter:
271 .    zerorows - the rows that are completely zero
272 
273   Notes:
274     zerorows is set to NULL if no rows are zero.
275 
276   Level: intermediate
277 
278  @*/
279 PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
280 {
281   PetscErrorCode ierr;
282   IS keptrows;
283   PetscInt m, n;
284 
285   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
286   PetscValidType(mat,1);
287 
288   ierr = MatFindNonzeroRows(mat, &keptrows);CHKERRQ(ierr);
289   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
290      In keeping with this convention, we set zerorows to NULL if there are no zero
291      rows. */
292   if (keptrows == NULL) {
293     *zerorows = NULL;
294   } else {
295     ierr = MatGetOwnershipRange(mat,&m,&n);CHKERRQ(ierr);
296     ierr = ISComplement(keptrows,m,n,zerorows);CHKERRQ(ierr);
297     ierr = ISDestroy(&keptrows);CHKERRQ(ierr);
298   }
299   PetscFunctionReturn(0);
300 }
301 
302 /*@
303    MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
304 
305    Not Collective
306 
307    Input Parameters:
308 .   A - the matrix
309 
310    Output Parameters:
311 .   a - the diagonal part (which is a SEQUENTIAL matrix)
312 
313    Notes:
314     see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.
315           Use caution, as the reference count on the returned matrix is not incremented and it is used as
316           part of the containing MPI Mat's normal operation.
317 
318    Level: advanced
319 
320 @*/
321 PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
322 {
323   PetscErrorCode ierr;
324 
325   PetscFunctionBegin;
326   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
327   PetscValidType(A,1);
328   PetscValidPointer(a,2);
329   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
330   if (!A->ops->getdiagonalblock) {
331     PetscMPIInt size;
332     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRMPI(ierr);
333     if (size == 1) {
334       *a = A;
335       PetscFunctionReturn(0);
336     } else SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Not coded for matrix type %s",((PetscObject)A)->type_name);
337   }
338   ierr = (*A->ops->getdiagonalblock)(A,a);CHKERRQ(ierr);
339   PetscFunctionReturn(0);
340 }
341 
342 /*@
343    MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
344 
345    Collective on Mat
346 
347    Input Parameters:
348 .  mat - the matrix
349 
350    Output Parameter:
351 .   trace - the sum of the diagonal entries
352 
353    Level: advanced
354 
355 @*/
356 PetscErrorCode MatGetTrace(Mat mat,PetscScalar *trace)
357 {
358   PetscErrorCode ierr;
359   Vec            diag;
360 
361   PetscFunctionBegin;
362   ierr = MatCreateVecs(mat,&diag,NULL);CHKERRQ(ierr);
363   ierr = MatGetDiagonal(mat,diag);CHKERRQ(ierr);
364   ierr = VecSum(diag,trace);CHKERRQ(ierr);
365   ierr = VecDestroy(&diag);CHKERRQ(ierr);
366   PetscFunctionReturn(0);
367 }
368 
369 /*@
370    MatRealPart - Zeros out the imaginary part of the matrix
371 
372    Logically Collective on Mat
373 
374    Input Parameters:
375 .  mat - the matrix
376 
377    Level: advanced
378 
379 .seealso: MatImaginaryPart()
380 @*/
381 PetscErrorCode MatRealPart(Mat mat)
382 {
383   PetscErrorCode ierr;
384 
385   PetscFunctionBegin;
386   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
387   PetscValidType(mat,1);
388   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
389   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
390   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
391   MatCheckPreallocated(mat,1);
392   ierr = (*mat->ops->realpart)(mat);CHKERRQ(ierr);
393   PetscFunctionReturn(0);
394 }
395 
396 /*@C
397    MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix
398 
399    Collective on Mat
400 
401    Input Parameter:
402 .  mat - the matrix
403 
404    Output Parameters:
405 +   nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
406 -   ghosts - the global indices of the ghost points
407 
408    Notes:
409     the nghosts and ghosts are suitable to pass into VecCreateGhost()
410 
411    Level: advanced
412 
413 @*/
414 PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
415 {
416   PetscErrorCode ierr;
417 
418   PetscFunctionBegin;
419   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
420   PetscValidType(mat,1);
421   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
422   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
423   if (!mat->ops->getghosts) {
424     if (nghosts) *nghosts = 0;
425     if (ghosts) *ghosts = NULL;
426   } else {
427     ierr = (*mat->ops->getghosts)(mat,nghosts,ghosts);CHKERRQ(ierr);
428   }
429   PetscFunctionReturn(0);
430 }
431 
432 /*@
433    MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
434 
435    Logically Collective on Mat
436 
437    Input Parameters:
438 .  mat - the matrix
439 
440    Level: advanced
441 
442 .seealso: MatRealPart()
443 @*/
444 PetscErrorCode MatImaginaryPart(Mat mat)
445 {
446   PetscErrorCode ierr;
447 
448   PetscFunctionBegin;
449   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
450   PetscValidType(mat,1);
451   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
452   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
453   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
454   MatCheckPreallocated(mat,1);
455   ierr = (*mat->ops->imaginarypart)(mat);CHKERRQ(ierr);
456   PetscFunctionReturn(0);
457 }
458 
459 /*@
460    MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)
461 
462    Not Collective
463 
464    Input Parameter:
465 .  mat - the matrix
466 
467    Output Parameters:
468 +  missing - is any diagonal missing
469 -  dd - first diagonal entry that is missing (optional) on this process
470 
471    Level: advanced
472 
473 .seealso: MatRealPart()
474 @*/
475 PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
476 {
477   PetscErrorCode ierr;
478 
479   PetscFunctionBegin;
480   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
481   PetscValidType(mat,1);
482   PetscValidPointer(missing,2);
483   if (!mat->assembled) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix %s",((PetscObject)mat)->type_name);
484   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
485   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
486   ierr = (*mat->ops->missingdiagonal)(mat,missing,dd);CHKERRQ(ierr);
487   PetscFunctionReturn(0);
488 }
489 
490 /*@C
491    MatGetRow - Gets a row of a matrix.  You MUST call MatRestoreRow()
492    for each row that you get to ensure that your application does
493    not bleed memory.
494 
495    Not Collective
496 
497    Input Parameters:
498 +  mat - the matrix
499 -  row - the row to get
500 
501    Output Parameters:
502 +  ncols -  if not NULL, the number of nonzeros in the row
503 .  cols - if not NULL, the column numbers
504 -  vals - if not NULL, the values
505 
506    Notes:
507    This routine is provided for people who need to have direct access
508    to the structure of a matrix.  We hope that we provide enough
509    high-level matrix routines that few users will need it.
510 
511    MatGetRow() always returns 0-based column indices, regardless of
512    whether the internal representation is 0-based (default) or 1-based.
513 
514    For better efficiency, set cols and/or vals to NULL if you do
515    not wish to extract these quantities.
516 
517    The user can only examine the values extracted with MatGetRow();
518    the values cannot be altered.  To change the matrix entries, one
519    must use MatSetValues().
520 
521    You can only have one call to MatGetRow() outstanding for a particular
522    matrix at a time, per processor. MatGetRow() can only obtain rows
523    associated with the given processor, it cannot get rows from the
524    other processors; for that we suggest using MatCreateSubMatrices(), then
525    MatGetRow() on the submatrix. The row index passed to MatGetRow()
526    is in the global number of rows.
527 
528    Fortran Notes:
529    The calling sequence from Fortran is
530 .vb
531    MatGetRow(matrix,row,ncols,cols,values,ierr)
532          Mat     matrix (input)
533          integer row    (input)
534          integer ncols  (output)
535          integer cols(maxcols) (output)
536          double precision (or double complex) values(maxcols) output
537 .ve
538    where maxcols >= maximum nonzeros in any row of the matrix.
539 
540    Caution:
541    Do not try to change the contents of the output arrays (cols and vals).
542    In some cases, this may corrupt the matrix.
543 
544    Level: advanced
545 
546 .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
547 @*/
548 PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
549 {
550   PetscErrorCode ierr;
551   PetscInt       incols;
552 
553   PetscFunctionBegin;
554   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
555   PetscValidType(mat,1);
556   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
557   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
558   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
559   MatCheckPreallocated(mat,1);
560   if (row < mat->rmap->rstart || row >= mat->rmap->rend) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Only for local rows, %D not in [%D,%D)",row,mat->rmap->rstart,mat->rmap->rend);
561   ierr = PetscLogEventBegin(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
562   ierr = (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);CHKERRQ(ierr);
563   if (ncols) *ncols = incols;
564   ierr = PetscLogEventEnd(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
565   PetscFunctionReturn(0);
566 }
567 
568 /*@
569    MatConjugate - replaces the matrix values with their complex conjugates
570 
571    Logically Collective on Mat
572 
573    Input Parameters:
574 .  mat - the matrix
575 
576    Level: advanced
577 
578 .seealso:  VecConjugate()
579 @*/
580 PetscErrorCode MatConjugate(Mat mat)
581 {
582 #if defined(PETSC_USE_COMPLEX)
583   PetscErrorCode ierr;
584 
585   PetscFunctionBegin;
586   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
587   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
588   if (!mat->ops->conjugate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not provided for matrix type %s, send email to petsc-maint@mcs.anl.gov",((PetscObject)mat)->type_name);
589   ierr = (*mat->ops->conjugate)(mat);CHKERRQ(ierr);
590 #else
591   PetscFunctionBegin;
592 #endif
593   PetscFunctionReturn(0);
594 }
595 
596 /*@C
597    MatRestoreRow - Frees any temporary space allocated by MatGetRow().
598 
599    Not Collective
600 
601    Input Parameters:
602 +  mat - the matrix
603 .  row - the row to get
604 .  ncols, cols - the number of nonzeros and their columns
605 -  vals - if nonzero the column values
606 
607    Notes:
608    This routine should be called after you have finished examining the entries.
609 
610    This routine zeros out ncols, cols, and vals. This is to prevent accidental
611    us of the array after it has been restored. If you pass NULL, it will
612    not zero the pointers.  Use of cols or vals after MatRestoreRow is invalid.
613 
614    Fortran Notes:
615    The calling sequence from Fortran is
616 .vb
617    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
618       Mat     matrix (input)
619       integer row    (input)
620       integer ncols  (output)
621       integer cols(maxcols) (output)
622       double precision (or double complex) values(maxcols) output
623 .ve
624    Where maxcols >= maximum nonzeros in any row of the matrix.
625 
626    In Fortran MatRestoreRow() MUST be called after MatGetRow()
627    before another call to MatGetRow() can be made.
628 
629    Level: advanced
630 
631 .seealso:  MatGetRow()
632 @*/
633 PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
634 {
635   PetscErrorCode ierr;
636 
637   PetscFunctionBegin;
638   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
639   if (ncols) PetscValidIntPointer(ncols,3);
640   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
641   if (!mat->ops->restorerow) PetscFunctionReturn(0);
642   ierr = (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);CHKERRQ(ierr);
643   if (ncols) *ncols = 0;
644   if (cols)  *cols = NULL;
645   if (vals)  *vals = NULL;
646   PetscFunctionReturn(0);
647 }
648 
649 /*@
650    MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
651    You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.
652 
653    Not Collective
654 
655    Input Parameters:
656 .  mat - the matrix
657 
658    Notes:
659    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.
660 
661    Level: advanced
662 
663 .seealso: MatRestoreRowUpperTriangular()
664 @*/
665 PetscErrorCode MatGetRowUpperTriangular(Mat mat)
666 {
667   PetscErrorCode ierr;
668 
669   PetscFunctionBegin;
670   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
671   PetscValidType(mat,1);
672   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
673   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
674   MatCheckPreallocated(mat,1);
675   if (!mat->ops->getrowuppertriangular) PetscFunctionReturn(0);
676   ierr = (*mat->ops->getrowuppertriangular)(mat);CHKERRQ(ierr);
677   PetscFunctionReturn(0);
678 }
679 
680 /*@
681    MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.
682 
683    Not Collective
684 
685    Input Parameters:
686 .  mat - the matrix
687 
688    Notes:
689    This routine should be called after you have finished MatGetRow/MatRestoreRow().
690 
691    Level: advanced
692 
693 .seealso:  MatGetRowUpperTriangular()
694 @*/
695 PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
696 {
697   PetscErrorCode ierr;
698 
699   PetscFunctionBegin;
700   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
701   PetscValidType(mat,1);
702   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
703   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
704   MatCheckPreallocated(mat,1);
705   if (!mat->ops->restorerowuppertriangular) PetscFunctionReturn(0);
706   ierr = (*mat->ops->restorerowuppertriangular)(mat);CHKERRQ(ierr);
707   PetscFunctionReturn(0);
708 }
709 
710 /*@C
711    MatSetOptionsPrefix - Sets the prefix used for searching for all
712    Mat options in the database.
713 
714    Logically Collective on Mat
715 
716    Input Parameter:
717 +  A - the Mat context
718 -  prefix - the prefix to prepend to all option names
719 
720    Notes:
721    A hyphen (-) must NOT be given at the beginning of the prefix name.
722    The first character of all runtime options is AUTOMATICALLY the hyphen.
723 
724    Level: advanced
725 
726 .seealso: MatSetFromOptions()
727 @*/
728 PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
729 {
730   PetscErrorCode ierr;
731 
732   PetscFunctionBegin;
733   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
734   ierr = PetscObjectSetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
735   PetscFunctionReturn(0);
736 }
737 
738 /*@C
739    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
740    Mat options in the database.
741 
742    Logically Collective on Mat
743 
744    Input Parameters:
745 +  A - the Mat context
746 -  prefix - the prefix to prepend to all option names
747 
748    Notes:
749    A hyphen (-) must NOT be given at the beginning of the prefix name.
750    The first character of all runtime options is AUTOMATICALLY the hyphen.
751 
752    Level: advanced
753 
754 .seealso: MatGetOptionsPrefix()
755 @*/
756 PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
757 {
758   PetscErrorCode ierr;
759 
760   PetscFunctionBegin;
761   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
762   ierr = PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
763   PetscFunctionReturn(0);
764 }
765 
766 /*@C
767    MatGetOptionsPrefix - Gets the prefix used for searching for all
768    Mat options in the database.
769 
770    Not Collective
771 
772    Input Parameter:
773 .  A - the Mat context
774 
775    Output Parameter:
776 .  prefix - pointer to the prefix string used
777 
778    Notes:
779     On the fortran side, the user should pass in a string 'prefix' of
780    sufficient length to hold the prefix.
781 
782    Level: advanced
783 
784 .seealso: MatAppendOptionsPrefix()
785 @*/
786 PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
787 {
788   PetscErrorCode ierr;
789 
790   PetscFunctionBegin;
791   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
792   ierr = PetscObjectGetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
793   PetscFunctionReturn(0);
794 }
795 
796 /*@
797    MatResetPreallocation - Reset mat to use the original nonzero pattern provided by users.
798 
799    Collective on Mat
800 
801    Input Parameters:
802 .  A - the Mat context
803 
804    Notes:
805    The allocated memory will be shrunk after calling MatAssembly with MAT_FINAL_ASSEMBLY. Users can reset the preallocation to access the original memory.
806    Currently support MPIAIJ and SEQAIJ.
807 
808    Level: beginner
809 
810 .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
811 @*/
812 PetscErrorCode MatResetPreallocation(Mat A)
813 {
814   PetscErrorCode ierr;
815 
816   PetscFunctionBegin;
817   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
818   PetscValidType(A,1);
819   ierr = PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));CHKERRQ(ierr);
820   PetscFunctionReturn(0);
821 }
822 
823 /*@
824    MatSetUp - Sets up the internal matrix data structures for later use.
825 
826    Collective on Mat
827 
828    Input Parameters:
829 .  A - the Mat context
830 
831    Notes:
832    If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.
833 
834    If a suitable preallocation routine is used, this function does not need to be called.
835 
836    See the Performance chapter of the PETSc users manual for how to preallocate matrices
837 
838    Level: beginner
839 
840 .seealso: MatCreate(), MatDestroy()
841 @*/
842 PetscErrorCode MatSetUp(Mat A)
843 {
844   PetscMPIInt    size;
845   PetscErrorCode ierr;
846 
847   PetscFunctionBegin;
848   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
849   if (!((PetscObject)A)->type_name) {
850     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);CHKERRMPI(ierr);
851     if (size == 1) {
852       ierr = MatSetType(A, MATSEQAIJ);CHKERRQ(ierr);
853     } else {
854       ierr = MatSetType(A, MATMPIAIJ);CHKERRQ(ierr);
855     }
856   }
857   if (!A->preallocated && A->ops->setup) {
858     ierr = PetscInfo(A,"Warning not preallocating matrix storage\n");CHKERRQ(ierr);
859     ierr = (*A->ops->setup)(A);CHKERRQ(ierr);
860   }
861   ierr = PetscLayoutSetUp(A->rmap);CHKERRQ(ierr);
862   ierr = PetscLayoutSetUp(A->cmap);CHKERRQ(ierr);
863   A->preallocated = PETSC_TRUE;
864   PetscFunctionReturn(0);
865 }
866 
867 #if defined(PETSC_HAVE_SAWS)
868 #include <petscviewersaws.h>
869 #endif
870 
871 /*@C
872    MatViewFromOptions - View from Options
873 
874    Collective on Mat
875 
876    Input Parameters:
877 +  A - the Mat context
878 .  obj - Optional object
879 -  name - command line option
880 
881    Level: intermediate
882 .seealso:  Mat, MatView, PetscObjectViewFromOptions(), MatCreate()
883 @*/
884 PetscErrorCode  MatViewFromOptions(Mat A,PetscObject obj,const char name[])
885 {
886   PetscErrorCode ierr;
887 
888   PetscFunctionBegin;
889   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
890   ierr = PetscObjectViewFromOptions((PetscObject)A,obj,name);CHKERRQ(ierr);
891   PetscFunctionReturn(0);
892 }
893 
894 /*@C
895    MatView - Visualizes a matrix object.
896 
897    Collective on Mat
898 
899    Input Parameters:
900 +  mat - the matrix
901 -  viewer - visualization context
902 
903   Notes:
904   The available visualization contexts include
905 +    PETSC_VIEWER_STDOUT_SELF - for sequential matrices
906 .    PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
907 .    PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
908 -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
909 
910    The user can open alternative visualization contexts with
911 +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
912 .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
913          specified file; corresponding input uses MatLoad()
914 .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
915          an X window display
916 -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
917          Currently only the sequential dense and AIJ
918          matrix types support the Socket viewer.
919 
920    The user can call PetscViewerPushFormat() to specify the output
921    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
922    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
923 +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
924 .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
925 .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
926 .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
927          format common among all matrix types
928 .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
929          format (which is in many cases the same as the default)
930 .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
931          size and structure (not the matrix entries)
932 -    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
933          the matrix structure
934 
935    Options Database Keys:
936 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
937 .  -mat_view ::ascii_info_detail - Prints more detailed info
938 .  -mat_view - Prints matrix in ASCII format
939 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
940 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
941 .  -display <name> - Sets display name (default is host)
942 .  -draw_pause <sec> - Sets number of seconds to pause after display
943 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: ch_matlab for details)
944 .  -viewer_socket_machine <machine> -
945 .  -viewer_socket_port <port> -
946 .  -mat_view binary - save matrix to file in binary format
947 -  -viewer_binary_filename <name> -
948    Level: beginner
949 
950    Notes:
951     The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
952     the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
953 
954     In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).
955 
956     See the manual page for MatLoad() for the exact format of the binary file when the binary
957       viewer is used.
958 
959       See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
960       viewer is used and lib/petsc/bin/PetscBinaryIO.py for loading them into Python.
961 
962       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
963       and then use the following mouse functions.
964 + left mouse: zoom in
965 . middle mouse: zoom out
966 - right mouse: continue with the simulation
967 
968 .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
969           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
970 @*/
971 PetscErrorCode MatView(Mat mat,PetscViewer viewer)
972 {
973   PetscErrorCode    ierr;
974   PetscInt          rows,cols,rbs,cbs;
975   PetscBool         isascii,isstring,issaws;
976   PetscViewerFormat format;
977   PetscMPIInt       size;
978 
979   PetscFunctionBegin;
980   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
981   PetscValidType(mat,1);
982   if (!viewer) {ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);CHKERRQ(ierr);}
983   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
984   PetscCheckSameComm(mat,1,viewer,2);
985   MatCheckPreallocated(mat,1);
986 
987   ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
988   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRMPI(ierr);
989   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(0);
990 
991   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
992   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);CHKERRQ(ierr);
993   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);CHKERRQ(ierr);
994   if ((!isascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
995     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detail");
996   }
997 
998   ierr = PetscLogEventBegin(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
999   if (isascii) {
1000     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1001     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);CHKERRQ(ierr);
1002     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1003       MatNullSpace nullsp,transnullsp;
1004 
1005       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1006       ierr = MatGetSize(mat,&rows,&cols);CHKERRQ(ierr);
1007       ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
1008       if (rbs != 1 || cbs != 1) {
1009         if (rbs != cbs) {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs=%D\n",rows,cols,rbs,cbs);CHKERRQ(ierr);}
1010         else            {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);CHKERRQ(ierr);}
1011       } else {
1012         ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);CHKERRQ(ierr);
1013       }
1014       if (mat->factortype) {
1015         MatSolverType solver;
1016         ierr = MatFactorGetSolverType(mat,&solver);CHKERRQ(ierr);
1017         ierr = PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);CHKERRQ(ierr);
1018       }
1019       if (mat->ops->getinfo) {
1020         MatInfo info;
1021         ierr = MatGetInfo(mat,MAT_GLOBAL_SUM,&info);CHKERRQ(ierr);
1022         ierr = PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);CHKERRQ(ierr);
1023         if (!mat->factortype) {
1024           ierr = PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls=%D\n",(PetscInt)info.mallocs);CHKERRQ(ierr);
1025         }
1026       }
1027       ierr = MatGetNullSpace(mat,&nullsp);CHKERRQ(ierr);
1028       ierr = MatGetTransposeNullSpace(mat,&transnullsp);CHKERRQ(ierr);
1029       if (nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached null space\n");CHKERRQ(ierr);}
1030       if (transnullsp && transnullsp != nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached transposed null space\n");CHKERRQ(ierr);}
1031       ierr = MatGetNearNullSpace(mat,&nullsp);CHKERRQ(ierr);
1032       if (nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");CHKERRQ(ierr);}
1033       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1034       ierr = MatProductView(mat,viewer);CHKERRQ(ierr);
1035       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1036     }
1037   } else if (issaws) {
1038 #if defined(PETSC_HAVE_SAWS)
1039     PetscMPIInt rank;
1040 
1041     ierr = PetscObjectName((PetscObject)mat);CHKERRQ(ierr);
1042     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRMPI(ierr);
1043     if (!((PetscObject)mat)->amsmem && !rank) {
1044       ierr = PetscObjectViewSAWs((PetscObject)mat,viewer);CHKERRQ(ierr);
1045     }
1046 #endif
1047   } else if (isstring) {
1048     const char *type;
1049     ierr = MatGetType(mat,&type);CHKERRQ(ierr);
1050     ierr = PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);CHKERRQ(ierr);
1051     if (mat->ops->view) {ierr = (*mat->ops->view)(mat,viewer);CHKERRQ(ierr);}
1052   }
1053   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1054     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1055     ierr = (*mat->ops->viewnative)(mat,viewer);CHKERRQ(ierr);
1056     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1057   } else if (mat->ops->view) {
1058     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1059     ierr = (*mat->ops->view)(mat,viewer);CHKERRQ(ierr);
1060     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1061   }
1062   if (isascii) {
1063     ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
1064     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1065       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1066     }
1067   }
1068   ierr = PetscLogEventEnd(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
1069   PetscFunctionReturn(0);
1070 }
1071 
1072 #if defined(PETSC_USE_DEBUG)
1073 #include <../src/sys/totalview/tv_data_display.h>
1074 PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1075 {
1076   TV_add_row("Local rows", "int", &mat->rmap->n);
1077   TV_add_row("Local columns", "int", &mat->cmap->n);
1078   TV_add_row("Global rows", "int", &mat->rmap->N);
1079   TV_add_row("Global columns", "int", &mat->cmap->N);
1080   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1081   return TV_format_OK;
1082 }
1083 #endif
1084 
1085 /*@C
1086    MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1087    with MatView().  The matrix format is determined from the options database.
1088    Generates a parallel MPI matrix if the communicator has more than one
1089    processor.  The default matrix type is AIJ.
1090 
1091    Collective on PetscViewer
1092 
1093    Input Parameters:
1094 +  mat - the newly loaded matrix, this needs to have been created with MatCreate()
1095             or some related function before a call to MatLoad()
1096 -  viewer - binary/HDF5 file viewer
1097 
1098    Options Database Keys:
1099    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1100    block size
1101 .    -matload_block_size <bs>
1102 
1103    Level: beginner
1104 
1105    Notes:
1106    If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1107    Mat before calling this routine if you wish to set it from the options database.
1108 
1109    MatLoad() automatically loads into the options database any options
1110    given in the file filename.info where filename is the name of the file
1111    that was passed to the PetscViewerBinaryOpen(). The options in the info
1112    file will be ignored if you use the -viewer_binary_skip_info option.
1113 
1114    If the type or size of mat is not set before a call to MatLoad, PETSc
1115    sets the default matrix type AIJ and sets the local and global sizes.
1116    If type and/or size is already set, then the same are used.
1117 
1118    In parallel, each processor can load a subset of rows (or the
1119    entire matrix).  This routine is especially useful when a large
1120    matrix is stored on disk and only part of it is desired on each
1121    processor.  For example, a parallel solver may access only some of
1122    the rows from each processor.  The algorithm used here reads
1123    relatively small blocks of data rather than reading the entire
1124    matrix and then subsetting it.
1125 
1126    Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1127    Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1128    or the sequence like
1129 $    PetscViewer v;
1130 $    PetscViewerCreate(PETSC_COMM_WORLD,&v);
1131 $    PetscViewerSetType(v,PETSCVIEWERBINARY);
1132 $    PetscViewerSetFromOptions(v);
1133 $    PetscViewerFileSetMode(v,FILE_MODE_READ);
1134 $    PetscViewerFileSetName(v,"datafile");
1135    The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1136 $ -viewer_type {binary,hdf5}
1137 
1138    See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1139    and src/mat/tutorials/ex10.c with the second approach.
1140 
1141    Notes about the PETSc binary format:
1142    In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1143    is read onto rank 0 and then shipped to its destination rank, one after another.
1144    Multiple objects, both matrices and vectors, can be stored within the same file.
1145    Their PetscObject name is ignored; they are loaded in the order of their storage.
1146 
1147    Most users should not need to know the details of the binary storage
1148    format, since MatLoad() and MatView() completely hide these details.
1149    But for anyone who's interested, the standard binary matrix storage
1150    format is
1151 
1152 $    PetscInt    MAT_FILE_CLASSID
1153 $    PetscInt    number of rows
1154 $    PetscInt    number of columns
1155 $    PetscInt    total number of nonzeros
1156 $    PetscInt    *number nonzeros in each row
1157 $    PetscInt    *column indices of all nonzeros (starting index is zero)
1158 $    PetscScalar *values of all nonzeros
1159 
1160    PETSc automatically does the byte swapping for
1161 machines that store the bytes reversed, e.g.  DEC alpha, freebsd,
1162 linux, Windows and the paragon; thus if you write your own binary
1163 read/write routines you have to swap the bytes; see PetscBinaryRead()
1164 and PetscBinaryWrite() to see how this may be done.
1165 
1166    Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1167    In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1168    Each processor's chunk is loaded independently by its owning rank.
1169    Multiple objects, both matrices and vectors, can be stored within the same file.
1170    They are looked up by their PetscObject name.
1171 
1172    As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1173    by default the same structure and naming of the AIJ arrays and column count
1174    within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1175 $    save example.mat A b -v7.3
1176    can be directly read by this routine (see Reference 1 for details).
1177    Note that depending on your MATLAB version, this format might be a default,
1178    otherwise you can set it as default in Preferences.
1179 
1180    Unless -nocompression flag is used to save the file in MATLAB,
1181    PETSc must be configured with ZLIB package.
1182 
1183    See also examples src/mat/tutorials/ex10.c and src/ksp/ksp/tutorials/ex27.c
1184 
1185    Current HDF5 (MAT-File) limitations:
1186    This reader currently supports only real MATSEQAIJ, MATMPIAIJ, MATSEQDENSE and MATMPIDENSE matrices.
1187 
1188    Corresponding MatView() is not yet implemented.
1189 
1190    The loaded matrix is actually a transpose of the original one in MATLAB,
1191    unless you push PETSC_VIEWER_HDF5_MAT format (see examples above).
1192    With this format, matrix is automatically transposed by PETSc,
1193    unless the matrix is marked as SPD or symmetric
1194    (see MatSetOption(), MAT_SPD, MAT_SYMMETRIC).
1195 
1196    References:
1197 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version
1198 
1199 .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), MatView(), VecLoad()
1200 
1201  @*/
1202 PetscErrorCode MatLoad(Mat mat,PetscViewer viewer)
1203 {
1204   PetscErrorCode ierr;
1205   PetscBool      flg;
1206 
1207   PetscFunctionBegin;
1208   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1209   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1210 
1211   if (!((PetscObject)mat)->type_name) {
1212     ierr = MatSetType(mat,MATAIJ);CHKERRQ(ierr);
1213   }
1214 
1215   flg  = PETSC_FALSE;
1216   ierr = PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_symmetric",&flg,NULL);CHKERRQ(ierr);
1217   if (flg) {
1218     ierr = MatSetOption(mat,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
1219     ierr = MatSetOption(mat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);CHKERRQ(ierr);
1220   }
1221   flg  = PETSC_FALSE;
1222   ierr = PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_spd",&flg,NULL);CHKERRQ(ierr);
1223   if (flg) {
1224     ierr = MatSetOption(mat,MAT_SPD,PETSC_TRUE);CHKERRQ(ierr);
1225   }
1226 
1227   if (!mat->ops->load) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type %s",((PetscObject)mat)->type_name);
1228   ierr = PetscLogEventBegin(MAT_Load,mat,viewer,0,0);CHKERRQ(ierr);
1229   ierr = (*mat->ops->load)(mat,viewer);CHKERRQ(ierr);
1230   ierr = PetscLogEventEnd(MAT_Load,mat,viewer,0,0);CHKERRQ(ierr);
1231   PetscFunctionReturn(0);
1232 }
1233 
1234 static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1235 {
1236   PetscErrorCode ierr;
1237   Mat_Redundant  *redund = *redundant;
1238   PetscInt       i;
1239 
1240   PetscFunctionBegin;
1241   if (redund){
1242     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1243       ierr = ISDestroy(&redund->isrow);CHKERRQ(ierr);
1244       ierr = ISDestroy(&redund->iscol);CHKERRQ(ierr);
1245       ierr = MatDestroySubMatrices(1,&redund->matseq);CHKERRQ(ierr);
1246     } else {
1247       ierr = PetscFree2(redund->send_rank,redund->recv_rank);CHKERRQ(ierr);
1248       ierr = PetscFree(redund->sbuf_j);CHKERRQ(ierr);
1249       ierr = PetscFree(redund->sbuf_a);CHKERRQ(ierr);
1250       for (i=0; i<redund->nrecvs; i++) {
1251         ierr = PetscFree(redund->rbuf_j[i]);CHKERRQ(ierr);
1252         ierr = PetscFree(redund->rbuf_a[i]);CHKERRQ(ierr);
1253       }
1254       ierr = PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);CHKERRQ(ierr);
1255     }
1256 
1257     if (redund->subcomm) {
1258       ierr = PetscCommDestroy(&redund->subcomm);CHKERRQ(ierr);
1259     }
1260     ierr = PetscFree(redund);CHKERRQ(ierr);
1261   }
1262   PetscFunctionReturn(0);
1263 }
1264 
1265 /*@C
1266    MatDestroy - Frees space taken by a matrix.
1267 
1268    Collective on Mat
1269 
1270    Input Parameter:
1271 .  A - the matrix
1272 
1273    Level: beginner
1274 
1275 @*/
1276 PetscErrorCode MatDestroy(Mat *A)
1277 {
1278   PetscErrorCode ierr;
1279 
1280   PetscFunctionBegin;
1281   if (!*A) PetscFunctionReturn(0);
1282   PetscValidHeaderSpecific(*A,MAT_CLASSID,1);
1283   if (--((PetscObject)(*A))->refct > 0) {*A = NULL; PetscFunctionReturn(0);}
1284 
1285   /* if memory was published with SAWs then destroy it */
1286   ierr = PetscObjectSAWsViewOff((PetscObject)*A);CHKERRQ(ierr);
1287   if ((*A)->ops->destroy) {
1288     ierr = (*(*A)->ops->destroy)(*A);CHKERRQ(ierr);
1289   }
1290 
1291   ierr = PetscFree((*A)->defaultvectype);CHKERRQ(ierr);
1292   ierr = PetscFree((*A)->bsizes);CHKERRQ(ierr);
1293   ierr = PetscFree((*A)->solvertype);CHKERRQ(ierr);
1294   for (PetscInt i=0; i<MAT_FACTOR_NUM_TYPES; i++) {
1295     ierr = PetscFree((*A)->preferredordering[i]);CHKERRQ(ierr);
1296   }
1297   ierr = MatDestroy_Redundant(&(*A)->redundant);CHKERRQ(ierr);
1298   ierr = MatProductClear(*A);CHKERRQ(ierr);
1299   ierr = MatNullSpaceDestroy(&(*A)->nullsp);CHKERRQ(ierr);
1300   ierr = MatNullSpaceDestroy(&(*A)->transnullsp);CHKERRQ(ierr);
1301   ierr = MatNullSpaceDestroy(&(*A)->nearnullsp);CHKERRQ(ierr);
1302   ierr = MatDestroy(&(*A)->schur);CHKERRQ(ierr);
1303   ierr = PetscLayoutDestroy(&(*A)->rmap);CHKERRQ(ierr);
1304   ierr = PetscLayoutDestroy(&(*A)->cmap);CHKERRQ(ierr);
1305   ierr = PetscHeaderDestroy(A);CHKERRQ(ierr);
1306   PetscFunctionReturn(0);
1307 }
1308 
1309 /*@C
1310    MatSetValues - Inserts or adds a block of values into a matrix.
1311    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1312    MUST be called after all calls to MatSetValues() have been completed.
1313 
1314    Not Collective
1315 
1316    Input Parameters:
1317 +  mat - the matrix
1318 .  v - a logically two-dimensional array of values
1319 .  m, idxm - the number of rows and their global indices
1320 .  n, idxn - the number of columns and their global indices
1321 -  addv - either ADD_VALUES or INSERT_VALUES, where
1322    ADD_VALUES adds values to any existing entries, and
1323    INSERT_VALUES replaces existing entries with new values
1324 
1325    Notes:
1326    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1327       MatSetUp() before using this routine
1328 
1329    By default the values, v, are row-oriented. See MatSetOption() for other options.
1330 
1331    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1332    options cannot be mixed without intervening calls to the assembly
1333    routines.
1334 
1335    MatSetValues() uses 0-based row and column numbers in Fortran
1336    as well as in C.
1337 
1338    Negative indices may be passed in idxm and idxn, these rows and columns are
1339    simply ignored. This allows easily inserting element stiffness matrices
1340    with homogeneous Dirchlet boundary conditions that you don't want represented
1341    in the matrix.
1342 
1343    Efficiency Alert:
1344    The routine MatSetValuesBlocked() may offer much better efficiency
1345    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1346 
1347    Level: beginner
1348 
1349    Developer Notes:
1350     This is labeled with C so does not automatically generate Fortran stubs and interfaces
1351                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1352 
1353 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1354           InsertMode, INSERT_VALUES, ADD_VALUES
1355 @*/
1356 PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1357 {
1358   PetscErrorCode ierr;
1359 
1360   PetscFunctionBeginHot;
1361   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1362   PetscValidType(mat,1);
1363   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1364   PetscValidIntPointer(idxm,3);
1365   PetscValidIntPointer(idxn,5);
1366   MatCheckPreallocated(mat,1);
1367 
1368   if (mat->insertmode == NOT_SET_VALUES) {
1369     mat->insertmode = addv;
1370   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1371   if (PetscDefined(USE_DEBUG)) {
1372     PetscInt       i,j;
1373 
1374     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1375     if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1376 
1377     for (i=0; i<m; i++) {
1378       for (j=0; j<n; j++) {
1379         if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1380 #if defined(PETSC_USE_COMPLEX)
1381           SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g+ig at matrix entry (%D,%D)",(double)PetscRealPart(v[i*n+j]),(double)PetscImaginaryPart(v[i*n+j]),idxm[i],idxn[j]);
1382 #else
1383           SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1384 #endif
1385       }
1386     }
1387     for (i=0; i<m; i++) if (idxm[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot insert in row %D, maximum is %D",idxm[i],mat->rmap->N-1);
1388     for (i=0; i<n; i++) if (idxn[i] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot insert in column %D, maximum is %D",idxn[i],mat->cmap->N-1);
1389   }
1390 
1391   if (mat->assembled) {
1392     mat->was_assembled = PETSC_TRUE;
1393     mat->assembled     = PETSC_FALSE;
1394   }
1395   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1396   ierr = (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);CHKERRQ(ierr);
1397   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1398   PetscFunctionReturn(0);
1399 }
1400 
1401 /*@
1402    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1403         values into a matrix
1404 
1405    Not Collective
1406 
1407    Input Parameters:
1408 +  mat - the matrix
1409 .  row - the (block) row to set
1410 -  v - a logically two-dimensional array of values
1411 
1412    Notes:
1413    By the values, v, are column-oriented (for the block version) and sorted
1414 
1415    All the nonzeros in the row must be provided
1416 
1417    The matrix must have previously had its column indices set
1418 
1419    The row must belong to this process
1420 
1421    Level: intermediate
1422 
1423 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1424           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1425 @*/
1426 PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1427 {
1428   PetscErrorCode ierr;
1429   PetscInt       globalrow;
1430 
1431   PetscFunctionBegin;
1432   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1433   PetscValidType(mat,1);
1434   PetscValidScalarPointer(v,3);
1435   ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);CHKERRQ(ierr);
1436   ierr = MatSetValuesRow(mat,globalrow,v);CHKERRQ(ierr);
1437   PetscFunctionReturn(0);
1438 }
1439 
1440 /*@
1441    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1442         values into a matrix
1443 
1444    Not Collective
1445 
1446    Input Parameters:
1447 +  mat - the matrix
1448 .  row - the (block) row to set
1449 -  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
1450 
1451    Notes:
1452    The values, v, are column-oriented for the block version.
1453 
1454    All the nonzeros in the row must be provided
1455 
1456    THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1457 
1458    The row must belong to this process
1459 
1460    Level: advanced
1461 
1462 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1463           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1464 @*/
1465 PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1466 {
1467   PetscErrorCode ierr;
1468 
1469   PetscFunctionBeginHot;
1470   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1471   PetscValidType(mat,1);
1472   MatCheckPreallocated(mat,1);
1473   PetscValidScalarPointer(v,3);
1474   if (PetscUnlikely(mat->insertmode == ADD_VALUES)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1475   if (PetscUnlikely(mat->factortype)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1476   mat->insertmode = INSERT_VALUES;
1477 
1478   if (mat->assembled) {
1479     mat->was_assembled = PETSC_TRUE;
1480     mat->assembled     = PETSC_FALSE;
1481   }
1482   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1483   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1484   ierr = (*mat->ops->setvaluesrow)(mat,row,v);CHKERRQ(ierr);
1485   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1486   PetscFunctionReturn(0);
1487 }
1488 
1489 /*@
1490    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1491      Using structured grid indexing
1492 
1493    Not Collective
1494 
1495    Input Parameters:
1496 +  mat - the matrix
1497 .  m - number of rows being entered
1498 .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1499 .  n - number of columns being entered
1500 .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1501 .  v - a logically two-dimensional array of values
1502 -  addv - either ADD_VALUES or INSERT_VALUES, where
1503    ADD_VALUES adds values to any existing entries, and
1504    INSERT_VALUES replaces existing entries with new values
1505 
1506    Notes:
1507    By default the values, v, are row-oriented.  See MatSetOption() for other options.
1508 
1509    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1510    options cannot be mixed without intervening calls to the assembly
1511    routines.
1512 
1513    The grid coordinates are across the entire grid, not just the local portion
1514 
1515    MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1516    as well as in C.
1517 
1518    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1519 
1520    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1521    or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1522 
1523    The columns and rows in the stencil passed in MUST be contained within the
1524    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1525    if you create a DMDA with an overlap of one grid level and on a particular process its first
1526    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1527    first i index you can use in your column and row indices in MatSetStencil() is 5.
1528 
1529    In Fortran idxm and idxn should be declared as
1530 $     MatStencil idxm(4,m),idxn(4,n)
1531    and the values inserted using
1532 $    idxm(MatStencil_i,1) = i
1533 $    idxm(MatStencil_j,1) = j
1534 $    idxm(MatStencil_k,1) = k
1535 $    idxm(MatStencil_c,1) = c
1536    etc
1537 
1538    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1539    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1540    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1541    DM_BOUNDARY_PERIODIC boundary type.
1542 
1543    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
1544    a single value per point) you can skip filling those indices.
1545 
1546    Inspired by the structured grid interface to the HYPRE package
1547    (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1548 
1549    Efficiency Alert:
1550    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1551    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1552 
1553    Level: beginner
1554 
1555 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1556           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1557 @*/
1558 PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1559 {
1560   PetscErrorCode ierr;
1561   PetscInt       buf[8192],*bufm=NULL,*bufn=NULL,*jdxm,*jdxn;
1562   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1563   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1564 
1565   PetscFunctionBegin;
1566   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1567   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1568   PetscValidType(mat,1);
1569   PetscValidPointer(idxm,3);
1570   PetscValidPointer(idxn,5);
1571 
1572   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1573     jdxm = buf; jdxn = buf+m;
1574   } else {
1575     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1576     jdxm = bufm; jdxn = bufn;
1577   }
1578   for (i=0; i<m; i++) {
1579     for (j=0; j<3-sdim; j++) dxm++;
1580     tmp = *dxm++ - starts[0];
1581     for (j=0; j<dim-1; j++) {
1582       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1583       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1584     }
1585     if (mat->stencil.noc) dxm++;
1586     jdxm[i] = tmp;
1587   }
1588   for (i=0; i<n; i++) {
1589     for (j=0; j<3-sdim; j++) dxn++;
1590     tmp = *dxn++ - starts[0];
1591     for (j=0; j<dim-1; j++) {
1592       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1593       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1594     }
1595     if (mat->stencil.noc) dxn++;
1596     jdxn[i] = tmp;
1597   }
1598   ierr = MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1599   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1600   PetscFunctionReturn(0);
1601 }
1602 
1603 /*@
1604    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1605      Using structured grid indexing
1606 
1607    Not Collective
1608 
1609    Input Parameters:
1610 +  mat - the matrix
1611 .  m - number of rows being entered
1612 .  idxm - grid coordinates for matrix rows being entered
1613 .  n - number of columns being entered
1614 .  idxn - grid coordinates for matrix columns being entered
1615 .  v - a logically two-dimensional array of values
1616 -  addv - either ADD_VALUES or INSERT_VALUES, where
1617    ADD_VALUES adds values to any existing entries, and
1618    INSERT_VALUES replaces existing entries with new values
1619 
1620    Notes:
1621    By default the values, v, are row-oriented and unsorted.
1622    See MatSetOption() for other options.
1623 
1624    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1625    options cannot be mixed without intervening calls to the assembly
1626    routines.
1627 
1628    The grid coordinates are across the entire grid, not just the local portion
1629 
1630    MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1631    as well as in C.
1632 
1633    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1634 
1635    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1636    or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1637 
1638    The columns and rows in the stencil passed in MUST be contained within the
1639    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1640    if you create a DMDA with an overlap of one grid level and on a particular process its first
1641    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1642    first i index you can use in your column and row indices in MatSetStencil() is 5.
1643 
1644    In Fortran idxm and idxn should be declared as
1645 $     MatStencil idxm(4,m),idxn(4,n)
1646    and the values inserted using
1647 $    idxm(MatStencil_i,1) = i
1648 $    idxm(MatStencil_j,1) = j
1649 $    idxm(MatStencil_k,1) = k
1650    etc
1651 
1652    Negative indices may be passed in idxm and idxn, these rows and columns are
1653    simply ignored. This allows easily inserting element stiffness matrices
1654    with homogeneous Dirchlet boundary conditions that you don't want represented
1655    in the matrix.
1656 
1657    Inspired by the structured grid interface to the HYPRE package
1658    (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1659 
1660    Level: beginner
1661 
1662 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1663           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1664           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1665 @*/
1666 PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1667 {
1668   PetscErrorCode ierr;
1669   PetscInt       buf[8192],*bufm=NULL,*bufn=NULL,*jdxm,*jdxn;
1670   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1671   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1672 
1673   PetscFunctionBegin;
1674   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1675   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1676   PetscValidType(mat,1);
1677   PetscValidPointer(idxm,3);
1678   PetscValidPointer(idxn,5);
1679   PetscValidScalarPointer(v,6);
1680 
1681   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1682     jdxm = buf; jdxn = buf+m;
1683   } else {
1684     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1685     jdxm = bufm; jdxn = bufn;
1686   }
1687   for (i=0; i<m; i++) {
1688     for (j=0; j<3-sdim; j++) dxm++;
1689     tmp = *dxm++ - starts[0];
1690     for (j=0; j<sdim-1; j++) {
1691       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1692       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1693     }
1694     dxm++;
1695     jdxm[i] = tmp;
1696   }
1697   for (i=0; i<n; i++) {
1698     for (j=0; j<3-sdim; j++) dxn++;
1699     tmp = *dxn++ - starts[0];
1700     for (j=0; j<sdim-1; j++) {
1701       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1702       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1703     }
1704     dxn++;
1705     jdxn[i] = tmp;
1706   }
1707   ierr = MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1708   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1709   PetscFunctionReturn(0);
1710 }
1711 
1712 /*@
1713    MatSetStencil - Sets the grid information for setting values into a matrix via
1714         MatSetValuesStencil()
1715 
1716    Not Collective
1717 
1718    Input Parameters:
1719 +  mat - the matrix
1720 .  dim - dimension of the grid 1, 2, or 3
1721 .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1722 .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1723 -  dof - number of degrees of freedom per node
1724 
1725    Inspired by the structured grid interface to the HYPRE package
1726    (www.llnl.gov/CASC/hyper)
1727 
1728    For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1729    user.
1730 
1731    Level: beginner
1732 
1733 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1734           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1735 @*/
1736 PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1737 {
1738   PetscInt i;
1739 
1740   PetscFunctionBegin;
1741   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1742   PetscValidIntPointer(dims,3);
1743   PetscValidIntPointer(starts,4);
1744 
1745   mat->stencil.dim = dim + (dof > 1);
1746   for (i=0; i<dim; i++) {
1747     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1748     mat->stencil.starts[i] = starts[dim-i-1];
1749   }
1750   mat->stencil.dims[dim]   = dof;
1751   mat->stencil.starts[dim] = 0;
1752   mat->stencil.noc         = (PetscBool)(dof == 1);
1753   PetscFunctionReturn(0);
1754 }
1755 
1756 /*@C
1757    MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1758 
1759    Not Collective
1760 
1761    Input Parameters:
1762 +  mat - the matrix
1763 .  v - a logically two-dimensional array of values
1764 .  m, idxm - the number of block rows and their global block indices
1765 .  n, idxn - the number of block columns and their global block indices
1766 -  addv - either ADD_VALUES or INSERT_VALUES, where
1767    ADD_VALUES adds values to any existing entries, and
1768    INSERT_VALUES replaces existing entries with new values
1769 
1770    Notes:
1771    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1772    MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1773 
1774    The m and n count the NUMBER of blocks in the row direction and column direction,
1775    NOT the total number of rows/columns; for example, if the block size is 2 and
1776    you are passing in values for rows 2,3,4,5  then m would be 2 (not 4).
1777    The values in idxm would be 1 2; that is the first index for each block divided by
1778    the block size.
1779 
1780    Note that you must call MatSetBlockSize() when constructing this matrix (before
1781    preallocating it).
1782 
1783    By default the values, v, are row-oriented, so the layout of
1784    v is the same as for MatSetValues(). See MatSetOption() for other options.
1785 
1786    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1787    options cannot be mixed without intervening calls to the assembly
1788    routines.
1789 
1790    MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1791    as well as in C.
1792 
1793    Negative indices may be passed in idxm and idxn, these rows and columns are
1794    simply ignored. This allows easily inserting element stiffness matrices
1795    with homogeneous Dirchlet boundary conditions that you don't want represented
1796    in the matrix.
1797 
1798    Each time an entry is set within a sparse matrix via MatSetValues(),
1799    internal searching must be done to determine where to place the
1800    data in the matrix storage space.  By instead inserting blocks of
1801    entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1802    reduced.
1803 
1804    Example:
1805 $   Suppose m=n=2 and block size(bs) = 2 The array is
1806 $
1807 $   1  2  | 3  4
1808 $   5  6  | 7  8
1809 $   - - - | - - -
1810 $   9  10 | 11 12
1811 $   13 14 | 15 16
1812 $
1813 $   v[] should be passed in like
1814 $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1815 $
1816 $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1817 $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1818 
1819    Level: intermediate
1820 
1821 .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1822 @*/
1823 PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1824 {
1825   PetscErrorCode ierr;
1826 
1827   PetscFunctionBeginHot;
1828   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1829   PetscValidType(mat,1);
1830   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1831   PetscValidIntPointer(idxm,3);
1832   PetscValidIntPointer(idxn,5);
1833   PetscValidScalarPointer(v,6);
1834   MatCheckPreallocated(mat,1);
1835   if (mat->insertmode == NOT_SET_VALUES) {
1836     mat->insertmode = addv;
1837   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1838   if (PetscDefined(USE_DEBUG)) {
1839     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1840     if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(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       if (idxm[i]*rbs >= M) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row block index %D (index %D) greater than row length %D",i,idxm[i],M);
1848     }
1849     for (i=0; i<n; i++) {
1850       if (idxn[i]*cbs >= N) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column block index %D (index %D) great than column length %D",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     ierr = MatGetBlockSizes(mat,&bs,&cbs);CHKERRQ(ierr);
1864     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1865       iidxm = buf; iidxn = buf + m*bs;
1866     } else {
1867       ierr  = PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);CHKERRQ(ierr);
1868       iidxm = bufr; iidxn = bufc;
1869     }
1870     for (i=0; i<m; i++) {
1871       for (j=0; j<bs; j++) {
1872         iidxm[i*bs+j] = bs*idxm[i] + j;
1873       }
1874     }
1875     for (i=0; i<n; i++) {
1876       for (j=0; j<cbs; j++) {
1877         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1878       }
1879     }
1880     ierr = MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);CHKERRQ(ierr);
1881     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
1882   }
1883   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1884   PetscFunctionReturn(0);
1885 }
1886 
1887 /*@C
1888    MatGetValues - Gets a block of values from a matrix.
1889 
1890    Not Collective; can only return values that are owned by the give process
1891 
1892    Input Parameters:
1893 +  mat - the matrix
1894 .  v - a logically two-dimensional array for storing the values
1895 .  m, idxm - the number of rows and their global indices
1896 -  n, idxn - the number of columns and their global indices
1897 
1898    Notes:
1899      The user must allocate space (m*n PetscScalars) for the values, v.
1900      The values, v, are then returned in a row-oriented format,
1901      analogous to that used by default in MatSetValues().
1902 
1903      MatGetValues() uses 0-based row and column numbers in
1904      Fortran as well as in C.
1905 
1906      MatGetValues() requires that the matrix has been assembled
1907      with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1908      MatSetValues() and MatGetValues() CANNOT be made in succession
1909      without intermediate matrix assembly.
1910 
1911      Negative row or column indices will be ignored and those locations in v[] will be
1912      left unchanged.
1913 
1914      For the standard row-based matrix formats, idxm[] can only contain rows owned by the requesting MPI rank.
1915      That is, rows with global index greater than or equal to restart and less than rend where restart and rend are obtainable
1916      from MatGetOwnershipRange(mat,&rstart,&rend).
1917 
1918    Level: advanced
1919 
1920 .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues(), MatGetOwnershipRange(), MatGetValuesLocal()
1921 @*/
1922 PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1923 {
1924   PetscErrorCode ierr;
1925 
1926   PetscFunctionBegin;
1927   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1928   PetscValidType(mat,1);
1929   if (!m || !n) PetscFunctionReturn(0);
1930   PetscValidIntPointer(idxm,3);
1931   PetscValidIntPointer(idxn,5);
1932   PetscValidScalarPointer(v,6);
1933   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1934   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1935   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1936   MatCheckPreallocated(mat,1);
1937 
1938   ierr = PetscLogEventBegin(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1939   ierr = (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);CHKERRQ(ierr);
1940   ierr = PetscLogEventEnd(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1941   PetscFunctionReturn(0);
1942 }
1943 
1944 /*@C
1945    MatGetValuesLocal - retrieves values from certain locations in a matrix using the local numbering of the indices
1946      defined previously by MatSetLocalToGlobalMapping()
1947 
1948    Not Collective
1949 
1950    Input Parameters:
1951 +  mat - the matrix
1952 .  nrow, irow - number of rows and their local indices
1953 -  ncol, icol - number of columns and their local indices
1954 
1955    Output Parameter:
1956 .  y -  a logically two-dimensional array of values
1957 
1958    Notes:
1959      If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine.
1960 
1961      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,
1962      are greater than or equal to restart and less than rend where restart and rend are obtainable from MatGetOwnershipRange(mat,&rstart,&rend). One can
1963      determine if the resulting global row associated with the local row r is owned by the requesting MPI rank by applying the ISLocalToGlobalMapping set
1964      with MatSetLocalToGlobalMapping().
1965 
1966    Developer Notes:
1967       This is labelled with C so does not automatically generate Fortran stubs and interfaces
1968       because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1969 
1970    Level: advanced
1971 
1972 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1973            MatSetValuesLocal(), MatGetValues()
1974 @*/
1975 PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1976 {
1977   PetscErrorCode ierr;
1978 
1979   PetscFunctionBeginHot;
1980   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1981   PetscValidType(mat,1);
1982   MatCheckPreallocated(mat,1);
1983   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to retrieve */
1984   PetscValidIntPointer(irow,3);
1985   PetscValidIntPointer(icol,5);
1986   if (PetscDefined(USE_DEBUG)) {
1987     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1988     if (!mat->ops->getvalueslocal && !mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1989   }
1990   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1991   ierr = PetscLogEventBegin(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1992   if (mat->ops->getvalueslocal) {
1993     ierr = (*mat->ops->getvalueslocal)(mat,nrow,irow,ncol,icol,y);CHKERRQ(ierr);
1994   } else {
1995     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*irowm,*icolm;
1996     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1997       irowm = buf; icolm = buf+nrow;
1998     } else {
1999       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2000       irowm = bufr; icolm = bufc;
2001     }
2002     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2003     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2004     ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2005     ierr = ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2006     ierr = MatGetValues(mat,nrow,irowm,ncol,icolm,y);CHKERRQ(ierr);
2007     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2008   }
2009   ierr = PetscLogEventEnd(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
2010   PetscFunctionReturn(0);
2011 }
2012 
2013 /*@
2014   MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
2015   the same size. Currently, this can only be called once and creates the given matrix.
2016 
2017   Not Collective
2018 
2019   Input Parameters:
2020 + mat - the matrix
2021 . nb - the number of blocks
2022 . bs - the number of rows (and columns) in each block
2023 . rows - a concatenation of the rows for each block
2024 - v - a concatenation of logically two-dimensional arrays of values
2025 
2026   Notes:
2027   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
2028 
2029   Level: advanced
2030 
2031 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2032           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2033 @*/
2034 PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2035 {
2036   PetscErrorCode ierr;
2037 
2038   PetscFunctionBegin;
2039   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2040   PetscValidType(mat,1);
2041   PetscValidIntPointer(rows,4);
2042   PetscValidScalarPointer(v,5);
2043   if (PetscUnlikelyDebug(mat->factortype)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2044 
2045   ierr = PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
2046   if (mat->ops->setvaluesbatch) {
2047     ierr = (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);CHKERRQ(ierr);
2048   } else {
2049     PetscInt b;
2050     for (b = 0; b < nb; ++b) {
2051       ierr = MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);CHKERRQ(ierr);
2052     }
2053   }
2054   ierr = PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
2055   PetscFunctionReturn(0);
2056 }
2057 
2058 /*@
2059    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2060    the routine MatSetValuesLocal() to allow users to insert matrix entries
2061    using a local (per-processor) numbering.
2062 
2063    Not Collective
2064 
2065    Input Parameters:
2066 +  x - the matrix
2067 .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2068 - cmapping - column mapping
2069 
2070    Level: intermediate
2071 
2072 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal(), MatGetValuesLocal()
2073 @*/
2074 PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2075 {
2076   PetscErrorCode ierr;
2077 
2078   PetscFunctionBegin;
2079   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
2080   PetscValidType(x,1);
2081   PetscValidHeaderSpecific(rmapping,IS_LTOGM_CLASSID,2);
2082   PetscValidHeaderSpecific(cmapping,IS_LTOGM_CLASSID,3);
2083 
2084   if (x->ops->setlocaltoglobalmapping) {
2085     ierr = (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);CHKERRQ(ierr);
2086   } else {
2087     ierr = PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);CHKERRQ(ierr);
2088     ierr = PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);CHKERRQ(ierr);
2089   }
2090   PetscFunctionReturn(0);
2091 }
2092 
2093 /*@
2094    MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
2095 
2096    Not Collective
2097 
2098    Input Parameters:
2099 .  A - the matrix
2100 
2101    Output Parameters:
2102 + rmapping - row mapping
2103 - cmapping - column mapping
2104 
2105    Level: advanced
2106 
2107 .seealso:  MatSetValuesLocal()
2108 @*/
2109 PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2110 {
2111   PetscFunctionBegin;
2112   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
2113   PetscValidType(A,1);
2114   if (rmapping) PetscValidPointer(rmapping,2);
2115   if (cmapping) PetscValidPointer(cmapping,3);
2116   if (rmapping) *rmapping = A->rmap->mapping;
2117   if (cmapping) *cmapping = A->cmap->mapping;
2118   PetscFunctionReturn(0);
2119 }
2120 
2121 /*@
2122    MatSetLayouts - Sets the PetscLayout objects for rows and columns of a matrix
2123 
2124    Logically Collective on A
2125 
2126    Input Parameters:
2127 +  A - the matrix
2128 . rmap - row layout
2129 - cmap - column layout
2130 
2131    Level: advanced
2132 
2133 .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatGetLayouts()
2134 @*/
2135 PetscErrorCode MatSetLayouts(Mat A,PetscLayout rmap,PetscLayout cmap)
2136 {
2137   PetscErrorCode ierr;
2138 
2139   PetscFunctionBegin;
2140   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
2141 
2142   ierr = PetscLayoutReference(rmap,&A->rmap);CHKERRQ(ierr);
2143   ierr = PetscLayoutReference(cmap,&A->cmap);CHKERRQ(ierr);
2144   PetscFunctionReturn(0);
2145 }
2146 
2147 /*@
2148    MatGetLayouts - Gets the PetscLayout objects for rows and columns
2149 
2150    Not Collective
2151 
2152    Input Parameters:
2153 .  A - the matrix
2154 
2155    Output Parameters:
2156 + rmap - row layout
2157 - cmap - column layout
2158 
2159    Level: advanced
2160 
2161 .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping(), MatSetLayouts()
2162 @*/
2163 PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2164 {
2165   PetscFunctionBegin;
2166   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
2167   PetscValidType(A,1);
2168   if (rmap) PetscValidPointer(rmap,2);
2169   if (cmap) PetscValidPointer(cmap,3);
2170   if (rmap) *rmap = A->rmap;
2171   if (cmap) *cmap = A->cmap;
2172   PetscFunctionReturn(0);
2173 }
2174 
2175 /*@C
2176    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2177    using a local numbering of the nodes.
2178 
2179    Not Collective
2180 
2181    Input Parameters:
2182 +  mat - the matrix
2183 .  nrow, irow - number of rows and their local indices
2184 .  ncol, icol - number of columns and their local indices
2185 .  y -  a logically two-dimensional array of values
2186 -  addv - either INSERT_VALUES or ADD_VALUES, where
2187    ADD_VALUES adds values to any existing entries, and
2188    INSERT_VALUES replaces existing entries with new values
2189 
2190    Notes:
2191    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2192       MatSetUp() before using this routine
2193 
2194    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
2195 
2196    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2197    options cannot be mixed without intervening calls to the assembly
2198    routines.
2199 
2200    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2201    MUST be called after all calls to MatSetValuesLocal() have been completed.
2202 
2203    Level: intermediate
2204 
2205    Developer Notes:
2206     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2207                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2208 
2209 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2210            MatSetValueLocal(), MatGetValuesLocal()
2211 @*/
2212 PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2213 {
2214   PetscErrorCode ierr;
2215 
2216   PetscFunctionBeginHot;
2217   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2218   PetscValidType(mat,1);
2219   MatCheckPreallocated(mat,1);
2220   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
2221   PetscValidIntPointer(irow,3);
2222   PetscValidIntPointer(icol,5);
2223   if (mat->insertmode == NOT_SET_VALUES) {
2224     mat->insertmode = addv;
2225   }
2226   else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2227   if (PetscDefined(USE_DEBUG)) {
2228     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2229     if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2230   }
2231 
2232   if (mat->assembled) {
2233     mat->was_assembled = PETSC_TRUE;
2234     mat->assembled     = PETSC_FALSE;
2235   }
2236   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2237   if (mat->ops->setvalueslocal) {
2238     ierr = (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2239   } else {
2240     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*irowm,*icolm;
2241     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2242       irowm = buf; icolm = buf+nrow;
2243     } else {
2244       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2245       irowm = bufr; icolm = bufc;
2246     }
2247     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2248     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2249     ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2250     ierr = ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2251     ierr = MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2252     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2253   }
2254   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2255   PetscFunctionReturn(0);
2256 }
2257 
2258 /*@C
2259    MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2260    using a local ordering of the nodes a block at a time.
2261 
2262    Not Collective
2263 
2264    Input Parameters:
2265 +  x - the matrix
2266 .  nrow, irow - number of rows and their local indices
2267 .  ncol, icol - number of columns and their local indices
2268 .  y -  a logically two-dimensional array of values
2269 -  addv - either INSERT_VALUES or ADD_VALUES, where
2270    ADD_VALUES adds values to any existing entries, and
2271    INSERT_VALUES replaces existing entries with new values
2272 
2273    Notes:
2274    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2275       MatSetUp() before using this routine
2276 
2277    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2278       before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2279 
2280    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2281    options cannot be mixed without intervening calls to the assembly
2282    routines.
2283 
2284    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2285    MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2286 
2287    Level: intermediate
2288 
2289    Developer Notes:
2290     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2291                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2292 
2293 .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2294            MatSetValuesLocal(),  MatSetValuesBlocked()
2295 @*/
2296 PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2297 {
2298   PetscErrorCode ierr;
2299 
2300   PetscFunctionBeginHot;
2301   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2302   PetscValidType(mat,1);
2303   MatCheckPreallocated(mat,1);
2304   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
2305   PetscValidIntPointer(irow,3);
2306   PetscValidIntPointer(icol,5);
2307   PetscValidScalarPointer(y,6);
2308   if (mat->insertmode == NOT_SET_VALUES) {
2309     mat->insertmode = addv;
2310   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2311   if (PetscDefined(USE_DEBUG)) {
2312     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2313     if (!mat->ops->setvaluesblockedlocal && !mat->ops->setvaluesblocked && !mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2314   }
2315 
2316   if (mat->assembled) {
2317     mat->was_assembled = PETSC_TRUE;
2318     mat->assembled     = PETSC_FALSE;
2319   }
2320   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2321     PetscInt irbs, rbs;
2322     ierr = MatGetBlockSizes(mat, &rbs, NULL);CHKERRQ(ierr);
2323     ierr = ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);CHKERRQ(ierr);
2324     if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2325   }
2326   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2327     PetscInt icbs, cbs;
2328     ierr = MatGetBlockSizes(mat,NULL,&cbs);CHKERRQ(ierr);
2329     ierr = ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);CHKERRQ(ierr);
2330     if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2331   }
2332   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2333   if (mat->ops->setvaluesblockedlocal) {
2334     ierr = (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2335   } else {
2336     PetscInt buf[8192],*bufr=NULL,*bufc=NULL,*irowm,*icolm;
2337     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2338       irowm = buf; icolm = buf + nrow;
2339     } else {
2340       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2341       irowm = bufr; icolm = bufc;
2342     }
2343     ierr = ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2344     ierr = ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2345     ierr = MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2346     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2347   }
2348   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2349   PetscFunctionReturn(0);
2350 }
2351 
2352 /*@
2353    MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2354 
2355    Collective on Mat
2356 
2357    Input Parameters:
2358 +  mat - the matrix
2359 -  x   - the vector to be multiplied
2360 
2361    Output Parameters:
2362 .  y - the result
2363 
2364    Notes:
2365    The vectors x and y cannot be the same.  I.e., one cannot
2366    call MatMult(A,y,y).
2367 
2368    Level: developer
2369 
2370 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2371 @*/
2372 PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2373 {
2374   PetscErrorCode ierr;
2375 
2376   PetscFunctionBegin;
2377   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2378   PetscValidType(mat,1);
2379   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2380   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2381 
2382   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2383   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2384   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2385   MatCheckPreallocated(mat,1);
2386 
2387   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2388   ierr = (*mat->ops->multdiagonalblock)(mat,x,y);CHKERRQ(ierr);
2389   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2390   PetscFunctionReturn(0);
2391 }
2392 
2393 /* --------------------------------------------------------*/
2394 /*@
2395    MatMult - Computes the matrix-vector product, y = Ax.
2396 
2397    Neighbor-wise Collective on Mat
2398 
2399    Input Parameters:
2400 +  mat - the matrix
2401 -  x   - the vector to be multiplied
2402 
2403    Output Parameters:
2404 .  y - the result
2405 
2406    Notes:
2407    The vectors x and y cannot be the same.  I.e., one cannot
2408    call MatMult(A,y,y).
2409 
2410    Level: beginner
2411 
2412 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2413 @*/
2414 PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2415 {
2416   PetscErrorCode ierr;
2417 
2418   PetscFunctionBegin;
2419   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2420   PetscValidType(mat,1);
2421   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2422   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2423   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2424   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2425   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2426 #if !defined(PETSC_HAVE_CONSTRAINTS)
2427   if (mat->cmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2428   if (mat->rmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2429   if (mat->rmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap->n,y->map->n);
2430 #endif
2431   ierr = VecSetErrorIfLocked(y,3);CHKERRQ(ierr);
2432   if (mat->erroriffailure) {ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);}
2433   MatCheckPreallocated(mat,1);
2434 
2435   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2436   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2437   ierr = PetscLogEventBegin(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2438   ierr = (*mat->ops->mult)(mat,x,y);CHKERRQ(ierr);
2439   ierr = PetscLogEventEnd(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2440   if (mat->erroriffailure) {ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);}
2441   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2442   PetscFunctionReturn(0);
2443 }
2444 
2445 /*@
2446    MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.
2447 
2448    Neighbor-wise Collective on Mat
2449 
2450    Input Parameters:
2451 +  mat - the matrix
2452 -  x   - the vector to be multiplied
2453 
2454    Output Parameters:
2455 .  y - the result
2456 
2457    Notes:
2458    The vectors x and y cannot be the same.  I.e., one cannot
2459    call MatMultTranspose(A,y,y).
2460 
2461    For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2462    use MatMultHermitianTranspose()
2463 
2464    Level: beginner
2465 
2466 .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2467 @*/
2468 PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2469 {
2470   PetscErrorCode (*op)(Mat,Vec,Vec)=NULL,ierr;
2471 
2472   PetscFunctionBegin;
2473   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2474   PetscValidType(mat,1);
2475   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2476   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2477 
2478   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2479   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2480   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2481 #if !defined(PETSC_HAVE_CONSTRAINTS)
2482   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2483   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2484 #endif
2485   if (mat->erroriffailure) {ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);}
2486   MatCheckPreallocated(mat,1);
2487 
2488   if (!mat->ops->multtranspose) {
2489     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
2490     if (!op) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined or is symmetric and does not have a multiply defined",((PetscObject)mat)->type_name);
2491   } else op = mat->ops->multtranspose;
2492   ierr = PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2493   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2494   ierr = (*op)(mat,x,y);CHKERRQ(ierr);
2495   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2496   ierr = PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2497   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2498   if (mat->erroriffailure) {ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);}
2499   PetscFunctionReturn(0);
2500 }
2501 
2502 /*@
2503    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2504 
2505    Neighbor-wise Collective on Mat
2506 
2507    Input Parameters:
2508 +  mat - the matrix
2509 -  x   - the vector to be multilplied
2510 
2511    Output Parameters:
2512 .  y - the result
2513 
2514    Notes:
2515    The vectors x and y cannot be the same.  I.e., one cannot
2516    call MatMultHermitianTranspose(A,y,y).
2517 
2518    Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2519 
2520    For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2521 
2522    Level: beginner
2523 
2524 .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2525 @*/
2526 PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2527 {
2528   PetscErrorCode ierr;
2529 
2530   PetscFunctionBegin;
2531   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2532   PetscValidType(mat,1);
2533   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2534   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2535 
2536   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2537   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2538   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2539 #if !defined(PETSC_HAVE_CONSTRAINTS)
2540   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2541   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2542 #endif
2543   MatCheckPreallocated(mat,1);
2544 
2545   ierr = PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2546 #if defined(PETSC_USE_COMPLEX)
2547   if (mat->ops->multhermitiantranspose || (mat->hermitian && mat->ops->mult)) {
2548     ierr = VecLockReadPush(x);CHKERRQ(ierr);
2549     if (mat->ops->multhermitiantranspose) {
2550       ierr = (*mat->ops->multhermitiantranspose)(mat,x,y);CHKERRQ(ierr);
2551     } else {
2552       ierr = (*mat->ops->mult)(mat,x,y);CHKERRQ(ierr);
2553     }
2554     ierr = VecLockReadPop(x);CHKERRQ(ierr);
2555   } else {
2556     Vec w;
2557     ierr = VecDuplicate(x,&w);CHKERRQ(ierr);
2558     ierr = VecCopy(x,w);CHKERRQ(ierr);
2559     ierr = VecConjugate(w);CHKERRQ(ierr);
2560     ierr = MatMultTranspose(mat,w,y);CHKERRQ(ierr);
2561     ierr = VecDestroy(&w);CHKERRQ(ierr);
2562     ierr = VecConjugate(y);CHKERRQ(ierr);
2563   }
2564   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2565 #else
2566   ierr = MatMultTranspose(mat,x,y);CHKERRQ(ierr);
2567 #endif
2568   ierr = PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2569   PetscFunctionReturn(0);
2570 }
2571 
2572 /*@
2573     MatMultAdd -  Computes v3 = v2 + A * v1.
2574 
2575     Neighbor-wise Collective on Mat
2576 
2577     Input Parameters:
2578 +   mat - the matrix
2579 -   v1, v2 - the vectors
2580 
2581     Output Parameters:
2582 .   v3 - the result
2583 
2584     Notes:
2585     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2586     call MatMultAdd(A,v1,v2,v1).
2587 
2588     Level: beginner
2589 
2590 .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2591 @*/
2592 PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2593 {
2594   PetscErrorCode ierr;
2595 
2596   PetscFunctionBegin;
2597   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2598   PetscValidType(mat,1);
2599   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2600   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2601   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2602 
2603   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2604   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2605   if (mat->cmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->cmap->N,v1->map->N);
2606   /* if (mat->rmap->N != v2->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->rmap->N,v2->map->N);
2607      if (mat->rmap->N != v3->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->rmap->N,v3->map->N); */
2608   if (mat->rmap->n != v3->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: local dim %D %D",mat->rmap->n,v3->map->n);
2609   if (mat->rmap->n != v2->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: local dim %D %D",mat->rmap->n,v2->map->n);
2610   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2611   MatCheckPreallocated(mat,1);
2612 
2613   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2614   ierr = PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2615   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2616   ierr = (*mat->ops->multadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2617   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2618   ierr = PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2619   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2620   PetscFunctionReturn(0);
2621 }
2622 
2623 /*@
2624    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2625 
2626    Neighbor-wise Collective on Mat
2627 
2628    Input Parameters:
2629 +  mat - the matrix
2630 -  v1, v2 - the vectors
2631 
2632    Output Parameters:
2633 .  v3 - the result
2634 
2635    Notes:
2636    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2637    call MatMultTransposeAdd(A,v1,v2,v1).
2638 
2639    Level: beginner
2640 
2641 .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2642 @*/
2643 PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2644 {
2645   PetscErrorCode ierr;
2646 
2647   PetscFunctionBegin;
2648   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2649   PetscValidType(mat,1);
2650   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2651   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2652   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2653 
2654   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2655   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2656   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2657   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2658   if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2659   if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2660   if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2661   MatCheckPreallocated(mat,1);
2662 
2663   ierr = PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2664   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2665   ierr = (*mat->ops->multtransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2666   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2667   ierr = PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2668   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2669   PetscFunctionReturn(0);
2670 }
2671 
2672 /*@
2673    MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2674 
2675    Neighbor-wise Collective on Mat
2676 
2677    Input Parameters:
2678 +  mat - the matrix
2679 -  v1, v2 - the vectors
2680 
2681    Output Parameters:
2682 .  v3 - the result
2683 
2684    Notes:
2685    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2686    call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2687 
2688    Level: beginner
2689 
2690 .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2691 @*/
2692 PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2693 {
2694   PetscErrorCode ierr;
2695 
2696   PetscFunctionBegin;
2697   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2698   PetscValidType(mat,1);
2699   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2700   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2701   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2702 
2703   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2704   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2705   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2706   if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2707   if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2708   if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2709   MatCheckPreallocated(mat,1);
2710 
2711   ierr = PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2712   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2713   if (mat->ops->multhermitiantransposeadd) {
2714     ierr = (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2715   } else {
2716     Vec w,z;
2717     ierr = VecDuplicate(v1,&w);CHKERRQ(ierr);
2718     ierr = VecCopy(v1,w);CHKERRQ(ierr);
2719     ierr = VecConjugate(w);CHKERRQ(ierr);
2720     ierr = VecDuplicate(v3,&z);CHKERRQ(ierr);
2721     ierr = MatMultTranspose(mat,w,z);CHKERRQ(ierr);
2722     ierr = VecDestroy(&w);CHKERRQ(ierr);
2723     ierr = VecConjugate(z);CHKERRQ(ierr);
2724     if (v2 != v3) {
2725       ierr = VecWAXPY(v3,1.0,v2,z);CHKERRQ(ierr);
2726     } else {
2727       ierr = VecAXPY(v3,1.0,z);CHKERRQ(ierr);
2728     }
2729     ierr = VecDestroy(&z);CHKERRQ(ierr);
2730   }
2731   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2732   ierr = PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2733   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2734   PetscFunctionReturn(0);
2735 }
2736 
2737 /*@
2738    MatMultConstrained - The inner multiplication routine for a
2739    constrained matrix P^T A P.
2740 
2741    Neighbor-wise Collective on Mat
2742 
2743    Input Parameters:
2744 +  mat - the matrix
2745 -  x   - the vector to be multilplied
2746 
2747    Output Parameters:
2748 .  y - the result
2749 
2750    Notes:
2751    The vectors x and y cannot be the same.  I.e., one cannot
2752    call MatMult(A,y,y).
2753 
2754    Level: beginner
2755 
2756 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2757 @*/
2758 PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2759 {
2760   PetscErrorCode ierr;
2761 
2762   PetscFunctionBegin;
2763   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2764   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2765   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2766   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2767   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2768   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2769   if (mat->cmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2770   if (mat->rmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2771   if (mat->rmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap->n,y->map->n);
2772 
2773   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2774   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2775   ierr = (*mat->ops->multconstrained)(mat,x,y);CHKERRQ(ierr);
2776   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2777   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2778   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2779   PetscFunctionReturn(0);
2780 }
2781 
2782 /*@
2783    MatMultTransposeConstrained - The inner multiplication routine for a
2784    constrained matrix P^T A^T P.
2785 
2786    Neighbor-wise Collective on Mat
2787 
2788    Input Parameters:
2789 +  mat - the matrix
2790 -  x   - the vector to be multilplied
2791 
2792    Output Parameters:
2793 .  y - the result
2794 
2795    Notes:
2796    The vectors x and y cannot be the same.  I.e., one cannot
2797    call MatMult(A,y,y).
2798 
2799    Level: beginner
2800 
2801 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2802 @*/
2803 PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2804 {
2805   PetscErrorCode ierr;
2806 
2807   PetscFunctionBegin;
2808   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2809   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2810   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2811   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2812   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2813   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2814   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2815   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2816 
2817   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2818   ierr = (*mat->ops->multtransposeconstrained)(mat,x,y);CHKERRQ(ierr);
2819   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2820   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2821   PetscFunctionReturn(0);
2822 }
2823 
2824 /*@C
2825    MatGetFactorType - gets the type of factorization it is
2826 
2827    Not Collective
2828 
2829    Input Parameters:
2830 .  mat - the matrix
2831 
2832    Output Parameters:
2833 .  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2834 
2835    Level: intermediate
2836 
2837 .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2838 @*/
2839 PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2840 {
2841   PetscFunctionBegin;
2842   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2843   PetscValidType(mat,1);
2844   PetscValidPointer(t,2);
2845   *t = mat->factortype;
2846   PetscFunctionReturn(0);
2847 }
2848 
2849 /*@C
2850    MatSetFactorType - sets the type of factorization it is
2851 
2852    Logically Collective on Mat
2853 
2854    Input Parameters:
2855 +  mat - the matrix
2856 -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2857 
2858    Level: intermediate
2859 
2860 .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2861 @*/
2862 PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2863 {
2864   PetscFunctionBegin;
2865   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2866   PetscValidType(mat,1);
2867   mat->factortype = t;
2868   PetscFunctionReturn(0);
2869 }
2870 
2871 /* ------------------------------------------------------------*/
2872 /*@C
2873    MatGetInfo - Returns information about matrix storage (number of
2874    nonzeros, memory, etc.).
2875 
2876    Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2877 
2878    Input Parameters:
2879 .  mat - the matrix
2880 
2881    Output Parameters:
2882 +  flag - flag indicating the type of parameters to be returned
2883    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2884    MAT_GLOBAL_SUM - sum over all processors)
2885 -  info - matrix information context
2886 
2887    Notes:
2888    The MatInfo context contains a variety of matrix data, including
2889    number of nonzeros allocated and used, number of mallocs during
2890    matrix assembly, etc.  Additional information for factored matrices
2891    is provided (such as the fill ratio, number of mallocs during
2892    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2893    when using the runtime options
2894 $       -info -mat_view ::ascii_info
2895 
2896    Example for C/C++ Users:
2897    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2898    data within the MatInfo context.  For example,
2899 .vb
2900       MatInfo info;
2901       Mat     A;
2902       double  mal, nz_a, nz_u;
2903 
2904       MatGetInfo(A,MAT_LOCAL,&info);
2905       mal  = info.mallocs;
2906       nz_a = info.nz_allocated;
2907 .ve
2908 
2909    Example for Fortran Users:
2910    Fortran users should declare info as a double precision
2911    array of dimension MAT_INFO_SIZE, and then extract the parameters
2912    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2913    a complete list of parameter names.
2914 .vb
2915       double  precision info(MAT_INFO_SIZE)
2916       double  precision mal, nz_a
2917       Mat     A
2918       integer ierr
2919 
2920       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2921       mal = info(MAT_INFO_MALLOCS)
2922       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2923 .ve
2924 
2925     Level: intermediate
2926 
2927     Developer Note: fortran interface is not autogenerated as the f90
2928     interface defintion cannot be generated correctly [due to MatInfo]
2929 
2930 .seealso: MatStashGetInfo()
2931 
2932 @*/
2933 PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2934 {
2935   PetscErrorCode ierr;
2936 
2937   PetscFunctionBegin;
2938   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2939   PetscValidType(mat,1);
2940   PetscValidPointer(info,3);
2941   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2942   MatCheckPreallocated(mat,1);
2943   ierr = (*mat->ops->getinfo)(mat,flag,info);CHKERRQ(ierr);
2944   PetscFunctionReturn(0);
2945 }
2946 
2947 /*
2948    This is used by external packages where it is not easy to get the info from the actual
2949    matrix factorization.
2950 */
2951 PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2952 {
2953   PetscErrorCode ierr;
2954 
2955   PetscFunctionBegin;
2956   ierr = PetscMemzero(info,sizeof(MatInfo));CHKERRQ(ierr);
2957   PetscFunctionReturn(0);
2958 }
2959 
2960 /* ----------------------------------------------------------*/
2961 
2962 /*@C
2963    MatLUFactor - Performs in-place LU factorization of matrix.
2964 
2965    Collective on Mat
2966 
2967    Input Parameters:
2968 +  mat - the matrix
2969 .  row - row permutation
2970 .  col - column permutation
2971 -  info - options for factorization, includes
2972 $          fill - expected fill as ratio of original fill.
2973 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2974 $                   Run with the option -info to determine an optimal value to use
2975 
2976    Notes:
2977    Most users should employ the simplified KSP interface for linear solvers
2978    instead of working directly with matrix algebra routines such as this.
2979    See, e.g., KSPCreate().
2980 
2981    This changes the state of the matrix to a factored matrix; it cannot be used
2982    for example with MatSetValues() unless one first calls MatSetUnfactored().
2983 
2984    Level: developer
2985 
2986 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2987           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2988 
2989     Developer Note: fortran interface is not autogenerated as the f90
2990     interface defintion cannot be generated correctly [due to MatFactorInfo]
2991 
2992 @*/
2993 PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2994 {
2995   PetscErrorCode ierr;
2996   MatFactorInfo  tinfo;
2997 
2998   PetscFunctionBegin;
2999   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3000   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
3001   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
3002   if (info) PetscValidPointer(info,4);
3003   PetscValidType(mat,1);
3004   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3005   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3006   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3007   MatCheckPreallocated(mat,1);
3008   if (!info) {
3009     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3010     info = &tinfo;
3011   }
3012 
3013   ierr = PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
3014   ierr = (*mat->ops->lufactor)(mat,row,col,info);CHKERRQ(ierr);
3015   ierr = PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
3016   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3017   PetscFunctionReturn(0);
3018 }
3019 
3020 /*@C
3021    MatILUFactor - Performs in-place ILU factorization of matrix.
3022 
3023    Collective on Mat
3024 
3025    Input Parameters:
3026 +  mat - the matrix
3027 .  row - row permutation
3028 .  col - column permutation
3029 -  info - structure containing
3030 $      levels - number of levels of fill.
3031 $      expected fill - as ratio of original fill.
3032 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3033                 missing diagonal entries)
3034 
3035    Notes:
3036    Probably really in-place only when level of fill is zero, otherwise allocates
3037    new space to store factored matrix and deletes previous memory.
3038 
3039    Most users should employ the simplified KSP interface for linear solvers
3040    instead of working directly with matrix algebra routines such as this.
3041    See, e.g., KSPCreate().
3042 
3043    Level: developer
3044 
3045 .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
3046 
3047     Developer Note: fortran interface is not autogenerated as the f90
3048     interface defintion cannot be generated correctly [due to MatFactorInfo]
3049 
3050 @*/
3051 PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3052 {
3053   PetscErrorCode ierr;
3054 
3055   PetscFunctionBegin;
3056   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3057   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
3058   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
3059   PetscValidPointer(info,4);
3060   PetscValidType(mat,1);
3061   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
3062   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3063   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3064   if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3065   MatCheckPreallocated(mat,1);
3066 
3067   ierr = PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
3068   ierr = (*mat->ops->ilufactor)(mat,row,col,info);CHKERRQ(ierr);
3069   ierr = PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
3070   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3071   PetscFunctionReturn(0);
3072 }
3073 
3074 /*@C
3075    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3076    Call this routine before calling MatLUFactorNumeric().
3077 
3078    Collective on Mat
3079 
3080    Input Parameters:
3081 +  fact - the factor matrix obtained with MatGetFactor()
3082 .  mat - the matrix
3083 .  row, col - row and column permutations
3084 -  info - options for factorization, includes
3085 $          fill - expected fill as ratio of original fill.
3086 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3087 $                   Run with the option -info to determine an optimal value to use
3088 
3089    Notes:
3090     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
3091 
3092    Most users should employ the simplified KSP interface for linear solvers
3093    instead of working directly with matrix algebra routines such as this.
3094    See, e.g., KSPCreate().
3095 
3096    Level: developer
3097 
3098 .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
3099 
3100     Developer Note: fortran interface is not autogenerated as the f90
3101     interface defintion cannot be generated correctly [due to MatFactorInfo]
3102 
3103 @*/
3104 PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3105 {
3106   PetscErrorCode ierr;
3107   MatFactorInfo  tinfo;
3108 
3109   PetscFunctionBegin;
3110   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
3111   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,3);
3112   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,4);
3113   if (info) PetscValidPointer(info,5);
3114   PetscValidType(mat,2);
3115   PetscValidPointer(fact,1);
3116   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3117   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3118   if (!(fact)->ops->lufactorsymbolic) {
3119     MatSolverType stype;
3120     ierr = MatFactorGetSolverType(fact,&stype);CHKERRQ(ierr);
3121     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,stype);
3122   }
3123   MatCheckPreallocated(mat,2);
3124   if (!info) {
3125     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3126     info = &tinfo;
3127   }
3128 
3129   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);}
3130   ierr = (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
3131   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);}
3132   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3133   PetscFunctionReturn(0);
3134 }
3135 
3136 /*@C
3137    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3138    Call this routine after first calling MatLUFactorSymbolic().
3139 
3140    Collective on Mat
3141 
3142    Input Parameters:
3143 +  fact - the factor matrix obtained with MatGetFactor()
3144 .  mat - the matrix
3145 -  info - options for factorization
3146 
3147    Notes:
3148    See MatLUFactor() for in-place factorization.  See
3149    MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3150 
3151    Most users should employ the simplified KSP interface for linear solvers
3152    instead of working directly with matrix algebra routines such as this.
3153    See, e.g., KSPCreate().
3154 
3155    Level: developer
3156 
3157 .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3158 
3159     Developer Note: fortran interface is not autogenerated as the f90
3160     interface defintion cannot be generated correctly [due to MatFactorInfo]
3161 
3162 @*/
3163 PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3164 {
3165   MatFactorInfo  tinfo;
3166   PetscErrorCode ierr;
3167 
3168   PetscFunctionBegin;
3169   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
3170   PetscValidType(mat,2);
3171   PetscValidPointer(fact,1);
3172   PetscValidHeaderSpecific(fact,MAT_CLASSID,1);
3173   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3174   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dimensions are different %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3175 
3176   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3177   MatCheckPreallocated(mat,2);
3178   if (!info) {
3179     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3180     info = &tinfo;
3181   }
3182 
3183   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);}
3184   else {ierr = PetscLogEventBegin(MAT_LUFactor,mat,fact,0,0);CHKERRQ(ierr);}
3185   ierr = (fact->ops->lufactornumeric)(fact,mat,info);CHKERRQ(ierr);
3186   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);}
3187   else {ierr = PetscLogEventEnd(MAT_LUFactor,mat,fact,0,0);CHKERRQ(ierr);}
3188   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3189   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3190   PetscFunctionReturn(0);
3191 }
3192 
3193 /*@C
3194    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3195    symmetric matrix.
3196 
3197    Collective on Mat
3198 
3199    Input Parameters:
3200 +  mat - the matrix
3201 .  perm - row and column permutations
3202 -  f - expected fill as ratio of original fill
3203 
3204    Notes:
3205    See MatLUFactor() for the nonsymmetric case.  See also
3206    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3207 
3208    Most users should employ the simplified KSP interface for linear solvers
3209    instead of working directly with matrix algebra routines such as this.
3210    See, e.g., KSPCreate().
3211 
3212    Level: developer
3213 
3214 .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3215           MatGetOrdering()
3216 
3217     Developer Note: fortran interface is not autogenerated as the f90
3218     interface defintion cannot be generated correctly [due to MatFactorInfo]
3219 
3220 @*/
3221 PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3222 {
3223   PetscErrorCode ierr;
3224   MatFactorInfo  tinfo;
3225 
3226   PetscFunctionBegin;
3227   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3228   PetscValidType(mat,1);
3229   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3230   if (info) PetscValidPointer(info,3);
3231   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3232   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3233   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3234   if (!mat->ops->choleskyfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"In-place factorization for Mat type %s is not supported, try out-of-place factorization. See MatCholeskyFactorSymbolic/Numeric",((PetscObject)mat)->type_name);
3235   MatCheckPreallocated(mat,1);
3236   if (!info) {
3237     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3238     info = &tinfo;
3239   }
3240 
3241   ierr = PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3242   ierr = (*mat->ops->choleskyfactor)(mat,perm,info);CHKERRQ(ierr);
3243   ierr = PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3244   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3245   PetscFunctionReturn(0);
3246 }
3247 
3248 /*@C
3249    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3250    of a symmetric matrix.
3251 
3252    Collective on Mat
3253 
3254    Input Parameters:
3255 +  fact - the factor matrix obtained with MatGetFactor()
3256 .  mat - the matrix
3257 .  perm - row and column permutations
3258 -  info - options for factorization, includes
3259 $          fill - expected fill as ratio of original fill.
3260 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3261 $                   Run with the option -info to determine an optimal value to use
3262 
3263    Notes:
3264    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3265    MatCholeskyFactor() and MatCholeskyFactorNumeric().
3266 
3267    Most users should employ the simplified KSP interface for linear solvers
3268    instead of working directly with matrix algebra routines such as this.
3269    See, e.g., KSPCreate().
3270 
3271    Level: developer
3272 
3273 .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3274           MatGetOrdering()
3275 
3276     Developer Note: fortran interface is not autogenerated as the f90
3277     interface defintion cannot be generated correctly [due to MatFactorInfo]
3278 
3279 @*/
3280 PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3281 {
3282   PetscErrorCode ierr;
3283   MatFactorInfo  tinfo;
3284 
3285   PetscFunctionBegin;
3286   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
3287   PetscValidType(mat,2);
3288   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,3);
3289   if (info) PetscValidPointer(info,4);
3290   PetscValidPointer(fact,1);
3291   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3292   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3293   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3294   if (!(fact)->ops->choleskyfactorsymbolic) {
3295     MatSolverType stype;
3296     ierr = MatFactorGetSolverType(fact,&stype);CHKERRQ(ierr);
3297     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,stype);
3298   }
3299   MatCheckPreallocated(mat,2);
3300   if (!info) {
3301     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3302     info = &tinfo;
3303   }
3304 
3305   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);}
3306   ierr = (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
3307   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);}
3308   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3309   PetscFunctionReturn(0);
3310 }
3311 
3312 /*@C
3313    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3314    of a symmetric matrix. Call this routine after first calling
3315    MatCholeskyFactorSymbolic().
3316 
3317    Collective on Mat
3318 
3319    Input Parameters:
3320 +  fact - the factor matrix obtained with MatGetFactor()
3321 .  mat - the initial matrix
3322 .  info - options for factorization
3323 -  fact - the symbolic factor of mat
3324 
3325    Notes:
3326    Most users should employ the simplified KSP interface for linear solvers
3327    instead of working directly with matrix algebra routines such as this.
3328    See, e.g., KSPCreate().
3329 
3330    Level: developer
3331 
3332 .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3333 
3334     Developer Note: fortran interface is not autogenerated as the f90
3335     interface defintion cannot be generated correctly [due to MatFactorInfo]
3336 
3337 @*/
3338 PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3339 {
3340   MatFactorInfo  tinfo;
3341   PetscErrorCode ierr;
3342 
3343   PetscFunctionBegin;
3344   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
3345   PetscValidType(mat,2);
3346   PetscValidPointer(fact,1);
3347   PetscValidHeaderSpecific(fact,MAT_CLASSID,1);
3348   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3349   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3350   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dim %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3351   MatCheckPreallocated(mat,2);
3352   if (!info) {
3353     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3354     info = &tinfo;
3355   }
3356 
3357   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);}
3358   else {ierr = PetscLogEventBegin(MAT_CholeskyFactor,mat,fact,0,0);CHKERRQ(ierr);}
3359   ierr = (fact->ops->choleskyfactornumeric)(fact,mat,info);CHKERRQ(ierr);
3360   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);}
3361   else {ierr = PetscLogEventEnd(MAT_CholeskyFactor,mat,fact,0,0);CHKERRQ(ierr);}
3362   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3363   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3364   PetscFunctionReturn(0);
3365 }
3366 
3367 /*@C
3368    MatQRFactor - Performs in-place QR factorization of matrix.
3369 
3370    Collective on Mat
3371 
3372    Input Parameters:
3373 +  mat - the matrix
3374 .  col - column permutation
3375 -  info - options for factorization, includes
3376 $          fill - expected fill as ratio of original fill.
3377 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3378 $                   Run with the option -info to determine an optimal value to use
3379 
3380    Notes:
3381    Most users should employ the simplified KSP interface for linear solvers
3382    instead of working directly with matrix algebra routines such as this.
3383    See, e.g., KSPCreate().
3384 
3385    This changes the state of the matrix to a factored matrix; it cannot be used
3386    for example with MatSetValues() unless one first calls MatSetUnfactored().
3387 
3388    Level: developer
3389 
3390 .seealso: MatQRFactorSymbolic(), MatQRFactorNumeric(), MatLUFactor(),
3391           MatSetUnfactored(), MatFactorInfo, MatGetFactor()
3392 
3393     Developer Note: fortran interface is not autogenerated as the f90
3394     interface defintion cannot be generated correctly [due to MatFactorInfo]
3395 
3396 @*/
3397 PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3398 {
3399   PetscErrorCode ierr;
3400 
3401   PetscFunctionBegin;
3402   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3403   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,2);
3404   if (info) PetscValidPointer(info,3);
3405   PetscValidType(mat,1);
3406   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3407   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3408   MatCheckPreallocated(mat,1);
3409   ierr = PetscLogEventBegin(MAT_QRFactor,mat,col,0,0);CHKERRQ(ierr);
3410   ierr = PetscUseMethod(mat,"MatQRFactor_C", (Mat,IS,const MatFactorInfo*), (mat, col, info));CHKERRQ(ierr);
3411   ierr = PetscLogEventEnd(MAT_QRFactor,mat,col,0,0);CHKERRQ(ierr);
3412   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3413   PetscFunctionReturn(0);
3414 }
3415 
3416 /*@C
3417    MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3418    Call this routine before calling MatQRFactorNumeric().
3419 
3420    Collective on Mat
3421 
3422    Input Parameters:
3423 +  fact - the factor matrix obtained with MatGetFactor()
3424 .  mat - the matrix
3425 .  col - column permutation
3426 -  info - options for factorization, includes
3427 $          fill - expected fill as ratio of original fill.
3428 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3429 $                   Run with the option -info to determine an optimal value to use
3430 
3431    Most users should employ the simplified KSP interface for linear solvers
3432    instead of working directly with matrix algebra routines such as this.
3433    See, e.g., KSPCreate().
3434 
3435    Level: developer
3436 
3437 .seealso: MatQRFactor(), MatQRFactorNumeric(), MatLUFactor(), MatFactorInfo, MatFactorInfoInitialize()
3438 
3439     Developer Note: fortran interface is not autogenerated as the f90
3440     interface defintion cannot be generated correctly [due to MatFactorInfo]
3441 
3442 @*/
3443 PetscErrorCode MatQRFactorSymbolic(Mat fact,Mat mat,IS col,const MatFactorInfo *info)
3444 {
3445   PetscErrorCode ierr;
3446   MatFactorInfo  tinfo;
3447 
3448   PetscFunctionBegin;
3449   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
3450   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
3451   if (info) PetscValidPointer(info,4);
3452   PetscValidType(mat,2);
3453   PetscValidPointer(fact,1);
3454   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3455   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3456   MatCheckPreallocated(mat,2);
3457   if (!info) {
3458     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3459     info = &tinfo;
3460   }
3461 
3462   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_QRFactorSymbolic,fact,mat,col,0);CHKERRQ(ierr);}
3463   ierr = PetscUseMethod(fact,"MatQRFactorSymbolic_C", (Mat,Mat,IS,const MatFactorInfo*), (fact, mat, col, info));CHKERRQ(ierr);
3464   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_QRFactorSymbolic,fact,mat,col,0);CHKERRQ(ierr);}
3465   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3466   PetscFunctionReturn(0);
3467 }
3468 
3469 /*@C
3470    MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3471    Call this routine after first calling MatQRFactorSymbolic().
3472 
3473    Collective on Mat
3474 
3475    Input Parameters:
3476 +  fact - the factor matrix obtained with MatGetFactor()
3477 .  mat - the matrix
3478 -  info - options for factorization
3479 
3480    Notes:
3481    See MatQRFactor() for in-place factorization.
3482 
3483    Most users should employ the simplified KSP interface for linear solvers
3484    instead of working directly with matrix algebra routines such as this.
3485    See, e.g., KSPCreate().
3486 
3487    Level: developer
3488 
3489 .seealso: MatQRFactorSymbolic(), MatLUFactor()
3490 
3491     Developer Note: fortran interface is not autogenerated as the f90
3492     interface defintion cannot be generated correctly [due to MatFactorInfo]
3493 
3494 @*/
3495 PetscErrorCode MatQRFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3496 {
3497   MatFactorInfo  tinfo;
3498   PetscErrorCode ierr;
3499 
3500   PetscFunctionBegin;
3501   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
3502   PetscValidType(mat,2);
3503   PetscValidPointer(fact,1);
3504   PetscValidHeaderSpecific(fact,MAT_CLASSID,1);
3505   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3506   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dimensions are different %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3507 
3508   MatCheckPreallocated(mat,2);
3509   if (!info) {
3510     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3511     info = &tinfo;
3512   }
3513 
3514   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_QRFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);}
3515   else  {ierr = PetscLogEventBegin(MAT_QRFactor,mat,fact,0,0);CHKERRQ(ierr);}
3516   ierr = PetscUseMethod(fact,"MatQRFactorNumeric_C", (Mat,Mat,const MatFactorInfo*), (fact, mat, info));CHKERRQ(ierr);
3517   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_QRFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);}
3518   else {ierr = PetscLogEventEnd(MAT_QRFactor,mat,fact,0,0);CHKERRQ(ierr);}
3519   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3520   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3521   PetscFunctionReturn(0);
3522 }
3523 
3524 /* ----------------------------------------------------------------*/
3525 /*@
3526    MatSolve - Solves A x = b, given a factored matrix.
3527 
3528    Neighbor-wise Collective on Mat
3529 
3530    Input Parameters:
3531 +  mat - the factored matrix
3532 -  b - the right-hand-side vector
3533 
3534    Output Parameter:
3535 .  x - the result vector
3536 
3537    Notes:
3538    The vectors b and x cannot be the same.  I.e., one cannot
3539    call MatSolve(A,x,x).
3540 
3541    Notes:
3542    Most users should employ the simplified KSP interface for linear solvers
3543    instead of working directly with matrix algebra routines such as this.
3544    See, e.g., KSPCreate().
3545 
3546    Level: developer
3547 
3548 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3549 @*/
3550 PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3551 {
3552   PetscErrorCode ierr;
3553 
3554   PetscFunctionBegin;
3555   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3556   PetscValidType(mat,1);
3557   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3558   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3559   PetscCheckSameComm(mat,1,b,2);
3560   PetscCheckSameComm(mat,1,x,3);
3561   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3562   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3563   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3564   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3565   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3566   MatCheckPreallocated(mat,1);
3567 
3568   ierr = PetscLogEventBegin(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3569   if (mat->factorerrortype) {
3570     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3571     ierr = VecSetInf(x);CHKERRQ(ierr);
3572   } else {
3573     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3574     ierr = (*mat->ops->solve)(mat,b,x);CHKERRQ(ierr);
3575   }
3576   ierr = PetscLogEventEnd(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3577   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3578   PetscFunctionReturn(0);
3579 }
3580 
3581 static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3582 {
3583   PetscErrorCode ierr;
3584   Vec            b,x;
3585   PetscInt       m,N,i;
3586   PetscScalar    *bb,*xx;
3587   PetscErrorCode (*f)(Mat,Vec,Vec);
3588 
3589   PetscFunctionBegin;
3590   if (A->factorerrortype) {
3591     ierr = PetscInfo1(A,"MatFactorError %D\n",A->factorerrortype);CHKERRQ(ierr);
3592     ierr = MatSetInf(X);CHKERRQ(ierr);
3593     PetscFunctionReturn(0);
3594   }
3595   f = trans ? A->ops->solvetranspose : A->ops->solve;
3596   if (!f) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3597 
3598   ierr = MatDenseGetArrayRead(B,(const PetscScalar**)&bb);CHKERRQ(ierr);
3599   ierr = MatDenseGetArray(X,&xx);CHKERRQ(ierr);
3600   ierr = MatGetLocalSize(B,&m,NULL);CHKERRQ(ierr);  /* number local rows */
3601   ierr = MatGetSize(B,NULL,&N);CHKERRQ(ierr);       /* total columns in dense matrix */
3602   ierr = MatCreateVecs(A,&x,&b);CHKERRQ(ierr);
3603   for (i=0; i<N; i++) {
3604     ierr = VecPlaceArray(b,bb + i*m);CHKERRQ(ierr);
3605     ierr = VecPlaceArray(x,xx + i*m);CHKERRQ(ierr);
3606     ierr = (*f)(A,b,x);CHKERRQ(ierr);
3607     ierr = VecResetArray(x);CHKERRQ(ierr);
3608     ierr = VecResetArray(b);CHKERRQ(ierr);
3609   }
3610   ierr = VecDestroy(&b);CHKERRQ(ierr);
3611   ierr = VecDestroy(&x);CHKERRQ(ierr);
3612   ierr = MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);CHKERRQ(ierr);
3613   ierr = MatDenseRestoreArray(X,&xx);CHKERRQ(ierr);
3614   PetscFunctionReturn(0);
3615 }
3616 
3617 /*@
3618    MatMatSolve - Solves A X = B, given a factored matrix.
3619 
3620    Neighbor-wise Collective on Mat
3621 
3622    Input Parameters:
3623 +  A - the factored matrix
3624 -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)
3625 
3626    Output Parameter:
3627 .  X - the result matrix (dense matrix)
3628 
3629    Notes:
3630    If B is a MATDENSE matrix then one can call MatMatSolve(A,B,B) except with MKL_CPARDISO;
3631    otherwise, B and X cannot be the same.
3632 
3633    Notes:
3634    Most users should usually employ the simplified KSP interface for linear solvers
3635    instead of working directly with matrix algebra routines such as this.
3636    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3637    at a time.
3638 
3639    Level: developer
3640 
3641 .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3642 @*/
3643 PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3644 {
3645   PetscErrorCode ierr;
3646 
3647   PetscFunctionBegin;
3648   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3649   PetscValidType(A,1);
3650   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3651   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3652   PetscCheckSameComm(A,1,B,2);
3653   PetscCheckSameComm(A,1,X,3);
3654   if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3655   if (A->rmap->N != B->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap->N,B->rmap->N);
3656   if (X->cmap->N != B->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3657   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3658   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3659   MatCheckPreallocated(A,1);
3660 
3661   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3662   if (!A->ops->matsolve) {
3663     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3664     ierr = MatMatSolve_Basic(A,B,X,PETSC_FALSE);CHKERRQ(ierr);
3665   } else {
3666     ierr = (*A->ops->matsolve)(A,B,X);CHKERRQ(ierr);
3667   }
3668   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3669   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3670   PetscFunctionReturn(0);
3671 }
3672 
3673 /*@
3674    MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3675 
3676    Neighbor-wise Collective on Mat
3677 
3678    Input Parameters:
3679 +  A - the factored matrix
3680 -  B - the right-hand-side matrix  (dense matrix)
3681 
3682    Output Parameter:
3683 .  X - the result matrix (dense matrix)
3684 
3685    Notes:
3686    The matrices B and X cannot be the same.  I.e., one cannot
3687    call MatMatSolveTranspose(A,X,X).
3688 
3689    Notes:
3690    Most users should usually employ the simplified KSP interface for linear solvers
3691    instead of working directly with matrix algebra routines such as this.
3692    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3693    at a time.
3694 
3695    When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3696 
3697    Level: developer
3698 
3699 .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3700 @*/
3701 PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3702 {
3703   PetscErrorCode ierr;
3704 
3705   PetscFunctionBegin;
3706   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3707   PetscValidType(A,1);
3708   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3709   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3710   PetscCheckSameComm(A,1,B,2);
3711   PetscCheckSameComm(A,1,X,3);
3712   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3713   if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3714   if (A->rmap->N != B->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap->N,B->rmap->N);
3715   if (A->rmap->n != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat A,Mat B: local dim %D %D",A->rmap->n,B->rmap->n);
3716   if (X->cmap->N < B->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3717   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3718   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3719   MatCheckPreallocated(A,1);
3720 
3721   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3722   if (!A->ops->matsolvetranspose) {
3723     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3724     ierr = MatMatSolve_Basic(A,B,X,PETSC_TRUE);CHKERRQ(ierr);
3725   } else {
3726     ierr = (*A->ops->matsolvetranspose)(A,B,X);CHKERRQ(ierr);
3727   }
3728   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3729   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3730   PetscFunctionReturn(0);
3731 }
3732 
3733 /*@
3734    MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3735 
3736    Neighbor-wise Collective on Mat
3737 
3738    Input Parameters:
3739 +  A - the factored matrix
3740 -  Bt - the transpose of right-hand-side matrix
3741 
3742    Output Parameter:
3743 .  X - the result matrix (dense matrix)
3744 
3745    Notes:
3746    Most users should usually employ the simplified KSP interface for linear solvers
3747    instead of working directly with matrix algebra routines such as this.
3748    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3749    at a time.
3750 
3751    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().
3752 
3753    Level: developer
3754 
3755 .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3756 @*/
3757 PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3758 {
3759   PetscErrorCode ierr;
3760 
3761   PetscFunctionBegin;
3762   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3763   PetscValidType(A,1);
3764   PetscValidHeaderSpecific(Bt,MAT_CLASSID,2);
3765   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3766   PetscCheckSameComm(A,1,Bt,2);
3767   PetscCheckSameComm(A,1,X,3);
3768 
3769   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3770   if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3771   if (A->rmap->N != Bt->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat Bt: global dim %D %D",A->rmap->N,Bt->cmap->N);
3772   if (X->cmap->N < Bt->rmap->N) SETERRQ(PetscObjectComm((PetscObject)X),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as row number of the rhs matrix");
3773   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3774   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3775   MatCheckPreallocated(A,1);
3776 
3777   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3778   ierr = PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3779   ierr = (*A->ops->mattransposesolve)(A,Bt,X);CHKERRQ(ierr);
3780   ierr = PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3781   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3782   PetscFunctionReturn(0);
3783 }
3784 
3785 /*@
3786    MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3787                             U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3788 
3789    Neighbor-wise Collective on Mat
3790 
3791    Input Parameters:
3792 +  mat - the factored matrix
3793 -  b - the right-hand-side vector
3794 
3795    Output Parameter:
3796 .  x - the result vector
3797 
3798    Notes:
3799    MatSolve() should be used for most applications, as it performs
3800    a forward solve followed by a backward solve.
3801 
3802    The vectors b and x cannot be the same,  i.e., one cannot
3803    call MatForwardSolve(A,x,x).
3804 
3805    For matrix in seqsbaij format with block size larger than 1,
3806    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3807    MatForwardSolve() solves U^T*D y = b, and
3808    MatBackwardSolve() solves U x = y.
3809    Thus they do not provide a symmetric preconditioner.
3810 
3811    Most users should employ the simplified KSP interface for linear solvers
3812    instead of working directly with matrix algebra routines such as this.
3813    See, e.g., KSPCreate().
3814 
3815    Level: developer
3816 
3817 .seealso: MatSolve(), MatBackwardSolve()
3818 @*/
3819 PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3820 {
3821   PetscErrorCode ierr;
3822 
3823   PetscFunctionBegin;
3824   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3825   PetscValidType(mat,1);
3826   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3827   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3828   PetscCheckSameComm(mat,1,b,2);
3829   PetscCheckSameComm(mat,1,x,3);
3830   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3831   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3832   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3833   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3834   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3835   MatCheckPreallocated(mat,1);
3836 
3837   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3838   ierr = PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3839   ierr = (*mat->ops->forwardsolve)(mat,b,x);CHKERRQ(ierr);
3840   ierr = PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3841   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3842   PetscFunctionReturn(0);
3843 }
3844 
3845 /*@
3846    MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3847                              D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3848 
3849    Neighbor-wise Collective on Mat
3850 
3851    Input Parameters:
3852 +  mat - the factored matrix
3853 -  b - the right-hand-side vector
3854 
3855    Output Parameter:
3856 .  x - the result vector
3857 
3858    Notes:
3859    MatSolve() should be used for most applications, as it performs
3860    a forward solve followed by a backward solve.
3861 
3862    The vectors b and x cannot be the same.  I.e., one cannot
3863    call MatBackwardSolve(A,x,x).
3864 
3865    For matrix in seqsbaij format with block size larger than 1,
3866    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3867    MatForwardSolve() solves U^T*D y = b, and
3868    MatBackwardSolve() solves U x = y.
3869    Thus they do not provide a symmetric preconditioner.
3870 
3871    Most users should employ the simplified KSP interface for linear solvers
3872    instead of working directly with matrix algebra routines such as this.
3873    See, e.g., KSPCreate().
3874 
3875    Level: developer
3876 
3877 .seealso: MatSolve(), MatForwardSolve()
3878 @*/
3879 PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3880 {
3881   PetscErrorCode ierr;
3882 
3883   PetscFunctionBegin;
3884   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3885   PetscValidType(mat,1);
3886   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3887   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3888   PetscCheckSameComm(mat,1,b,2);
3889   PetscCheckSameComm(mat,1,x,3);
3890   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3891   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3892   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3893   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3894   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3895   MatCheckPreallocated(mat,1);
3896 
3897   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3898   ierr = PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3899   ierr = (*mat->ops->backwardsolve)(mat,b,x);CHKERRQ(ierr);
3900   ierr = PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3901   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3902   PetscFunctionReturn(0);
3903 }
3904 
3905 /*@
3906    MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3907 
3908    Neighbor-wise Collective on Mat
3909 
3910    Input Parameters:
3911 +  mat - the factored matrix
3912 .  b - the right-hand-side vector
3913 -  y - the vector to be added to
3914 
3915    Output Parameter:
3916 .  x - the result vector
3917 
3918    Notes:
3919    The vectors b and x cannot be the same.  I.e., one cannot
3920    call MatSolveAdd(A,x,y,x).
3921 
3922    Most users should employ the simplified KSP interface for linear solvers
3923    instead of working directly with matrix algebra routines such as this.
3924    See, e.g., KSPCreate().
3925 
3926    Level: developer
3927 
3928 .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3929 @*/
3930 PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3931 {
3932   PetscScalar    one = 1.0;
3933   Vec            tmp;
3934   PetscErrorCode ierr;
3935 
3936   PetscFunctionBegin;
3937   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3938   PetscValidType(mat,1);
3939   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
3940   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3941   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3942   PetscCheckSameComm(mat,1,b,2);
3943   PetscCheckSameComm(mat,1,y,3);
3944   PetscCheckSameComm(mat,1,x,4);
3945   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3946   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3947   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3948   if (mat->rmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
3949   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3950   if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
3951   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3952    MatCheckPreallocated(mat,1);
3953 
3954   ierr = PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3955   if (mat->factorerrortype) {
3956     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3957     ierr = VecSetInf(x);CHKERRQ(ierr);
3958   } else if (mat->ops->solveadd) {
3959     ierr = (*mat->ops->solveadd)(mat,b,y,x);CHKERRQ(ierr);
3960   } else {
3961     /* do the solve then the add manually */
3962     if (x != y) {
3963       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3964       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3965     } else {
3966       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3967       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3968       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3969       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3970       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3971       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3972     }
3973   }
3974   ierr = PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3975   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3976   PetscFunctionReturn(0);
3977 }
3978 
3979 /*@
3980    MatSolveTranspose - Solves A' x = b, given a factored matrix.
3981 
3982    Neighbor-wise Collective on Mat
3983 
3984    Input Parameters:
3985 +  mat - the factored matrix
3986 -  b - the right-hand-side vector
3987 
3988    Output Parameter:
3989 .  x - the result vector
3990 
3991    Notes:
3992    The vectors b and x cannot be the same.  I.e., one cannot
3993    call MatSolveTranspose(A,x,x).
3994 
3995    Most users should employ the simplified KSP interface for linear solvers
3996    instead of working directly with matrix algebra routines such as this.
3997    See, e.g., KSPCreate().
3998 
3999    Level: developer
4000 
4001 .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
4002 @*/
4003 PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
4004 {
4005   PetscErrorCode ierr;
4006 
4007   PetscFunctionBegin;
4008   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4009   PetscValidType(mat,1);
4010   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
4011   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
4012   PetscCheckSameComm(mat,1,b,2);
4013   PetscCheckSameComm(mat,1,x,3);
4014   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
4015   if (mat->rmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
4016   if (mat->cmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap->N,b->map->N);
4017   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
4018   MatCheckPreallocated(mat,1);
4019   ierr = PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
4020   if (mat->factorerrortype) {
4021     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
4022     ierr = VecSetInf(x);CHKERRQ(ierr);
4023   } else {
4024     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
4025     ierr = (*mat->ops->solvetranspose)(mat,b,x);CHKERRQ(ierr);
4026   }
4027   ierr = PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
4028   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
4029   PetscFunctionReturn(0);
4030 }
4031 
4032 /*@
4033    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
4034                       factored matrix.
4035 
4036    Neighbor-wise Collective on Mat
4037 
4038    Input Parameters:
4039 +  mat - the factored matrix
4040 .  b - the right-hand-side vector
4041 -  y - the vector to be added to
4042 
4043    Output Parameter:
4044 .  x - the result vector
4045 
4046    Notes:
4047    The vectors b and x cannot be the same.  I.e., one cannot
4048    call MatSolveTransposeAdd(A,x,y,x).
4049 
4050    Most users should employ the simplified KSP interface for linear solvers
4051    instead of working directly with matrix algebra routines such as this.
4052    See, e.g., KSPCreate().
4053 
4054    Level: developer
4055 
4056 .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
4057 @*/
4058 PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
4059 {
4060   PetscScalar    one = 1.0;
4061   PetscErrorCode ierr;
4062   Vec            tmp;
4063 
4064   PetscFunctionBegin;
4065   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4066   PetscValidType(mat,1);
4067   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
4068   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
4069   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
4070   PetscCheckSameComm(mat,1,b,2);
4071   PetscCheckSameComm(mat,1,y,3);
4072   PetscCheckSameComm(mat,1,x,4);
4073   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
4074   if (mat->rmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
4075   if (mat->cmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap->N,b->map->N);
4076   if (mat->cmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
4077   if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
4078   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
4079    MatCheckPreallocated(mat,1);
4080 
4081   ierr = PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
4082   if (mat->factorerrortype) {
4083     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
4084     ierr = VecSetInf(x);CHKERRQ(ierr);
4085   } else if (mat->ops->solvetransposeadd){
4086     ierr = (*mat->ops->solvetransposeadd)(mat,b,y,x);CHKERRQ(ierr);
4087   } else {
4088     /* do the solve then the add manually */
4089     if (x != y) {
4090       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
4091       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
4092     } else {
4093       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
4094       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
4095       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
4096       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
4097       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
4098       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
4099     }
4100   }
4101   ierr = PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
4102   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
4103   PetscFunctionReturn(0);
4104 }
4105 /* ----------------------------------------------------------------*/
4106 
4107 /*@
4108    MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
4109 
4110    Neighbor-wise Collective on Mat
4111 
4112    Input Parameters:
4113 +  mat - the matrix
4114 .  b - the right hand side
4115 .  omega - the relaxation factor
4116 .  flag - flag indicating the type of SOR (see below)
4117 .  shift -  diagonal shift
4118 .  its - the number of iterations
4119 -  lits - the number of local iterations
4120 
4121    Output Parameters:
4122 .  x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
4123 
4124    SOR Flags:
4125 +     SOR_FORWARD_SWEEP - forward SOR
4126 .     SOR_BACKWARD_SWEEP - backward SOR
4127 .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
4128 .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
4129 .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
4130 .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
4131 .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
4132          upper/lower triangular part of matrix to
4133          vector (with omega)
4134 -     SOR_ZERO_INITIAL_GUESS - zero initial guess
4135 
4136    Notes:
4137    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
4138    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
4139    on each processor.
4140 
4141    Application programmers will not generally use MatSOR() directly,
4142    but instead will employ the KSP/PC interface.
4143 
4144    Notes:
4145     for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
4146 
4147    Notes for Advanced Users:
4148    The flags are implemented as bitwise inclusive or operations.
4149    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
4150    to specify a zero initial guess for SSOR.
4151 
4152    Most users should employ the simplified KSP interface for linear solvers
4153    instead of working directly with matrix algebra routines such as this.
4154    See, e.g., KSPCreate().
4155 
4156    Vectors x and b CANNOT be the same
4157 
4158    Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
4159 
4160    Level: developer
4161 
4162 @*/
4163 PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
4164 {
4165   PetscErrorCode ierr;
4166 
4167   PetscFunctionBegin;
4168   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4169   PetscValidType(mat,1);
4170   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
4171   PetscValidHeaderSpecific(x,VEC_CLASSID,8);
4172   PetscCheckSameComm(mat,1,b,2);
4173   PetscCheckSameComm(mat,1,x,8);
4174   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4175   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4176   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4177   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
4178   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
4179   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
4180   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
4181   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
4182   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
4183 
4184   MatCheckPreallocated(mat,1);
4185   ierr = PetscLogEventBegin(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
4186   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);CHKERRQ(ierr);
4187   ierr = PetscLogEventEnd(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
4188   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
4189   PetscFunctionReturn(0);
4190 }
4191 
4192 /*
4193       Default matrix copy routine.
4194 */
4195 PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4196 {
4197   PetscErrorCode    ierr;
4198   PetscInt          i,rstart = 0,rend = 0,nz;
4199   const PetscInt    *cwork;
4200   const PetscScalar *vwork;
4201 
4202   PetscFunctionBegin;
4203   if (B->assembled) {
4204     ierr = MatZeroEntries(B);CHKERRQ(ierr);
4205   }
4206   if (str == SAME_NONZERO_PATTERN) {
4207     ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
4208     for (i=rstart; i<rend; i++) {
4209       ierr = MatGetRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
4210       ierr = MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);CHKERRQ(ierr);
4211       ierr = MatRestoreRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
4212     }
4213   } else {
4214     ierr = MatAYPX(B,0.0,A,str);CHKERRQ(ierr);
4215   }
4216   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4217   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4218   PetscFunctionReturn(0);
4219 }
4220 
4221 /*@
4222    MatCopy - Copies a matrix to another matrix.
4223 
4224    Collective on Mat
4225 
4226    Input Parameters:
4227 +  A - the matrix
4228 -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
4229 
4230    Output Parameter:
4231 .  B - where the copy is put
4232 
4233    Notes:
4234    If you use SAME_NONZERO_PATTERN then the two matrices must have the same nonzero pattern or the routine will crash.
4235 
4236    MatCopy() copies the matrix entries of a matrix to another existing
4237    matrix (after first zeroing the second matrix).  A related routine is
4238    MatConvert(), which first creates a new matrix and then copies the data.
4239 
4240    Level: intermediate
4241 
4242 .seealso: MatConvert(), MatDuplicate()
4243 
4244 @*/
4245 PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4246 {
4247   PetscErrorCode ierr;
4248   PetscInt       i;
4249 
4250   PetscFunctionBegin;
4251   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4252   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4253   PetscValidType(A,1);
4254   PetscValidType(B,2);
4255   PetscCheckSameComm(A,1,B,2);
4256   MatCheckPreallocated(B,2);
4257   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4258   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4259   if (A->rmap->N != B->rmap->N || A->cmap->N != B->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim (%D,%D) (%D,%D)",A->rmap->N,B->rmap->N,A->cmap->N,B->cmap->N);
4260   MatCheckPreallocated(A,1);
4261   if (A == B) PetscFunctionReturn(0);
4262 
4263   ierr = PetscLogEventBegin(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
4264   if (A->ops->copy) {
4265     ierr = (*A->ops->copy)(A,B,str);CHKERRQ(ierr);
4266   } else { /* generic conversion */
4267     ierr = MatCopy_Basic(A,B,str);CHKERRQ(ierr);
4268   }
4269 
4270   B->stencil.dim = A->stencil.dim;
4271   B->stencil.noc = A->stencil.noc;
4272   for (i=0; i<=A->stencil.dim; i++) {
4273     B->stencil.dims[i]   = A->stencil.dims[i];
4274     B->stencil.starts[i] = A->stencil.starts[i];
4275   }
4276 
4277   ierr = PetscLogEventEnd(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
4278   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4279   PetscFunctionReturn(0);
4280 }
4281 
4282 /*@C
4283    MatConvert - Converts a matrix to another matrix, either of the same
4284    or different type.
4285 
4286    Collective on Mat
4287 
4288    Input Parameters:
4289 +  mat - the matrix
4290 .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4291    same type as the original matrix.
4292 -  reuse - denotes if the destination matrix is to be created or reused.
4293    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
4294    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).
4295 
4296    Output Parameter:
4297 .  M - pointer to place new matrix
4298 
4299    Notes:
4300    MatConvert() first creates a new matrix and then copies the data from
4301    the first matrix.  A related routine is MatCopy(), which copies the matrix
4302    entries of one matrix to another already existing matrix context.
4303 
4304    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4305    the MPI communicator of the generated matrix is always the same as the communicator
4306    of the input matrix.
4307 
4308    Level: intermediate
4309 
4310 .seealso: MatCopy(), MatDuplicate()
4311 @*/
4312 PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4313 {
4314   PetscErrorCode ierr;
4315   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4316   char           convname[256],mtype[256];
4317   Mat            B;
4318 
4319   PetscFunctionBegin;
4320   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4321   PetscValidType(mat,1);
4322   PetscValidPointer(M,4);
4323   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4324   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4325   MatCheckPreallocated(mat,1);
4326 
4327   ierr = PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,sizeof(mtype),&flg);CHKERRQ(ierr);
4328   if (flg) newtype = mtype;
4329 
4330   ierr = PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);CHKERRQ(ierr);
4331   ierr = PetscStrcmp(newtype,"same",&issame);CHKERRQ(ierr);
4332   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4333   if ((reuse == MAT_REUSE_MATRIX) && (mat == *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4334 
4335   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4336     ierr = PetscInfo3(mat,"Early return for inplace %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);CHKERRQ(ierr);
4337     PetscFunctionReturn(0);
4338   }
4339 
4340   /* Cache Mat options because some converter use MatHeaderReplace  */
4341   issymmetric = mat->symmetric;
4342   ishermitian = mat->hermitian;
4343 
4344   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4345     ierr = PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);CHKERRQ(ierr);
4346     ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4347   } else {
4348     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4349     const char     *prefix[3] = {"seq","mpi",""};
4350     PetscInt       i;
4351     /*
4352        Order of precedence:
4353        0) See if newtype is a superclass of the current matrix.
4354        1) See if a specialized converter is known to the current matrix.
4355        2) See if a specialized converter is known to the desired matrix class.
4356        3) See if a good general converter is registered for the desired class
4357           (as of 6/27/03 only MATMPIADJ falls into this category).
4358        4) See if a good general converter is known for the current matrix.
4359        5) Use a really basic converter.
4360     */
4361 
4362     /* 0) See if newtype is a superclass of the current matrix.
4363           i.e mat is mpiaij and newtype is aij */
4364     for (i=0; i<2; i++) {
4365       ierr = PetscStrncpy(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4366       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4367       ierr = PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);CHKERRQ(ierr);
4368       ierr = PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);CHKERRQ(ierr);
4369       if (flg) {
4370         if (reuse == MAT_INPLACE_MATRIX) {
4371           ierr = PetscInfo(mat,"Early return\n");CHKERRQ(ierr);
4372           PetscFunctionReturn(0);
4373         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4374           ierr = PetscInfo(mat,"Calling MatDuplicate\n");CHKERRQ(ierr);
4375           ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4376           PetscFunctionReturn(0);
4377         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4378           ierr = PetscInfo(mat,"Calling MatCopy\n");CHKERRQ(ierr);
4379           ierr = MatCopy(mat,*M,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
4380           PetscFunctionReturn(0);
4381         }
4382       }
4383     }
4384     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4385     for (i=0; i<3; i++) {
4386       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4387       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4388       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4389       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4390       ierr = PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));CHKERRQ(ierr);
4391       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4392       ierr = PetscObjectQueryFunction((PetscObject)mat,convname,&conv);CHKERRQ(ierr);
4393       ierr = PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);CHKERRQ(ierr);
4394       if (conv) goto foundconv;
4395     }
4396 
4397     /* 2)  See if a specialized converter is known to the desired matrix class. */
4398     ierr = MatCreate(PetscObjectComm((PetscObject)mat),&B);CHKERRQ(ierr);
4399     ierr = MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);CHKERRQ(ierr);
4400     ierr = MatSetType(B,newtype);CHKERRQ(ierr);
4401     for (i=0; i<3; i++) {
4402       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4403       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4404       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4405       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4406       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4407       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4408       ierr = PetscObjectQueryFunction((PetscObject)B,convname,&conv);CHKERRQ(ierr);
4409       ierr = PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);CHKERRQ(ierr);
4410       if (conv) {
4411         ierr = MatDestroy(&B);CHKERRQ(ierr);
4412         goto foundconv;
4413       }
4414     }
4415 
4416     /* 3) See if a good general converter is registered for the desired class */
4417     conv = B->ops->convertfrom;
4418     ierr = PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);CHKERRQ(ierr);
4419     ierr = MatDestroy(&B);CHKERRQ(ierr);
4420     if (conv) goto foundconv;
4421 
4422     /* 4) See if a good general converter is known for the current matrix */
4423     if (mat->ops->convert) conv = mat->ops->convert;
4424 
4425     ierr = PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);CHKERRQ(ierr);
4426     if (conv) goto foundconv;
4427 
4428     /* 5) Use a really basic converter. */
4429     ierr = PetscInfo(mat,"Using MatConvert_Basic\n");CHKERRQ(ierr);
4430     conv = MatConvert_Basic;
4431 
4432 foundconv:
4433     ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4434     ierr = (*conv)(mat,newtype,reuse,M);CHKERRQ(ierr);
4435     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4436       /* the block sizes must be same if the mappings are copied over */
4437       (*M)->rmap->bs = mat->rmap->bs;
4438       (*M)->cmap->bs = mat->cmap->bs;
4439       ierr = PetscObjectReference((PetscObject)mat->rmap->mapping);CHKERRQ(ierr);
4440       ierr = PetscObjectReference((PetscObject)mat->cmap->mapping);CHKERRQ(ierr);
4441       (*M)->rmap->mapping = mat->rmap->mapping;
4442       (*M)->cmap->mapping = mat->cmap->mapping;
4443     }
4444     (*M)->stencil.dim = mat->stencil.dim;
4445     (*M)->stencil.noc = mat->stencil.noc;
4446     for (i=0; i<=mat->stencil.dim; i++) {
4447       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4448       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4449     }
4450     ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4451   }
4452   ierr = PetscObjectStateIncrease((PetscObject)*M);CHKERRQ(ierr);
4453 
4454   /* Copy Mat options */
4455   if (issymmetric) {
4456     ierr = MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
4457   }
4458   if (ishermitian) {
4459     ierr = MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
4460   }
4461   PetscFunctionReturn(0);
4462 }
4463 
4464 /*@C
4465    MatFactorGetSolverType - Returns name of the package providing the factorization routines
4466 
4467    Not Collective
4468 
4469    Input Parameter:
4470 .  mat - the matrix, must be a factored matrix
4471 
4472    Output Parameter:
4473 .   type - the string name of the package (do not free this string)
4474 
4475    Notes:
4476       In Fortran you pass in a empty string and the package name will be copied into it.
4477     (Make sure the string is long enough)
4478 
4479    Level: intermediate
4480 
4481 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4482 @*/
4483 PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4484 {
4485   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4486 
4487   PetscFunctionBegin;
4488   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4489   PetscValidType(mat,1);
4490   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4491   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);CHKERRQ(ierr);
4492   if (!conv) {
4493     *type = MATSOLVERPETSC;
4494   } else {
4495     ierr = (*conv)(mat,type);CHKERRQ(ierr);
4496   }
4497   PetscFunctionReturn(0);
4498 }
4499 
4500 typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4501 struct _MatSolverTypeForSpecifcType {
4502   MatType                        mtype;
4503   /* no entry for MAT_FACTOR_NONE */
4504   PetscErrorCode                 (*createfactor[MAT_FACTOR_NUM_TYPES-1])(Mat,MatFactorType,Mat*);
4505   MatSolverTypeForSpecifcType next;
4506 };
4507 
4508 typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4509 struct _MatSolverTypeHolder {
4510   char                        *name;
4511   MatSolverTypeForSpecifcType handlers;
4512   MatSolverTypeHolder         next;
4513 };
4514 
4515 static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4516 
4517 /*@C
4518    MatSolverTypeRegister - Registers a MatSolverType that works for a particular matrix type
4519 
4520    Input Parameters:
4521 +    package - name of the package, for example petsc or superlu
4522 .    mtype - the matrix type that works with this package
4523 .    ftype - the type of factorization supported by the package
4524 -    createfactor - routine that will create the factored matrix ready to be used
4525 
4526     Level: intermediate
4527 
4528 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4529 @*/
4530 PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*createfactor)(Mat,MatFactorType,Mat*))
4531 {
4532   PetscErrorCode              ierr;
4533   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4534   PetscBool                   flg;
4535   MatSolverTypeForSpecifcType inext,iprev = NULL;
4536 
4537   PetscFunctionBegin;
4538   ierr = MatInitializePackage();CHKERRQ(ierr);
4539   if (!next) {
4540     ierr = PetscNew(&MatSolverTypeHolders);CHKERRQ(ierr);
4541     ierr = PetscStrallocpy(package,&MatSolverTypeHolders->name);CHKERRQ(ierr);
4542     ierr = PetscNew(&MatSolverTypeHolders->handlers);CHKERRQ(ierr);
4543     ierr = PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);CHKERRQ(ierr);
4544     MatSolverTypeHolders->handlers->createfactor[(int)ftype-1] = createfactor;
4545     PetscFunctionReturn(0);
4546   }
4547   while (next) {
4548     ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4549     if (flg) {
4550       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4551       inext = next->handlers;
4552       while (inext) {
4553         ierr = PetscStrcasecmp(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4554         if (flg) {
4555           inext->createfactor[(int)ftype-1] = createfactor;
4556           PetscFunctionReturn(0);
4557         }
4558         iprev = inext;
4559         inext = inext->next;
4560       }
4561       ierr = PetscNew(&iprev->next);CHKERRQ(ierr);
4562       ierr = PetscStrallocpy(mtype,(char **)&iprev->next->mtype);CHKERRQ(ierr);
4563       iprev->next->createfactor[(int)ftype-1] = createfactor;
4564       PetscFunctionReturn(0);
4565     }
4566     prev = next;
4567     next = next->next;
4568   }
4569   ierr = PetscNew(&prev->next);CHKERRQ(ierr);
4570   ierr = PetscStrallocpy(package,&prev->next->name);CHKERRQ(ierr);
4571   ierr = PetscNew(&prev->next->handlers);CHKERRQ(ierr);
4572   ierr = PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);CHKERRQ(ierr);
4573   prev->next->handlers->createfactor[(int)ftype-1] = createfactor;
4574   PetscFunctionReturn(0);
4575 }
4576 
4577 /*@C
4578    MatSolveTypeGet - Gets the function that creates the factor matrix if it exist
4579 
4580    Input Parameters:
4581 +    type - name of the package, for example petsc or superlu
4582 .    ftype - the type of factorization supported by the type
4583 -    mtype - the matrix type that works with this type
4584 
4585    Output Parameters:
4586 +   foundtype - PETSC_TRUE if the type was registered
4587 .   foundmtype - PETSC_TRUE if the type supports the requested mtype
4588 -   createfactor - routine that will create the factored matrix ready to be used or NULL if not found
4589 
4590     Level: intermediate
4591 
4592 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatSolverTypeRegister(), MatGetFactor()
4593 @*/
4594 PetscErrorCode MatSolverTypeGet(MatSolverType type,MatType mtype,MatFactorType ftype,PetscBool *foundtype,PetscBool *foundmtype,PetscErrorCode (**createfactor)(Mat,MatFactorType,Mat*))
4595 {
4596   PetscErrorCode              ierr;
4597   MatSolverTypeHolder         next = MatSolverTypeHolders;
4598   PetscBool                   flg;
4599   MatSolverTypeForSpecifcType inext;
4600 
4601   PetscFunctionBegin;
4602   if (foundtype) *foundtype = PETSC_FALSE;
4603   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4604   if (createfactor) *createfactor    = NULL;
4605 
4606   if (type) {
4607     while (next) {
4608       ierr = PetscStrcasecmp(type,next->name,&flg);CHKERRQ(ierr);
4609       if (flg) {
4610         if (foundtype) *foundtype = PETSC_TRUE;
4611         inext = next->handlers;
4612         while (inext) {
4613           ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4614           if (flg) {
4615             if (foundmtype) *foundmtype = PETSC_TRUE;
4616             if (createfactor)  *createfactor  = inext->createfactor[(int)ftype-1];
4617             PetscFunctionReturn(0);
4618           }
4619           inext = inext->next;
4620         }
4621       }
4622       next = next->next;
4623     }
4624   } else {
4625     while (next) {
4626       inext = next->handlers;
4627       while (inext) {
4628         ierr = PetscStrcmp(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4629         if (flg && inext->createfactor[(int)ftype-1]) {
4630           if (foundtype) *foundtype = PETSC_TRUE;
4631           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4632           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4633           PetscFunctionReturn(0);
4634         }
4635         inext = inext->next;
4636       }
4637       next = next->next;
4638     }
4639     /* try with base classes inext->mtype */
4640     next = MatSolverTypeHolders;
4641     while (next) {
4642       inext = next->handlers;
4643       while (inext) {
4644         ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4645         if (flg && inext->createfactor[(int)ftype-1]) {
4646           if (foundtype) *foundtype = PETSC_TRUE;
4647           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4648           if (createfactor) *createfactor = inext->createfactor[(int)ftype-1];
4649           PetscFunctionReturn(0);
4650         }
4651         inext = inext->next;
4652       }
4653       next = next->next;
4654     }
4655   }
4656   PetscFunctionReturn(0);
4657 }
4658 
4659 PetscErrorCode MatSolverTypeDestroy(void)
4660 {
4661   PetscErrorCode              ierr;
4662   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4663   MatSolverTypeForSpecifcType inext,iprev;
4664 
4665   PetscFunctionBegin;
4666   while (next) {
4667     ierr = PetscFree(next->name);CHKERRQ(ierr);
4668     inext = next->handlers;
4669     while (inext) {
4670       ierr = PetscFree(inext->mtype);CHKERRQ(ierr);
4671       iprev = inext;
4672       inext = inext->next;
4673       ierr = PetscFree(iprev);CHKERRQ(ierr);
4674     }
4675     prev = next;
4676     next = next->next;
4677     ierr = PetscFree(prev);CHKERRQ(ierr);
4678   }
4679   MatSolverTypeHolders = NULL;
4680   PetscFunctionReturn(0);
4681 }
4682 
4683 /*@C
4684    MatFactorGetCanUseOrdering - Indicates if the factorization can use the ordering provided in MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4685 
4686    Logically Collective on Mat
4687 
4688    Input Parameters:
4689 .  mat - the matrix
4690 
4691    Output Parameters:
4692 .  flg - PETSC_TRUE if uses the ordering
4693 
4694    Notes:
4695       Most internal PETSc factorizations use the ordering passed to the factorization routine but external
4696       packages do not, thus we want to skip generating the ordering when it is not needed or used.
4697 
4698    Level: developer
4699 
4700 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4701 @*/
4702 PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4703 {
4704   PetscFunctionBegin;
4705   *flg = mat->canuseordering;
4706   PetscFunctionReturn(0);
4707 }
4708 
4709 /*@C
4710    MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object
4711 
4712    Logically Collective on Mat
4713 
4714    Input Parameters:
4715 .  mat - the matrix
4716 
4717    Output Parameters:
4718 .  otype - the preferred type
4719 
4720    Level: developer
4721 
4722 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4723 @*/
4724 PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4725 {
4726   PetscFunctionBegin;
4727   *otype = mat->preferredordering[ftype];
4728   if (!*otype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatFactor did not have a preferred ordering");
4729   PetscFunctionReturn(0);
4730 }
4731 
4732 /*@C
4733    MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4734 
4735    Collective on Mat
4736 
4737    Input Parameters:
4738 +  mat - the matrix
4739 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4740 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4741 
4742    Output Parameters:
4743 .  f - the factor matrix used with MatXXFactorSymbolic() calls
4744 
4745    Notes:
4746       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4747      such as pastix, superlu, mumps etc.
4748 
4749       PETSc must have been ./configure to use the external solver, using the option --download-package
4750 
4751    Developer Notes:
4752       This should actually be called MatCreateFactor() since it creates a new factor object
4753 
4754    Level: intermediate
4755 
4756 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetCanUseOrdering(), MatSolverTypeRegister()
4757 @*/
4758 PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4759 {
4760   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4761   PetscBool      foundtype,foundmtype;
4762 
4763   PetscFunctionBegin;
4764   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4765   PetscValidType(mat,1);
4766 
4767   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4768   MatCheckPreallocated(mat,1);
4769 
4770   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundtype,&foundmtype,&conv);CHKERRQ(ierr);
4771   if (!foundtype) {
4772     if (type) {
4773       SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver type %s for factorization type %s and matrix type %s. Perhaps you must ./configure with --download-%s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name,type);
4774     } else {
4775       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver type for factorization type %s and matrix type %s.",MatFactorTypes[ftype],((PetscObject)mat)->type_name);
4776     }
4777   }
4778   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4779   if (!conv) SETERRQ3(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support factorization type %s for matrix type %s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name);
4780 
4781   ierr = (*conv)(mat,ftype,f);CHKERRQ(ierr);
4782   PetscFunctionReturn(0);
4783 }
4784 
4785 /*@C
4786    MatGetFactorAvailable - Returns a a flag if matrix supports particular type and factor type
4787 
4788    Not Collective
4789 
4790    Input Parameters:
4791 +  mat - the matrix
4792 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4793 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4794 
4795    Output Parameter:
4796 .    flg - PETSC_TRUE if the factorization is available
4797 
4798    Notes:
4799       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4800      such as pastix, superlu, mumps etc.
4801 
4802       PETSc must have been ./configure to use the external solver, using the option --download-package
4803 
4804    Developer Notes:
4805       This should actually be called MatCreateFactorAvailable() since MatGetFactor() creates a new factor object
4806 
4807    Level: intermediate
4808 
4809 .seealso: MatCopy(), MatDuplicate(), MatGetFactor(), MatSolverTypeRegister()
4810 @*/
4811 PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4812 {
4813   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4814 
4815   PetscFunctionBegin;
4816   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4817   PetscValidType(mat,1);
4818 
4819   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4820   MatCheckPreallocated(mat,1);
4821 
4822   *flg = PETSC_FALSE;
4823   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);CHKERRQ(ierr);
4824   if (gconv) {
4825     *flg = PETSC_TRUE;
4826   }
4827   PetscFunctionReturn(0);
4828 }
4829 
4830 #include <petscdmtypes.h>
4831 
4832 /*@
4833    MatDuplicate - Duplicates a matrix including the non-zero structure.
4834 
4835    Collective on Mat
4836 
4837    Input Parameters:
4838 +  mat - the matrix
4839 -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4840         See the manual page for MatDuplicateOption for an explanation of these options.
4841 
4842    Output Parameter:
4843 .  M - pointer to place new matrix
4844 
4845    Level: intermediate
4846 
4847    Notes:
4848     You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4849     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.
4850 
4851 .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4852 @*/
4853 PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4854 {
4855   PetscErrorCode ierr;
4856   Mat            B;
4857   PetscInt       i;
4858   DM             dm;
4859   void           (*viewf)(void);
4860 
4861   PetscFunctionBegin;
4862   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4863   PetscValidType(mat,1);
4864   PetscValidPointer(M,3);
4865   if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4866   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4867   MatCheckPreallocated(mat,1);
4868 
4869   *M = NULL;
4870   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4871   ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4872   ierr = (*mat->ops->duplicate)(mat,op,M);CHKERRQ(ierr);
4873   B    = *M;
4874 
4875   ierr = MatGetOperation(mat,MATOP_VIEW,&viewf);CHKERRQ(ierr);
4876   if (viewf) {
4877     ierr = MatSetOperation(B,MATOP_VIEW,viewf);CHKERRQ(ierr);
4878   }
4879 
4880   B->stencil.dim = mat->stencil.dim;
4881   B->stencil.noc = mat->stencil.noc;
4882   for (i=0; i<=mat->stencil.dim; i++) {
4883     B->stencil.dims[i]   = mat->stencil.dims[i];
4884     B->stencil.starts[i] = mat->stencil.starts[i];
4885   }
4886 
4887   B->nooffproczerorows = mat->nooffproczerorows;
4888   B->nooffprocentries  = mat->nooffprocentries;
4889 
4890   ierr = PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);CHKERRQ(ierr);
4891   if (dm) {
4892     ierr = PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);CHKERRQ(ierr);
4893   }
4894   ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4895   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4896   PetscFunctionReturn(0);
4897 }
4898 
4899 /*@
4900    MatGetDiagonal - Gets the diagonal of a matrix.
4901 
4902    Logically Collective on Mat
4903 
4904    Input Parameters:
4905 +  mat - the matrix
4906 -  v - the vector for storing the diagonal
4907 
4908    Output Parameter:
4909 .  v - the diagonal of the matrix
4910 
4911    Level: intermediate
4912 
4913    Note:
4914    Currently only correct in parallel for square matrices.
4915 
4916 .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4917 @*/
4918 PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4919 {
4920   PetscErrorCode ierr;
4921 
4922   PetscFunctionBegin;
4923   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4924   PetscValidType(mat,1);
4925   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4926   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4927   if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4928   MatCheckPreallocated(mat,1);
4929 
4930   ierr = (*mat->ops->getdiagonal)(mat,v);CHKERRQ(ierr);
4931   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4932   PetscFunctionReturn(0);
4933 }
4934 
4935 /*@C
4936    MatGetRowMin - Gets the minimum value (of the real part) of each
4937         row of the matrix
4938 
4939    Logically Collective on Mat
4940 
4941    Input Parameters:
4942 .  mat - the matrix
4943 
4944    Output Parameter:
4945 +  v - the vector for storing the maximums
4946 -  idx - the indices of the column found for each row (optional)
4947 
4948    Level: intermediate
4949 
4950    Notes:
4951     The result of this call are the same as if one converted the matrix to dense format
4952       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4953 
4954     This code is only implemented for a couple of matrix formats.
4955 
4956 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4957           MatGetRowMax()
4958 @*/
4959 PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4960 {
4961   PetscErrorCode ierr;
4962 
4963   PetscFunctionBegin;
4964   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4965   PetscValidType(mat,1);
4966   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4967   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4968 
4969   if (!mat->cmap->N) {
4970     ierr = VecSet(v,PETSC_MAX_REAL);CHKERRQ(ierr);
4971     if (idx) {
4972       PetscInt i,m = mat->rmap->n;
4973       for (i=0; i<m; i++) idx[i] = -1;
4974     }
4975   } else {
4976     if (!mat->ops->getrowmin) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4977     MatCheckPreallocated(mat,1);
4978   }
4979   ierr = (*mat->ops->getrowmin)(mat,v,idx);CHKERRQ(ierr);
4980   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4981   PetscFunctionReturn(0);
4982 }
4983 
4984 /*@C
4985    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4986         row of the matrix
4987 
4988    Logically Collective on Mat
4989 
4990    Input Parameters:
4991 .  mat - the matrix
4992 
4993    Output Parameter:
4994 +  v - the vector for storing the minimums
4995 -  idx - the indices of the column found for each row (or NULL if not needed)
4996 
4997    Level: intermediate
4998 
4999    Notes:
5000     if a row is completely empty or has only 0.0 values then the idx[] value for that
5001     row is 0 (the first column).
5002 
5003     This code is only implemented for a couple of matrix formats.
5004 
5005 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
5006 @*/
5007 PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
5008 {
5009   PetscErrorCode ierr;
5010 
5011   PetscFunctionBegin;
5012   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5013   PetscValidType(mat,1);
5014   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
5015   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5016   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5017 
5018   if (!mat->cmap->N) {
5019     ierr = VecSet(v,0.0);CHKERRQ(ierr);
5020     if (idx) {
5021       PetscInt i,m = mat->rmap->n;
5022       for (i=0; i<m; i++) idx[i] = -1;
5023     }
5024   } else {
5025     if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5026     MatCheckPreallocated(mat,1);
5027     if (idx) {ierr = PetscArrayzero(idx,mat->rmap->n);CHKERRQ(ierr);}
5028     ierr = (*mat->ops->getrowminabs)(mat,v,idx);CHKERRQ(ierr);
5029   }
5030   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
5031   PetscFunctionReturn(0);
5032 }
5033 
5034 /*@C
5035    MatGetRowMax - Gets the maximum value (of the real part) of each
5036         row of the matrix
5037 
5038    Logically Collective on Mat
5039 
5040    Input Parameters:
5041 .  mat - the matrix
5042 
5043    Output Parameter:
5044 +  v - the vector for storing the maximums
5045 -  idx - the indices of the column found for each row (optional)
5046 
5047    Level: intermediate
5048 
5049    Notes:
5050     The result of this call are the same as if one converted the matrix to dense format
5051       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5052 
5053     This code is only implemented for a couple of matrix formats.
5054 
5055 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
5056 @*/
5057 PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
5058 {
5059   PetscErrorCode ierr;
5060 
5061   PetscFunctionBegin;
5062   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5063   PetscValidType(mat,1);
5064   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
5065   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5066 
5067   if (!mat->cmap->N) {
5068     ierr = VecSet(v,PETSC_MIN_REAL);CHKERRQ(ierr);
5069     if (idx) {
5070       PetscInt i,m = mat->rmap->n;
5071       for (i=0; i<m; i++) idx[i] = -1;
5072     }
5073   } else {
5074     if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5075     MatCheckPreallocated(mat,1);
5076     ierr = (*mat->ops->getrowmax)(mat,v,idx);CHKERRQ(ierr);
5077   }
5078   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
5079   PetscFunctionReturn(0);
5080 }
5081 
5082 /*@C
5083    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5084         row of the matrix
5085 
5086    Logically Collective on Mat
5087 
5088    Input Parameters:
5089 .  mat - the matrix
5090 
5091    Output Parameter:
5092 +  v - the vector for storing the maximums
5093 -  idx - the indices of the column found for each row (or NULL if not needed)
5094 
5095    Level: intermediate
5096 
5097    Notes:
5098     if a row is completely empty or has only 0.0 values then the idx[] value for that
5099     row is 0 (the first column).
5100 
5101     This code is only implemented for a couple of matrix formats.
5102 
5103 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
5104 @*/
5105 PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
5106 {
5107   PetscErrorCode ierr;
5108 
5109   PetscFunctionBegin;
5110   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5111   PetscValidType(mat,1);
5112   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
5113   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5114 
5115   if (!mat->cmap->N) {
5116     ierr = VecSet(v,0.0);CHKERRQ(ierr);
5117     if (idx) {
5118       PetscInt i,m = mat->rmap->n;
5119       for (i=0; i<m; i++) idx[i] = -1;
5120     }
5121   } else {
5122     if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5123     MatCheckPreallocated(mat,1);
5124     if (idx) {ierr = PetscArrayzero(idx,mat->rmap->n);CHKERRQ(ierr);}
5125     ierr = (*mat->ops->getrowmaxabs)(mat,v,idx);CHKERRQ(ierr);
5126   }
5127   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
5128   PetscFunctionReturn(0);
5129 }
5130 
5131 /*@
5132    MatGetRowSum - Gets the sum of each row of the matrix
5133 
5134    Logically or Neighborhood Collective on Mat
5135 
5136    Input Parameters:
5137 .  mat - the matrix
5138 
5139    Output Parameter:
5140 .  v - the vector for storing the sum of rows
5141 
5142    Level: intermediate
5143 
5144    Notes:
5145     This code is slow since it is not currently specialized for different formats
5146 
5147 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
5148 @*/
5149 PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5150 {
5151   Vec            ones;
5152   PetscErrorCode ierr;
5153 
5154   PetscFunctionBegin;
5155   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5156   PetscValidType(mat,1);
5157   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
5158   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5159   MatCheckPreallocated(mat,1);
5160   ierr = MatCreateVecs(mat,&ones,NULL);CHKERRQ(ierr);
5161   ierr = VecSet(ones,1.);CHKERRQ(ierr);
5162   ierr = MatMult(mat,ones,v);CHKERRQ(ierr);
5163   ierr = VecDestroy(&ones);CHKERRQ(ierr);
5164   PetscFunctionReturn(0);
5165 }
5166 
5167 /*@
5168    MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
5169 
5170    Collective on Mat
5171 
5172    Input Parameters:
5173 +  mat - the matrix to transpose
5174 -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
5175 
5176    Output Parameter:
5177 .  B - the transpose
5178 
5179    Notes:
5180      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
5181 
5182      MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
5183 
5184      Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
5185 
5186    Level: intermediate
5187 
5188 .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5189 @*/
5190 PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
5191 {
5192   PetscErrorCode ierr;
5193 
5194   PetscFunctionBegin;
5195   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5196   PetscValidType(mat,1);
5197   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5198   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5199   if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5200   if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
5201   if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
5202   MatCheckPreallocated(mat,1);
5203 
5204   ierr = PetscLogEventBegin(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
5205   ierr = (*mat->ops->transpose)(mat,reuse,B);CHKERRQ(ierr);
5206   ierr = PetscLogEventEnd(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
5207   if (B) {ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);}
5208   PetscFunctionReturn(0);
5209 }
5210 
5211 /*@
5212    MatIsTranspose - Test whether a matrix is another one's transpose,
5213         or its own, in which case it tests symmetry.
5214 
5215    Collective on Mat
5216 
5217    Input Parameter:
5218 +  A - the matrix to test
5219 -  B - the matrix to test against, this can equal the first parameter
5220 
5221    Output Parameters:
5222 .  flg - the result
5223 
5224    Notes:
5225    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
5226    has a running time of the order of the number of nonzeros; the parallel
5227    test involves parallel copies of the block-offdiagonal parts of the matrix.
5228 
5229    Level: intermediate
5230 
5231 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
5232 @*/
5233 PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5234 {
5235   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
5236 
5237   PetscFunctionBegin;
5238   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
5239   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
5240   PetscValidBoolPointer(flg,4);
5241   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);CHKERRQ(ierr);
5242   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);CHKERRQ(ierr);
5243   *flg = PETSC_FALSE;
5244   if (f && g) {
5245     if (f == g) {
5246       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
5247     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
5248   } else {
5249     MatType mattype;
5250     if (!f) {
5251       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
5252     } else {
5253       ierr = MatGetType(B,&mattype);CHKERRQ(ierr);
5254     }
5255     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
5256   }
5257   PetscFunctionReturn(0);
5258 }
5259 
5260 /*@
5261    MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
5262 
5263    Collective on Mat
5264 
5265    Input Parameters:
5266 +  mat - the matrix to transpose and complex conjugate
5267 -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
5268 
5269    Output Parameter:
5270 .  B - the Hermitian
5271 
5272    Level: intermediate
5273 
5274 .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5275 @*/
5276 PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5277 {
5278   PetscErrorCode ierr;
5279 
5280   PetscFunctionBegin;
5281   ierr = MatTranspose(mat,reuse,B);CHKERRQ(ierr);
5282 #if defined(PETSC_USE_COMPLEX)
5283   ierr = MatConjugate(*B);CHKERRQ(ierr);
5284 #endif
5285   PetscFunctionReturn(0);
5286 }
5287 
5288 /*@
5289    MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
5290 
5291    Collective on Mat
5292 
5293    Input Parameter:
5294 +  A - the matrix to test
5295 -  B - the matrix to test against, this can equal the first parameter
5296 
5297    Output Parameters:
5298 .  flg - the result
5299 
5300    Notes:
5301    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
5302    has a running time of the order of the number of nonzeros; the parallel
5303    test involves parallel copies of the block-offdiagonal parts of the matrix.
5304 
5305    Level: intermediate
5306 
5307 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5308 @*/
5309 PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5310 {
5311   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
5312 
5313   PetscFunctionBegin;
5314   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
5315   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
5316   PetscValidBoolPointer(flg,4);
5317   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);CHKERRQ(ierr);
5318   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);CHKERRQ(ierr);
5319   if (f && g) {
5320     if (f==g) {
5321       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
5322     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5323   }
5324   PetscFunctionReturn(0);
5325 }
5326 
5327 /*@
5328    MatPermute - Creates a new matrix with rows and columns permuted from the
5329    original.
5330 
5331    Collective on Mat
5332 
5333    Input Parameters:
5334 +  mat - the matrix to permute
5335 .  row - row permutation, each processor supplies only the permutation for its rows
5336 -  col - column permutation, each processor supplies only the permutation for its columns
5337 
5338    Output Parameters:
5339 .  B - the permuted matrix
5340 
5341    Level: advanced
5342 
5343    Note:
5344    The index sets map from row/col of permuted matrix to row/col of original matrix.
5345    The index sets should be on the same communicator as Mat and have the same local sizes.
5346 
5347    Developer Note:
5348      If you want to implement MatPermute for a matrix type, and your approach doesn't
5349      exploit the fact that row and col are permutations, consider implementing the
5350      more general MatCreateSubMatrix() instead.
5351 
5352 .seealso: MatGetOrdering(), ISAllGather()
5353 
5354 @*/
5355 PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5356 {
5357   PetscErrorCode ierr;
5358 
5359   PetscFunctionBegin;
5360   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5361   PetscValidType(mat,1);
5362   PetscValidHeaderSpecific(row,IS_CLASSID,2);
5363   PetscValidHeaderSpecific(col,IS_CLASSID,3);
5364   PetscValidPointer(B,4);
5365   PetscCheckSameComm(mat,1,row,2);
5366   if (row != col) PetscCheckSameComm(row,2,col,3);
5367   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5368   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5369   if (!mat->ops->permute && !mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
5370   MatCheckPreallocated(mat,1);
5371 
5372   if (mat->ops->permute) {
5373     ierr = (*mat->ops->permute)(mat,row,col,B);CHKERRQ(ierr);
5374     ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);
5375   } else {
5376     ierr = MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B);CHKERRQ(ierr);
5377   }
5378   PetscFunctionReturn(0);
5379 }
5380 
5381 /*@
5382    MatEqual - Compares two matrices.
5383 
5384    Collective on Mat
5385 
5386    Input Parameters:
5387 +  A - the first matrix
5388 -  B - the second matrix
5389 
5390    Output Parameter:
5391 .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
5392 
5393    Level: intermediate
5394 
5395 @*/
5396 PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5397 {
5398   PetscErrorCode ierr;
5399 
5400   PetscFunctionBegin;
5401   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
5402   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
5403   PetscValidType(A,1);
5404   PetscValidType(B,2);
5405   PetscValidBoolPointer(flg,3);
5406   PetscCheckSameComm(A,1,B,2);
5407   MatCheckPreallocated(B,2);
5408   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5409   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5410   if (A->rmap->N != B->rmap->N || A->cmap->N != B->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D %D %D",A->rmap->N,B->rmap->N,A->cmap->N,B->cmap->N);
5411   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5412   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5413   if (A->ops->equal != B->ops->equal) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"A is type: %s\nB is type: %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
5414   MatCheckPreallocated(A,1);
5415 
5416   ierr = (*A->ops->equal)(A,B,flg);CHKERRQ(ierr);
5417   PetscFunctionReturn(0);
5418 }
5419 
5420 /*@
5421    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5422    matrices that are stored as vectors.  Either of the two scaling
5423    matrices can be NULL.
5424 
5425    Collective on Mat
5426 
5427    Input Parameters:
5428 +  mat - the matrix to be scaled
5429 .  l - the left scaling vector (or NULL)
5430 -  r - the right scaling vector (or NULL)
5431 
5432    Notes:
5433    MatDiagonalScale() computes A = LAR, where
5434    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5435    The L scales the rows of the matrix, the R scales the columns of the matrix.
5436 
5437    Level: intermediate
5438 
5439 .seealso: MatScale(), MatShift(), MatDiagonalSet()
5440 @*/
5441 PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5442 {
5443   PetscErrorCode ierr;
5444 
5445   PetscFunctionBegin;
5446   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5447   PetscValidType(mat,1);
5448   if (l) {PetscValidHeaderSpecific(l,VEC_CLASSID,2);PetscCheckSameComm(mat,1,l,2);}
5449   if (r) {PetscValidHeaderSpecific(r,VEC_CLASSID,3);PetscCheckSameComm(mat,1,r,3);}
5450   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5451   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5452   MatCheckPreallocated(mat,1);
5453   if (!l && !r) PetscFunctionReturn(0);
5454 
5455   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5456   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5457   ierr = (*mat->ops->diagonalscale)(mat,l,r);CHKERRQ(ierr);
5458   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5459   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5460   PetscFunctionReturn(0);
5461 }
5462 
5463 /*@
5464     MatScale - Scales all elements of a matrix by a given number.
5465 
5466     Logically Collective on Mat
5467 
5468     Input Parameters:
5469 +   mat - the matrix to be scaled
5470 -   a  - the scaling value
5471 
5472     Output Parameter:
5473 .   mat - the scaled matrix
5474 
5475     Level: intermediate
5476 
5477 .seealso: MatDiagonalScale()
5478 @*/
5479 PetscErrorCode MatScale(Mat mat,PetscScalar a)
5480 {
5481   PetscErrorCode ierr;
5482 
5483   PetscFunctionBegin;
5484   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5485   PetscValidType(mat,1);
5486   if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5487   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5488   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5489   PetscValidLogicalCollectiveScalar(mat,a,2);
5490   MatCheckPreallocated(mat,1);
5491 
5492   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5493   if (a != (PetscScalar)1.0) {
5494     ierr = (*mat->ops->scale)(mat,a);CHKERRQ(ierr);
5495     ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5496   }
5497   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5498   PetscFunctionReturn(0);
5499 }
5500 
5501 /*@
5502    MatNorm - Calculates various norms of a matrix.
5503 
5504    Collective on Mat
5505 
5506    Input Parameters:
5507 +  mat - the matrix
5508 -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5509 
5510    Output Parameters:
5511 .  nrm - the resulting norm
5512 
5513    Level: intermediate
5514 
5515 @*/
5516 PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5517 {
5518   PetscErrorCode ierr;
5519 
5520   PetscFunctionBegin;
5521   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5522   PetscValidType(mat,1);
5523   PetscValidRealPointer(nrm,3);
5524 
5525   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5526   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5527   if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5528   MatCheckPreallocated(mat,1);
5529 
5530   ierr = (*mat->ops->norm)(mat,type,nrm);CHKERRQ(ierr);
5531   PetscFunctionReturn(0);
5532 }
5533 
5534 /*
5535      This variable is used to prevent counting of MatAssemblyBegin() that
5536    are called from within a MatAssemblyEnd().
5537 */
5538 static PetscInt MatAssemblyEnd_InUse = 0;
5539 /*@
5540    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5541    be called after completing all calls to MatSetValues().
5542 
5543    Collective on Mat
5544 
5545    Input Parameters:
5546 +  mat - the matrix
5547 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5548 
5549    Notes:
5550    MatSetValues() generally caches the values.  The matrix is ready to
5551    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5552    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5553    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5554    using the matrix.
5555 
5556    ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5557    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
5558    a global collective operation requring all processes that share the matrix.
5559 
5560    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5561    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5562    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5563 
5564    Level: beginner
5565 
5566 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5567 @*/
5568 PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5569 {
5570   PetscErrorCode ierr;
5571 
5572   PetscFunctionBegin;
5573   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5574   PetscValidType(mat,1);
5575   MatCheckPreallocated(mat,1);
5576   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5577   if (mat->assembled) {
5578     mat->was_assembled = PETSC_TRUE;
5579     mat->assembled     = PETSC_FALSE;
5580   }
5581 
5582   if (!MatAssemblyEnd_InUse) {
5583     ierr = PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5584     if (mat->ops->assemblybegin) {ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);}
5585     ierr = PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5586   } else if (mat->ops->assemblybegin) {
5587     ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);
5588   }
5589   PetscFunctionReturn(0);
5590 }
5591 
5592 /*@
5593    MatAssembled - Indicates if a matrix has been assembled and is ready for
5594      use; for example, in matrix-vector product.
5595 
5596    Not Collective
5597 
5598    Input Parameter:
5599 .  mat - the matrix
5600 
5601    Output Parameter:
5602 .  assembled - PETSC_TRUE or PETSC_FALSE
5603 
5604    Level: advanced
5605 
5606 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5607 @*/
5608 PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5609 {
5610   PetscFunctionBegin;
5611   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5612   PetscValidPointer(assembled,2);
5613   *assembled = mat->assembled;
5614   PetscFunctionReturn(0);
5615 }
5616 
5617 /*@
5618    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5619    be called after MatAssemblyBegin().
5620 
5621    Collective on Mat
5622 
5623    Input Parameters:
5624 +  mat - the matrix
5625 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5626 
5627    Options Database Keys:
5628 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5629 .  -mat_view ::ascii_info_detail - Prints more detailed info
5630 .  -mat_view - Prints matrix in ASCII format
5631 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5632 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5633 .  -display <name> - Sets display name (default is host)
5634 .  -draw_pause <sec> - Sets number of seconds to pause after display
5635 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab)
5636 .  -viewer_socket_machine <machine> - Machine to use for socket
5637 .  -viewer_socket_port <port> - Port number to use for socket
5638 -  -mat_view binary:filename[:append] - Save matrix to file in binary format
5639 
5640    Notes:
5641    MatSetValues() generally caches the values.  The matrix is ready to
5642    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5643    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5644    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5645    using the matrix.
5646 
5647    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5648    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5649    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5650 
5651    Level: beginner
5652 
5653 .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5654 @*/
5655 PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5656 {
5657   PetscErrorCode  ierr;
5658   static PetscInt inassm = 0;
5659   PetscBool       flg    = PETSC_FALSE;
5660 
5661   PetscFunctionBegin;
5662   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5663   PetscValidType(mat,1);
5664 
5665   inassm++;
5666   MatAssemblyEnd_InUse++;
5667   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5668     ierr = PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5669     if (mat->ops->assemblyend) {
5670       ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5671     }
5672     ierr = PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5673   } else if (mat->ops->assemblyend) {
5674     ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5675   }
5676 
5677   /* Flush assembly is not a true assembly */
5678   if (type != MAT_FLUSH_ASSEMBLY) {
5679     mat->num_ass++;
5680     mat->assembled        = PETSC_TRUE;
5681     mat->ass_nonzerostate = mat->nonzerostate;
5682   }
5683 
5684   mat->insertmode = NOT_SET_VALUES;
5685   MatAssemblyEnd_InUse--;
5686   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5687   if (!mat->symmetric_eternal) {
5688     mat->symmetric_set              = PETSC_FALSE;
5689     mat->hermitian_set              = PETSC_FALSE;
5690     mat->structurally_symmetric_set = PETSC_FALSE;
5691   }
5692   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5693     ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5694 
5695     if (mat->checksymmetryonassembly) {
5696       ierr = MatIsSymmetric(mat,mat->checksymmetrytol,&flg);CHKERRQ(ierr);
5697       if (flg) {
5698         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5699       } else {
5700         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5701       }
5702     }
5703     if (mat->nullsp && mat->checknullspaceonassembly) {
5704       ierr = MatNullSpaceTest(mat->nullsp,mat,NULL);CHKERRQ(ierr);
5705     }
5706   }
5707   inassm--;
5708   PetscFunctionReturn(0);
5709 }
5710 
5711 /*@
5712    MatSetOption - Sets a parameter option for a matrix. Some options
5713    may be specific to certain storage formats.  Some options
5714    determine how values will be inserted (or added). Sorted,
5715    row-oriented input will generally assemble the fastest. The default
5716    is row-oriented.
5717 
5718    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5719 
5720    Input Parameters:
5721 +  mat - the matrix
5722 .  option - the option, one of those listed below (and possibly others),
5723 -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5724 
5725   Options Describing Matrix Structure:
5726 +    MAT_SPD - symmetric positive definite
5727 .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5728 .    MAT_HERMITIAN - transpose is the complex conjugation
5729 .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5730 -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5731                             you set to be kept with all future use of the matrix
5732                             including after MatAssemblyBegin/End() which could
5733                             potentially change the symmetry structure, i.e. you
5734                             KNOW the matrix will ALWAYS have the property you set.
5735                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5736                             the relevant flags must be set independently.
5737 
5738    Options For Use with MatSetValues():
5739    Insert a logically dense subblock, which can be
5740 .    MAT_ROW_ORIENTED - row-oriented (default)
5741 
5742    Note these options reflect the data you pass in with MatSetValues(); it has
5743    nothing to do with how the data is stored internally in the matrix
5744    data structure.
5745 
5746    When (re)assembling a matrix, we can restrict the input for
5747    efficiency/debugging purposes.  These options include:
5748 +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5749 .    MAT_FORCE_DIAGONAL_ENTRIES - forces diagonal entries to be allocated
5750 .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5751 .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5752 .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5753 .    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5754         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5755         performance for very large process counts.
5756 -    MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5757         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5758         functions, instead sending only neighbor messages.
5759 
5760    Notes:
5761    Except for MAT_UNUSED_NONZERO_LOCATION_ERR and  MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5762 
5763    Some options are relevant only for particular matrix types and
5764    are thus ignored by others.  Other options are not supported by
5765    certain matrix types and will generate an error message if set.
5766 
5767    If using a Fortran 77 module to compute a matrix, one may need to
5768    use the column-oriented option (or convert to the row-oriented
5769    format).
5770 
5771    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5772    that would generate a new entry in the nonzero structure is instead
5773    ignored.  Thus, if memory has not alredy been allocated for this particular
5774    data, then the insertion is ignored. For dense matrices, in which
5775    the entire array is allocated, no entries are ever ignored.
5776    Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5777 
5778    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5779    that would generate a new entry in the nonzero structure instead produces
5780    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
5781 
5782    MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5783    that would generate a new entry that has not been preallocated will
5784    instead produce an error. (Currently supported for AIJ and BAIJ formats
5785    only.) This is a useful flag when debugging matrix memory preallocation.
5786    If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5787 
5788    MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5789    other processors should be dropped, rather than stashed.
5790    This is useful if you know that the "owning" processor is also
5791    always generating the correct matrix entries, so that PETSc need
5792    not transfer duplicate entries generated on another processor.
5793 
5794    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5795    searches during matrix assembly. When this flag is set, the hash table
5796    is created during the first Matrix Assembly. This hash table is
5797    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5798    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5799    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5800    supported by MATMPIBAIJ format only.
5801 
5802    MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5803    are kept in the nonzero structure
5804 
5805    MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5806    a zero location in the matrix
5807 
5808    MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5809 
5810    MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5811         zero row routines and thus improves performance for very large process counts.
5812 
5813    MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5814         part of the matrix (since they should match the upper triangular part).
5815 
5816    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5817                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5818                      with finite difference schemes with non-periodic boundary conditions.
5819 
5820    Level: intermediate
5821 
5822 .seealso:  MatOption, Mat
5823 
5824 @*/
5825 PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5826 {
5827   PetscErrorCode ierr;
5828 
5829   PetscFunctionBegin;
5830   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5831   if (op > 0) {
5832     PetscValidLogicalCollectiveEnum(mat,op,2);
5833     PetscValidLogicalCollectiveBool(mat,flg,3);
5834   }
5835 
5836   if (((int) op) <= MAT_OPTION_MIN || ((int) op) >= MAT_OPTION_MAX) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Options %d is out of range",(int)op);
5837 
5838   switch (op) {
5839   case MAT_FORCE_DIAGONAL_ENTRIES:
5840     mat->force_diagonals = flg;
5841     PetscFunctionReturn(0);
5842   case MAT_NO_OFF_PROC_ENTRIES:
5843     mat->nooffprocentries = flg;
5844     PetscFunctionReturn(0);
5845   case MAT_SUBSET_OFF_PROC_ENTRIES:
5846     mat->assembly_subset = flg;
5847     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5848 #if !defined(PETSC_HAVE_MPIUNI)
5849       ierr = MatStashScatterDestroy_BTS(&mat->stash);CHKERRQ(ierr);
5850 #endif
5851       mat->stash.first_assembly_done = PETSC_FALSE;
5852     }
5853     PetscFunctionReturn(0);
5854   case MAT_NO_OFF_PROC_ZERO_ROWS:
5855     mat->nooffproczerorows = flg;
5856     PetscFunctionReturn(0);
5857   case MAT_SPD:
5858     mat->spd_set = PETSC_TRUE;
5859     mat->spd     = flg;
5860     if (flg) {
5861       mat->symmetric                  = PETSC_TRUE;
5862       mat->structurally_symmetric     = PETSC_TRUE;
5863       mat->symmetric_set              = PETSC_TRUE;
5864       mat->structurally_symmetric_set = PETSC_TRUE;
5865     }
5866     break;
5867   case MAT_SYMMETRIC:
5868     mat->symmetric = flg;
5869     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5870     mat->symmetric_set              = PETSC_TRUE;
5871     mat->structurally_symmetric_set = flg;
5872 #if !defined(PETSC_USE_COMPLEX)
5873     mat->hermitian     = flg;
5874     mat->hermitian_set = PETSC_TRUE;
5875 #endif
5876     break;
5877   case MAT_HERMITIAN:
5878     mat->hermitian = flg;
5879     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5880     mat->hermitian_set              = PETSC_TRUE;
5881     mat->structurally_symmetric_set = flg;
5882 #if !defined(PETSC_USE_COMPLEX)
5883     mat->symmetric     = flg;
5884     mat->symmetric_set = PETSC_TRUE;
5885 #endif
5886     break;
5887   case MAT_STRUCTURALLY_SYMMETRIC:
5888     mat->structurally_symmetric     = flg;
5889     mat->structurally_symmetric_set = PETSC_TRUE;
5890     break;
5891   case MAT_SYMMETRY_ETERNAL:
5892     mat->symmetric_eternal = flg;
5893     break;
5894   case MAT_STRUCTURE_ONLY:
5895     mat->structure_only = flg;
5896     break;
5897   case MAT_SORTED_FULL:
5898     mat->sortedfull = flg;
5899     break;
5900   default:
5901     break;
5902   }
5903   if (mat->ops->setoption) {
5904     ierr = (*mat->ops->setoption)(mat,op,flg);CHKERRQ(ierr);
5905   }
5906   PetscFunctionReturn(0);
5907 }
5908 
5909 /*@
5910    MatGetOption - Gets a parameter option that has been set for a matrix.
5911 
5912    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5913 
5914    Input Parameters:
5915 +  mat - the matrix
5916 -  option - the option, this only responds to certain options, check the code for which ones
5917 
5918    Output Parameter:
5919 .  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5920 
5921     Notes:
5922     Can only be called after MatSetSizes() and MatSetType() have been set.
5923 
5924    Level: intermediate
5925 
5926 .seealso:  MatOption, MatSetOption()
5927 
5928 @*/
5929 PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5930 {
5931   PetscFunctionBegin;
5932   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5933   PetscValidType(mat,1);
5934 
5935   if (((int) op) <= MAT_OPTION_MIN || ((int) op) >= MAT_OPTION_MAX) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Options %d is out of range",(int)op);
5936   if (!((PetscObject)mat)->type_name) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_TYPENOTSET,"Cannot get options until type and size have been set, see MatSetType() and MatSetSizes()");
5937 
5938   switch (op) {
5939   case MAT_NO_OFF_PROC_ENTRIES:
5940     *flg = mat->nooffprocentries;
5941     break;
5942   case MAT_NO_OFF_PROC_ZERO_ROWS:
5943     *flg = mat->nooffproczerorows;
5944     break;
5945   case MAT_SYMMETRIC:
5946     *flg = mat->symmetric;
5947     break;
5948   case MAT_HERMITIAN:
5949     *flg = mat->hermitian;
5950     break;
5951   case MAT_STRUCTURALLY_SYMMETRIC:
5952     *flg = mat->structurally_symmetric;
5953     break;
5954   case MAT_SYMMETRY_ETERNAL:
5955     *flg = mat->symmetric_eternal;
5956     break;
5957   case MAT_SPD:
5958     *flg = mat->spd;
5959     break;
5960   default:
5961     break;
5962   }
5963   PetscFunctionReturn(0);
5964 }
5965 
5966 /*@
5967    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5968    this routine retains the old nonzero structure.
5969 
5970    Logically Collective on Mat
5971 
5972    Input Parameters:
5973 .  mat - the matrix
5974 
5975    Level: intermediate
5976 
5977    Notes:
5978     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.
5979    See the Performance chapter of the users manual for information on preallocating matrices.
5980 
5981 .seealso: MatZeroRows()
5982 @*/
5983 PetscErrorCode MatZeroEntries(Mat mat)
5984 {
5985   PetscErrorCode ierr;
5986 
5987   PetscFunctionBegin;
5988   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5989   PetscValidType(mat,1);
5990   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5991   if (mat->insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for matrices where you have set values but not yet assembled");
5992   if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5993   MatCheckPreallocated(mat,1);
5994 
5995   ierr = PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5996   ierr = (*mat->ops->zeroentries)(mat);CHKERRQ(ierr);
5997   ierr = PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5998   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5999   PetscFunctionReturn(0);
6000 }
6001 
6002 /*@
6003    MatZeroRowsColumns - 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 .  numRows - the number of rows to remove
6011 .  rows - the global row indices
6012 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6013 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6014 -  b - optional vector of right hand side, that will be adjusted by provided solution
6015 
6016    Notes:
6017    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
6018 
6019    The user can set a value in the diagonal entry (or for the AIJ and
6020    row formats can optionally remove the main diagonal entry from the
6021    nonzero structure as well, by passing 0.0 as the final argument).
6022 
6023    For the parallel case, all processes that share the matrix (i.e.,
6024    those in the communicator used for matrix creation) MUST call this
6025    routine, regardless of whether any rows being zeroed are owned by
6026    them.
6027 
6028    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6029    list only rows local to itself).
6030 
6031    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
6032 
6033    Level: intermediate
6034 
6035 .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6036           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6037 @*/
6038 PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6039 {
6040   PetscErrorCode ierr;
6041 
6042   PetscFunctionBegin;
6043   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6044   PetscValidType(mat,1);
6045   if (numRows) PetscValidIntPointer(rows,3);
6046   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6047   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6048   if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6049   MatCheckPreallocated(mat,1);
6050 
6051   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6052   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
6053   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6054   PetscFunctionReturn(0);
6055 }
6056 
6057 /*@
6058    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6059    of a set of rows and columns of a matrix.
6060 
6061    Collective on Mat
6062 
6063    Input Parameters:
6064 +  mat - the matrix
6065 .  is - the rows to zero
6066 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6067 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6068 -  b - optional vector of right hand side, that will be adjusted by provided solution
6069 
6070    Notes:
6071    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
6072 
6073    The user can set a value in the diagonal entry (or for the AIJ and
6074    row formats can optionally remove the main diagonal entry from the
6075    nonzero structure as well, by passing 0.0 as the final argument).
6076 
6077    For the parallel case, all processes that share the matrix (i.e.,
6078    those in the communicator used for matrix creation) MUST call this
6079    routine, regardless of whether any rows being zeroed are owned by
6080    them.
6081 
6082    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6083    list only rows local to itself).
6084 
6085    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
6086 
6087    Level: intermediate
6088 
6089 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6090           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
6091 @*/
6092 PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6093 {
6094   PetscErrorCode ierr;
6095   PetscInt       numRows;
6096   const PetscInt *rows;
6097 
6098   PetscFunctionBegin;
6099   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6100   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6101   PetscValidType(mat,1);
6102   PetscValidType(is,2);
6103   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6104   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6105   ierr = MatZeroRowsColumns(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6106   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6107   PetscFunctionReturn(0);
6108 }
6109 
6110 /*@
6111    MatZeroRows - Zeros all entries (except possibly the main diagonal)
6112    of a set of rows of a matrix.
6113 
6114    Collective on Mat
6115 
6116    Input Parameters:
6117 +  mat - the matrix
6118 .  numRows - the number of rows to remove
6119 .  rows - the global row indices
6120 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6121 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6122 -  b - optional vector of right hand side, that will be adjusted by provided solution
6123 
6124    Notes:
6125    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6126    but does not release memory.  For the dense and block diagonal
6127    formats this does not alter the nonzero structure.
6128 
6129    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6130    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6131    merely zeroed.
6132 
6133    The user can set a value in the diagonal entry (or for the AIJ and
6134    row formats can optionally remove the main diagonal entry from the
6135    nonzero structure as well, by passing 0.0 as the final argument).
6136 
6137    For the parallel case, all processes that share the matrix (i.e.,
6138    those in the communicator used for matrix creation) MUST call this
6139    routine, regardless of whether any rows being zeroed are owned by
6140    them.
6141 
6142    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6143    list only rows local to itself).
6144 
6145    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6146    owns that are to be zeroed. This saves a global synchronization in the implementation.
6147 
6148    Level: intermediate
6149 
6150 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6151           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6152 @*/
6153 PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6154 {
6155   PetscErrorCode ierr;
6156 
6157   PetscFunctionBegin;
6158   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6159   PetscValidType(mat,1);
6160   if (numRows) PetscValidIntPointer(rows,3);
6161   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6162   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6163   if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6164   MatCheckPreallocated(mat,1);
6165 
6166   ierr = (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6167   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
6168   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6169   PetscFunctionReturn(0);
6170 }
6171 
6172 /*@
6173    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6174    of a set of rows of a matrix.
6175 
6176    Collective on Mat
6177 
6178    Input Parameters:
6179 +  mat - the matrix
6180 .  is - index set of rows to remove
6181 .  diag - value put in all diagonals of eliminated rows
6182 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6183 -  b - optional vector of right hand side, that will be adjusted by provided solution
6184 
6185    Notes:
6186    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6187    but does not release memory.  For the dense and block diagonal
6188    formats this does not alter the nonzero structure.
6189 
6190    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6191    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6192    merely zeroed.
6193 
6194    The user can set a value in the diagonal entry (or for the AIJ and
6195    row formats can optionally remove the main diagonal entry from the
6196    nonzero structure as well, by passing 0.0 as the final argument).
6197 
6198    For the parallel case, all processes that share the matrix (i.e.,
6199    those in the communicator used for matrix creation) MUST call this
6200    routine, regardless of whether any rows being zeroed are owned by
6201    them.
6202 
6203    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6204    list only rows local to itself).
6205 
6206    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6207    owns that are to be zeroed. This saves a global synchronization in the implementation.
6208 
6209    Level: intermediate
6210 
6211 .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6212           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6213 @*/
6214 PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6215 {
6216   PetscInt       numRows;
6217   const PetscInt *rows;
6218   PetscErrorCode ierr;
6219 
6220   PetscFunctionBegin;
6221   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6222   PetscValidType(mat,1);
6223   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6224   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6225   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6226   ierr = MatZeroRows(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6227   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6228   PetscFunctionReturn(0);
6229 }
6230 
6231 /*@
6232    MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6233    of a set of rows of a matrix. These rows must be local to the process.
6234 
6235    Collective on Mat
6236 
6237    Input Parameters:
6238 +  mat - the matrix
6239 .  numRows - the number of rows to remove
6240 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
6241 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6242 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6243 -  b - optional vector of right hand side, that will be adjusted by provided solution
6244 
6245    Notes:
6246    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6247    but does not release memory.  For the dense and block diagonal
6248    formats this does not alter the nonzero structure.
6249 
6250    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6251    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6252    merely zeroed.
6253 
6254    The user can set a value in the diagonal entry (or for the AIJ and
6255    row formats can optionally remove the main diagonal entry from the
6256    nonzero structure as well, by passing 0.0 as the final argument).
6257 
6258    For the parallel case, all processes that share the matrix (i.e.,
6259    those in the communicator used for matrix creation) MUST call this
6260    routine, regardless of whether any rows being zeroed are owned by
6261    them.
6262 
6263    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6264    list only rows local to itself).
6265 
6266    The grid coordinates are across the entire grid, not just the local portion
6267 
6268    In Fortran idxm and idxn should be declared as
6269 $     MatStencil idxm(4,m)
6270    and the values inserted using
6271 $    idxm(MatStencil_i,1) = i
6272 $    idxm(MatStencil_j,1) = j
6273 $    idxm(MatStencil_k,1) = k
6274 $    idxm(MatStencil_c,1) = c
6275    etc
6276 
6277    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6278    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6279    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6280    DM_BOUNDARY_PERIODIC boundary type.
6281 
6282    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
6283    a single value per point) you can skip filling those indices.
6284 
6285    Level: intermediate
6286 
6287 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6288           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6289 @*/
6290 PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6291 {
6292   PetscInt       dim     = mat->stencil.dim;
6293   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6294   PetscInt       *dims   = mat->stencil.dims+1;
6295   PetscInt       *starts = mat->stencil.starts;
6296   PetscInt       *dxm    = (PetscInt*) rows;
6297   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
6298   PetscErrorCode ierr;
6299 
6300   PetscFunctionBegin;
6301   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6302   PetscValidType(mat,1);
6303   if (numRows) PetscValidPointer(rows,3);
6304 
6305   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
6306   for (i = 0; i < numRows; ++i) {
6307     /* Skip unused dimensions (they are ordered k, j, i, c) */
6308     for (j = 0; j < 3-sdim; ++j) dxm++;
6309     /* Local index in X dir */
6310     tmp = *dxm++ - starts[0];
6311     /* Loop over remaining dimensions */
6312     for (j = 0; j < dim-1; ++j) {
6313       /* If nonlocal, set index to be negative */
6314       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6315       /* Update local index */
6316       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6317     }
6318     /* Skip component slot if necessary */
6319     if (mat->stencil.noc) dxm++;
6320     /* Local row number */
6321     if (tmp >= 0) {
6322       jdxm[numNewRows++] = tmp;
6323     }
6324   }
6325   ierr = MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
6326   ierr = PetscFree(jdxm);CHKERRQ(ierr);
6327   PetscFunctionReturn(0);
6328 }
6329 
6330 /*@
6331    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6332    of a set of rows and columns of a matrix.
6333 
6334    Collective on Mat
6335 
6336    Input Parameters:
6337 +  mat - the matrix
6338 .  numRows - the number of rows/columns to remove
6339 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
6340 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6341 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6342 -  b - optional vector of right hand side, that will be adjusted by provided solution
6343 
6344    Notes:
6345    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6346    but does not release memory.  For the dense and block diagonal
6347    formats this does not alter the nonzero structure.
6348 
6349    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6350    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6351    merely zeroed.
6352 
6353    The user can set a value in the diagonal entry (or for the AIJ and
6354    row formats can optionally remove the main diagonal entry from the
6355    nonzero structure as well, by passing 0.0 as the final argument).
6356 
6357    For the parallel case, all processes that share the matrix (i.e.,
6358    those in the communicator used for matrix creation) MUST call this
6359    routine, regardless of whether any rows being zeroed are owned by
6360    them.
6361 
6362    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6363    list only rows local to itself, but the row/column numbers are given in local numbering).
6364 
6365    The grid coordinates are across the entire grid, not just the local portion
6366 
6367    In Fortran idxm and idxn should be declared as
6368 $     MatStencil idxm(4,m)
6369    and the values inserted using
6370 $    idxm(MatStencil_i,1) = i
6371 $    idxm(MatStencil_j,1) = j
6372 $    idxm(MatStencil_k,1) = k
6373 $    idxm(MatStencil_c,1) = c
6374    etc
6375 
6376    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6377    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6378    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6379    DM_BOUNDARY_PERIODIC boundary type.
6380 
6381    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
6382    a single value per point) you can skip filling those indices.
6383 
6384    Level: intermediate
6385 
6386 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6387           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6388 @*/
6389 PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6390 {
6391   PetscInt       dim     = mat->stencil.dim;
6392   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6393   PetscInt       *dims   = mat->stencil.dims+1;
6394   PetscInt       *starts = mat->stencil.starts;
6395   PetscInt       *dxm    = (PetscInt*) rows;
6396   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
6397   PetscErrorCode ierr;
6398 
6399   PetscFunctionBegin;
6400   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6401   PetscValidType(mat,1);
6402   if (numRows) PetscValidPointer(rows,3);
6403 
6404   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
6405   for (i = 0; i < numRows; ++i) {
6406     /* Skip unused dimensions (they are ordered k, j, i, c) */
6407     for (j = 0; j < 3-sdim; ++j) dxm++;
6408     /* Local index in X dir */
6409     tmp = *dxm++ - starts[0];
6410     /* Loop over remaining dimensions */
6411     for (j = 0; j < dim-1; ++j) {
6412       /* If nonlocal, set index to be negative */
6413       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6414       /* Update local index */
6415       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6416     }
6417     /* Skip component slot if necessary */
6418     if (mat->stencil.noc) dxm++;
6419     /* Local row number */
6420     if (tmp >= 0) {
6421       jdxm[numNewRows++] = tmp;
6422     }
6423   }
6424   ierr = MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
6425   ierr = PetscFree(jdxm);CHKERRQ(ierr);
6426   PetscFunctionReturn(0);
6427 }
6428 
6429 /*@C
6430    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6431    of a set of rows of a matrix; using local numbering of rows.
6432 
6433    Collective on Mat
6434 
6435    Input Parameters:
6436 +  mat - the matrix
6437 .  numRows - the number of rows to remove
6438 .  rows - the global row indices
6439 .  diag - value put in all diagonals of eliminated rows
6440 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6441 -  b - optional vector of right hand side, that will be adjusted by provided solution
6442 
6443    Notes:
6444    Before calling MatZeroRowsLocal(), the user must first set the
6445    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6446 
6447    For the AIJ matrix formats this removes the old nonzero structure,
6448    but does not release memory.  For the dense and block diagonal
6449    formats this does not alter the nonzero structure.
6450 
6451    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6452    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6453    merely zeroed.
6454 
6455    The user can set a value in the diagonal entry (or for the AIJ and
6456    row formats can optionally remove the main diagonal entry from the
6457    nonzero structure as well, by passing 0.0 as the final argument).
6458 
6459    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6460    owns that are to be zeroed. This saves a global synchronization in the implementation.
6461 
6462    Level: intermediate
6463 
6464 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6465           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6466 @*/
6467 PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6468 {
6469   PetscErrorCode ierr;
6470 
6471   PetscFunctionBegin;
6472   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6473   PetscValidType(mat,1);
6474   if (numRows) PetscValidIntPointer(rows,3);
6475   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6476   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6477   MatCheckPreallocated(mat,1);
6478 
6479   if (mat->ops->zerorowslocal) {
6480     ierr = (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6481   } else {
6482     IS             is, newis;
6483     const PetscInt *newRows;
6484 
6485     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6486     ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6487     ierr = ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);CHKERRQ(ierr);
6488     ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6489     ierr = (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6490     ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6491     ierr = ISDestroy(&newis);CHKERRQ(ierr);
6492     ierr = ISDestroy(&is);CHKERRQ(ierr);
6493   }
6494   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6495   PetscFunctionReturn(0);
6496 }
6497 
6498 /*@
6499    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6500    of a set of rows of a matrix; using local numbering of rows.
6501 
6502    Collective on Mat
6503 
6504    Input Parameters:
6505 +  mat - the matrix
6506 .  is - index set of rows to remove
6507 .  diag - value put in all diagonals of eliminated rows
6508 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6509 -  b - optional vector of right hand side, that will be adjusted by provided solution
6510 
6511    Notes:
6512    Before calling MatZeroRowsLocalIS(), the user must first set the
6513    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6514 
6515    For the AIJ matrix formats this removes the old nonzero structure,
6516    but does not release memory.  For the dense and block diagonal
6517    formats this does not alter the nonzero structure.
6518 
6519    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6520    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6521    merely zeroed.
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    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6528    owns that are to be zeroed. This saves a global synchronization in the implementation.
6529 
6530    Level: intermediate
6531 
6532 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6533           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6534 @*/
6535 PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6536 {
6537   PetscErrorCode ierr;
6538   PetscInt       numRows;
6539   const PetscInt *rows;
6540 
6541   PetscFunctionBegin;
6542   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6543   PetscValidType(mat,1);
6544   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6545   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6546   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6547   MatCheckPreallocated(mat,1);
6548 
6549   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6550   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6551   ierr = MatZeroRowsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6552   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6553   PetscFunctionReturn(0);
6554 }
6555 
6556 /*@
6557    MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6558    of a set of rows and columns of a matrix; using local numbering of rows.
6559 
6560    Collective on Mat
6561 
6562    Input Parameters:
6563 +  mat - the matrix
6564 .  numRows - the number of rows to remove
6565 .  rows - the global row indices
6566 .  diag - value put in all diagonals of eliminated rows
6567 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6568 -  b - optional vector of right hand side, that will be adjusted by provided solution
6569 
6570    Notes:
6571    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6572    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6573 
6574    The user can set a value in the diagonal entry (or for the AIJ and
6575    row formats can optionally remove the main diagonal entry from the
6576    nonzero structure as well, by passing 0.0 as the final argument).
6577 
6578    Level: intermediate
6579 
6580 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6581           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6582 @*/
6583 PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6584 {
6585   PetscErrorCode ierr;
6586   IS             is, newis;
6587   const PetscInt *newRows;
6588 
6589   PetscFunctionBegin;
6590   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6591   PetscValidType(mat,1);
6592   if (numRows) PetscValidIntPointer(rows,3);
6593   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6594   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6595   MatCheckPreallocated(mat,1);
6596 
6597   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6598   ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6599   ierr = ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);CHKERRQ(ierr);
6600   ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6601   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6602   ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6603   ierr = ISDestroy(&newis);CHKERRQ(ierr);
6604   ierr = ISDestroy(&is);CHKERRQ(ierr);
6605   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6606   PetscFunctionReturn(0);
6607 }
6608 
6609 /*@
6610    MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6611    of a set of rows and columns of a matrix; using local numbering of rows.
6612 
6613    Collective on Mat
6614 
6615    Input Parameters:
6616 +  mat - the matrix
6617 .  is - index set of rows to remove
6618 .  diag - value put in all diagonals of eliminated rows
6619 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6620 -  b - optional vector of right hand side, that will be adjusted by provided solution
6621 
6622    Notes:
6623    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6624    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6625 
6626    The user can set a value in the diagonal entry (or for the AIJ and
6627    row formats can optionally remove the main diagonal entry from the
6628    nonzero structure as well, by passing 0.0 as the final argument).
6629 
6630    Level: intermediate
6631 
6632 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6633           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6634 @*/
6635 PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6636 {
6637   PetscErrorCode ierr;
6638   PetscInt       numRows;
6639   const PetscInt *rows;
6640 
6641   PetscFunctionBegin;
6642   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6643   PetscValidType(mat,1);
6644   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6645   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6646   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6647   MatCheckPreallocated(mat,1);
6648 
6649   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6650   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6651   ierr = MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6652   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6653   PetscFunctionReturn(0);
6654 }
6655 
6656 /*@C
6657    MatGetSize - Returns the numbers of rows and columns in a matrix.
6658 
6659    Not Collective
6660 
6661    Input Parameter:
6662 .  mat - the matrix
6663 
6664    Output Parameters:
6665 +  m - the number of global rows
6666 -  n - the number of global columns
6667 
6668    Note: both output parameters can be NULL on input.
6669 
6670    Level: beginner
6671 
6672 .seealso: MatGetLocalSize()
6673 @*/
6674 PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6675 {
6676   PetscFunctionBegin;
6677   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6678   if (m) *m = mat->rmap->N;
6679   if (n) *n = mat->cmap->N;
6680   PetscFunctionReturn(0);
6681 }
6682 
6683 /*@C
6684    MatGetLocalSize - Returns the number of local rows and local columns
6685    of a matrix, that is the local size of the left and right vectors as returned by MatCreateVecs().
6686 
6687    Not Collective
6688 
6689    Input Parameters:
6690 .  mat - the matrix
6691 
6692    Output Parameters:
6693 +  m - the number of local rows
6694 -  n - the number of local columns
6695 
6696    Note: both output parameters can be NULL on input.
6697 
6698    Level: beginner
6699 
6700 .seealso: MatGetSize()
6701 @*/
6702 PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6703 {
6704   PetscFunctionBegin;
6705   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6706   if (m) PetscValidIntPointer(m,2);
6707   if (n) PetscValidIntPointer(n,3);
6708   if (m) *m = mat->rmap->n;
6709   if (n) *n = mat->cmap->n;
6710   PetscFunctionReturn(0);
6711 }
6712 
6713 /*@C
6714    MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6715    this processor. (The columns of the "diagonal block")
6716 
6717    Not Collective, unless matrix has not been allocated, then collective on Mat
6718 
6719    Input Parameters:
6720 .  mat - the matrix
6721 
6722    Output Parameters:
6723 +  m - the global index of the first local column
6724 -  n - one more than the global index of the last local column
6725 
6726    Notes:
6727     both output parameters can be NULL on input.
6728 
6729    Level: developer
6730 
6731 .seealso:  MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6732 
6733 @*/
6734 PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6735 {
6736   PetscFunctionBegin;
6737   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6738   PetscValidType(mat,1);
6739   if (m) PetscValidIntPointer(m,2);
6740   if (n) PetscValidIntPointer(n,3);
6741   MatCheckPreallocated(mat,1);
6742   if (m) *m = mat->cmap->rstart;
6743   if (n) *n = mat->cmap->rend;
6744   PetscFunctionReturn(0);
6745 }
6746 
6747 /*@C
6748    MatGetOwnershipRange - Returns the range of matrix rows owned by
6749    this processor, assuming that the matrix is laid out with the first
6750    n1 rows on the first processor, the next n2 rows on the second, etc.
6751    For certain parallel layouts this range may not be well defined.
6752 
6753    Not Collective
6754 
6755    Input Parameters:
6756 .  mat - the matrix
6757 
6758    Output Parameters:
6759 +  m - the global index of the first local row
6760 -  n - one more than the global index of the last local row
6761 
6762    Note: Both output parameters can be NULL on input.
6763 $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6764 $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6765 $  and then MPI_Scan() to calculate prefix sums of the local sizes.
6766 
6767    Level: beginner
6768 
6769 .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6770 
6771 @*/
6772 PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6773 {
6774   PetscFunctionBegin;
6775   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6776   PetscValidType(mat,1);
6777   if (m) PetscValidIntPointer(m,2);
6778   if (n) PetscValidIntPointer(n,3);
6779   MatCheckPreallocated(mat,1);
6780   if (m) *m = mat->rmap->rstart;
6781   if (n) *n = mat->rmap->rend;
6782   PetscFunctionReturn(0);
6783 }
6784 
6785 /*@C
6786    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6787    each process
6788 
6789    Not Collective, unless matrix has not been allocated, then collective on Mat
6790 
6791    Input Parameters:
6792 .  mat - the matrix
6793 
6794    Output Parameters:
6795 .  ranges - start of each processors portion plus one more than the total length at the end
6796 
6797    Level: beginner
6798 
6799 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6800 
6801 @*/
6802 PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6803 {
6804   PetscErrorCode ierr;
6805 
6806   PetscFunctionBegin;
6807   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6808   PetscValidType(mat,1);
6809   MatCheckPreallocated(mat,1);
6810   ierr = PetscLayoutGetRanges(mat->rmap,ranges);CHKERRQ(ierr);
6811   PetscFunctionReturn(0);
6812 }
6813 
6814 /*@C
6815    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6816    this processor. (The columns of the "diagonal blocks" for each process)
6817 
6818    Not Collective, unless matrix has not been allocated, then collective on Mat
6819 
6820    Input Parameters:
6821 .  mat - the matrix
6822 
6823    Output Parameters:
6824 .  ranges - start of each processors portion plus one more then the total length at the end
6825 
6826    Level: beginner
6827 
6828 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6829 
6830 @*/
6831 PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6832 {
6833   PetscErrorCode ierr;
6834 
6835   PetscFunctionBegin;
6836   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6837   PetscValidType(mat,1);
6838   MatCheckPreallocated(mat,1);
6839   ierr = PetscLayoutGetRanges(mat->cmap,ranges);CHKERRQ(ierr);
6840   PetscFunctionReturn(0);
6841 }
6842 
6843 /*@C
6844    MatGetOwnershipIS - Get row and column ownership as index sets
6845 
6846    Not Collective
6847 
6848    Input Arguments:
6849 .  A - matrix of type Elemental or ScaLAPACK
6850 
6851    Output Arguments:
6852 +  rows - rows in which this process owns elements
6853 -  cols - columns in which this process owns elements
6854 
6855    Level: intermediate
6856 
6857 .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6858 @*/
6859 PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6860 {
6861   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6862 
6863   PetscFunctionBegin;
6864   MatCheckPreallocated(A,1);
6865   ierr = PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);CHKERRQ(ierr);
6866   if (f) {
6867     ierr = (*f)(A,rows,cols);CHKERRQ(ierr);
6868   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6869     if (rows) {ierr = ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);CHKERRQ(ierr);}
6870     if (cols) {ierr = ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);CHKERRQ(ierr);}
6871   }
6872   PetscFunctionReturn(0);
6873 }
6874 
6875 /*@C
6876    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6877    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6878    to complete the factorization.
6879 
6880    Collective on Mat
6881 
6882    Input Parameters:
6883 +  mat - the matrix
6884 .  row - row permutation
6885 .  column - column permutation
6886 -  info - structure containing
6887 $      levels - number of levels of fill.
6888 $      expected fill - as ratio of original fill.
6889 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6890                 missing diagonal entries)
6891 
6892    Output Parameters:
6893 .  fact - new matrix that has been symbolically factored
6894 
6895    Notes:
6896     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6897 
6898    Most users should employ the simplified KSP interface for linear solvers
6899    instead of working directly with matrix algebra routines such as this.
6900    See, e.g., KSPCreate().
6901 
6902    Level: developer
6903 
6904 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6905           MatGetOrdering(), MatFactorInfo
6906 
6907     Note: this uses the definition of level of fill as in Y. Saad, 2003
6908 
6909     Developer Note: fortran interface is not autogenerated as the f90
6910     interface defintion cannot be generated correctly [due to MatFactorInfo]
6911 
6912    References:
6913      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6914 @*/
6915 PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6916 {
6917   PetscErrorCode ierr;
6918 
6919   PetscFunctionBegin;
6920   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
6921   PetscValidType(mat,2);
6922   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,3);
6923   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,4);
6924   PetscValidPointer(info,5);
6925   PetscValidPointer(fact,1);
6926   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6927   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6928   if (!fact->ops->ilufactorsymbolic) {
6929     MatSolverType stype;
6930     ierr = MatFactorGetSolverType(fact,&stype);CHKERRQ(ierr);
6931     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver type %s",((PetscObject)mat)->type_name,stype);
6932   }
6933   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6934   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6935   MatCheckPreallocated(mat,2);
6936 
6937   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);}
6938   ierr = (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
6939   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);}
6940   PetscFunctionReturn(0);
6941 }
6942 
6943 /*@C
6944    MatICCFactorSymbolic - Performs symbolic incomplete
6945    Cholesky factorization for a symmetric matrix.  Use
6946    MatCholeskyFactorNumeric() to complete the factorization.
6947 
6948    Collective on Mat
6949 
6950    Input Parameters:
6951 +  mat - the matrix
6952 .  perm - row and column permutation
6953 -  info - structure containing
6954 $      levels - number of levels of fill.
6955 $      expected fill - as ratio of original fill.
6956 
6957    Output Parameter:
6958 .  fact - the factored matrix
6959 
6960    Notes:
6961    Most users should employ the KSP interface for linear solvers
6962    instead of working directly with matrix algebra routines such as this.
6963    See, e.g., KSPCreate().
6964 
6965    Level: developer
6966 
6967 .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6968 
6969     Note: this uses the definition of level of fill as in Y. Saad, 2003
6970 
6971     Developer Note: fortran interface is not autogenerated as the f90
6972     interface defintion cannot be generated correctly [due to MatFactorInfo]
6973 
6974    References:
6975      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6976 @*/
6977 PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6978 {
6979   PetscErrorCode ierr;
6980 
6981   PetscFunctionBegin;
6982   PetscValidHeaderSpecific(mat,MAT_CLASSID,2);
6983   PetscValidType(mat,2);
6984   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,3);
6985   PetscValidPointer(info,4);
6986   PetscValidPointer(fact,1);
6987   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6988   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6989   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6990   if (!(fact)->ops->iccfactorsymbolic) {
6991     MatSolverType stype;
6992     ierr = MatFactorGetSolverType(fact,&stype);CHKERRQ(ierr);
6993     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver type %s",((PetscObject)mat)->type_name,stype);
6994   }
6995   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6996   MatCheckPreallocated(mat,2);
6997 
6998   if (!fact->trivialsymbolic) {ierr = PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);}
6999   ierr = (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
7000   if (!fact->trivialsymbolic) {ierr = PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);}
7001   PetscFunctionReturn(0);
7002 }
7003 
7004 /*@C
7005    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7006    points to an array of valid matrices, they may be reused to store the new
7007    submatrices.
7008 
7009    Collective on Mat
7010 
7011    Input Parameters:
7012 +  mat - the matrix
7013 .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
7014 .  irow, icol - index sets of rows and columns to extract
7015 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7016 
7017    Output Parameter:
7018 .  submat - the array of submatrices
7019 
7020    Notes:
7021    MatCreateSubMatrices() can extract ONLY sequential submatrices
7022    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
7023    to extract a parallel submatrix.
7024 
7025    Some matrix types place restrictions on the row and column
7026    indices, such as that they be sorted or that they be equal to each other.
7027 
7028    The index sets may not have duplicate entries.
7029 
7030    When extracting submatrices from a parallel matrix, each processor can
7031    form a different submatrix by setting the rows and columns of its
7032    individual index sets according to the local submatrix desired.
7033 
7034    When finished using the submatrices, the user should destroy
7035    them with MatDestroySubMatrices().
7036 
7037    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
7038    original matrix has not changed from that last call to MatCreateSubMatrices().
7039 
7040    This routine creates the matrices in submat; you should NOT create them before
7041    calling it. It also allocates the array of matrix pointers submat.
7042 
7043    For BAIJ matrices the index sets must respect the block structure, that is if they
7044    request one row/column in a block, they must request all rows/columns that are in
7045    that block. For example, if the block size is 2 you cannot request just row 0 and
7046    column 0.
7047 
7048    Fortran Note:
7049    The Fortran interface is slightly different from that given below; it
7050    requires one to pass in  as submat a Mat (integer) array of size at least n+1.
7051 
7052    Level: advanced
7053 
7054 .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
7055 @*/
7056 PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
7057 {
7058   PetscErrorCode ierr;
7059   PetscInt       i;
7060   PetscBool      eq;
7061 
7062   PetscFunctionBegin;
7063   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7064   PetscValidType(mat,1);
7065   if (n) {
7066     PetscValidPointer(irow,3);
7067     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
7068     PetscValidPointer(icol,4);
7069     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
7070   }
7071   PetscValidPointer(submat,6);
7072   if (n && scall == MAT_REUSE_MATRIX) {
7073     PetscValidPointer(*submat,6);
7074     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
7075   }
7076   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7077   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7078   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7079   MatCheckPreallocated(mat,1);
7080 
7081   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
7082   ierr = (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
7083   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
7084   for (i=0; i<n; i++) {
7085     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
7086     ierr = ISEqualUnsorted(irow[i],icol[i],&eq);CHKERRQ(ierr);
7087     if (eq) {
7088       ierr = MatPropagateSymmetryOptions(mat,(*submat)[i]);CHKERRQ(ierr);
7089     }
7090   }
7091   PetscFunctionReturn(0);
7092 }
7093 
7094 /*@C
7095    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
7096 
7097    Collective on Mat
7098 
7099    Input Parameters:
7100 +  mat - the matrix
7101 .  n   - the number of submatrixes to be extracted
7102 .  irow, icol - index sets of rows and columns to extract
7103 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7104 
7105    Output Parameter:
7106 .  submat - the array of submatrices
7107 
7108    Level: advanced
7109 
7110 .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
7111 @*/
7112 PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
7113 {
7114   PetscErrorCode ierr;
7115   PetscInt       i;
7116   PetscBool      eq;
7117 
7118   PetscFunctionBegin;
7119   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7120   PetscValidType(mat,1);
7121   if (n) {
7122     PetscValidPointer(irow,3);
7123     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
7124     PetscValidPointer(icol,4);
7125     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
7126   }
7127   PetscValidPointer(submat,6);
7128   if (n && scall == MAT_REUSE_MATRIX) {
7129     PetscValidPointer(*submat,6);
7130     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
7131   }
7132   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7133   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7134   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7135   MatCheckPreallocated(mat,1);
7136 
7137   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
7138   ierr = (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
7139   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
7140   for (i=0; i<n; i++) {
7141     ierr = ISEqualUnsorted(irow[i],icol[i],&eq);CHKERRQ(ierr);
7142     if (eq) {
7143       ierr = MatPropagateSymmetryOptions(mat,(*submat)[i]);CHKERRQ(ierr);
7144     }
7145   }
7146   PetscFunctionReturn(0);
7147 }
7148 
7149 /*@C
7150    MatDestroyMatrices - Destroys an array of matrices.
7151 
7152    Collective on Mat
7153 
7154    Input Parameters:
7155 +  n - the number of local matrices
7156 -  mat - the matrices (note that this is a pointer to the array of matrices)
7157 
7158    Level: advanced
7159 
7160     Notes:
7161     Frees not only the matrices, but also the array that contains the matrices
7162            In Fortran will not free the array.
7163 
7164 .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
7165 @*/
7166 PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
7167 {
7168   PetscErrorCode ierr;
7169   PetscInt       i;
7170 
7171   PetscFunctionBegin;
7172   if (!*mat) PetscFunctionReturn(0);
7173   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
7174   PetscValidPointer(mat,2);
7175 
7176   for (i=0; i<n; i++) {
7177     ierr = MatDestroy(&(*mat)[i]);CHKERRQ(ierr);
7178   }
7179 
7180   /* memory is allocated even if n = 0 */
7181   ierr = PetscFree(*mat);CHKERRQ(ierr);
7182   PetscFunctionReturn(0);
7183 }
7184 
7185 /*@C
7186    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
7187 
7188    Collective on Mat
7189 
7190    Input Parameters:
7191 +  n - the number of local matrices
7192 -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
7193                        sequence of MatCreateSubMatrices())
7194 
7195    Level: advanced
7196 
7197     Notes:
7198     Frees not only the matrices, but also the array that contains the matrices
7199            In Fortran will not free the array.
7200 
7201 .seealso: MatCreateSubMatrices()
7202 @*/
7203 PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
7204 {
7205   PetscErrorCode ierr;
7206   Mat            mat0;
7207 
7208   PetscFunctionBegin;
7209   if (!*mat) PetscFunctionReturn(0);
7210   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7211   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
7212   PetscValidPointer(mat,2);
7213 
7214   mat0 = (*mat)[0];
7215   if (mat0 && mat0->ops->destroysubmatrices) {
7216     ierr = (mat0->ops->destroysubmatrices)(n,mat);CHKERRQ(ierr);
7217   } else {
7218     ierr = MatDestroyMatrices(n,mat);CHKERRQ(ierr);
7219   }
7220   PetscFunctionReturn(0);
7221 }
7222 
7223 /*@C
7224    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
7225 
7226    Collective on Mat
7227 
7228    Input Parameters:
7229 .  mat - the matrix
7230 
7231    Output Parameter:
7232 .  matstruct - the sequential matrix with the nonzero structure of mat
7233 
7234   Level: intermediate
7235 
7236 .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7237 @*/
7238 PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7239 {
7240   PetscErrorCode ierr;
7241 
7242   PetscFunctionBegin;
7243   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7244   PetscValidPointer(matstruct,2);
7245 
7246   PetscValidType(mat,1);
7247   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7248   MatCheckPreallocated(mat,1);
7249 
7250   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7251   ierr = PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
7252   ierr = (*mat->ops->getseqnonzerostructure)(mat,matstruct);CHKERRQ(ierr);
7253   ierr = PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
7254   PetscFunctionReturn(0);
7255 }
7256 
7257 /*@C
7258    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
7259 
7260    Collective on Mat
7261 
7262    Input Parameters:
7263 .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
7264                        sequence of MatGetSequentialNonzeroStructure())
7265 
7266    Level: advanced
7267 
7268     Notes:
7269     Frees not only the matrices, but also the array that contains the matrices
7270 
7271 .seealso: MatGetSeqNonzeroStructure()
7272 @*/
7273 PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7274 {
7275   PetscErrorCode ierr;
7276 
7277   PetscFunctionBegin;
7278   PetscValidPointer(mat,1);
7279   ierr = MatDestroy(mat);CHKERRQ(ierr);
7280   PetscFunctionReturn(0);
7281 }
7282 
7283 /*@
7284    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7285    replaces the index sets by larger ones that represent submatrices with
7286    additional overlap.
7287 
7288    Collective on Mat
7289 
7290    Input Parameters:
7291 +  mat - the matrix
7292 .  n   - the number of index sets
7293 .  is  - the array of index sets (these index sets will changed during the call)
7294 -  ov  - the additional overlap requested
7295 
7296    Options Database:
7297 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7298 
7299    Level: developer
7300 
7301 .seealso: MatCreateSubMatrices()
7302 @*/
7303 PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7304 {
7305   PetscErrorCode ierr;
7306 
7307   PetscFunctionBegin;
7308   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7309   PetscValidType(mat,1);
7310   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7311   if (n) {
7312     PetscValidPointer(is,3);
7313     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
7314   }
7315   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7316   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7317   MatCheckPreallocated(mat,1);
7318 
7319   if (!ov) PetscFunctionReturn(0);
7320   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7321   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7322   ierr = (*mat->ops->increaseoverlap)(mat,n,is,ov);CHKERRQ(ierr);
7323   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7324   PetscFunctionReturn(0);
7325 }
7326 
7327 PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
7328 
7329 /*@
7330    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7331    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7332    additional overlap.
7333 
7334    Collective on Mat
7335 
7336    Input Parameters:
7337 +  mat - the matrix
7338 .  n   - the number of index sets
7339 .  is  - the array of index sets (these index sets will changed during the call)
7340 -  ov  - the additional overlap requested
7341 
7342    Options Database:
7343 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7344 
7345    Level: developer
7346 
7347 .seealso: MatCreateSubMatrices()
7348 @*/
7349 PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7350 {
7351   PetscInt       i;
7352   PetscErrorCode ierr;
7353 
7354   PetscFunctionBegin;
7355   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7356   PetscValidType(mat,1);
7357   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7358   if (n) {
7359     PetscValidPointer(is,3);
7360     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
7361   }
7362   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7363   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7364   MatCheckPreallocated(mat,1);
7365   if (!ov) PetscFunctionReturn(0);
7366   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7367   for (i=0; i<n; i++){
7368         ierr =  MatIncreaseOverlapSplit_Single(mat,&is[i],ov);CHKERRQ(ierr);
7369   }
7370   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7371   PetscFunctionReturn(0);
7372 }
7373 
7374 /*@
7375    MatGetBlockSize - Returns the matrix block size.
7376 
7377    Not Collective
7378 
7379    Input Parameter:
7380 .  mat - the matrix
7381 
7382    Output Parameter:
7383 .  bs - block size
7384 
7385    Notes:
7386     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7387 
7388    If the block size has not been set yet this routine returns 1.
7389 
7390    Level: intermediate
7391 
7392 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7393 @*/
7394 PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7395 {
7396   PetscFunctionBegin;
7397   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7398   PetscValidIntPointer(bs,2);
7399   *bs = PetscAbs(mat->rmap->bs);
7400   PetscFunctionReturn(0);
7401 }
7402 
7403 /*@
7404    MatGetBlockSizes - Returns the matrix block row and column sizes.
7405 
7406    Not Collective
7407 
7408    Input Parameter:
7409 .  mat - the matrix
7410 
7411    Output Parameter:
7412 +  rbs - row block size
7413 -  cbs - column block size
7414 
7415    Notes:
7416     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7417     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7418 
7419    If a block size has not been set yet this routine returns 1.
7420 
7421    Level: intermediate
7422 
7423 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7424 @*/
7425 PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7426 {
7427   PetscFunctionBegin;
7428   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7429   if (rbs) PetscValidIntPointer(rbs,2);
7430   if (cbs) PetscValidIntPointer(cbs,3);
7431   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7432   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7433   PetscFunctionReturn(0);
7434 }
7435 
7436 /*@
7437    MatSetBlockSize - Sets the matrix block size.
7438 
7439    Logically Collective on Mat
7440 
7441    Input Parameters:
7442 +  mat - the matrix
7443 -  bs - block size
7444 
7445    Notes:
7446     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7447     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7448 
7449     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7450     is compatible with the matrix local sizes.
7451 
7452    Level: intermediate
7453 
7454 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7455 @*/
7456 PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7457 {
7458   PetscErrorCode ierr;
7459 
7460   PetscFunctionBegin;
7461   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7462   PetscValidLogicalCollectiveInt(mat,bs,2);
7463   ierr = MatSetBlockSizes(mat,bs,bs);CHKERRQ(ierr);
7464   PetscFunctionReturn(0);
7465 }
7466 
7467 /*@
7468    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7469 
7470    Logically Collective on Mat
7471 
7472    Input Parameters:
7473 +  mat - the matrix
7474 .  nblocks - the number of blocks on this process
7475 -  bsizes - the block sizes
7476 
7477    Notes:
7478     Currently used by PCVPBJACOBI for SeqAIJ matrices
7479 
7480    Level: intermediate
7481 
7482 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7483 @*/
7484 PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7485 {
7486   PetscErrorCode ierr;
7487   PetscInt       i,ncnt = 0, nlocal;
7488 
7489   PetscFunctionBegin;
7490   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7491   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7492   ierr = MatGetLocalSize(mat,&nlocal,NULL);CHKERRQ(ierr);
7493   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7494   if (ncnt != nlocal) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Sum of local block sizes %D does not equal local size of matrix %D",ncnt,nlocal);
7495   ierr = PetscFree(mat->bsizes);CHKERRQ(ierr);
7496   mat->nblocks = nblocks;
7497   ierr = PetscMalloc1(nblocks,&mat->bsizes);CHKERRQ(ierr);
7498   ierr = PetscArraycpy(mat->bsizes,bsizes,nblocks);CHKERRQ(ierr);
7499   PetscFunctionReturn(0);
7500 }
7501 
7502 /*@C
7503    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7504 
7505    Logically Collective on Mat
7506 
7507    Input Parameters:
7508 .  mat - the matrix
7509 
7510    Output Parameters:
7511 +  nblocks - the number of blocks on this process
7512 -  bsizes - the block sizes
7513 
7514    Notes: Currently not supported from Fortran
7515 
7516    Level: intermediate
7517 
7518 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7519 @*/
7520 PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7521 {
7522   PetscFunctionBegin;
7523   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7524   *nblocks = mat->nblocks;
7525   *bsizes  = mat->bsizes;
7526   PetscFunctionReturn(0);
7527 }
7528 
7529 /*@
7530    MatSetBlockSizes - Sets the matrix block row and column sizes.
7531 
7532    Logically Collective on Mat
7533 
7534    Input Parameters:
7535 +  mat - the matrix
7536 .  rbs - row block size
7537 -  cbs - column block size
7538 
7539    Notes:
7540     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7541     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7542     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7543 
7544     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7545     are compatible with the matrix local sizes.
7546 
7547     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7548 
7549    Level: intermediate
7550 
7551 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7552 @*/
7553 PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7554 {
7555   PetscErrorCode ierr;
7556 
7557   PetscFunctionBegin;
7558   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7559   PetscValidLogicalCollectiveInt(mat,rbs,2);
7560   PetscValidLogicalCollectiveInt(mat,cbs,3);
7561   if (mat->ops->setblocksizes) {
7562     ierr = (*mat->ops->setblocksizes)(mat,rbs,cbs);CHKERRQ(ierr);
7563   }
7564   if (mat->rmap->refcnt) {
7565     ISLocalToGlobalMapping l2g = NULL;
7566     PetscLayout            nmap = NULL;
7567 
7568     ierr = PetscLayoutDuplicate(mat->rmap,&nmap);CHKERRQ(ierr);
7569     if (mat->rmap->mapping) {
7570       ierr = ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);CHKERRQ(ierr);
7571     }
7572     ierr = PetscLayoutDestroy(&mat->rmap);CHKERRQ(ierr);
7573     mat->rmap = nmap;
7574     mat->rmap->mapping = l2g;
7575   }
7576   if (mat->cmap->refcnt) {
7577     ISLocalToGlobalMapping l2g = NULL;
7578     PetscLayout            nmap = NULL;
7579 
7580     ierr = PetscLayoutDuplicate(mat->cmap,&nmap);CHKERRQ(ierr);
7581     if (mat->cmap->mapping) {
7582       ierr = ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);CHKERRQ(ierr);
7583     }
7584     ierr = PetscLayoutDestroy(&mat->cmap);CHKERRQ(ierr);
7585     mat->cmap = nmap;
7586     mat->cmap->mapping = l2g;
7587   }
7588   ierr = PetscLayoutSetBlockSize(mat->rmap,rbs);CHKERRQ(ierr);
7589   ierr = PetscLayoutSetBlockSize(mat->cmap,cbs);CHKERRQ(ierr);
7590   PetscFunctionReturn(0);
7591 }
7592 
7593 /*@
7594    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7595 
7596    Logically Collective on Mat
7597 
7598    Input Parameters:
7599 +  mat - the matrix
7600 .  fromRow - matrix from which to copy row block size
7601 -  fromCol - matrix from which to copy column block size (can be same as fromRow)
7602 
7603    Level: developer
7604 
7605 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7606 @*/
7607 PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7608 {
7609   PetscErrorCode ierr;
7610 
7611   PetscFunctionBegin;
7612   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7613   PetscValidHeaderSpecific(fromRow,MAT_CLASSID,2);
7614   PetscValidHeaderSpecific(fromCol,MAT_CLASSID,3);
7615   if (fromRow->rmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);CHKERRQ(ierr);}
7616   if (fromCol->cmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);CHKERRQ(ierr);}
7617   PetscFunctionReturn(0);
7618 }
7619 
7620 /*@
7621    MatResidual - Default routine to calculate the residual.
7622 
7623    Collective on Mat
7624 
7625    Input Parameters:
7626 +  mat - the matrix
7627 .  b   - the right-hand-side
7628 -  x   - the approximate solution
7629 
7630    Output Parameter:
7631 .  r - location to store the residual
7632 
7633    Level: developer
7634 
7635 .seealso: PCMGSetResidual()
7636 @*/
7637 PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7638 {
7639   PetscErrorCode ierr;
7640 
7641   PetscFunctionBegin;
7642   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7643   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
7644   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
7645   PetscValidHeaderSpecific(r,VEC_CLASSID,4);
7646   PetscValidType(mat,1);
7647   MatCheckPreallocated(mat,1);
7648   ierr  = PetscLogEventBegin(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7649   if (!mat->ops->residual) {
7650     ierr = MatMult(mat,x,r);CHKERRQ(ierr);
7651     ierr = VecAYPX(r,-1.0,b);CHKERRQ(ierr);
7652   } else {
7653     ierr  = (*mat->ops->residual)(mat,b,x,r);CHKERRQ(ierr);
7654   }
7655   ierr  = PetscLogEventEnd(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7656   PetscFunctionReturn(0);
7657 }
7658 
7659 /*@C
7660     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7661 
7662    Collective on Mat
7663 
7664     Input Parameters:
7665 +   mat - the matrix
7666 .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7667 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7668 -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7669                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7670                  always used.
7671 
7672     Output Parameters:
7673 +   n - number of rows in the (possibly compressed) matrix
7674 .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7675 .   ja - the column indices
7676 -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7677            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7678 
7679     Level: developer
7680 
7681     Notes:
7682     You CANNOT change any of the ia[] or ja[] values.
7683 
7684     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7685 
7686     Fortran Notes:
7687     In Fortran use
7688 $
7689 $      PetscInt ia(1), ja(1)
7690 $      PetscOffset iia, jja
7691 $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7692 $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7693 
7694      or
7695 $
7696 $    PetscInt, pointer :: ia(:),ja(:)
7697 $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7698 $    ! Access the ith and jth entries via ia(i) and ja(j)
7699 
7700 .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7701 @*/
7702 PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7703 {
7704   PetscErrorCode ierr;
7705 
7706   PetscFunctionBegin;
7707   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7708   PetscValidType(mat,1);
7709   PetscValidIntPointer(n,5);
7710   if (ia) PetscValidIntPointer(ia,6);
7711   if (ja) PetscValidIntPointer(ja,7);
7712   PetscValidBoolPointer(done,8);
7713   MatCheckPreallocated(mat,1);
7714   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7715   else {
7716     *done = PETSC_TRUE;
7717     ierr  = PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7718     ierr  = (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7719     ierr  = PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7720   }
7721   PetscFunctionReturn(0);
7722 }
7723 
7724 /*@C
7725     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7726 
7727     Collective on Mat
7728 
7729     Input Parameters:
7730 +   mat - the matrix
7731 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7732 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7733                 symmetrized
7734 .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7735                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7736                  always used.
7737 .   n - number of columns in the (possibly compressed) matrix
7738 .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7739 -   ja - the row indices
7740 
7741     Output Parameters:
7742 .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7743 
7744     Level: developer
7745 
7746 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7747 @*/
7748 PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7749 {
7750   PetscErrorCode ierr;
7751 
7752   PetscFunctionBegin;
7753   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7754   PetscValidType(mat,1);
7755   PetscValidIntPointer(n,5);
7756   if (ia) PetscValidIntPointer(ia,6);
7757   if (ja) PetscValidIntPointer(ja,7);
7758   PetscValidBoolPointer(done,8);
7759   MatCheckPreallocated(mat,1);
7760   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7761   else {
7762     *done = PETSC_TRUE;
7763     ierr  = (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7764   }
7765   PetscFunctionReturn(0);
7766 }
7767 
7768 /*@C
7769     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7770     MatGetRowIJ().
7771 
7772     Collective on Mat
7773 
7774     Input Parameters:
7775 +   mat - the matrix
7776 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7777 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7778                 symmetrized
7779 .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7780                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7781                  always used.
7782 .   n - size of (possibly compressed) matrix
7783 .   ia - the row pointers
7784 -   ja - the column indices
7785 
7786     Output Parameters:
7787 .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7788 
7789     Note:
7790     This routine zeros out n, ia, and ja. This is to prevent accidental
7791     us of the array after it has been restored. If you pass NULL, it will
7792     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.
7793 
7794     Level: developer
7795 
7796 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7797 @*/
7798 PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7799 {
7800   PetscErrorCode ierr;
7801 
7802   PetscFunctionBegin;
7803   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7804   PetscValidType(mat,1);
7805   if (ia) PetscValidIntPointer(ia,6);
7806   if (ja) PetscValidIntPointer(ja,7);
7807   PetscValidBoolPointer(done,8);
7808   MatCheckPreallocated(mat,1);
7809 
7810   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7811   else {
7812     *done = PETSC_TRUE;
7813     ierr  = (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7814     if (n)  *n = 0;
7815     if (ia) *ia = NULL;
7816     if (ja) *ja = NULL;
7817   }
7818   PetscFunctionReturn(0);
7819 }
7820 
7821 /*@C
7822     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7823     MatGetColumnIJ().
7824 
7825     Collective on Mat
7826 
7827     Input Parameters:
7828 +   mat - the matrix
7829 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7830 -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7831                 symmetrized
7832 -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7833                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7834                  always used.
7835 
7836     Output Parameters:
7837 +   n - size of (possibly compressed) matrix
7838 .   ia - the column pointers
7839 .   ja - the row indices
7840 -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7841 
7842     Level: developer
7843 
7844 .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7845 @*/
7846 PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7847 {
7848   PetscErrorCode ierr;
7849 
7850   PetscFunctionBegin;
7851   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7852   PetscValidType(mat,1);
7853   if (ia) PetscValidIntPointer(ia,6);
7854   if (ja) PetscValidIntPointer(ja,7);
7855   PetscValidBoolPointer(done,8);
7856   MatCheckPreallocated(mat,1);
7857 
7858   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7859   else {
7860     *done = PETSC_TRUE;
7861     ierr  = (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7862     if (n)  *n = 0;
7863     if (ia) *ia = NULL;
7864     if (ja) *ja = NULL;
7865   }
7866   PetscFunctionReturn(0);
7867 }
7868 
7869 /*@C
7870     MatColoringPatch -Used inside matrix coloring routines that
7871     use MatGetRowIJ() and/or MatGetColumnIJ().
7872 
7873     Collective on Mat
7874 
7875     Input Parameters:
7876 +   mat - the matrix
7877 .   ncolors - max color value
7878 .   n   - number of entries in colorarray
7879 -   colorarray - array indicating color for each column
7880 
7881     Output Parameters:
7882 .   iscoloring - coloring generated using colorarray information
7883 
7884     Level: developer
7885 
7886 .seealso: MatGetRowIJ(), MatGetColumnIJ()
7887 
7888 @*/
7889 PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7890 {
7891   PetscErrorCode ierr;
7892 
7893   PetscFunctionBegin;
7894   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7895   PetscValidType(mat,1);
7896   PetscValidIntPointer(colorarray,4);
7897   PetscValidPointer(iscoloring,5);
7898   MatCheckPreallocated(mat,1);
7899 
7900   if (!mat->ops->coloringpatch) {
7901     ierr = ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);CHKERRQ(ierr);
7902   } else {
7903     ierr = (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);CHKERRQ(ierr);
7904   }
7905   PetscFunctionReturn(0);
7906 }
7907 
7908 /*@
7909    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7910 
7911    Logically Collective on Mat
7912 
7913    Input Parameter:
7914 .  mat - the factored matrix to be reset
7915 
7916    Notes:
7917    This routine should be used only with factored matrices formed by in-place
7918    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7919    format).  This option can save memory, for example, when solving nonlinear
7920    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7921    ILU(0) preconditioner.
7922 
7923    Note that one can specify in-place ILU(0) factorization by calling
7924 .vb
7925      PCType(pc,PCILU);
7926      PCFactorSeUseInPlace(pc);
7927 .ve
7928    or by using the options -pc_type ilu -pc_factor_in_place
7929 
7930    In-place factorization ILU(0) can also be used as a local
7931    solver for the blocks within the block Jacobi or additive Schwarz
7932    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7933    for details on setting local solver options.
7934 
7935    Most users should employ the simplified KSP interface for linear solvers
7936    instead of working directly with matrix algebra routines such as this.
7937    See, e.g., KSPCreate().
7938 
7939    Level: developer
7940 
7941 .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7942 
7943 @*/
7944 PetscErrorCode MatSetUnfactored(Mat mat)
7945 {
7946   PetscErrorCode ierr;
7947 
7948   PetscFunctionBegin;
7949   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7950   PetscValidType(mat,1);
7951   MatCheckPreallocated(mat,1);
7952   mat->factortype = MAT_FACTOR_NONE;
7953   if (!mat->ops->setunfactored) PetscFunctionReturn(0);
7954   ierr = (*mat->ops->setunfactored)(mat);CHKERRQ(ierr);
7955   PetscFunctionReturn(0);
7956 }
7957 
7958 /*MC
7959     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7960 
7961     Synopsis:
7962     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7963 
7964     Not collective
7965 
7966     Input Parameter:
7967 .   x - matrix
7968 
7969     Output Parameters:
7970 +   xx_v - the Fortran90 pointer to the array
7971 -   ierr - error code
7972 
7973     Example of Usage:
7974 .vb
7975       PetscScalar, pointer xx_v(:,:)
7976       ....
7977       call MatDenseGetArrayF90(x,xx_v,ierr)
7978       a = xx_v(3)
7979       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7980 .ve
7981 
7982     Level: advanced
7983 
7984 .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7985 
7986 M*/
7987 
7988 /*MC
7989     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7990     accessed with MatDenseGetArrayF90().
7991 
7992     Synopsis:
7993     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7994 
7995     Not collective
7996 
7997     Input Parameters:
7998 +   x - matrix
7999 -   xx_v - the Fortran90 pointer to the array
8000 
8001     Output Parameter:
8002 .   ierr - error code
8003 
8004     Example of Usage:
8005 .vb
8006        PetscScalar, pointer xx_v(:,:)
8007        ....
8008        call MatDenseGetArrayF90(x,xx_v,ierr)
8009        a = xx_v(3)
8010        call MatDenseRestoreArrayF90(x,xx_v,ierr)
8011 .ve
8012 
8013     Level: advanced
8014 
8015 .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
8016 
8017 M*/
8018 
8019 /*MC
8020     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
8021 
8022     Synopsis:
8023     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
8024 
8025     Not collective
8026 
8027     Input Parameter:
8028 .   x - matrix
8029 
8030     Output Parameters:
8031 +   xx_v - the Fortran90 pointer to the array
8032 -   ierr - error code
8033 
8034     Example of Usage:
8035 .vb
8036       PetscScalar, pointer xx_v(:)
8037       ....
8038       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8039       a = xx_v(3)
8040       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8041 .ve
8042 
8043     Level: advanced
8044 
8045 .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
8046 
8047 M*/
8048 
8049 /*MC
8050     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
8051     accessed with MatSeqAIJGetArrayF90().
8052 
8053     Synopsis:
8054     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
8055 
8056     Not collective
8057 
8058     Input Parameters:
8059 +   x - matrix
8060 -   xx_v - the Fortran90 pointer to the array
8061 
8062     Output Parameter:
8063 .   ierr - error code
8064 
8065     Example of Usage:
8066 .vb
8067        PetscScalar, pointer xx_v(:)
8068        ....
8069        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8070        a = xx_v(3)
8071        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8072 .ve
8073 
8074     Level: advanced
8075 
8076 .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
8077 
8078 M*/
8079 
8080 /*@
8081     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8082                       as the original matrix.
8083 
8084     Collective on Mat
8085 
8086     Input Parameters:
8087 +   mat - the original matrix
8088 .   isrow - parallel IS containing the rows this processor should obtain
8089 .   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.
8090 -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
8091 
8092     Output Parameter:
8093 .   newmat - the new submatrix, of the same type as the old
8094 
8095     Level: advanced
8096 
8097     Notes:
8098     The submatrix will be able to be multiplied with vectors using the same layout as iscol.
8099 
8100     Some matrix types place restrictions on the row and column indices, such
8101     as that they be sorted or that they be equal to each other.
8102 
8103     The index sets may not have duplicate entries.
8104 
8105       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
8106    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
8107    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
8108    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
8109    you are finished using it.
8110 
8111     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8112     the input matrix.
8113 
8114     If iscol is NULL then all columns are obtained (not supported in Fortran).
8115 
8116    Example usage:
8117    Consider the following 8x8 matrix with 34 non-zero values, that is
8118    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8119    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8120    as follows:
8121 
8122 .vb
8123             1  2  0  |  0  3  0  |  0  4
8124     Proc0   0  5  6  |  7  0  0  |  8  0
8125             9  0 10  | 11  0  0  | 12  0
8126     -------------------------------------
8127            13  0 14  | 15 16 17  |  0  0
8128     Proc1   0 18  0  | 19 20 21  |  0  0
8129             0  0  0  | 22 23  0  | 24  0
8130     -------------------------------------
8131     Proc2  25 26 27  |  0  0 28  | 29  0
8132            30  0  0  | 31 32 33  |  0 34
8133 .ve
8134 
8135     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is
8136 
8137 .vb
8138             2  0  |  0  3  0  |  0
8139     Proc0   5  6  |  7  0  0  |  8
8140     -------------------------------
8141     Proc1  18  0  | 19 20 21  |  0
8142     -------------------------------
8143     Proc2  26 27  |  0  0 28  | 29
8144             0  0  | 31 32 33  |  0
8145 .ve
8146 
8147 .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
8148 @*/
8149 PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
8150 {
8151   PetscErrorCode ierr;
8152   PetscMPIInt    size;
8153   Mat            *local;
8154   IS             iscoltmp;
8155   PetscBool      flg;
8156 
8157   PetscFunctionBegin;
8158   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8159   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
8160   if (iscol) PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
8161   PetscValidPointer(newmat,5);
8162   if (cll == MAT_REUSE_MATRIX) PetscValidHeaderSpecific(*newmat,MAT_CLASSID,5);
8163   PetscValidType(mat,1);
8164   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8165   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
8166 
8167   MatCheckPreallocated(mat,1);
8168   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRMPI(ierr);
8169 
8170   if (!iscol || isrow == iscol) {
8171     PetscBool   stride;
8172     PetscMPIInt grabentirematrix = 0,grab;
8173     ierr = PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);CHKERRQ(ierr);
8174     if (stride) {
8175       PetscInt first,step,n,rstart,rend;
8176       ierr = ISStrideGetInfo(isrow,&first,&step);CHKERRQ(ierr);
8177       if (step == 1) {
8178         ierr = MatGetOwnershipRange(mat,&rstart,&rend);CHKERRQ(ierr);
8179         if (rstart == first) {
8180           ierr = ISGetLocalSize(isrow,&n);CHKERRQ(ierr);
8181           if (n == rend-rstart) {
8182             grabentirematrix = 1;
8183           }
8184         }
8185       }
8186     }
8187     ierr = MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));CHKERRMPI(ierr);
8188     if (grab) {
8189       ierr = PetscInfo(mat,"Getting entire matrix as submatrix\n");CHKERRQ(ierr);
8190       if (cll == MAT_INITIAL_MATRIX) {
8191         *newmat = mat;
8192         ierr    = PetscObjectReference((PetscObject)mat);CHKERRQ(ierr);
8193       }
8194       PetscFunctionReturn(0);
8195     }
8196   }
8197 
8198   if (!iscol) {
8199     ierr = ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);CHKERRQ(ierr);
8200   } else {
8201     iscoltmp = iscol;
8202   }
8203 
8204   /* if original matrix is on just one processor then use submatrix generated */
8205   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8206     ierr = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);CHKERRQ(ierr);
8207     goto setproperties;
8208   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8209     ierr    = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);CHKERRQ(ierr);
8210     *newmat = *local;
8211     ierr    = PetscFree(local);CHKERRQ(ierr);
8212     goto setproperties;
8213   } else if (!mat->ops->createsubmatrix) {
8214     /* Create a new matrix type that implements the operation using the full matrix */
8215     ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8216     switch (cll) {
8217     case MAT_INITIAL_MATRIX:
8218       ierr = MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);CHKERRQ(ierr);
8219       break;
8220     case MAT_REUSE_MATRIX:
8221       ierr = MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);CHKERRQ(ierr);
8222       break;
8223     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8224     }
8225     ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8226     goto setproperties;
8227   }
8228 
8229   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8230   ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8231   ierr = (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);CHKERRQ(ierr);
8232   ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8233 
8234 setproperties:
8235   ierr = ISEqualUnsorted(isrow,iscoltmp,&flg);CHKERRQ(ierr);
8236   if (flg) {
8237     ierr = MatPropagateSymmetryOptions(mat,*newmat);CHKERRQ(ierr);
8238   }
8239   if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
8240   if (*newmat && cll == MAT_INITIAL_MATRIX) {ierr = PetscObjectStateIncrease((PetscObject)*newmat);CHKERRQ(ierr);}
8241   PetscFunctionReturn(0);
8242 }
8243 
8244 /*@
8245    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix
8246 
8247    Not Collective
8248 
8249    Input Parameters:
8250 +  A - the matrix we wish to propagate options from
8251 -  B - the matrix we wish to propagate options to
8252 
8253    Level: beginner
8254 
8255    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC
8256 
8257 .seealso: MatSetOption()
8258 @*/
8259 PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8260 {
8261   PetscErrorCode ierr;
8262 
8263   PetscFunctionBegin;
8264   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8265   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
8266   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
8267     ierr = MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);CHKERRQ(ierr);
8268   }
8269   if (A->structurally_symmetric_set) {
8270     ierr = MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);CHKERRQ(ierr);
8271   }
8272   if (A->hermitian_set) {
8273     ierr = MatSetOption(B,MAT_HERMITIAN,A->hermitian);CHKERRQ(ierr);
8274   }
8275   if (A->spd_set) {
8276     ierr = MatSetOption(B,MAT_SPD,A->spd);CHKERRQ(ierr);
8277   }
8278   if (A->symmetric_set) {
8279     ierr = MatSetOption(B,MAT_SYMMETRIC,A->symmetric);CHKERRQ(ierr);
8280   }
8281   PetscFunctionReturn(0);
8282 }
8283 
8284 /*@
8285    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8286    used during the assembly process to store values that belong to
8287    other processors.
8288 
8289    Not Collective
8290 
8291    Input Parameters:
8292 +  mat   - the matrix
8293 .  size  - the initial size of the stash.
8294 -  bsize - the initial size of the block-stash(if used).
8295 
8296    Options Database Keys:
8297 +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8298 -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>
8299 
8300    Level: intermediate
8301 
8302    Notes:
8303      The block-stash is used for values set with MatSetValuesBlocked() while
8304      the stash is used for values set with MatSetValues()
8305 
8306      Run with the option -info and look for output of the form
8307      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8308      to determine the appropriate value, MM, to use for size and
8309      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8310      to determine the value, BMM to use for bsize
8311 
8312 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
8313 
8314 @*/
8315 PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8316 {
8317   PetscErrorCode ierr;
8318 
8319   PetscFunctionBegin;
8320   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8321   PetscValidType(mat,1);
8322   ierr = MatStashSetInitialSize_Private(&mat->stash,size);CHKERRQ(ierr);
8323   ierr = MatStashSetInitialSize_Private(&mat->bstash,bsize);CHKERRQ(ierr);
8324   PetscFunctionReturn(0);
8325 }
8326 
8327 /*@
8328    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8329      the matrix
8330 
8331    Neighbor-wise Collective on Mat
8332 
8333    Input Parameters:
8334 +  mat   - the matrix
8335 .  x,y - the vectors
8336 -  w - where the result is stored
8337 
8338    Level: intermediate
8339 
8340    Notes:
8341     w may be the same vector as y.
8342 
8343     This allows one to use either the restriction or interpolation (its transpose)
8344     matrix to do the interpolation
8345 
8346 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8347 
8348 @*/
8349 PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8350 {
8351   PetscErrorCode ierr;
8352   PetscInt       M,N,Ny;
8353 
8354   PetscFunctionBegin;
8355   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8356   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8357   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8358   PetscValidHeaderSpecific(w,VEC_CLASSID,4);
8359   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8360   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8361   if (M == Ny) {
8362     ierr = MatMultAdd(A,x,y,w);CHKERRQ(ierr);
8363   } else {
8364     ierr = MatMultTransposeAdd(A,x,y,w);CHKERRQ(ierr);
8365   }
8366   PetscFunctionReturn(0);
8367 }
8368 
8369 /*@
8370    MatInterpolate - y = A*x or A'*x depending on the shape of
8371      the matrix
8372 
8373    Neighbor-wise Collective on Mat
8374 
8375    Input Parameters:
8376 +  mat   - the matrix
8377 -  x,y - the vectors
8378 
8379    Level: intermediate
8380 
8381    Notes:
8382     This allows one to use either the restriction or interpolation (its transpose)
8383     matrix to do the interpolation
8384 
8385 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8386 
8387 @*/
8388 PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8389 {
8390   PetscErrorCode ierr;
8391   PetscInt       M,N,Ny;
8392 
8393   PetscFunctionBegin;
8394   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8395   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8396   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8397   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8398   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8399   if (M == Ny) {
8400     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8401   } else {
8402     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8403   }
8404   PetscFunctionReturn(0);
8405 }
8406 
8407 /*@
8408    MatRestrict - y = A*x or A'*x
8409 
8410    Neighbor-wise Collective on Mat
8411 
8412    Input Parameters:
8413 +  mat   - the matrix
8414 -  x,y - the vectors
8415 
8416    Level: intermediate
8417 
8418    Notes:
8419     This allows one to use either the restriction or interpolation (its transpose)
8420     matrix to do the restriction
8421 
8422 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8423 
8424 @*/
8425 PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8426 {
8427   PetscErrorCode ierr;
8428   PetscInt       M,N,Ny;
8429 
8430   PetscFunctionBegin;
8431   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8432   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8433   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8434   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8435   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8436   if (M == Ny) {
8437     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8438   } else {
8439     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8440   }
8441   PetscFunctionReturn(0);
8442 }
8443 
8444 /*@
8445    MatMatInterpolateAdd - Y = W + A*X or W + A'*X
8446 
8447    Neighbor-wise Collective on Mat
8448 
8449    Input Parameters:
8450 +  mat   - the matrix
8451 -  w, x - the input dense matrices
8452 
8453    Output Parameters:
8454 .  y - the output dense matrix
8455 
8456    Level: intermediate
8457 
8458    Notes:
8459     This allows one to use either the restriction or interpolation (its transpose)
8460     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
8461     otherwise it will be recreated. y must be initialized to NULL if not supplied.
8462 
8463 .seealso: MatInterpolateAdd(), MatMatInterpolate(), MatMatRestrict()
8464 
8465 @*/
8466 PetscErrorCode MatMatInterpolateAdd(Mat A,Mat x,Mat w,Mat *y)
8467 {
8468   PetscErrorCode ierr;
8469   PetscInt       M,N,Mx,Nx,Mo,My = 0,Ny = 0;
8470   PetscBool      trans = PETSC_TRUE;
8471   MatReuse       reuse = MAT_INITIAL_MATRIX;
8472 
8473   PetscFunctionBegin;
8474   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8475   PetscValidHeaderSpecific(x,MAT_CLASSID,2);
8476   PetscValidType(x,2);
8477   if (w) PetscValidHeaderSpecific(w,MAT_CLASSID,3);
8478   if (*y) PetscValidHeaderSpecific(*y,MAT_CLASSID,4);
8479   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8480   ierr = MatGetSize(x,&Mx,&Nx);CHKERRQ(ierr);
8481   if (N == Mx) trans = PETSC_FALSE;
8482   else if (M != Mx) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Size mismatch: A %Dx%D, X %Dx%D",M,N,Mx,Nx);
8483   Mo = trans ? N : M;
8484   if (*y) {
8485     ierr = MatGetSize(*y,&My,&Ny);CHKERRQ(ierr);
8486     if (Mo == My && Nx == Ny) { reuse = MAT_REUSE_MATRIX; }
8487     else {
8488       if (w && *y == w) SETERRQ6(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Cannot reuse y and w, size mismatch: A %Dx%D, X %Dx%D, Y %Dx%D",M,N,Mx,Nx,My,Ny);
8489       ierr = MatDestroy(y);CHKERRQ(ierr);
8490     }
8491   }
8492 
8493   if (w && *y == w) { /* this is to minimize changes in PCMG */
8494     PetscBool flg;
8495 
8496     ierr = PetscObjectQuery((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject*)&w);CHKERRQ(ierr);
8497     if (w) {
8498       PetscInt My,Ny,Mw,Nw;
8499 
8500       ierr = PetscObjectTypeCompare((PetscObject)*y,((PetscObject)w)->type_name,&flg);CHKERRQ(ierr);
8501       ierr = MatGetSize(*y,&My,&Ny);CHKERRQ(ierr);
8502       ierr = MatGetSize(w,&Mw,&Nw);CHKERRQ(ierr);
8503       if (!flg || My != Mw || Ny != Nw) w = NULL;
8504     }
8505     if (!w) {
8506       ierr = MatDuplicate(*y,MAT_COPY_VALUES,&w);CHKERRQ(ierr);
8507       ierr = PetscObjectCompose((PetscObject)*y,"__MatMatIntAdd_w",(PetscObject)w);CHKERRQ(ierr);
8508       ierr = PetscLogObjectParent((PetscObject)*y,(PetscObject)w);CHKERRQ(ierr);
8509       ierr = PetscObjectDereference((PetscObject)w);CHKERRQ(ierr);
8510     } else {
8511       ierr = MatCopy(*y,w,UNKNOWN_NONZERO_PATTERN);CHKERRQ(ierr);
8512     }
8513   }
8514   if (!trans) {
8515     ierr = MatMatMult(A,x,reuse,PETSC_DEFAULT,y);CHKERRQ(ierr);
8516   } else {
8517     ierr = MatTransposeMatMult(A,x,reuse,PETSC_DEFAULT,y);CHKERRQ(ierr);
8518   }
8519   if (w) {
8520     ierr = MatAXPY(*y,1.0,w,UNKNOWN_NONZERO_PATTERN);CHKERRQ(ierr);
8521   }
8522   PetscFunctionReturn(0);
8523 }
8524 
8525 /*@
8526    MatMatInterpolate - Y = A*X or A'*X
8527 
8528    Neighbor-wise Collective on Mat
8529 
8530    Input Parameters:
8531 +  mat   - the matrix
8532 -  x - the input dense matrix
8533 
8534    Output Parameters:
8535 .  y - the output dense matrix
8536 
8537    Level: intermediate
8538 
8539    Notes:
8540     This allows one to use either the restriction or interpolation (its transpose)
8541     matrix to do the interpolation. y matrix can be reused if already created with the proper sizes,
8542     otherwise it will be recreated. y must be initialized to NULL if not supplied.
8543 
8544 .seealso: MatInterpolate(), MatRestrict(), MatMatRestrict()
8545 
8546 @*/
8547 PetscErrorCode MatMatInterpolate(Mat A,Mat x,Mat *y)
8548 {
8549   PetscErrorCode ierr;
8550 
8551   PetscFunctionBegin;
8552   ierr = MatMatInterpolateAdd(A,x,NULL,y);CHKERRQ(ierr);
8553   PetscFunctionReturn(0);
8554 }
8555 
8556 /*@
8557    MatMatRestrict - Y = A*X or A'*X
8558 
8559    Neighbor-wise Collective on Mat
8560 
8561    Input Parameters:
8562 +  mat   - the matrix
8563 -  x - the input dense matrix
8564 
8565    Output Parameters:
8566 .  y - the output dense matrix
8567 
8568    Level: intermediate
8569 
8570    Notes:
8571     This allows one to use either the restriction or interpolation (its transpose)
8572     matrix to do the restriction. y matrix can be reused if already created with the proper sizes,
8573     otherwise it will be recreated. y must be initialized to NULL if not supplied.
8574 
8575 .seealso: MatRestrict(), MatInterpolate(), MatMatInterpolate()
8576 @*/
8577 PetscErrorCode MatMatRestrict(Mat A,Mat x,Mat *y)
8578 {
8579   PetscErrorCode ierr;
8580 
8581   PetscFunctionBegin;
8582   ierr = MatMatInterpolateAdd(A,x,NULL,y);CHKERRQ(ierr);
8583   PetscFunctionReturn(0);
8584 }
8585 
8586 /*@
8587    MatGetNullSpace - retrieves the null space of a matrix.
8588 
8589    Logically Collective on Mat
8590 
8591    Input Parameters:
8592 +  mat - the matrix
8593 -  nullsp - the null space object
8594 
8595    Level: developer
8596 
8597 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8598 @*/
8599 PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8600 {
8601   PetscFunctionBegin;
8602   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8603   PetscValidPointer(nullsp,2);
8604   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8605   PetscFunctionReturn(0);
8606 }
8607 
8608 /*@
8609    MatSetNullSpace - attaches a null space to a matrix.
8610 
8611    Logically Collective on Mat
8612 
8613    Input Parameters:
8614 +  mat - the matrix
8615 -  nullsp - the null space object
8616 
8617    Level: advanced
8618 
8619    Notes:
8620       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8621 
8622       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8623       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8624 
8625       You can remove the null space by calling this routine with an nullsp of NULL
8626 
8627       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8628    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).
8629    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
8630    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
8631    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).
8632 
8633       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8634 
8635     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
8636     routine also automatically calls MatSetTransposeNullSpace().
8637 
8638 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8639 @*/
8640 PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8641 {
8642   PetscErrorCode ierr;
8643 
8644   PetscFunctionBegin;
8645   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8646   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8647   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8648   ierr = MatNullSpaceDestroy(&mat->nullsp);CHKERRQ(ierr);
8649   mat->nullsp = nullsp;
8650   if (mat->symmetric_set && mat->symmetric) {
8651     ierr = MatSetTransposeNullSpace(mat,nullsp);CHKERRQ(ierr);
8652   }
8653   PetscFunctionReturn(0);
8654 }
8655 
8656 /*@
8657    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8658 
8659    Logically Collective on Mat
8660 
8661    Input Parameters:
8662 +  mat - the matrix
8663 -  nullsp - the null space object
8664 
8665    Level: developer
8666 
8667 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8668 @*/
8669 PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8670 {
8671   PetscFunctionBegin;
8672   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8673   PetscValidType(mat,1);
8674   PetscValidPointer(nullsp,2);
8675   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8676   PetscFunctionReturn(0);
8677 }
8678 
8679 /*@
8680    MatSetTransposeNullSpace - attaches a null space to a matrix.
8681 
8682    Logically Collective on Mat
8683 
8684    Input Parameters:
8685 +  mat - the matrix
8686 -  nullsp - the null space object
8687 
8688    Level: advanced
8689 
8690    Notes:
8691       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.
8692       You must also call MatSetNullSpace()
8693 
8694       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8695    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).
8696    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
8697    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
8698    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).
8699 
8700       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8701 
8702 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8703 @*/
8704 PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8705 {
8706   PetscErrorCode ierr;
8707 
8708   PetscFunctionBegin;
8709   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8710   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8711   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8712   ierr = MatNullSpaceDestroy(&mat->transnullsp);CHKERRQ(ierr);
8713   mat->transnullsp = nullsp;
8714   PetscFunctionReturn(0);
8715 }
8716 
8717 /*@
8718    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8719         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8720 
8721    Logically Collective on Mat
8722 
8723    Input Parameters:
8724 +  mat - the matrix
8725 -  nullsp - the null space object
8726 
8727    Level: advanced
8728 
8729    Notes:
8730       Overwrites any previous near null space that may have been attached
8731 
8732       You can remove the null space by calling this routine with an nullsp of NULL
8733 
8734 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8735 @*/
8736 PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8737 {
8738   PetscErrorCode ierr;
8739 
8740   PetscFunctionBegin;
8741   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8742   PetscValidType(mat,1);
8743   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8744   MatCheckPreallocated(mat,1);
8745   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8746   ierr = MatNullSpaceDestroy(&mat->nearnullsp);CHKERRQ(ierr);
8747   mat->nearnullsp = nullsp;
8748   PetscFunctionReturn(0);
8749 }
8750 
8751 /*@
8752    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()
8753 
8754    Not Collective
8755 
8756    Input Parameter:
8757 .  mat - the matrix
8758 
8759    Output Parameter:
8760 .  nullsp - the null space object, NULL if not set
8761 
8762    Level: developer
8763 
8764 .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8765 @*/
8766 PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8767 {
8768   PetscFunctionBegin;
8769   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8770   PetscValidType(mat,1);
8771   PetscValidPointer(nullsp,2);
8772   MatCheckPreallocated(mat,1);
8773   *nullsp = mat->nearnullsp;
8774   PetscFunctionReturn(0);
8775 }
8776 
8777 /*@C
8778    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8779 
8780    Collective on Mat
8781 
8782    Input Parameters:
8783 +  mat - the matrix
8784 .  row - row/column permutation
8785 .  fill - expected fill factor >= 1.0
8786 -  level - level of fill, for ICC(k)
8787 
8788    Notes:
8789    Probably really in-place only when level of fill is zero, otherwise allocates
8790    new space to store factored matrix and deletes previous memory.
8791 
8792    Most users should employ the simplified KSP interface for linear solvers
8793    instead of working directly with matrix algebra routines such as this.
8794    See, e.g., KSPCreate().
8795 
8796    Level: developer
8797 
8798 .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8799 
8800     Developer Note: fortran interface is not autogenerated as the f90
8801     interface defintion cannot be generated correctly [due to MatFactorInfo]
8802 
8803 @*/
8804 PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8805 {
8806   PetscErrorCode ierr;
8807 
8808   PetscFunctionBegin;
8809   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8810   PetscValidType(mat,1);
8811   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
8812   PetscValidPointer(info,3);
8813   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8814   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8815   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8816   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8817   MatCheckPreallocated(mat,1);
8818   ierr = (*mat->ops->iccfactor)(mat,row,info);CHKERRQ(ierr);
8819   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8820   PetscFunctionReturn(0);
8821 }
8822 
8823 /*@
8824    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8825          ghosted ones.
8826 
8827    Not Collective
8828 
8829    Input Parameters:
8830 +  mat - the matrix
8831 -  diag = the diagonal values, including ghost ones
8832 
8833    Level: developer
8834 
8835    Notes:
8836     Works only for MPIAIJ and MPIBAIJ matrices
8837 
8838 .seealso: MatDiagonalScale()
8839 @*/
8840 PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8841 {
8842   PetscErrorCode ierr;
8843   PetscMPIInt    size;
8844 
8845   PetscFunctionBegin;
8846   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8847   PetscValidHeaderSpecific(diag,VEC_CLASSID,2);
8848   PetscValidType(mat,1);
8849 
8850   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8851   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8852   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRMPI(ierr);
8853   if (size == 1) {
8854     PetscInt n,m;
8855     ierr = VecGetSize(diag,&n);CHKERRQ(ierr);
8856     ierr = MatGetSize(mat,NULL,&m);CHKERRQ(ierr);
8857     if (m == n) {
8858       ierr = MatDiagonalScale(mat,NULL,diag);CHKERRQ(ierr);
8859     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8860   } else {
8861     ierr = PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));CHKERRQ(ierr);
8862   }
8863   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8864   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8865   PetscFunctionReturn(0);
8866 }
8867 
8868 /*@
8869    MatGetInertia - Gets the inertia from a factored matrix
8870 
8871    Collective on Mat
8872 
8873    Input Parameter:
8874 .  mat - the matrix
8875 
8876    Output Parameters:
8877 +   nneg - number of negative eigenvalues
8878 .   nzero - number of zero eigenvalues
8879 -   npos - number of positive eigenvalues
8880 
8881    Level: advanced
8882 
8883    Notes:
8884     Matrix must have been factored by MatCholeskyFactor()
8885 
8886 @*/
8887 PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8888 {
8889   PetscErrorCode ierr;
8890 
8891   PetscFunctionBegin;
8892   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8893   PetscValidType(mat,1);
8894   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8895   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8896   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8897   ierr = (*mat->ops->getinertia)(mat,nneg,nzero,npos);CHKERRQ(ierr);
8898   PetscFunctionReturn(0);
8899 }
8900 
8901 /* ----------------------------------------------------------------*/
8902 /*@C
8903    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8904 
8905    Neighbor-wise Collective on Mats
8906 
8907    Input Parameters:
8908 +  mat - the factored matrix
8909 -  b - the right-hand-side vectors
8910 
8911    Output Parameter:
8912 .  x - the result vectors
8913 
8914    Notes:
8915    The vectors b and x cannot be the same.  I.e., one cannot
8916    call MatSolves(A,x,x).
8917 
8918    Notes:
8919    Most users should employ the simplified KSP interface for linear solvers
8920    instead of working directly with matrix algebra routines such as this.
8921    See, e.g., KSPCreate().
8922 
8923    Level: developer
8924 
8925 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8926 @*/
8927 PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8928 {
8929   PetscErrorCode ierr;
8930 
8931   PetscFunctionBegin;
8932   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8933   PetscValidType(mat,1);
8934   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8935   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8936   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
8937 
8938   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8939   MatCheckPreallocated(mat,1);
8940   ierr = PetscLogEventBegin(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8941   ierr = (*mat->ops->solves)(mat,b,x);CHKERRQ(ierr);
8942   ierr = PetscLogEventEnd(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8943   PetscFunctionReturn(0);
8944 }
8945 
8946 /*@
8947    MatIsSymmetric - Test whether a matrix is symmetric
8948 
8949    Collective on Mat
8950 
8951    Input Parameter:
8952 +  A - the matrix to test
8953 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8954 
8955    Output Parameters:
8956 .  flg - the result
8957 
8958    Notes:
8959     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8960 
8961    Level: intermediate
8962 
8963 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8964 @*/
8965 PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8966 {
8967   PetscErrorCode ierr;
8968 
8969   PetscFunctionBegin;
8970   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8971   PetscValidBoolPointer(flg,3);
8972 
8973   if (!A->symmetric_set) {
8974     if (!A->ops->issymmetric) {
8975       MatType mattype;
8976       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8977       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8978     }
8979     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8980     if (!tol) {
8981       ierr = MatSetOption(A,MAT_SYMMETRIC,*flg);CHKERRQ(ierr);
8982     }
8983   } else if (A->symmetric) {
8984     *flg = PETSC_TRUE;
8985   } else if (!tol) {
8986     *flg = PETSC_FALSE;
8987   } else {
8988     if (!A->ops->issymmetric) {
8989       MatType mattype;
8990       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8991       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8992     }
8993     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8994   }
8995   PetscFunctionReturn(0);
8996 }
8997 
8998 /*@
8999    MatIsHermitian - Test whether a matrix is Hermitian
9000 
9001    Collective on Mat
9002 
9003    Input Parameter:
9004 +  A - the matrix to test
9005 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
9006 
9007    Output Parameters:
9008 .  flg - the result
9009 
9010    Level: intermediate
9011 
9012 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
9013           MatIsSymmetricKnown(), MatIsSymmetric()
9014 @*/
9015 PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
9016 {
9017   PetscErrorCode ierr;
9018 
9019   PetscFunctionBegin;
9020   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9021   PetscValidBoolPointer(flg,3);
9022 
9023   if (!A->hermitian_set) {
9024     if (!A->ops->ishermitian) {
9025       MatType mattype;
9026       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
9027       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
9028     }
9029     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
9030     if (!tol) {
9031       ierr = MatSetOption(A,MAT_HERMITIAN,*flg);CHKERRQ(ierr);
9032     }
9033   } else if (A->hermitian) {
9034     *flg = PETSC_TRUE;
9035   } else if (!tol) {
9036     *flg = PETSC_FALSE;
9037   } else {
9038     if (!A->ops->ishermitian) {
9039       MatType mattype;
9040       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
9041       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
9042     }
9043     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
9044   }
9045   PetscFunctionReturn(0);
9046 }
9047 
9048 /*@
9049    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
9050 
9051    Not Collective
9052 
9053    Input Parameter:
9054 .  A - the matrix to check
9055 
9056    Output Parameters:
9057 +  set - if the symmetric flag is set (this tells you if the next flag is valid)
9058 -  flg - the result
9059 
9060    Level: advanced
9061 
9062    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
9063          if you want it explicitly checked
9064 
9065 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
9066 @*/
9067 PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
9068 {
9069   PetscFunctionBegin;
9070   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9071   PetscValidPointer(set,2);
9072   PetscValidBoolPointer(flg,3);
9073   if (A->symmetric_set) {
9074     *set = PETSC_TRUE;
9075     *flg = A->symmetric;
9076   } else {
9077     *set = PETSC_FALSE;
9078   }
9079   PetscFunctionReturn(0);
9080 }
9081 
9082 /*@
9083    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
9084 
9085    Not Collective
9086 
9087    Input Parameter:
9088 .  A - the matrix to check
9089 
9090    Output Parameters:
9091 +  set - if the hermitian flag is set (this tells you if the next flag is valid)
9092 -  flg - the result
9093 
9094    Level: advanced
9095 
9096    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
9097          if you want it explicitly checked
9098 
9099 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
9100 @*/
9101 PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
9102 {
9103   PetscFunctionBegin;
9104   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9105   PetscValidPointer(set,2);
9106   PetscValidBoolPointer(flg,3);
9107   if (A->hermitian_set) {
9108     *set = PETSC_TRUE;
9109     *flg = A->hermitian;
9110   } else {
9111     *set = PETSC_FALSE;
9112   }
9113   PetscFunctionReturn(0);
9114 }
9115 
9116 /*@
9117    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
9118 
9119    Collective on Mat
9120 
9121    Input Parameter:
9122 .  A - the matrix to test
9123 
9124    Output Parameters:
9125 .  flg - the result
9126 
9127    Level: intermediate
9128 
9129 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
9130 @*/
9131 PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
9132 {
9133   PetscErrorCode ierr;
9134 
9135   PetscFunctionBegin;
9136   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9137   PetscValidBoolPointer(flg,2);
9138   if (!A->structurally_symmetric_set) {
9139     if (!A->ops->isstructurallysymmetric) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type %s does not support checking for structural symmetric",((PetscObject)A)->type_name);
9140     ierr = (*A->ops->isstructurallysymmetric)(A,flg);CHKERRQ(ierr);
9141     ierr = MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);CHKERRQ(ierr);
9142   } else *flg = A->structurally_symmetric;
9143   PetscFunctionReturn(0);
9144 }
9145 
9146 /*@
9147    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9148        to be communicated to other processors during the MatAssemblyBegin/End() process
9149 
9150     Not collective
9151 
9152    Input Parameter:
9153 .   vec - the vector
9154 
9155    Output Parameters:
9156 +   nstash   - the size of the stash
9157 .   reallocs - the number of additional mallocs incurred.
9158 .   bnstash   - the size of the block stash
9159 -   breallocs - the number of additional mallocs incurred.in the block stash
9160 
9161    Level: advanced
9162 
9163 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
9164 
9165 @*/
9166 PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
9167 {
9168   PetscErrorCode ierr;
9169 
9170   PetscFunctionBegin;
9171   ierr = MatStashGetInfo_Private(&mat->stash,nstash,reallocs);CHKERRQ(ierr);
9172   ierr = MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);CHKERRQ(ierr);
9173   PetscFunctionReturn(0);
9174 }
9175 
9176 /*@C
9177    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9178      parallel layout
9179 
9180    Collective on Mat
9181 
9182    Input Parameter:
9183 .  mat - the matrix
9184 
9185    Output Parameter:
9186 +   right - (optional) vector that the matrix can be multiplied against
9187 -   left - (optional) vector that the matrix vector product can be stored in
9188 
9189    Notes:
9190     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().
9191 
9192   Notes:
9193     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
9194 
9195   Level: advanced
9196 
9197 .seealso: MatCreate(), VecDestroy()
9198 @*/
9199 PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
9200 {
9201   PetscErrorCode ierr;
9202 
9203   PetscFunctionBegin;
9204   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9205   PetscValidType(mat,1);
9206   if (mat->ops->getvecs) {
9207     ierr = (*mat->ops->getvecs)(mat,right,left);CHKERRQ(ierr);
9208   } else {
9209     PetscInt rbs,cbs;
9210     ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
9211     if (right) {
9212       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
9213       ierr = VecCreate(PetscObjectComm((PetscObject)mat),right);CHKERRQ(ierr);
9214       ierr = VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
9215       ierr = VecSetBlockSize(*right,cbs);CHKERRQ(ierr);
9216       ierr = VecSetType(*right,mat->defaultvectype);CHKERRQ(ierr);
9217       ierr = PetscLayoutReference(mat->cmap,&(*right)->map);CHKERRQ(ierr);
9218     }
9219     if (left) {
9220       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
9221       ierr = VecCreate(PetscObjectComm((PetscObject)mat),left);CHKERRQ(ierr);
9222       ierr = VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
9223       ierr = VecSetBlockSize(*left,rbs);CHKERRQ(ierr);
9224       ierr = VecSetType(*left,mat->defaultvectype);CHKERRQ(ierr);
9225       ierr = PetscLayoutReference(mat->rmap,&(*left)->map);CHKERRQ(ierr);
9226     }
9227   }
9228   PetscFunctionReturn(0);
9229 }
9230 
9231 /*@C
9232    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
9233      with default values.
9234 
9235    Not Collective
9236 
9237    Input Parameters:
9238 .    info - the MatFactorInfo data structure
9239 
9240    Notes:
9241     The solvers are generally used through the KSP and PC objects, for example
9242           PCLU, PCILU, PCCHOLESKY, PCICC
9243 
9244    Level: developer
9245 
9246 .seealso: MatFactorInfo
9247 
9248     Developer Note: fortran interface is not autogenerated as the f90
9249     interface defintion cannot be generated correctly [due to MatFactorInfo]
9250 
9251 @*/
9252 
9253 PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9254 {
9255   PetscErrorCode ierr;
9256 
9257   PetscFunctionBegin;
9258   ierr = PetscMemzero(info,sizeof(MatFactorInfo));CHKERRQ(ierr);
9259   PetscFunctionReturn(0);
9260 }
9261 
9262 /*@
9263    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
9264 
9265    Collective on Mat
9266 
9267    Input Parameters:
9268 +  mat - the factored matrix
9269 -  is - the index set defining the Schur indices (0-based)
9270 
9271    Notes:
9272     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
9273 
9274    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
9275 
9276    Level: developer
9277 
9278 .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
9279           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
9280 
9281 @*/
9282 PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
9283 {
9284   PetscErrorCode ierr,(*f)(Mat,IS);
9285 
9286   PetscFunctionBegin;
9287   PetscValidType(mat,1);
9288   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9289   PetscValidType(is,2);
9290   PetscValidHeaderSpecific(is,IS_CLASSID,2);
9291   PetscCheckSameComm(mat,1,is,2);
9292   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
9293   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);CHKERRQ(ierr);
9294   if (!f) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9295   ierr = MatDestroy(&mat->schur);CHKERRQ(ierr);
9296   ierr = (*f)(mat,is);CHKERRQ(ierr);
9297   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
9298   PetscFunctionReturn(0);
9299 }
9300 
9301 /*@
9302   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
9303 
9304    Logically Collective on Mat
9305 
9306    Input Parameters:
9307 +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
9308 .  S - location where to return the Schur complement, can be NULL
9309 -  status - the status of the Schur complement matrix, can be NULL
9310 
9311    Notes:
9312    You must call MatFactorSetSchurIS() before calling this routine.
9313 
9314    The routine provides a copy of the Schur matrix stored within the solver data structures.
9315    The caller must destroy the object when it is no longer needed.
9316    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
9317 
9318    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)
9319 
9320    Developer Notes:
9321     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9322    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
9323 
9324    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
9325 
9326    Level: advanced
9327 
9328    References:
9329 
9330 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
9331 @*/
9332 PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9333 {
9334   PetscErrorCode ierr;
9335 
9336   PetscFunctionBegin;
9337   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9338   if (S) PetscValidPointer(S,2);
9339   if (status) PetscValidPointer(status,3);
9340   if (S) {
9341     PetscErrorCode (*f)(Mat,Mat*);
9342 
9343     ierr = PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);CHKERRQ(ierr);
9344     if (f) {
9345       ierr = (*f)(F,S);CHKERRQ(ierr);
9346     } else {
9347       ierr = MatDuplicate(F->schur,MAT_COPY_VALUES,S);CHKERRQ(ierr);
9348     }
9349   }
9350   if (status) *status = F->schur_status;
9351   PetscFunctionReturn(0);
9352 }
9353 
9354 /*@
9355   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
9356 
9357    Logically Collective on Mat
9358 
9359    Input Parameters:
9360 +  F - the factored matrix obtained by calling MatGetFactor()
9361 .  *S - location where to return the Schur complement, can be NULL
9362 -  status - the status of the Schur complement matrix, can be NULL
9363 
9364    Notes:
9365    You must call MatFactorSetSchurIS() before calling this routine.
9366 
9367    Schur complement mode is currently implemented for sequential matrices.
9368    The routine returns a the Schur Complement stored within the data strutures of the solver.
9369    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
9370    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
9371 
9372    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
9373 
9374    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
9375 
9376    Level: advanced
9377 
9378    References:
9379 
9380 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9381 @*/
9382 PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9383 {
9384   PetscFunctionBegin;
9385   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9386   if (S) PetscValidPointer(S,2);
9387   if (status) PetscValidPointer(status,3);
9388   if (S) *S = F->schur;
9389   if (status) *status = F->schur_status;
9390   PetscFunctionReturn(0);
9391 }
9392 
9393 /*@
9394   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
9395 
9396    Logically Collective on Mat
9397 
9398    Input Parameters:
9399 +  F - the factored matrix obtained by calling MatGetFactor()
9400 .  *S - location where the Schur complement is stored
9401 -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)
9402 
9403    Notes:
9404 
9405    Level: advanced
9406 
9407    References:
9408 
9409 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9410 @*/
9411 PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9412 {
9413   PetscErrorCode ierr;
9414 
9415   PetscFunctionBegin;
9416   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9417   if (S) {
9418     PetscValidHeaderSpecific(*S,MAT_CLASSID,2);
9419     *S = NULL;
9420   }
9421   F->schur_status = status;
9422   ierr = MatFactorUpdateSchurStatus_Private(F);CHKERRQ(ierr);
9423   PetscFunctionReturn(0);
9424 }
9425 
9426 /*@
9427   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
9428 
9429    Logically Collective on Mat
9430 
9431    Input Parameters:
9432 +  F - the factored matrix obtained by calling MatGetFactor()
9433 .  rhs - location where the right hand side of the Schur complement system is stored
9434 -  sol - location where the solution of the Schur complement system has to be returned
9435 
9436    Notes:
9437    The sizes of the vectors should match the size of the Schur complement
9438 
9439    Must be called after MatFactorSetSchurIS()
9440 
9441    Level: advanced
9442 
9443    References:
9444 
9445 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9446 @*/
9447 PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9448 {
9449   PetscErrorCode ierr;
9450 
9451   PetscFunctionBegin;
9452   PetscValidType(F,1);
9453   PetscValidType(rhs,2);
9454   PetscValidType(sol,3);
9455   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9456   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
9457   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
9458   PetscCheckSameComm(F,1,rhs,2);
9459   PetscCheckSameComm(F,1,sol,3);
9460   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9461   switch (F->schur_status) {
9462   case MAT_FACTOR_SCHUR_FACTORED:
9463     ierr = MatSolveTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
9464     break;
9465   case MAT_FACTOR_SCHUR_INVERTED:
9466     ierr = MatMultTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
9467     break;
9468   default:
9469     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9470   }
9471   PetscFunctionReturn(0);
9472 }
9473 
9474 /*@
9475   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
9476 
9477    Logically Collective on Mat
9478 
9479    Input Parameters:
9480 +  F - the factored matrix obtained by calling MatGetFactor()
9481 .  rhs - location where the right hand side of the Schur complement system is stored
9482 -  sol - location where the solution of the Schur complement system has to be returned
9483 
9484    Notes:
9485    The sizes of the vectors should match the size of the Schur complement
9486 
9487    Must be called after MatFactorSetSchurIS()
9488 
9489    Level: advanced
9490 
9491    References:
9492 
9493 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9494 @*/
9495 PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9496 {
9497   PetscErrorCode ierr;
9498 
9499   PetscFunctionBegin;
9500   PetscValidType(F,1);
9501   PetscValidType(rhs,2);
9502   PetscValidType(sol,3);
9503   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9504   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
9505   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
9506   PetscCheckSameComm(F,1,rhs,2);
9507   PetscCheckSameComm(F,1,sol,3);
9508   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9509   switch (F->schur_status) {
9510   case MAT_FACTOR_SCHUR_FACTORED:
9511     ierr = MatSolve(F->schur,rhs,sol);CHKERRQ(ierr);
9512     break;
9513   case MAT_FACTOR_SCHUR_INVERTED:
9514     ierr = MatMult(F->schur,rhs,sol);CHKERRQ(ierr);
9515     break;
9516   default:
9517     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9518   }
9519   PetscFunctionReturn(0);
9520 }
9521 
9522 /*@
9523   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9524 
9525    Logically Collective on Mat
9526 
9527    Input Parameters:
9528 .  F - the factored matrix obtained by calling MatGetFactor()
9529 
9530    Notes:
9531     Must be called after MatFactorSetSchurIS().
9532 
9533    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9534 
9535    Level: advanced
9536 
9537    References:
9538 
9539 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9540 @*/
9541 PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9542 {
9543   PetscErrorCode ierr;
9544 
9545   PetscFunctionBegin;
9546   PetscValidType(F,1);
9547   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9548   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(0);
9549   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9550   ierr = MatFactorInvertSchurComplement_Private(F);CHKERRQ(ierr);
9551   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9552   PetscFunctionReturn(0);
9553 }
9554 
9555 /*@
9556   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9557 
9558    Logically Collective on Mat
9559 
9560    Input Parameters:
9561 .  F - the factored matrix obtained by calling MatGetFactor()
9562 
9563    Notes:
9564     Must be called after MatFactorSetSchurIS().
9565 
9566    Level: advanced
9567 
9568    References:
9569 
9570 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9571 @*/
9572 PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9573 {
9574   PetscErrorCode ierr;
9575 
9576   PetscFunctionBegin;
9577   PetscValidType(F,1);
9578   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9579   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(0);
9580   ierr = MatFactorFactorizeSchurComplement_Private(F);CHKERRQ(ierr);
9581   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9582   PetscFunctionReturn(0);
9583 }
9584 
9585 /*@
9586    MatPtAP - Creates the matrix product C = P^T * A * P
9587 
9588    Neighbor-wise Collective on Mat
9589 
9590    Input Parameters:
9591 +  A - the matrix
9592 .  P - the projection matrix
9593 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9594 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9595           if the result is a dense matrix this is irrelevent
9596 
9597    Output Parameters:
9598 .  C - the product matrix
9599 
9600    Notes:
9601    C will be created and must be destroyed by the user with MatDestroy().
9602 
9603    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().
9604 
9605    Level: intermediate
9606 
9607 .seealso: MatMatMult(), MatRARt()
9608 @*/
9609 PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9610 {
9611   PetscErrorCode ierr;
9612 
9613   PetscFunctionBegin;
9614   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9615   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9616 
9617   if (scall == MAT_INITIAL_MATRIX) {
9618     ierr = MatProductCreate(A,P,NULL,C);CHKERRQ(ierr);
9619     ierr = MatProductSetType(*C,MATPRODUCT_PtAP);CHKERRQ(ierr);
9620     ierr = MatProductSetAlgorithm(*C,"default");CHKERRQ(ierr);
9621     ierr = MatProductSetFill(*C,fill);CHKERRQ(ierr);
9622 
9623     (*C)->product->api_user = PETSC_TRUE;
9624     ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9625     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and P %s",MatProductTypes[MATPRODUCT_PtAP],((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9626     ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9627   } else { /* scall == MAT_REUSE_MATRIX */
9628     ierr = MatProductReplaceMats(A,P,NULL,*C);CHKERRQ(ierr);
9629   }
9630 
9631   ierr = MatProductNumeric(*C);CHKERRQ(ierr);
9632   if (A->symmetric_set && A->symmetric) {
9633     ierr = MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
9634   }
9635   PetscFunctionReturn(0);
9636 }
9637 
9638 /*@
9639    MatRARt - Creates the matrix product C = R * A * R^T
9640 
9641    Neighbor-wise Collective on Mat
9642 
9643    Input Parameters:
9644 +  A - the matrix
9645 .  R - the projection matrix
9646 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9647 -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9648           if the result is a dense matrix this is irrelevent
9649 
9650    Output Parameters:
9651 .  C - the product matrix
9652 
9653    Notes:
9654    C will be created and must be destroyed by the user with MatDestroy().
9655 
9656    This routine is currently only implemented for pairs of AIJ matrices and classes
9657    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9658    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9659    We recommend using MatPtAP().
9660 
9661    Level: intermediate
9662 
9663 .seealso: MatMatMult(), MatPtAP()
9664 @*/
9665 PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9666 {
9667   PetscErrorCode ierr;
9668 
9669   PetscFunctionBegin;
9670   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9671   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9672 
9673   if (scall == MAT_INITIAL_MATRIX) {
9674     ierr = MatProductCreate(A,R,NULL,C);CHKERRQ(ierr);
9675     ierr = MatProductSetType(*C,MATPRODUCT_RARt);CHKERRQ(ierr);
9676     ierr = MatProductSetAlgorithm(*C,"default");CHKERRQ(ierr);
9677     ierr = MatProductSetFill(*C,fill);CHKERRQ(ierr);
9678 
9679     (*C)->product->api_user = PETSC_TRUE;
9680     ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9681     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and R %s",MatProductTypes[MATPRODUCT_RARt],((PetscObject)A)->type_name,((PetscObject)R)->type_name);
9682     ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9683   } else { /* scall == MAT_REUSE_MATRIX */
9684     ierr = MatProductReplaceMats(A,R,NULL,*C);CHKERRQ(ierr);
9685   }
9686 
9687   ierr = MatProductNumeric(*C);CHKERRQ(ierr);
9688   if (A->symmetric_set && A->symmetric) {
9689     ierr = MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
9690   }
9691   PetscFunctionReturn(0);
9692 }
9693 
9694 static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
9695 {
9696   PetscErrorCode ierr;
9697 
9698   PetscFunctionBegin;
9699   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9700 
9701   if (scall == MAT_INITIAL_MATRIX) {
9702     ierr = PetscInfo1(A,"Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n",MatProductTypes[ptype]);CHKERRQ(ierr);
9703     ierr = MatProductCreate(A,B,NULL,C);CHKERRQ(ierr);
9704     ierr = MatProductSetType(*C,ptype);CHKERRQ(ierr);
9705     ierr = MatProductSetAlgorithm(*C,MATPRODUCTALGORITHM_DEFAULT);CHKERRQ(ierr);
9706     ierr = MatProductSetFill(*C,fill);CHKERRQ(ierr);
9707 
9708     (*C)->product->api_user = PETSC_TRUE;
9709     ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9710     ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9711   } else { /* scall == MAT_REUSE_MATRIX */
9712     Mat_Product *product = (*C)->product;
9713 
9714     ierr = PetscInfo2(A,"Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n",product ? "with" : "without",MatProductTypes[ptype]);CHKERRQ(ierr);
9715     if (!product) {
9716       /* user provide the dense matrix *C without calling MatProductCreate() */
9717       PetscBool isdense;
9718 
9719       ierr = PetscObjectBaseTypeCompareAny((PetscObject)(*C),&isdense,MATSEQDENSE,MATMPIDENSE,"");CHKERRQ(ierr);
9720       if (isdense) {
9721         /* user wants to reuse an assembled dense matrix */
9722         /* Create product -- see MatCreateProduct() */
9723         ierr = MatProductCreate_Private(A,B,NULL,*C);CHKERRQ(ierr);
9724         product = (*C)->product;
9725         product->fill     = fill;
9726         product->api_user = PETSC_TRUE;
9727         product->clear    = PETSC_TRUE;
9728 
9729         ierr = MatProductSetType(*C,ptype);CHKERRQ(ierr);
9730         ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9731         if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for %s and %s",MatProductTypes[ptype],((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9732         ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9733       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
9734     } else { /* user may change input matrices A or B when REUSE */
9735       ierr = MatProductReplaceMats(A,B,NULL,*C);CHKERRQ(ierr);
9736     }
9737   }
9738   ierr = MatProductNumeric(*C);CHKERRQ(ierr);
9739   PetscFunctionReturn(0);
9740 }
9741 
9742 /*@
9743    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
9744 
9745    Neighbor-wise Collective on Mat
9746 
9747    Input Parameters:
9748 +  A - the left matrix
9749 .  B - the right matrix
9750 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9751 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9752           if the result is a dense matrix this is irrelevent
9753 
9754    Output Parameters:
9755 .  C - the product matrix
9756 
9757    Notes:
9758    Unless scall is MAT_REUSE_MATRIX C will be created.
9759 
9760    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
9761    call to this function with MAT_INITIAL_MATRIX.
9762 
9763    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.
9764 
9765    If you have many matrices with the same non-zero structure to multiply, you should use MatProductCreate()/MatProductSymbolic(C)/ReplaceMats(), and call MatProductNumeric() repeatedly.
9766 
9767    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.
9768 
9769    Level: intermediate
9770 
9771 .seealso: MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
9772 @*/
9773 PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9774 {
9775   PetscErrorCode ierr;
9776 
9777   PetscFunctionBegin;
9778   ierr = MatProduct_Private(A,B,scall,fill,MATPRODUCT_AB,C);CHKERRQ(ierr);
9779   PetscFunctionReturn(0);
9780 }
9781 
9782 /*@
9783    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9784 
9785    Neighbor-wise Collective on Mat
9786 
9787    Input Parameters:
9788 +  A - the left matrix
9789 .  B - the right matrix
9790 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9791 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9792 
9793    Output Parameters:
9794 .  C - the product matrix
9795 
9796    Notes:
9797    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9798 
9799    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9800 
9801   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9802    actually needed.
9803 
9804    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9805    and for pairs of MPIDense matrices.
9806 
9807    Options Database Keys:
9808 .  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9809                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9810                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.
9811 
9812    Level: intermediate
9813 
9814 .seealso: MatMatMult(), MatTransposeMatMult() MatPtAP()
9815 @*/
9816 PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9817 {
9818   PetscErrorCode ierr;
9819 
9820   PetscFunctionBegin;
9821   ierr = MatProduct_Private(A,B,scall,fill,MATPRODUCT_ABt,C);CHKERRQ(ierr);
9822   PetscFunctionReturn(0);
9823 }
9824 
9825 /*@
9826    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
9827 
9828    Neighbor-wise Collective on Mat
9829 
9830    Input Parameters:
9831 +  A - the left matrix
9832 .  B - the right matrix
9833 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9834 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9835 
9836    Output Parameters:
9837 .  C - the product matrix
9838 
9839    Notes:
9840    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9841 
9842    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call.
9843 
9844   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9845    actually needed.
9846 
9847    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9848    which inherit from SeqAIJ.  C will be of same type as the input matrices.
9849 
9850    Level: intermediate
9851 
9852 .seealso: MatMatMult(), MatMatTransposeMult(), MatPtAP()
9853 @*/
9854 PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9855 {
9856   PetscErrorCode ierr;
9857 
9858   PetscFunctionBegin;
9859   ierr = MatProduct_Private(A,B,scall,fill,MATPRODUCT_AtB,C);CHKERRQ(ierr);
9860   PetscFunctionReturn(0);
9861 }
9862 
9863 /*@
9864    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
9865 
9866    Neighbor-wise Collective on Mat
9867 
9868    Input Parameters:
9869 +  A - the left matrix
9870 .  B - the middle matrix
9871 .  C - the right matrix
9872 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9873 -  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
9874           if the result is a dense matrix this is irrelevent
9875 
9876    Output Parameters:
9877 .  D - the product matrix
9878 
9879    Notes:
9880    Unless scall is MAT_REUSE_MATRIX D will be created.
9881 
9882    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
9883 
9884    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9885    actually needed.
9886 
9887    If you have many matrices with the same non-zero structure to multiply, you
9888    should use MAT_REUSE_MATRIX in all calls but the first or
9889 
9890    Level: intermediate
9891 
9892 .seealso: MatMatMult, MatPtAP()
9893 @*/
9894 PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9895 {
9896   PetscErrorCode ierr;
9897 
9898   PetscFunctionBegin;
9899   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D,6);
9900   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9901 
9902   if (scall == MAT_INITIAL_MATRIX) {
9903     ierr = MatProductCreate(A,B,C,D);CHKERRQ(ierr);
9904     ierr = MatProductSetType(*D,MATPRODUCT_ABC);CHKERRQ(ierr);
9905     ierr = MatProductSetAlgorithm(*D,"default");CHKERRQ(ierr);
9906     ierr = MatProductSetFill(*D,fill);CHKERRQ(ierr);
9907 
9908     (*D)->product->api_user = PETSC_TRUE;
9909     ierr = MatProductSetFromOptions(*D);CHKERRQ(ierr);
9910     if (!(*D)->ops->productsymbolic) SETERRQ4(PetscObjectComm((PetscObject)(*D)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s, B %s and C %s",MatProductTypes[MATPRODUCT_ABC],((PetscObject)A)->type_name,((PetscObject)B)->type_name,((PetscObject)C)->type_name);
9911     ierr = MatProductSymbolic(*D);CHKERRQ(ierr);
9912   } else { /* user may change input matrices when REUSE */
9913     ierr = MatProductReplaceMats(A,B,C,*D);CHKERRQ(ierr);
9914   }
9915   ierr = MatProductNumeric(*D);CHKERRQ(ierr);
9916   PetscFunctionReturn(0);
9917 }
9918 
9919 /*@
9920    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
9921 
9922    Collective on Mat
9923 
9924    Input Parameters:
9925 +  mat - the matrix
9926 .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9927 .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9928 -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9929 
9930    Output Parameter:
9931 .  matredundant - redundant matrix
9932 
9933    Notes:
9934    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9935    original matrix has not changed from that last call to MatCreateRedundantMatrix().
9936 
9937    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9938    calling it.
9939 
9940    Level: advanced
9941 
9942 .seealso: MatDestroy()
9943 @*/
9944 PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9945 {
9946   PetscErrorCode ierr;
9947   MPI_Comm       comm;
9948   PetscMPIInt    size;
9949   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9950   Mat_Redundant  *redund=NULL;
9951   PetscSubcomm   psubcomm=NULL;
9952   MPI_Comm       subcomm_in=subcomm;
9953   Mat            *matseq;
9954   IS             isrow,iscol;
9955   PetscBool      newsubcomm=PETSC_FALSE;
9956 
9957   PetscFunctionBegin;
9958   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9959   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9960     PetscValidPointer(*matredundant,5);
9961     PetscValidHeaderSpecific(*matredundant,MAT_CLASSID,5);
9962   }
9963 
9964   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRMPI(ierr);
9965   if (size == 1 || nsubcomm == 1) {
9966     if (reuse == MAT_INITIAL_MATRIX) {
9967       ierr = MatDuplicate(mat,MAT_COPY_VALUES,matredundant);CHKERRQ(ierr);
9968     } else {
9969       if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9970       ierr = MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
9971     }
9972     PetscFunctionReturn(0);
9973   }
9974 
9975   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9976   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9977   MatCheckPreallocated(mat,1);
9978 
9979   ierr = PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
9980   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9981     /* create psubcomm, then get subcomm */
9982     ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
9983     ierr = MPI_Comm_size(comm,&size);CHKERRMPI(ierr);
9984     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
9985 
9986     ierr = PetscSubcommCreate(comm,&psubcomm);CHKERRQ(ierr);
9987     ierr = PetscSubcommSetNumber(psubcomm,nsubcomm);CHKERRQ(ierr);
9988     ierr = PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);CHKERRQ(ierr);
9989     ierr = PetscSubcommSetFromOptions(psubcomm);CHKERRQ(ierr);
9990     ierr = PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);CHKERRQ(ierr);
9991     newsubcomm = PETSC_TRUE;
9992     ierr = PetscSubcommDestroy(&psubcomm);CHKERRQ(ierr);
9993   }
9994 
9995   /* get isrow, iscol and a local sequential matrix matseq[0] */
9996   if (reuse == MAT_INITIAL_MATRIX) {
9997     mloc_sub = PETSC_DECIDE;
9998     nloc_sub = PETSC_DECIDE;
9999     if (bs < 1) {
10000       ierr = PetscSplitOwnership(subcomm,&mloc_sub,&M);CHKERRQ(ierr);
10001       ierr = PetscSplitOwnership(subcomm,&nloc_sub,&N);CHKERRQ(ierr);
10002     } else {
10003       ierr = PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);CHKERRQ(ierr);
10004       ierr = PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);CHKERRQ(ierr);
10005     }
10006     ierr = MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);CHKERRMPI(ierr);
10007     rstart = rend - mloc_sub;
10008     ierr = ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);CHKERRQ(ierr);
10009     ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);CHKERRQ(ierr);
10010   } else { /* reuse == MAT_REUSE_MATRIX */
10011     if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
10012     /* retrieve subcomm */
10013     ierr = PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);CHKERRQ(ierr);
10014     redund = (*matredundant)->redundant;
10015     isrow  = redund->isrow;
10016     iscol  = redund->iscol;
10017     matseq = redund->matseq;
10018   }
10019   ierr = MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);CHKERRQ(ierr);
10020 
10021   /* get matredundant over subcomm */
10022   if (reuse == MAT_INITIAL_MATRIX) {
10023     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);CHKERRQ(ierr);
10024 
10025     /* create a supporting struct and attach it to C for reuse */
10026     ierr = PetscNewLog(*matredundant,&redund);CHKERRQ(ierr);
10027     (*matredundant)->redundant = redund;
10028     redund->isrow              = isrow;
10029     redund->iscol              = iscol;
10030     redund->matseq             = matseq;
10031     if (newsubcomm) {
10032       redund->subcomm          = subcomm;
10033     } else {
10034       redund->subcomm          = MPI_COMM_NULL;
10035     }
10036   } else {
10037     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);CHKERRQ(ierr);
10038   }
10039   ierr = PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
10040   PetscFunctionReturn(0);
10041 }
10042 
10043 /*@C
10044    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
10045    a given 'mat' object. Each submatrix can span multiple procs.
10046 
10047    Collective on Mat
10048 
10049    Input Parameters:
10050 +  mat - the matrix
10051 .  subcomm - the subcommunicator obtained by com_split(comm)
10052 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10053 
10054    Output Parameter:
10055 .  subMat - 'parallel submatrices each spans a given subcomm
10056 
10057   Notes:
10058   The submatrix partition across processors is dictated by 'subComm' a
10059   communicator obtained by com_split(comm). The comm_split
10060   is not restriced to be grouped with consecutive original ranks.
10061 
10062   Due the comm_split() usage, the parallel layout of the submatrices
10063   map directly to the layout of the original matrix [wrt the local
10064   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10065   into the 'DiagonalMat' of the subMat, hence it is used directly from
10066   the subMat. However the offDiagMat looses some columns - and this is
10067   reconstructed with MatSetValues()
10068 
10069   Level: advanced
10070 
10071 .seealso: MatCreateSubMatrices()
10072 @*/
10073 PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
10074 {
10075   PetscErrorCode ierr;
10076   PetscMPIInt    commsize,subCommSize;
10077 
10078   PetscFunctionBegin;
10079   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);CHKERRMPI(ierr);
10080   ierr = MPI_Comm_size(subComm,&subCommSize);CHKERRMPI(ierr);
10081   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
10082 
10083   if (scall == MAT_REUSE_MATRIX && *subMat == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
10084   ierr = PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
10085   ierr = (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);CHKERRQ(ierr);
10086   ierr = PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
10087   PetscFunctionReturn(0);
10088 }
10089 
10090 /*@
10091    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10092 
10093    Not Collective
10094 
10095    Input Arguments:
10096 +  mat - matrix to extract local submatrix from
10097 .  isrow - local row indices for submatrix
10098 -  iscol - local column indices for submatrix
10099 
10100    Output Arguments:
10101 .  submat - the submatrix
10102 
10103    Level: intermediate
10104 
10105    Notes:
10106    The submat should be returned with MatRestoreLocalSubMatrix().
10107 
10108    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
10109    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
10110 
10111    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
10112    MatSetValuesBlockedLocal() will also be implemented.
10113 
10114    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
10115    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.
10116 
10117 .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
10118 @*/
10119 PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10120 {
10121   PetscErrorCode ierr;
10122 
10123   PetscFunctionBegin;
10124   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10125   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
10126   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
10127   PetscCheckSameComm(isrow,2,iscol,3);
10128   PetscValidPointer(submat,4);
10129   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");
10130 
10131   if (mat->ops->getlocalsubmatrix) {
10132     ierr = (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
10133   } else {
10134     ierr = MatCreateLocalRef(mat,isrow,iscol,submat);CHKERRQ(ierr);
10135   }
10136   PetscFunctionReturn(0);
10137 }
10138 
10139 /*@
10140    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
10141 
10142    Not Collective
10143 
10144    Input Arguments:
10145    mat - matrix to extract local submatrix from
10146    isrow - local row indices for submatrix
10147    iscol - local column indices for submatrix
10148    submat - the submatrix
10149 
10150    Level: intermediate
10151 
10152 .seealso: MatGetLocalSubMatrix()
10153 @*/
10154 PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10155 {
10156   PetscErrorCode ierr;
10157 
10158   PetscFunctionBegin;
10159   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10160   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
10161   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
10162   PetscCheckSameComm(isrow,2,iscol,3);
10163   PetscValidPointer(submat,4);
10164   if (*submat) {
10165     PetscValidHeaderSpecific(*submat,MAT_CLASSID,4);
10166   }
10167 
10168   if (mat->ops->restorelocalsubmatrix) {
10169     ierr = (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
10170   } else {
10171     ierr = MatDestroy(submat);CHKERRQ(ierr);
10172   }
10173   *submat = NULL;
10174   PetscFunctionReturn(0);
10175 }
10176 
10177 /* --------------------------------------------------------*/
10178 /*@
10179    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
10180 
10181    Collective on Mat
10182 
10183    Input Parameter:
10184 .  mat - the matrix
10185 
10186    Output Parameter:
10187 .  is - if any rows have zero diagonals this contains the list of them
10188 
10189    Level: developer
10190 
10191 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10192 @*/
10193 PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
10194 {
10195   PetscErrorCode ierr;
10196 
10197   PetscFunctionBegin;
10198   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10199   PetscValidType(mat,1);
10200   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10201   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10202 
10203   if (!mat->ops->findzerodiagonals) {
10204     Vec                diag;
10205     const PetscScalar *a;
10206     PetscInt          *rows;
10207     PetscInt           rStart, rEnd, r, nrow = 0;
10208 
10209     ierr = MatCreateVecs(mat, &diag, NULL);CHKERRQ(ierr);
10210     ierr = MatGetDiagonal(mat, diag);CHKERRQ(ierr);
10211     ierr = MatGetOwnershipRange(mat, &rStart, &rEnd);CHKERRQ(ierr);
10212     ierr = VecGetArrayRead(diag, &a);CHKERRQ(ierr);
10213     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
10214     ierr = PetscMalloc1(nrow, &rows);CHKERRQ(ierr);
10215     nrow = 0;
10216     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
10217     ierr = VecRestoreArrayRead(diag, &a);CHKERRQ(ierr);
10218     ierr = VecDestroy(&diag);CHKERRQ(ierr);
10219     ierr = ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);CHKERRQ(ierr);
10220   } else {
10221     ierr = (*mat->ops->findzerodiagonals)(mat, is);CHKERRQ(ierr);
10222   }
10223   PetscFunctionReturn(0);
10224 }
10225 
10226 /*@
10227    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
10228 
10229    Collective on Mat
10230 
10231    Input Parameter:
10232 .  mat - the matrix
10233 
10234    Output Parameter:
10235 .  is - contains the list of rows with off block diagonal entries
10236 
10237    Level: developer
10238 
10239 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10240 @*/
10241 PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
10242 {
10243   PetscErrorCode ierr;
10244 
10245   PetscFunctionBegin;
10246   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10247   PetscValidType(mat,1);
10248   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10249   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10250 
10251   if (!mat->ops->findoffblockdiagonalentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a find off block diagonal entries defined",((PetscObject)mat)->type_name);
10252   ierr = (*mat->ops->findoffblockdiagonalentries)(mat,is);CHKERRQ(ierr);
10253   PetscFunctionReturn(0);
10254 }
10255 
10256 /*@C
10257   MatInvertBlockDiagonal - Inverts the block diagonal entries.
10258 
10259   Collective on Mat
10260 
10261   Input Parameters:
10262 . mat - the matrix
10263 
10264   Output Parameters:
10265 . values - the block inverses in column major order (FORTRAN-like)
10266 
10267    Note:
10268    This routine is not available from Fortran.
10269 
10270   Level: advanced
10271 
10272 .seealso: MatInvertBockDiagonalMat
10273 @*/
10274 PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
10275 {
10276   PetscErrorCode ierr;
10277 
10278   PetscFunctionBegin;
10279   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10280   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10281   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10282   if (!mat->ops->invertblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type %s",((PetscObject)mat)->type_name);
10283   ierr = (*mat->ops->invertblockdiagonal)(mat,values);CHKERRQ(ierr);
10284   PetscFunctionReturn(0);
10285 }
10286 
10287 /*@C
10288   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.
10289 
10290   Collective on Mat
10291 
10292   Input Parameters:
10293 + mat - the matrix
10294 . nblocks - the number of blocks
10295 - bsizes - the size of each block
10296 
10297   Output Parameters:
10298 . values - the block inverses in column major order (FORTRAN-like)
10299 
10300    Note:
10301    This routine is not available from Fortran.
10302 
10303   Level: advanced
10304 
10305 .seealso: MatInvertBockDiagonal()
10306 @*/
10307 PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
10308 {
10309   PetscErrorCode ierr;
10310 
10311   PetscFunctionBegin;
10312   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10313   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10314   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10315   if (!mat->ops->invertvariableblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type",((PetscObject)mat)->type_name);
10316   ierr = (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);CHKERRQ(ierr);
10317   PetscFunctionReturn(0);
10318 }
10319 
10320 /*@
10321   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A
10322 
10323   Collective on Mat
10324 
10325   Input Parameters:
10326 . A - the matrix
10327 
10328   Output Parameters:
10329 . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.
10330 
10331   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C
10332 
10333   Level: advanced
10334 
10335 .seealso: MatInvertBockDiagonal()
10336 @*/
10337 PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
10338 {
10339   PetscErrorCode     ierr;
10340   const PetscScalar *vals;
10341   PetscInt          *dnnz;
10342   PetscInt           M,N,m,n,rstart,rend,bs,i,j;
10343 
10344   PetscFunctionBegin;
10345   ierr = MatInvertBlockDiagonal(A,&vals);CHKERRQ(ierr);
10346   ierr = MatGetBlockSize(A,&bs);CHKERRQ(ierr);
10347   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
10348   ierr = MatGetLocalSize(A,&m,&n);CHKERRQ(ierr);
10349   ierr = MatSetSizes(C,m,n,M,N);CHKERRQ(ierr);
10350   ierr = MatSetBlockSize(C,bs);CHKERRQ(ierr);
10351   ierr = PetscMalloc1(m/bs,&dnnz);CHKERRQ(ierr);
10352   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
10353   ierr = MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);CHKERRQ(ierr);
10354   ierr = PetscFree(dnnz);CHKERRQ(ierr);
10355   ierr = MatGetOwnershipRange(C,&rstart,&rend);CHKERRQ(ierr);
10356   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);CHKERRQ(ierr);
10357   for (i = rstart/bs; i < rend/bs; i++) {
10358     ierr = MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);CHKERRQ(ierr);
10359   }
10360   ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10361   ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10362   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);CHKERRQ(ierr);
10363   PetscFunctionReturn(0);
10364 }
10365 
10366 /*@C
10367     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
10368     via MatTransposeColoringCreate().
10369 
10370     Collective on MatTransposeColoring
10371 
10372     Input Parameter:
10373 .   c - coloring context
10374 
10375     Level: intermediate
10376 
10377 .seealso: MatTransposeColoringCreate()
10378 @*/
10379 PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10380 {
10381   PetscErrorCode       ierr;
10382   MatTransposeColoring matcolor=*c;
10383 
10384   PetscFunctionBegin;
10385   if (!matcolor) PetscFunctionReturn(0);
10386   if (--((PetscObject)matcolor)->refct > 0) {matcolor = NULL; PetscFunctionReturn(0);}
10387 
10388   ierr = PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);CHKERRQ(ierr);
10389   ierr = PetscFree(matcolor->rows);CHKERRQ(ierr);
10390   ierr = PetscFree(matcolor->den2sp);CHKERRQ(ierr);
10391   ierr = PetscFree(matcolor->colorforcol);CHKERRQ(ierr);
10392   ierr = PetscFree(matcolor->columns);CHKERRQ(ierr);
10393   if (matcolor->brows>0) {
10394     ierr = PetscFree(matcolor->lstart);CHKERRQ(ierr);
10395   }
10396   ierr = PetscHeaderDestroy(c);CHKERRQ(ierr);
10397   PetscFunctionReturn(0);
10398 }
10399 
10400 /*@C
10401     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10402     a MatTransposeColoring context has been created, computes a dense B^T by Apply
10403     MatTransposeColoring to sparse B.
10404 
10405     Collective on MatTransposeColoring
10406 
10407     Input Parameters:
10408 +   B - sparse matrix B
10409 .   Btdense - symbolic dense matrix B^T
10410 -   coloring - coloring context created with MatTransposeColoringCreate()
10411 
10412     Output Parameter:
10413 .   Btdense - dense matrix B^T
10414 
10415     Level: advanced
10416 
10417      Notes:
10418     These are used internally for some implementations of MatRARt()
10419 
10420 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()
10421 
10422 @*/
10423 PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10424 {
10425   PetscErrorCode ierr;
10426 
10427   PetscFunctionBegin;
10428   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
10429   PetscValidHeaderSpecific(Btdense,MAT_CLASSID,3);
10430   PetscValidHeaderSpecific(coloring,MAT_TRANSPOSECOLORING_CLASSID,1);
10431 
10432   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10433   ierr = (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);CHKERRQ(ierr);
10434   PetscFunctionReturn(0);
10435 }
10436 
10437 /*@C
10438     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10439     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10440     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10441     Csp from Cden.
10442 
10443     Collective on MatTransposeColoring
10444 
10445     Input Parameters:
10446 +   coloring - coloring context created with MatTransposeColoringCreate()
10447 -   Cden - matrix product of a sparse matrix and a dense matrix Btdense
10448 
10449     Output Parameter:
10450 .   Csp - sparse matrix
10451 
10452     Level: advanced
10453 
10454      Notes:
10455     These are used internally for some implementations of MatRARt()
10456 
10457 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
10458 
10459 @*/
10460 PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10461 {
10462   PetscErrorCode ierr;
10463 
10464   PetscFunctionBegin;
10465   PetscValidHeaderSpecific(matcoloring,MAT_TRANSPOSECOLORING_CLASSID,1);
10466   PetscValidHeaderSpecific(Cden,MAT_CLASSID,2);
10467   PetscValidHeaderSpecific(Csp,MAT_CLASSID,3);
10468 
10469   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10470   ierr = (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);CHKERRQ(ierr);
10471   ierr = MatAssemblyBegin(Csp,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10472   ierr = MatAssemblyEnd(Csp,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10473   PetscFunctionReturn(0);
10474 }
10475 
10476 /*@C
10477    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
10478 
10479    Collective on Mat
10480 
10481    Input Parameters:
10482 +  mat - the matrix product C
10483 -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
10484 
10485     Output Parameter:
10486 .   color - the new coloring context
10487 
10488     Level: intermediate
10489 
10490 .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
10491            MatTransColoringApplyDenToSp()
10492 @*/
10493 PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10494 {
10495   MatTransposeColoring c;
10496   MPI_Comm             comm;
10497   PetscErrorCode       ierr;
10498 
10499   PetscFunctionBegin;
10500   ierr = PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10501   ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
10502   ierr = PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);CHKERRQ(ierr);
10503 
10504   c->ctype = iscoloring->ctype;
10505   if (mat->ops->transposecoloringcreate) {
10506     ierr = (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);CHKERRQ(ierr);
10507   } else SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for matrix type %s",((PetscObject)mat)->type_name);
10508 
10509   *color = c;
10510   ierr   = PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10511   PetscFunctionReturn(0);
10512 }
10513 
10514 /*@
10515       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10516         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10517         same, otherwise it will be larger
10518 
10519      Not Collective
10520 
10521   Input Parameter:
10522 .    A  - the matrix
10523 
10524   Output Parameter:
10525 .    state - the current state
10526 
10527   Notes:
10528     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10529          different matrices
10530 
10531   Level: intermediate
10532 
10533 @*/
10534 PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10535 {
10536   PetscFunctionBegin;
10537   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10538   *state = mat->nonzerostate;
10539   PetscFunctionReturn(0);
10540 }
10541 
10542 /*@
10543       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10544                  matrices from each processor
10545 
10546     Collective
10547 
10548    Input Parameters:
10549 +    comm - the communicators the parallel matrix will live on
10550 .    seqmat - the input sequential matrices
10551 .    n - number of local columns (or PETSC_DECIDE)
10552 -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10553 
10554    Output Parameter:
10555 .    mpimat - the parallel matrix generated
10556 
10557     Level: advanced
10558 
10559    Notes:
10560     The number of columns of the matrix in EACH processor MUST be the same.
10561 
10562 @*/
10563 PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10564 {
10565   PetscErrorCode ierr;
10566 
10567   PetscFunctionBegin;
10568   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10569   if (reuse == MAT_REUSE_MATRIX && seqmat == *mpimat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
10570 
10571   ierr = PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10572   ierr = (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);CHKERRQ(ierr);
10573   ierr = PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10574   PetscFunctionReturn(0);
10575 }
10576 
10577 /*@
10578      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10579                  ranks' ownership ranges.
10580 
10581     Collective on A
10582 
10583    Input Parameters:
10584 +    A   - the matrix to create subdomains from
10585 -    N   - requested number of subdomains
10586 
10587    Output Parameters:
10588 +    n   - number of subdomains resulting on this rank
10589 -    iss - IS list with indices of subdomains on this rank
10590 
10591     Level: advanced
10592 
10593     Notes:
10594     number of subdomains must be smaller than the communicator size
10595 @*/
10596 PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10597 {
10598   MPI_Comm        comm,subcomm;
10599   PetscMPIInt     size,rank,color;
10600   PetscInt        rstart,rend,k;
10601   PetscErrorCode  ierr;
10602 
10603   PetscFunctionBegin;
10604   ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr);
10605   ierr = MPI_Comm_size(comm,&size);CHKERRMPI(ierr);
10606   ierr = MPI_Comm_rank(comm,&rank);CHKERRMPI(ierr);
10607   if (N < 1 || N >= (PetscInt)size) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"number of subdomains must be > 0 and < %D, got N = %D",size,N);
10608   *n = 1;
10609   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10610   color = rank/k;
10611   ierr = MPI_Comm_split(comm,color,rank,&subcomm);CHKERRMPI(ierr);
10612   ierr = PetscMalloc1(1,iss);CHKERRQ(ierr);
10613   ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
10614   ierr = ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);CHKERRQ(ierr);
10615   ierr = MPI_Comm_free(&subcomm);CHKERRMPI(ierr);
10616   PetscFunctionReturn(0);
10617 }
10618 
10619 /*@
10620    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.
10621 
10622    If the interpolation and restriction operators are the same, uses MatPtAP.
10623    If they are not the same, use MatMatMatMult.
10624 
10625    Once the coarse grid problem is constructed, correct for interpolation operators
10626    that are not of full rank, which can legitimately happen in the case of non-nested
10627    geometric multigrid.
10628 
10629    Input Parameters:
10630 +  restrct - restriction operator
10631 .  dA - fine grid matrix
10632 .  interpolate - interpolation operator
10633 .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10634 -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate
10635 
10636    Output Parameters:
10637 .  A - the Galerkin coarse matrix
10638 
10639    Options Database Key:
10640 .  -pc_mg_galerkin <both,pmat,mat,none>
10641 
10642    Level: developer
10643 
10644 .seealso: MatPtAP(), MatMatMatMult()
10645 @*/
10646 PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10647 {
10648   PetscErrorCode ierr;
10649   IS             zerorows;
10650   Vec            diag;
10651 
10652   PetscFunctionBegin;
10653   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10654   /* Construct the coarse grid matrix */
10655   if (interpolate == restrct) {
10656     ierr = MatPtAP(dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10657   } else {
10658     ierr = MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10659   }
10660 
10661   /* If the interpolation matrix is not of full rank, A will have zero rows.
10662      This can legitimately happen in the case of non-nested geometric multigrid.
10663      In that event, we set the rows of the matrix to the rows of the identity,
10664      ignoring the equations (as the RHS will also be zero). */
10665 
10666   ierr = MatFindZeroRows(*A, &zerorows);CHKERRQ(ierr);
10667 
10668   if (zerorows != NULL) { /* if there are any zero rows */
10669     ierr = MatCreateVecs(*A, &diag, NULL);CHKERRQ(ierr);
10670     ierr = MatGetDiagonal(*A, diag);CHKERRQ(ierr);
10671     ierr = VecISSet(diag, zerorows, 1.0);CHKERRQ(ierr);
10672     ierr = MatDiagonalSet(*A, diag, INSERT_VALUES);CHKERRQ(ierr);
10673     ierr = VecDestroy(&diag);CHKERRQ(ierr);
10674     ierr = ISDestroy(&zerorows);CHKERRQ(ierr);
10675   }
10676   PetscFunctionReturn(0);
10677 }
10678 
10679 /*@C
10680     MatSetOperation - Allows user to set a matrix operation for any matrix type
10681 
10682    Logically Collective on Mat
10683 
10684     Input Parameters:
10685 +   mat - the matrix
10686 .   op - the name of the operation
10687 -   f - the function that provides the operation
10688 
10689    Level: developer
10690 
10691     Usage:
10692 $      extern PetscErrorCode usermult(Mat,Vec,Vec);
10693 $      ierr = MatCreateXXX(comm,...&A);
10694 $      ierr = MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
10695 
10696     Notes:
10697     See the file include/petscmat.h for a complete list of matrix
10698     operations, which all have the form MATOP_<OPERATION>, where
10699     <OPERATION> is the name (in all capital letters) of the
10700     user interface routine (e.g., MatMult() -> MATOP_MULT).
10701 
10702     All user-provided functions (except for MATOP_DESTROY) should have the same calling
10703     sequence as the usual matrix interface routines, since they
10704     are intended to be accessed via the usual matrix interface
10705     routines, e.g.,
10706 $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)
10707 
10708     In particular each function MUST return an error code of 0 on success and
10709     nonzero on failure.
10710 
10711     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.
10712 
10713 .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10714 @*/
10715 PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10716 {
10717   PetscFunctionBegin;
10718   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10719   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10720     mat->ops->viewnative = mat->ops->view;
10721   }
10722   (((void(**)(void))mat->ops)[op]) = f;
10723   PetscFunctionReturn(0);
10724 }
10725 
10726 /*@C
10727     MatGetOperation - Gets a matrix operation for any matrix type.
10728 
10729     Not Collective
10730 
10731     Input Parameters:
10732 +   mat - the matrix
10733 -   op - the name of the operation
10734 
10735     Output Parameter:
10736 .   f - the function that provides the operation
10737 
10738     Level: developer
10739 
10740     Usage:
10741 $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
10742 $      ierr = MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);
10743 
10744     Notes:
10745     See the file include/petscmat.h for a complete list of matrix
10746     operations, which all have the form MATOP_<OPERATION>, where
10747     <OPERATION> is the name (in all capital letters) of the
10748     user interface routine (e.g., MatMult() -> MATOP_MULT).
10749 
10750     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.
10751 
10752 .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
10753 @*/
10754 PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
10755 {
10756   PetscFunctionBegin;
10757   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10758   *f = (((void (**)(void))mat->ops)[op]);
10759   PetscFunctionReturn(0);
10760 }
10761 
10762 /*@
10763     MatHasOperation - Determines whether the given matrix supports the particular
10764     operation.
10765 
10766    Not Collective
10767 
10768    Input Parameters:
10769 +  mat - the matrix
10770 -  op - the operation, for example, MATOP_GET_DIAGONAL
10771 
10772    Output Parameter:
10773 .  has - either PETSC_TRUE or PETSC_FALSE
10774 
10775    Level: advanced
10776 
10777    Notes:
10778    See the file include/petscmat.h for a complete list of matrix
10779    operations, which all have the form MATOP_<OPERATION>, where
10780    <OPERATION> is the name (in all capital letters) of the
10781    user-level routine.  E.g., MatNorm() -> MATOP_NORM.
10782 
10783 .seealso: MatCreateShell()
10784 @*/
10785 PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
10786 {
10787   PetscErrorCode ierr;
10788 
10789   PetscFunctionBegin;
10790   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10791   /* symbolic product can be set before matrix type */
10792   if (op != MATOP_PRODUCTSYMBOLIC) PetscValidType(mat,1);
10793   PetscValidPointer(has,3);
10794   if (mat->ops->hasoperation) {
10795     ierr = (*mat->ops->hasoperation)(mat,op,has);CHKERRQ(ierr);
10796   } else {
10797     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
10798     else {
10799       *has = PETSC_FALSE;
10800       if (op == MATOP_CREATE_SUBMATRIX) {
10801         PetscMPIInt size;
10802 
10803         ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRMPI(ierr);
10804         if (size == 1) {
10805           ierr = MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);CHKERRQ(ierr);
10806         }
10807       }
10808     }
10809   }
10810   PetscFunctionReturn(0);
10811 }
10812 
10813 /*@
10814     MatHasCongruentLayouts - Determines whether the rows and columns layouts
10815     of the matrix are congruent
10816 
10817    Collective on mat
10818 
10819    Input Parameters:
10820 .  mat - the matrix
10821 
10822    Output Parameter:
10823 .  cong - either PETSC_TRUE or PETSC_FALSE
10824 
10825    Level: beginner
10826 
10827    Notes:
10828 
10829 .seealso: MatCreate(), MatSetSizes()
10830 @*/
10831 PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
10832 {
10833   PetscErrorCode ierr;
10834 
10835   PetscFunctionBegin;
10836   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10837   PetscValidType(mat,1);
10838   PetscValidPointer(cong,2);
10839   if (!mat->rmap || !mat->cmap) {
10840     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
10841     PetscFunctionReturn(0);
10842   }
10843   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
10844     ierr = PetscLayoutCompare(mat->rmap,mat->cmap,cong);CHKERRQ(ierr);
10845     if (*cong) mat->congruentlayouts = 1;
10846     else       mat->congruentlayouts = 0;
10847   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
10848   PetscFunctionReturn(0);
10849 }
10850 
10851 PetscErrorCode MatSetInf(Mat A)
10852 {
10853   PetscErrorCode ierr;
10854 
10855   PetscFunctionBegin;
10856   if (!A->ops->setinf) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"No support for this operation for this matrix type");
10857   ierr = (*A->ops->setinf)(A);CHKERRQ(ierr);
10858   PetscFunctionReturn(0);
10859 }
10860