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