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