xref: /petsc/src/mat/interface/matrix.c (revision 5b72a2ce2e245e80f3c4d5fd294a594e197f5e74)
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 (*op)(Mat,Vec,Vec)=NULL,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) {
2452     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
2453     if (!op) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined or is symmetric and does not have a multiply defined",((PetscObject)mat)->type_name);
2454   } else op = mat->ops->multtranspose;
2455   ierr = PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2456   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2457   ierr = (*op)(mat,x,y);CHKERRQ(ierr);
2458   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2459   ierr = PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2460   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2461   if (mat->erroriffailure) {ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);}
2462   PetscFunctionReturn(0);
2463 }
2464 
2465 /*@
2466    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2467 
2468    Neighbor-wise Collective on Mat
2469 
2470    Input Parameters:
2471 +  mat - the matrix
2472 -  x   - the vector to be multilplied
2473 
2474    Output Parameters:
2475 .  y - the result
2476 
2477    Notes:
2478    The vectors x and y cannot be the same.  I.e., one cannot
2479    call MatMultHermitianTranspose(A,y,y).
2480 
2481    Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2482 
2483    For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2484 
2485    Level: beginner
2486 
2487 .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2488 @*/
2489 PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2490 {
2491   PetscErrorCode ierr;
2492   Vec            w;
2493 
2494   PetscFunctionBegin;
2495   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2496   PetscValidType(mat,1);
2497   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2498   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2499 
2500   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2501   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2502   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2503 #if !defined(PETSC_HAVE_CONSTRAINTS)
2504   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);
2505   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);
2506 #endif
2507   MatCheckPreallocated(mat,1);
2508 
2509   ierr = PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2510   if (mat->ops->multhermitiantranspose || (mat->hermitian && mat->ops->mult)) {
2511     ierr = VecLockReadPush(x);CHKERRQ(ierr);
2512     if (mat->ops->multhermitiantranspose) {
2513       ierr = (*mat->ops->multhermitiantranspose)(mat,x,y);CHKERRQ(ierr);
2514     } else {
2515       ierr = (*mat->ops->mult)(mat,x,y);CHKERRQ(ierr);
2516     }
2517     ierr = VecLockReadPop(x);CHKERRQ(ierr);
2518   } else {
2519     ierr = VecDuplicate(x,&w);CHKERRQ(ierr);
2520     ierr = VecCopy(x,w);CHKERRQ(ierr);
2521     ierr = VecConjugate(w);CHKERRQ(ierr);
2522     ierr = MatMultTranspose(mat,w,y);CHKERRQ(ierr);
2523     ierr = VecDestroy(&w);CHKERRQ(ierr);
2524     ierr = VecConjugate(y);CHKERRQ(ierr);
2525   }
2526   ierr = PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2527   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2528   PetscFunctionReturn(0);
2529 }
2530 
2531 /*@
2532     MatMultAdd -  Computes v3 = v2 + A * v1.
2533 
2534     Neighbor-wise Collective on Mat
2535 
2536     Input Parameters:
2537 +   mat - the matrix
2538 -   v1, v2 - the vectors
2539 
2540     Output Parameters:
2541 .   v3 - the result
2542 
2543     Notes:
2544     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2545     call MatMultAdd(A,v1,v2,v1).
2546 
2547     Level: beginner
2548 
2549 .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2550 @*/
2551 PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2552 {
2553   PetscErrorCode ierr;
2554 
2555   PetscFunctionBegin;
2556   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2557   PetscValidType(mat,1);
2558   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2559   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2560   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2561 
2562   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2563   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2564   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);
2565   /* 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);
2566      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); */
2567   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);
2568   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);
2569   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2570   MatCheckPreallocated(mat,1);
2571 
2572   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2573   ierr = PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2574   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2575   ierr = (*mat->ops->multadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2576   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2577   ierr = PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2578   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2579   PetscFunctionReturn(0);
2580 }
2581 
2582 /*@
2583    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2584 
2585    Neighbor-wise Collective on Mat
2586 
2587    Input Parameters:
2588 +  mat - the matrix
2589 -  v1, v2 - the vectors
2590 
2591    Output Parameters:
2592 .  v3 - the result
2593 
2594    Notes:
2595    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2596    call MatMultTransposeAdd(A,v1,v2,v1).
2597 
2598    Level: beginner
2599 
2600 .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2601 @*/
2602 PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2603 {
2604   PetscErrorCode ierr;
2605 
2606   PetscFunctionBegin;
2607   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2608   PetscValidType(mat,1);
2609   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2610   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2611   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2612 
2613   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2614   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2615   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2616   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2617   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);
2618   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);
2619   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);
2620   MatCheckPreallocated(mat,1);
2621 
2622   ierr = PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2623   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2624   ierr = (*mat->ops->multtransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2625   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2626   ierr = PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2627   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2628   PetscFunctionReturn(0);
2629 }
2630 
2631 /*@
2632    MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2633 
2634    Neighbor-wise Collective on Mat
2635 
2636    Input Parameters:
2637 +  mat - the matrix
2638 -  v1, v2 - the vectors
2639 
2640    Output Parameters:
2641 .  v3 - the result
2642 
2643    Notes:
2644    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2645    call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2646 
2647    Level: beginner
2648 
2649 .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2650 @*/
2651 PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2652 {
2653   PetscErrorCode ierr;
2654 
2655   PetscFunctionBegin;
2656   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2657   PetscValidType(mat,1);
2658   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2659   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2660   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2661 
2662   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2663   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2664   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2665   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);
2666   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);
2667   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);
2668   MatCheckPreallocated(mat,1);
2669 
2670   ierr = PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2671   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2672   if (mat->ops->multhermitiantransposeadd) {
2673     ierr = (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2674   } else {
2675     Vec w,z;
2676     ierr = VecDuplicate(v1,&w);CHKERRQ(ierr);
2677     ierr = VecCopy(v1,w);CHKERRQ(ierr);
2678     ierr = VecConjugate(w);CHKERRQ(ierr);
2679     ierr = VecDuplicate(v3,&z);CHKERRQ(ierr);
2680     ierr = MatMultTranspose(mat,w,z);CHKERRQ(ierr);
2681     ierr = VecDestroy(&w);CHKERRQ(ierr);
2682     ierr = VecConjugate(z);CHKERRQ(ierr);
2683     if (v2 != v3) {
2684       ierr = VecWAXPY(v3,1.0,v2,z);CHKERRQ(ierr);
2685     } else {
2686       ierr = VecAXPY(v3,1.0,z);CHKERRQ(ierr);
2687     }
2688     ierr = VecDestroy(&z);CHKERRQ(ierr);
2689   }
2690   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2691   ierr = PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2692   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2693   PetscFunctionReturn(0);
2694 }
2695 
2696 /*@
2697    MatMultConstrained - The inner multiplication routine for a
2698    constrained matrix P^T A P.
2699 
2700    Neighbor-wise Collective on Mat
2701 
2702    Input Parameters:
2703 +  mat - the matrix
2704 -  x   - the vector to be multilplied
2705 
2706    Output Parameters:
2707 .  y - the result
2708 
2709    Notes:
2710    The vectors x and y cannot be the same.  I.e., one cannot
2711    call MatMult(A,y,y).
2712 
2713    Level: beginner
2714 
2715 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2716 @*/
2717 PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2718 {
2719   PetscErrorCode ierr;
2720 
2721   PetscFunctionBegin;
2722   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2723   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2724   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2725   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2726   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2727   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2728   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);
2729   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);
2730   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);
2731 
2732   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2733   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2734   ierr = (*mat->ops->multconstrained)(mat,x,y);CHKERRQ(ierr);
2735   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2736   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2737   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2738   PetscFunctionReturn(0);
2739 }
2740 
2741 /*@
2742    MatMultTransposeConstrained - The inner multiplication routine for a
2743    constrained matrix P^T A^T P.
2744 
2745    Neighbor-wise Collective on Mat
2746 
2747    Input Parameters:
2748 +  mat - the matrix
2749 -  x   - the vector to be multilplied
2750 
2751    Output Parameters:
2752 .  y - the result
2753 
2754    Notes:
2755    The vectors x and y cannot be the same.  I.e., one cannot
2756    call MatMult(A,y,y).
2757 
2758    Level: beginner
2759 
2760 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2761 @*/
2762 PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2763 {
2764   PetscErrorCode ierr;
2765 
2766   PetscFunctionBegin;
2767   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2768   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2769   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2770   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2771   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2772   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2773   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);
2774   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);
2775 
2776   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2777   ierr = (*mat->ops->multtransposeconstrained)(mat,x,y);CHKERRQ(ierr);
2778   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2779   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2780   PetscFunctionReturn(0);
2781 }
2782 
2783 /*@C
2784    MatGetFactorType - gets the type of factorization it is
2785 
2786    Not Collective
2787 
2788    Input Parameters:
2789 .  mat - the matrix
2790 
2791    Output Parameters:
2792 .  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2793 
2794    Level: intermediate
2795 
2796 .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2797 @*/
2798 PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2799 {
2800   PetscFunctionBegin;
2801   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2802   PetscValidType(mat,1);
2803   PetscValidPointer(t,2);
2804   *t = mat->factortype;
2805   PetscFunctionReturn(0);
2806 }
2807 
2808 /*@C
2809    MatSetFactorType - sets the type of factorization it is
2810 
2811    Logically Collective on Mat
2812 
2813    Input Parameters:
2814 +  mat - the matrix
2815 -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2816 
2817    Level: intermediate
2818 
2819 .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2820 @*/
2821 PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2822 {
2823   PetscFunctionBegin;
2824   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2825   PetscValidType(mat,1);
2826   mat->factortype = t;
2827   PetscFunctionReturn(0);
2828 }
2829 
2830 /* ------------------------------------------------------------*/
2831 /*@C
2832    MatGetInfo - Returns information about matrix storage (number of
2833    nonzeros, memory, etc.).
2834 
2835    Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2836 
2837    Input Parameters:
2838 .  mat - the matrix
2839 
2840    Output Parameters:
2841 +  flag - flag indicating the type of parameters to be returned
2842    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2843    MAT_GLOBAL_SUM - sum over all processors)
2844 -  info - matrix information context
2845 
2846    Notes:
2847    The MatInfo context contains a variety of matrix data, including
2848    number of nonzeros allocated and used, number of mallocs during
2849    matrix assembly, etc.  Additional information for factored matrices
2850    is provided (such as the fill ratio, number of mallocs during
2851    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2852    when using the runtime options
2853 $       -info -mat_view ::ascii_info
2854 
2855    Example for C/C++ Users:
2856    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2857    data within the MatInfo context.  For example,
2858 .vb
2859       MatInfo info;
2860       Mat     A;
2861       double  mal, nz_a, nz_u;
2862 
2863       MatGetInfo(A,MAT_LOCAL,&info);
2864       mal  = info.mallocs;
2865       nz_a = info.nz_allocated;
2866 .ve
2867 
2868    Example for Fortran Users:
2869    Fortran users should declare info as a double precision
2870    array of dimension MAT_INFO_SIZE, and then extract the parameters
2871    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2872    a complete list of parameter names.
2873 .vb
2874       double  precision info(MAT_INFO_SIZE)
2875       double  precision mal, nz_a
2876       Mat     A
2877       integer ierr
2878 
2879       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2880       mal = info(MAT_INFO_MALLOCS)
2881       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2882 .ve
2883 
2884     Level: intermediate
2885 
2886     Developer Note: fortran interface is not autogenerated as the f90
2887     interface defintion cannot be generated correctly [due to MatInfo]
2888 
2889 .seealso: MatStashGetInfo()
2890 
2891 @*/
2892 PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2893 {
2894   PetscErrorCode ierr;
2895 
2896   PetscFunctionBegin;
2897   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2898   PetscValidType(mat,1);
2899   PetscValidPointer(info,3);
2900   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2901   MatCheckPreallocated(mat,1);
2902   ierr = (*mat->ops->getinfo)(mat,flag,info);CHKERRQ(ierr);
2903   PetscFunctionReturn(0);
2904 }
2905 
2906 /*
2907    This is used by external packages where it is not easy to get the info from the actual
2908    matrix factorization.
2909 */
2910 PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2911 {
2912   PetscErrorCode ierr;
2913 
2914   PetscFunctionBegin;
2915   ierr = PetscMemzero(info,sizeof(MatInfo));CHKERRQ(ierr);
2916   PetscFunctionReturn(0);
2917 }
2918 
2919 /* ----------------------------------------------------------*/
2920 
2921 /*@C
2922    MatLUFactor - Performs in-place LU factorization of matrix.
2923 
2924    Collective on Mat
2925 
2926    Input Parameters:
2927 +  mat - the matrix
2928 .  row - row permutation
2929 .  col - column permutation
2930 -  info - options for factorization, includes
2931 $          fill - expected fill as ratio of original fill.
2932 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2933 $                   Run with the option -info to determine an optimal value to use
2934 
2935    Notes:
2936    Most users should employ the simplified KSP interface for linear solvers
2937    instead of working directly with matrix algebra routines such as this.
2938    See, e.g., KSPCreate().
2939 
2940    This changes the state of the matrix to a factored matrix; it cannot be used
2941    for example with MatSetValues() unless one first calls MatSetUnfactored().
2942 
2943    Level: developer
2944 
2945 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2946           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2947 
2948     Developer Note: fortran interface is not autogenerated as the f90
2949     interface defintion cannot be generated correctly [due to MatFactorInfo]
2950 
2951 @*/
2952 PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2953 {
2954   PetscErrorCode ierr;
2955   MatFactorInfo  tinfo;
2956 
2957   PetscFunctionBegin;
2958   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2959   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2960   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2961   if (info) PetscValidPointer(info,4);
2962   PetscValidType(mat,1);
2963   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2964   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2965   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2966   MatCheckPreallocated(mat,1);
2967   if (!info) {
2968     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
2969     info = &tinfo;
2970   }
2971 
2972   ierr = PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2973   ierr = (*mat->ops->lufactor)(mat,row,col,info);CHKERRQ(ierr);
2974   ierr = PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2975   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
2976   PetscFunctionReturn(0);
2977 }
2978 
2979 /*@C
2980    MatILUFactor - Performs in-place ILU factorization of matrix.
2981 
2982    Collective on Mat
2983 
2984    Input Parameters:
2985 +  mat - the matrix
2986 .  row - row permutation
2987 .  col - column permutation
2988 -  info - structure containing
2989 $      levels - number of levels of fill.
2990 $      expected fill - as ratio of original fill.
2991 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2992                 missing diagonal entries)
2993 
2994    Notes:
2995    Probably really in-place only when level of fill is zero, otherwise allocates
2996    new space to store factored matrix and deletes previous memory.
2997 
2998    Most users should employ the simplified KSP interface for linear solvers
2999    instead of working directly with matrix algebra routines such as this.
3000    See, e.g., KSPCreate().
3001 
3002    Level: developer
3003 
3004 .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
3005 
3006     Developer Note: fortran interface is not autogenerated as the f90
3007     interface defintion cannot be generated correctly [due to MatFactorInfo]
3008 
3009 @*/
3010 PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3011 {
3012   PetscErrorCode ierr;
3013 
3014   PetscFunctionBegin;
3015   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3016   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
3017   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
3018   PetscValidPointer(info,4);
3019   PetscValidType(mat,1);
3020   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
3021   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3022   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3023   if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3024   MatCheckPreallocated(mat,1);
3025 
3026   ierr = PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
3027   ierr = (*mat->ops->ilufactor)(mat,row,col,info);CHKERRQ(ierr);
3028   ierr = PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
3029   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3030   PetscFunctionReturn(0);
3031 }
3032 
3033 /*@C
3034    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3035    Call this routine before calling MatLUFactorNumeric().
3036 
3037    Collective on Mat
3038 
3039    Input Parameters:
3040 +  fact - the factor matrix obtained with MatGetFactor()
3041 .  mat - the matrix
3042 .  row, col - row and column permutations
3043 -  info - options for factorization, includes
3044 $          fill - expected fill as ratio of original fill.
3045 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3046 $                   Run with the option -info to determine an optimal value to use
3047 
3048 
3049    Notes:
3050     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
3051 
3052    Most users should employ the simplified KSP interface for linear solvers
3053    instead of working directly with matrix algebra routines such as this.
3054    See, e.g., KSPCreate().
3055 
3056    Level: developer
3057 
3058 .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
3059 
3060     Developer Note: fortran interface is not autogenerated as the f90
3061     interface defintion cannot be generated correctly [due to MatFactorInfo]
3062 
3063 @*/
3064 PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3065 {
3066   PetscErrorCode ierr;
3067   MatFactorInfo  tinfo;
3068 
3069   PetscFunctionBegin;
3070   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3071   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
3072   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
3073   if (info) PetscValidPointer(info,4);
3074   PetscValidType(mat,1);
3075   PetscValidPointer(fact,5);
3076   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3077   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3078   if (!(fact)->ops->lufactorsymbolic) {
3079     MatSolverType spackage;
3080     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
3081     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3082   }
3083   MatCheckPreallocated(mat,2);
3084   if (!info) {
3085     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3086     info = &tinfo;
3087   }
3088 
3089   ierr = PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
3090   ierr = (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
3091   ierr = PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
3092   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3093   PetscFunctionReturn(0);
3094 }
3095 
3096 /*@C
3097    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3098    Call this routine after first calling MatLUFactorSymbolic().
3099 
3100    Collective on Mat
3101 
3102    Input Parameters:
3103 +  fact - the factor matrix obtained with MatGetFactor()
3104 .  mat - the matrix
3105 -  info - options for factorization
3106 
3107    Notes:
3108    See MatLUFactor() for in-place factorization.  See
3109    MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3110 
3111    Most users should employ the simplified KSP interface for linear solvers
3112    instead of working directly with matrix algebra routines such as this.
3113    See, e.g., KSPCreate().
3114 
3115    Level: developer
3116 
3117 .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3118 
3119     Developer Note: fortran interface is not autogenerated as the f90
3120     interface defintion cannot be generated correctly [due to MatFactorInfo]
3121 
3122 @*/
3123 PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3124 {
3125   MatFactorInfo  tinfo;
3126   PetscErrorCode ierr;
3127 
3128   PetscFunctionBegin;
3129   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3130   PetscValidType(mat,1);
3131   PetscValidPointer(fact,2);
3132   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
3133   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3134   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);
3135 
3136   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3137   MatCheckPreallocated(mat,2);
3138   if (!info) {
3139     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3140     info = &tinfo;
3141   }
3142 
3143   ierr = PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3144   ierr = (fact->ops->lufactornumeric)(fact,mat,info);CHKERRQ(ierr);
3145   ierr = PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3146   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3147   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3148   PetscFunctionReturn(0);
3149 }
3150 
3151 /*@C
3152    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3153    symmetric matrix.
3154 
3155    Collective on Mat
3156 
3157    Input Parameters:
3158 +  mat - the matrix
3159 .  perm - row and column permutations
3160 -  f - expected fill as ratio of original fill
3161 
3162    Notes:
3163    See MatLUFactor() for the nonsymmetric case.  See also
3164    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3165 
3166    Most users should employ the simplified KSP interface for linear solvers
3167    instead of working directly with matrix algebra routines such as this.
3168    See, e.g., KSPCreate().
3169 
3170    Level: developer
3171 
3172 .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3173           MatGetOrdering()
3174 
3175     Developer Note: fortran interface is not autogenerated as the f90
3176     interface defintion cannot be generated correctly [due to MatFactorInfo]
3177 
3178 @*/
3179 PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3180 {
3181   PetscErrorCode ierr;
3182   MatFactorInfo  tinfo;
3183 
3184   PetscFunctionBegin;
3185   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3186   PetscValidType(mat,1);
3187   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3188   if (info) PetscValidPointer(info,3);
3189   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3190   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3191   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3192   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);
3193   MatCheckPreallocated(mat,1);
3194   if (!info) {
3195     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3196     info = &tinfo;
3197   }
3198 
3199   ierr = PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3200   ierr = (*mat->ops->choleskyfactor)(mat,perm,info);CHKERRQ(ierr);
3201   ierr = PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3202   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3203   PetscFunctionReturn(0);
3204 }
3205 
3206 /*@C
3207    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3208    of a symmetric matrix.
3209 
3210    Collective on Mat
3211 
3212    Input Parameters:
3213 +  fact - the factor matrix obtained with MatGetFactor()
3214 .  mat - the matrix
3215 .  perm - row and column permutations
3216 -  info - options for factorization, includes
3217 $          fill - expected fill as ratio of original fill.
3218 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3219 $                   Run with the option -info to determine an optimal value to use
3220 
3221    Notes:
3222    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3223    MatCholeskyFactor() and MatCholeskyFactorNumeric().
3224 
3225    Most users should employ the simplified KSP interface for linear solvers
3226    instead of working directly with matrix algebra routines such as this.
3227    See, e.g., KSPCreate().
3228 
3229    Level: developer
3230 
3231 .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3232           MatGetOrdering()
3233 
3234     Developer Note: fortran interface is not autogenerated as the f90
3235     interface defintion cannot be generated correctly [due to MatFactorInfo]
3236 
3237 @*/
3238 PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3239 {
3240   PetscErrorCode ierr;
3241   MatFactorInfo  tinfo;
3242 
3243   PetscFunctionBegin;
3244   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3245   PetscValidType(mat,1);
3246   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3247   if (info) PetscValidPointer(info,3);
3248   PetscValidPointer(fact,4);
3249   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3250   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3251   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3252   if (!(fact)->ops->choleskyfactorsymbolic) {
3253     MatSolverType spackage;
3254     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
3255     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3256   }
3257   MatCheckPreallocated(mat,2);
3258   if (!info) {
3259     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3260     info = &tinfo;
3261   }
3262 
3263   ierr = PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3264   ierr = (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
3265   ierr = PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3266   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3267   PetscFunctionReturn(0);
3268 }
3269 
3270 /*@C
3271    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3272    of a symmetric matrix. Call this routine after first calling
3273    MatCholeskyFactorSymbolic().
3274 
3275    Collective on Mat
3276 
3277    Input Parameters:
3278 +  fact - the factor matrix obtained with MatGetFactor()
3279 .  mat - the initial matrix
3280 .  info - options for factorization
3281 -  fact - the symbolic factor of mat
3282 
3283 
3284    Notes:
3285    Most users should employ the simplified KSP interface for linear solvers
3286    instead of working directly with matrix algebra routines such as this.
3287    See, e.g., KSPCreate().
3288 
3289    Level: developer
3290 
3291 .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3292 
3293     Developer Note: fortran interface is not autogenerated as the f90
3294     interface defintion cannot be generated correctly [due to MatFactorInfo]
3295 
3296 @*/
3297 PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3298 {
3299   MatFactorInfo  tinfo;
3300   PetscErrorCode ierr;
3301 
3302   PetscFunctionBegin;
3303   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3304   PetscValidType(mat,1);
3305   PetscValidPointer(fact,2);
3306   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
3307   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3308   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3309   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);
3310   MatCheckPreallocated(mat,2);
3311   if (!info) {
3312     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3313     info = &tinfo;
3314   }
3315 
3316   ierr = PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3317   ierr = (fact->ops->choleskyfactornumeric)(fact,mat,info);CHKERRQ(ierr);
3318   ierr = PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3319   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3320   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3321   PetscFunctionReturn(0);
3322 }
3323 
3324 /* ----------------------------------------------------------------*/
3325 /*@
3326    MatSolve - Solves A x = b, given a factored matrix.
3327 
3328    Neighbor-wise Collective on Mat
3329 
3330    Input Parameters:
3331 +  mat - the factored matrix
3332 -  b - the right-hand-side vector
3333 
3334    Output Parameter:
3335 .  x - the result vector
3336 
3337    Notes:
3338    The vectors b and x cannot be the same.  I.e., one cannot
3339    call MatSolve(A,x,x).
3340 
3341    Notes:
3342    Most users should employ the simplified KSP interface for linear solvers
3343    instead of working directly with matrix algebra routines such as this.
3344    See, e.g., KSPCreate().
3345 
3346    Level: developer
3347 
3348 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3349 @*/
3350 PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3351 {
3352   PetscErrorCode ierr;
3353 
3354   PetscFunctionBegin;
3355   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3356   PetscValidType(mat,1);
3357   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3358   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3359   PetscCheckSameComm(mat,1,b,2);
3360   PetscCheckSameComm(mat,1,x,3);
3361   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3362   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);
3363   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);
3364   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);
3365   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3366   MatCheckPreallocated(mat,1);
3367 
3368   ierr = PetscLogEventBegin(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3369   if (mat->factorerrortype) {
3370     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3371     ierr = VecSetInf(x);CHKERRQ(ierr);
3372   } else {
3373     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3374     ierr = (*mat->ops->solve)(mat,b,x);CHKERRQ(ierr);
3375   }
3376   ierr = PetscLogEventEnd(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3377   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3378   PetscFunctionReturn(0);
3379 }
3380 
3381 static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3382 {
3383   PetscErrorCode ierr;
3384   Vec            b,x;
3385   PetscInt       m,N,i;
3386   PetscScalar    *bb,*xx;
3387 
3388   PetscFunctionBegin;
3389   ierr = MatDenseGetArrayRead(B,(const PetscScalar**)&bb);CHKERRQ(ierr);
3390   ierr = MatDenseGetArray(X,&xx);CHKERRQ(ierr);
3391   ierr = MatGetLocalSize(B,&m,NULL);CHKERRQ(ierr);  /* number local rows */
3392   ierr = MatGetSize(B,NULL,&N);CHKERRQ(ierr);       /* total columns in dense matrix */
3393   ierr = MatCreateVecs(A,&x,&b);CHKERRQ(ierr);
3394   for (i=0; i<N; i++) {
3395     ierr = VecPlaceArray(b,bb + i*m);CHKERRQ(ierr);
3396     ierr = VecPlaceArray(x,xx + i*m);CHKERRQ(ierr);
3397     if (trans) {
3398       ierr = MatSolveTranspose(A,b,x);CHKERRQ(ierr);
3399     } else {
3400       ierr = MatSolve(A,b,x);CHKERRQ(ierr);
3401     }
3402     ierr = VecResetArray(x);CHKERRQ(ierr);
3403     ierr = VecResetArray(b);CHKERRQ(ierr);
3404   }
3405   ierr = VecDestroy(&b);CHKERRQ(ierr);
3406   ierr = VecDestroy(&x);CHKERRQ(ierr);
3407   ierr = MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);CHKERRQ(ierr);
3408   ierr = MatDenseRestoreArray(X,&xx);CHKERRQ(ierr);
3409   PetscFunctionReturn(0);
3410 }
3411 
3412 /*@
3413    MatMatSolve - Solves A X = B, given a factored matrix.
3414 
3415    Neighbor-wise Collective on Mat
3416 
3417    Input Parameters:
3418 +  A - the factored matrix
3419 -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)
3420 
3421    Output Parameter:
3422 .  X - the result matrix (dense matrix)
3423 
3424    Notes:
3425    If B is a MATDENSE matrix then one can call MatMatSolve(A,B,B);
3426    otherwise, B and X cannot be the same.
3427 
3428    Notes:
3429    Most users should usually employ the simplified KSP interface for linear solvers
3430    instead of working directly with matrix algebra routines such as this.
3431    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3432    at a time.
3433 
3434    Level: developer
3435 
3436 .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3437 @*/
3438 PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3439 {
3440   PetscErrorCode ierr;
3441 
3442   PetscFunctionBegin;
3443   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3444   PetscValidType(A,1);
3445   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3446   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3447   PetscCheckSameComm(A,1,B,2);
3448   PetscCheckSameComm(A,1,X,3);
3449   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);
3450   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);
3451   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");
3452   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3453   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3454   MatCheckPreallocated(A,1);
3455 
3456   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3457   if (!A->ops->matsolve) {
3458     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3459     ierr = MatMatSolve_Basic(A,B,X,PETSC_FALSE);CHKERRQ(ierr);
3460   } else {
3461     ierr = (*A->ops->matsolve)(A,B,X);CHKERRQ(ierr);
3462   }
3463   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3464   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3465   PetscFunctionReturn(0);
3466 }
3467 
3468 /*@
3469    MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3470 
3471    Neighbor-wise Collective on Mat
3472 
3473    Input Parameters:
3474 +  A - the factored matrix
3475 -  B - the right-hand-side matrix  (dense matrix)
3476 
3477    Output Parameter:
3478 .  X - the result matrix (dense matrix)
3479 
3480    Notes:
3481    The matrices B and X cannot be the same.  I.e., one cannot
3482    call MatMatSolveTranspose(A,X,X).
3483 
3484    Notes:
3485    Most users should usually employ the simplified KSP interface for linear solvers
3486    instead of working directly with matrix algebra routines such as this.
3487    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3488    at a time.
3489 
3490    When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3491 
3492    Level: developer
3493 
3494 .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3495 @*/
3496 PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3497 {
3498   PetscErrorCode ierr;
3499 
3500   PetscFunctionBegin;
3501   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3502   PetscValidType(A,1);
3503   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3504   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3505   PetscCheckSameComm(A,1,B,2);
3506   PetscCheckSameComm(A,1,X,3);
3507   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3508   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);
3509   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);
3510   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);
3511   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");
3512   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3513   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3514   MatCheckPreallocated(A,1);
3515 
3516   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3517   if (!A->ops->matsolvetranspose) {
3518     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3519     ierr = MatMatSolve_Basic(A,B,X,PETSC_TRUE);CHKERRQ(ierr);
3520   } else {
3521     ierr = (*A->ops->matsolvetranspose)(A,B,X);CHKERRQ(ierr);
3522   }
3523   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3524   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3525   PetscFunctionReturn(0);
3526 }
3527 
3528 /*@
3529    MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3530 
3531    Neighbor-wise Collective on Mat
3532 
3533    Input Parameters:
3534 +  A - the factored matrix
3535 -  Bt - the transpose of right-hand-side matrix
3536 
3537    Output Parameter:
3538 .  X - the result matrix (dense matrix)
3539 
3540    Notes:
3541    Most users should usually employ the simplified KSP interface for linear solvers
3542    instead of working directly with matrix algebra routines such as this.
3543    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3544    at a time.
3545 
3546    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().
3547 
3548    Level: developer
3549 
3550 .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3551 @*/
3552 PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3553 {
3554   PetscErrorCode ierr;
3555 
3556   PetscFunctionBegin;
3557   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3558   PetscValidType(A,1);
3559   PetscValidHeaderSpecific(Bt,MAT_CLASSID,2);
3560   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3561   PetscCheckSameComm(A,1,Bt,2);
3562   PetscCheckSameComm(A,1,X,3);
3563 
3564   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3565   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);
3566   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);
3567   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");
3568   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3569   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3570   MatCheckPreallocated(A,1);
3571 
3572   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3573   ierr = PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3574   ierr = (*A->ops->mattransposesolve)(A,Bt,X);CHKERRQ(ierr);
3575   ierr = PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3576   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3577   PetscFunctionReturn(0);
3578 }
3579 
3580 /*@
3581    MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3582                             U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3583 
3584    Neighbor-wise Collective on Mat
3585 
3586    Input Parameters:
3587 +  mat - the factored matrix
3588 -  b - the right-hand-side vector
3589 
3590    Output Parameter:
3591 .  x - the result vector
3592 
3593    Notes:
3594    MatSolve() should be used for most applications, as it performs
3595    a forward solve followed by a backward solve.
3596 
3597    The vectors b and x cannot be the same,  i.e., one cannot
3598    call MatForwardSolve(A,x,x).
3599 
3600    For matrix in seqsbaij format with block size larger than 1,
3601    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3602    MatForwardSolve() solves U^T*D y = b, and
3603    MatBackwardSolve() solves U x = y.
3604    Thus they do not provide a symmetric preconditioner.
3605 
3606    Most users should employ the simplified KSP interface for linear solvers
3607    instead of working directly with matrix algebra routines such as this.
3608    See, e.g., KSPCreate().
3609 
3610    Level: developer
3611 
3612 .seealso: MatSolve(), MatBackwardSolve()
3613 @*/
3614 PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3615 {
3616   PetscErrorCode ierr;
3617 
3618   PetscFunctionBegin;
3619   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3620   PetscValidType(mat,1);
3621   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3622   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3623   PetscCheckSameComm(mat,1,b,2);
3624   PetscCheckSameComm(mat,1,x,3);
3625   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3626   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);
3627   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);
3628   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);
3629   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3630   MatCheckPreallocated(mat,1);
3631 
3632   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3633   ierr = PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3634   ierr = (*mat->ops->forwardsolve)(mat,b,x);CHKERRQ(ierr);
3635   ierr = PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3636   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3637   PetscFunctionReturn(0);
3638 }
3639 
3640 /*@
3641    MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3642                              D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3643 
3644    Neighbor-wise Collective on Mat
3645 
3646    Input Parameters:
3647 +  mat - the factored matrix
3648 -  b - the right-hand-side vector
3649 
3650    Output Parameter:
3651 .  x - the result vector
3652 
3653    Notes:
3654    MatSolve() should be used for most applications, as it performs
3655    a forward solve followed by a backward solve.
3656 
3657    The vectors b and x cannot be the same.  I.e., one cannot
3658    call MatBackwardSolve(A,x,x).
3659 
3660    For matrix in seqsbaij format with block size larger than 1,
3661    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3662    MatForwardSolve() solves U^T*D y = b, and
3663    MatBackwardSolve() solves U x = y.
3664    Thus they do not provide a symmetric preconditioner.
3665 
3666    Most users should employ the simplified KSP interface for linear solvers
3667    instead of working directly with matrix algebra routines such as this.
3668    See, e.g., KSPCreate().
3669 
3670    Level: developer
3671 
3672 .seealso: MatSolve(), MatForwardSolve()
3673 @*/
3674 PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3675 {
3676   PetscErrorCode ierr;
3677 
3678   PetscFunctionBegin;
3679   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3680   PetscValidType(mat,1);
3681   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3682   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3683   PetscCheckSameComm(mat,1,b,2);
3684   PetscCheckSameComm(mat,1,x,3);
3685   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3686   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);
3687   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);
3688   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);
3689   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3690   MatCheckPreallocated(mat,1);
3691 
3692   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3693   ierr = PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3694   ierr = (*mat->ops->backwardsolve)(mat,b,x);CHKERRQ(ierr);
3695   ierr = PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3696   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3697   PetscFunctionReturn(0);
3698 }
3699 
3700 /*@
3701    MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3702 
3703    Neighbor-wise Collective on Mat
3704 
3705    Input Parameters:
3706 +  mat - the factored matrix
3707 .  b - the right-hand-side vector
3708 -  y - the vector to be added to
3709 
3710    Output Parameter:
3711 .  x - the result vector
3712 
3713    Notes:
3714    The vectors b and x cannot be the same.  I.e., one cannot
3715    call MatSolveAdd(A,x,y,x).
3716 
3717    Most users should employ the simplified KSP interface for linear solvers
3718    instead of working directly with matrix algebra routines such as this.
3719    See, e.g., KSPCreate().
3720 
3721    Level: developer
3722 
3723 .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3724 @*/
3725 PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3726 {
3727   PetscScalar    one = 1.0;
3728   Vec            tmp;
3729   PetscErrorCode ierr;
3730 
3731   PetscFunctionBegin;
3732   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3733   PetscValidType(mat,1);
3734   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3735   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3736   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3737   PetscCheckSameComm(mat,1,b,2);
3738   PetscCheckSameComm(mat,1,y,2);
3739   PetscCheckSameComm(mat,1,x,3);
3740   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3741   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);
3742   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);
3743   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);
3744   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);
3745   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);
3746   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3747    MatCheckPreallocated(mat,1);
3748 
3749   ierr = PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3750   if (mat->factorerrortype) {
3751     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3752     ierr = VecSetInf(x);CHKERRQ(ierr);
3753   } else if (mat->ops->solveadd) {
3754     ierr = (*mat->ops->solveadd)(mat,b,y,x);CHKERRQ(ierr);
3755   } else {
3756     /* do the solve then the add manually */
3757     if (x != y) {
3758       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3759       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3760     } else {
3761       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3762       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3763       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3764       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3765       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3766       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3767     }
3768   }
3769   ierr = PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3770   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3771   PetscFunctionReturn(0);
3772 }
3773 
3774 /*@
3775    MatSolveTranspose - Solves A' x = b, given a factored matrix.
3776 
3777    Neighbor-wise Collective on Mat
3778 
3779    Input Parameters:
3780 +  mat - the factored matrix
3781 -  b - the right-hand-side vector
3782 
3783    Output Parameter:
3784 .  x - the result vector
3785 
3786    Notes:
3787    The vectors b and x cannot be the same.  I.e., one cannot
3788    call MatSolveTranspose(A,x,x).
3789 
3790    Most users should employ the simplified KSP interface for linear solvers
3791    instead of working directly with matrix algebra routines such as this.
3792    See, e.g., KSPCreate().
3793 
3794    Level: developer
3795 
3796 .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3797 @*/
3798 PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3799 {
3800   PetscErrorCode ierr;
3801 
3802   PetscFunctionBegin;
3803   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3804   PetscValidType(mat,1);
3805   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3806   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3807   PetscCheckSameComm(mat,1,b,2);
3808   PetscCheckSameComm(mat,1,x,3);
3809   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3810   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);
3811   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);
3812   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3813   MatCheckPreallocated(mat,1);
3814   ierr = PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3815   if (mat->factorerrortype) {
3816     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3817     ierr = VecSetInf(x);CHKERRQ(ierr);
3818   } else {
3819     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3820     ierr = (*mat->ops->solvetranspose)(mat,b,x);CHKERRQ(ierr);
3821   }
3822   ierr = PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3823   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3824   PetscFunctionReturn(0);
3825 }
3826 
3827 /*@
3828    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3829                       factored matrix.
3830 
3831    Neighbor-wise Collective on Mat
3832 
3833    Input Parameters:
3834 +  mat - the factored matrix
3835 .  b - the right-hand-side vector
3836 -  y - the vector to be added to
3837 
3838    Output Parameter:
3839 .  x - the result vector
3840 
3841    Notes:
3842    The vectors b and x cannot be the same.  I.e., one cannot
3843    call MatSolveTransposeAdd(A,x,y,x).
3844 
3845    Most users should employ the simplified KSP interface for linear solvers
3846    instead of working directly with matrix algebra routines such as this.
3847    See, e.g., KSPCreate().
3848 
3849    Level: developer
3850 
3851 .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3852 @*/
3853 PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3854 {
3855   PetscScalar    one = 1.0;
3856   PetscErrorCode ierr;
3857   Vec            tmp;
3858 
3859   PetscFunctionBegin;
3860   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3861   PetscValidType(mat,1);
3862   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3863   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3864   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3865   PetscCheckSameComm(mat,1,b,2);
3866   PetscCheckSameComm(mat,1,y,3);
3867   PetscCheckSameComm(mat,1,x,4);
3868   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3869   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);
3870   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);
3871   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);
3872   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);
3873   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3874    MatCheckPreallocated(mat,1);
3875 
3876   ierr = PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3877   if (mat->factorerrortype) {
3878     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3879     ierr = VecSetInf(x);CHKERRQ(ierr);
3880   } else if (mat->ops->solvetransposeadd){
3881     ierr = (*mat->ops->solvetransposeadd)(mat,b,y,x);CHKERRQ(ierr);
3882   } else {
3883     /* do the solve then the add manually */
3884     if (x != y) {
3885       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3886       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3887     } else {
3888       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3889       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3890       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3891       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3892       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3893       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3894     }
3895   }
3896   ierr = PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3897   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3898   PetscFunctionReturn(0);
3899 }
3900 /* ----------------------------------------------------------------*/
3901 
3902 /*@
3903    MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3904 
3905    Neighbor-wise Collective on Mat
3906 
3907    Input Parameters:
3908 +  mat - the matrix
3909 .  b - the right hand side
3910 .  omega - the relaxation factor
3911 .  flag - flag indicating the type of SOR (see below)
3912 .  shift -  diagonal shift
3913 .  its - the number of iterations
3914 -  lits - the number of local iterations
3915 
3916    Output Parameters:
3917 .  x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3918 
3919    SOR Flags:
3920 +     SOR_FORWARD_SWEEP - forward SOR
3921 .     SOR_BACKWARD_SWEEP - backward SOR
3922 .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3923 .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3924 .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3925 .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3926 .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3927          upper/lower triangular part of matrix to
3928          vector (with omega)
3929 -     SOR_ZERO_INITIAL_GUESS - zero initial guess
3930 
3931    Notes:
3932    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3933    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3934    on each processor.
3935 
3936    Application programmers will not generally use MatSOR() directly,
3937    but instead will employ the KSP/PC interface.
3938 
3939    Notes:
3940     for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3941 
3942    Notes for Advanced Users:
3943    The flags are implemented as bitwise inclusive or operations.
3944    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3945    to specify a zero initial guess for SSOR.
3946 
3947    Most users should employ the simplified KSP interface for linear solvers
3948    instead of working directly with matrix algebra routines such as this.
3949    See, e.g., KSPCreate().
3950 
3951    Vectors x and b CANNOT be the same
3952 
3953    Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3954 
3955    Level: developer
3956 
3957 @*/
3958 PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3959 {
3960   PetscErrorCode ierr;
3961 
3962   PetscFunctionBegin;
3963   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3964   PetscValidType(mat,1);
3965   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3966   PetscValidHeaderSpecific(x,VEC_CLASSID,8);
3967   PetscCheckSameComm(mat,1,b,2);
3968   PetscCheckSameComm(mat,1,x,8);
3969   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3970   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3971   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3972   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);
3973   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);
3974   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);
3975   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3976   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3977   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
3978 
3979   MatCheckPreallocated(mat,1);
3980   ierr = PetscLogEventBegin(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
3981   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);CHKERRQ(ierr);
3982   ierr = PetscLogEventEnd(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
3983   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3984   PetscFunctionReturn(0);
3985 }
3986 
3987 /*
3988       Default matrix copy routine.
3989 */
3990 PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3991 {
3992   PetscErrorCode    ierr;
3993   PetscInt          i,rstart = 0,rend = 0,nz;
3994   const PetscInt    *cwork;
3995   const PetscScalar *vwork;
3996 
3997   PetscFunctionBegin;
3998   if (B->assembled) {
3999     ierr = MatZeroEntries(B);CHKERRQ(ierr);
4000   }
4001   if (str == SAME_NONZERO_PATTERN) {
4002     ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
4003     for (i=rstart; i<rend; i++) {
4004       ierr = MatGetRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
4005       ierr = MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);CHKERRQ(ierr);
4006       ierr = MatRestoreRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
4007     }
4008   } else {
4009     ierr = MatAYPX(B,0.0,A,str);CHKERRQ(ierr);
4010   }
4011   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4012   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4013   PetscFunctionReturn(0);
4014 }
4015 
4016 /*@
4017    MatCopy - Copies a matrix to another matrix.
4018 
4019    Collective on Mat
4020 
4021    Input Parameters:
4022 +  A - the matrix
4023 -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
4024 
4025    Output Parameter:
4026 .  B - where the copy is put
4027 
4028    Notes:
4029    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4030    same nonzero pattern or the routine will crash.
4031 
4032    MatCopy() copies the matrix entries of a matrix to another existing
4033    matrix (after first zeroing the second matrix).  A related routine is
4034    MatConvert(), which first creates a new matrix and then copies the data.
4035 
4036    Level: intermediate
4037 
4038 .seealso: MatConvert(), MatDuplicate()
4039 
4040 @*/
4041 PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4042 {
4043   PetscErrorCode ierr;
4044   PetscInt       i;
4045 
4046   PetscFunctionBegin;
4047   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4048   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4049   PetscValidType(A,1);
4050   PetscValidType(B,2);
4051   PetscCheckSameComm(A,1,B,2);
4052   MatCheckPreallocated(B,2);
4053   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4054   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4055   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);
4056   MatCheckPreallocated(A,1);
4057   if (A == B) PetscFunctionReturn(0);
4058 
4059   ierr = PetscLogEventBegin(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
4060   if (A->ops->copy) {
4061     ierr = (*A->ops->copy)(A,B,str);CHKERRQ(ierr);
4062   } else { /* generic conversion */
4063     ierr = MatCopy_Basic(A,B,str);CHKERRQ(ierr);
4064   }
4065 
4066   B->stencil.dim = A->stencil.dim;
4067   B->stencil.noc = A->stencil.noc;
4068   for (i=0; i<=A->stencil.dim; i++) {
4069     B->stencil.dims[i]   = A->stencil.dims[i];
4070     B->stencil.starts[i] = A->stencil.starts[i];
4071   }
4072 
4073   ierr = PetscLogEventEnd(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
4074   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4075   PetscFunctionReturn(0);
4076 }
4077 
4078 /*@C
4079    MatConvert - Converts a matrix to another matrix, either of the same
4080    or different type.
4081 
4082    Collective on Mat
4083 
4084    Input Parameters:
4085 +  mat - the matrix
4086 .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4087    same type as the original matrix.
4088 -  reuse - denotes if the destination matrix is to be created or reused.
4089    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
4090    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).
4091 
4092    Output Parameter:
4093 .  M - pointer to place new matrix
4094 
4095    Notes:
4096    MatConvert() first creates a new matrix and then copies the data from
4097    the first matrix.  A related routine is MatCopy(), which copies the matrix
4098    entries of one matrix to another already existing matrix context.
4099 
4100    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4101    the MPI communicator of the generated matrix is always the same as the communicator
4102    of the input matrix.
4103 
4104    Level: intermediate
4105 
4106 .seealso: MatCopy(), MatDuplicate()
4107 @*/
4108 PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4109 {
4110   PetscErrorCode ierr;
4111   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4112   char           convname[256],mtype[256];
4113   Mat            B;
4114 
4115   PetscFunctionBegin;
4116   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4117   PetscValidType(mat,1);
4118   PetscValidPointer(M,3);
4119   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4120   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4121   MatCheckPreallocated(mat,1);
4122 
4123   ierr = PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);CHKERRQ(ierr);
4124   if (flg) newtype = mtype;
4125 
4126   ierr = PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);CHKERRQ(ierr);
4127   ierr = PetscStrcmp(newtype,"same",&issame);CHKERRQ(ierr);
4128   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4129   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");
4130 
4131   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4132     ierr = PetscInfo3(mat,"Early return for inplace %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);CHKERRQ(ierr);
4133     PetscFunctionReturn(0);
4134   }
4135 
4136   /* Cache Mat options because some converter use MatHeaderReplace  */
4137   issymmetric = mat->symmetric;
4138   ishermitian = mat->hermitian;
4139 
4140   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4141     ierr = PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);CHKERRQ(ierr);
4142     ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4143   } else {
4144     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4145     const char     *prefix[3] = {"seq","mpi",""};
4146     PetscInt       i;
4147     /*
4148        Order of precedence:
4149        0) See if newtype is a superclass of the current matrix.
4150        1) See if a specialized converter is known to the current matrix.
4151        2) See if a specialized converter is known to the desired matrix class.
4152        3) See if a good general converter is registered for the desired class
4153           (as of 6/27/03 only MATMPIADJ falls into this category).
4154        4) See if a good general converter is known for the current matrix.
4155        5) Use a really basic converter.
4156     */
4157 
4158     /* 0) See if newtype is a superclass of the current matrix.
4159           i.e mat is mpiaij and newtype is aij */
4160     for (i=0; i<2; i++) {
4161       ierr = PetscStrncpy(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4162       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4163       ierr = PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);CHKERRQ(ierr);
4164       ierr = PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);CHKERRQ(ierr);
4165       if (flg) {
4166         if (reuse == MAT_INPLACE_MATRIX) {
4167           PetscFunctionReturn(0);
4168         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4169           ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4170           PetscFunctionReturn(0);
4171         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4172           ierr = MatCopy(mat,*M,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
4173           PetscFunctionReturn(0);
4174         }
4175       }
4176     }
4177     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4178     for (i=0; i<3; i++) {
4179       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4180       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4181       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4182       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4183       ierr = PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));CHKERRQ(ierr);
4184       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4185       ierr = PetscObjectQueryFunction((PetscObject)mat,convname,&conv);CHKERRQ(ierr);
4186       ierr = PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);CHKERRQ(ierr);
4187       if (conv) goto foundconv;
4188     }
4189 
4190     /* 2)  See if a specialized converter is known to the desired matrix class. */
4191     ierr = MatCreate(PetscObjectComm((PetscObject)mat),&B);CHKERRQ(ierr);
4192     ierr = MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);CHKERRQ(ierr);
4193     ierr = MatSetType(B,newtype);CHKERRQ(ierr);
4194     for (i=0; i<3; i++) {
4195       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4196       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4197       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4198       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4199       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4200       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4201       ierr = PetscObjectQueryFunction((PetscObject)B,convname,&conv);CHKERRQ(ierr);
4202       ierr = PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);CHKERRQ(ierr);
4203       if (conv) {
4204         ierr = MatDestroy(&B);CHKERRQ(ierr);
4205         goto foundconv;
4206       }
4207     }
4208 
4209     /* 3) See if a good general converter is registered for the desired class */
4210     conv = B->ops->convertfrom;
4211     ierr = PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);CHKERRQ(ierr);
4212     ierr = MatDestroy(&B);CHKERRQ(ierr);
4213     if (conv) goto foundconv;
4214 
4215     /* 4) See if a good general converter is known for the current matrix */
4216     if (mat->ops->convert) conv = mat->ops->convert;
4217 
4218     ierr = PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);CHKERRQ(ierr);
4219     if (conv) goto foundconv;
4220 
4221     /* 5) Use a really basic converter. */
4222     ierr = PetscInfo(mat,"Using MatConvert_Basic\n");CHKERRQ(ierr);
4223     conv = MatConvert_Basic;
4224 
4225 foundconv:
4226     ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4227     ierr = (*conv)(mat,newtype,reuse,M);CHKERRQ(ierr);
4228     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4229       /* the block sizes must be same if the mappings are copied over */
4230       (*M)->rmap->bs = mat->rmap->bs;
4231       (*M)->cmap->bs = mat->cmap->bs;
4232       ierr = PetscObjectReference((PetscObject)mat->rmap->mapping);CHKERRQ(ierr);
4233       ierr = PetscObjectReference((PetscObject)mat->cmap->mapping);CHKERRQ(ierr);
4234       (*M)->rmap->mapping = mat->rmap->mapping;
4235       (*M)->cmap->mapping = mat->cmap->mapping;
4236     }
4237     (*M)->stencil.dim = mat->stencil.dim;
4238     (*M)->stencil.noc = mat->stencil.noc;
4239     for (i=0; i<=mat->stencil.dim; i++) {
4240       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4241       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4242     }
4243     ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4244   }
4245   ierr = PetscObjectStateIncrease((PetscObject)*M);CHKERRQ(ierr);
4246 
4247   /* Copy Mat options */
4248   if (issymmetric) {
4249     ierr = MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
4250   }
4251   if (ishermitian) {
4252     ierr = MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
4253   }
4254   PetscFunctionReturn(0);
4255 }
4256 
4257 /*@C
4258    MatFactorGetSolverType - Returns name of the package providing the factorization routines
4259 
4260    Not Collective
4261 
4262    Input Parameter:
4263 .  mat - the matrix, must be a factored matrix
4264 
4265    Output Parameter:
4266 .   type - the string name of the package (do not free this string)
4267 
4268    Notes:
4269       In Fortran you pass in a empty string and the package name will be copied into it.
4270     (Make sure the string is long enough)
4271 
4272    Level: intermediate
4273 
4274 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4275 @*/
4276 PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4277 {
4278   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4279 
4280   PetscFunctionBegin;
4281   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4282   PetscValidType(mat,1);
4283   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4284   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);CHKERRQ(ierr);
4285   if (!conv) {
4286     *type = MATSOLVERPETSC;
4287   } else {
4288     ierr = (*conv)(mat,type);CHKERRQ(ierr);
4289   }
4290   PetscFunctionReturn(0);
4291 }
4292 
4293 typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4294 struct _MatSolverTypeForSpecifcType {
4295   MatType                        mtype;
4296   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4297   MatSolverTypeForSpecifcType next;
4298 };
4299 
4300 typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4301 struct _MatSolverTypeHolder {
4302   char                           *name;
4303   MatSolverTypeForSpecifcType handlers;
4304   MatSolverTypeHolder         next;
4305 };
4306 
4307 static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4308 
4309 /*@C
4310    MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type
4311 
4312    Input Parameters:
4313 +    package - name of the package, for example petsc or superlu
4314 .    mtype - the matrix type that works with this package
4315 .    ftype - the type of factorization supported by the package
4316 -    getfactor - routine that will create the factored matrix ready to be used
4317 
4318     Level: intermediate
4319 
4320 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4321 @*/
4322 PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4323 {
4324   PetscErrorCode              ierr;
4325   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4326   PetscBool                   flg;
4327   MatSolverTypeForSpecifcType inext,iprev = NULL;
4328 
4329   PetscFunctionBegin;
4330   ierr = MatInitializePackage();CHKERRQ(ierr);
4331   if (!next) {
4332     ierr = PetscNew(&MatSolverTypeHolders);CHKERRQ(ierr);
4333     ierr = PetscStrallocpy(package,&MatSolverTypeHolders->name);CHKERRQ(ierr);
4334     ierr = PetscNew(&MatSolverTypeHolders->handlers);CHKERRQ(ierr);
4335     ierr = PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);CHKERRQ(ierr);
4336     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4337     PetscFunctionReturn(0);
4338   }
4339   while (next) {
4340     ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4341     if (flg) {
4342       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4343       inext = next->handlers;
4344       while (inext) {
4345         ierr = PetscStrcasecmp(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4346         if (flg) {
4347           inext->getfactor[(int)ftype-1] = getfactor;
4348           PetscFunctionReturn(0);
4349         }
4350         iprev = inext;
4351         inext = inext->next;
4352       }
4353       ierr = PetscNew(&iprev->next);CHKERRQ(ierr);
4354       ierr = PetscStrallocpy(mtype,(char **)&iprev->next->mtype);CHKERRQ(ierr);
4355       iprev->next->getfactor[(int)ftype-1] = getfactor;
4356       PetscFunctionReturn(0);
4357     }
4358     prev = next;
4359     next = next->next;
4360   }
4361   ierr = PetscNew(&prev->next);CHKERRQ(ierr);
4362   ierr = PetscStrallocpy(package,&prev->next->name);CHKERRQ(ierr);
4363   ierr = PetscNew(&prev->next->handlers);CHKERRQ(ierr);
4364   ierr = PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);CHKERRQ(ierr);
4365   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4366   PetscFunctionReturn(0);
4367 }
4368 
4369 /*@C
4370    MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4371 
4372    Input Parameters:
4373 +    package - name of the package, for example petsc or superlu
4374 .    ftype - the type of factorization supported by the package
4375 -    mtype - the matrix type that works with this package
4376 
4377    Output Parameters:
4378 +   foundpackage - PETSC_TRUE if the package was registered
4379 .   foundmtype - PETSC_TRUE if the package supports the requested mtype
4380 -   getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4381 
4382     Level: intermediate
4383 
4384 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4385 @*/
4386 PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4387 {
4388   PetscErrorCode              ierr;
4389   MatSolverTypeHolder         next = MatSolverTypeHolders;
4390   PetscBool                   flg;
4391   MatSolverTypeForSpecifcType inext;
4392 
4393   PetscFunctionBegin;
4394   if (foundpackage) *foundpackage = PETSC_FALSE;
4395   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4396   if (getfactor)    *getfactor    = NULL;
4397 
4398   if (package) {
4399     while (next) {
4400       ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4401       if (flg) {
4402         if (foundpackage) *foundpackage = PETSC_TRUE;
4403         inext = next->handlers;
4404         while (inext) {
4405           ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4406           if (flg) {
4407             if (foundmtype) *foundmtype = PETSC_TRUE;
4408             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4409             PetscFunctionReturn(0);
4410           }
4411           inext = inext->next;
4412         }
4413       }
4414       next = next->next;
4415     }
4416   } else {
4417     while (next) {
4418       inext = next->handlers;
4419       while (inext) {
4420         ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4421         if (flg && inext->getfactor[(int)ftype-1]) {
4422           if (foundpackage) *foundpackage = PETSC_TRUE;
4423           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4424           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
4425           PetscFunctionReturn(0);
4426         }
4427         inext = inext->next;
4428       }
4429       next = next->next;
4430     }
4431   }
4432   PetscFunctionReturn(0);
4433 }
4434 
4435 PetscErrorCode MatSolverTypeDestroy(void)
4436 {
4437   PetscErrorCode              ierr;
4438   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4439   MatSolverTypeForSpecifcType inext,iprev;
4440 
4441   PetscFunctionBegin;
4442   while (next) {
4443     ierr = PetscFree(next->name);CHKERRQ(ierr);
4444     inext = next->handlers;
4445     while (inext) {
4446       ierr = PetscFree(inext->mtype);CHKERRQ(ierr);
4447       iprev = inext;
4448       inext = inext->next;
4449       ierr = PetscFree(iprev);CHKERRQ(ierr);
4450     }
4451     prev = next;
4452     next = next->next;
4453     ierr = PetscFree(prev);CHKERRQ(ierr);
4454   }
4455   MatSolverTypeHolders = NULL;
4456   PetscFunctionReturn(0);
4457 }
4458 
4459 /*@C
4460    MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4461 
4462    Collective on Mat
4463 
4464    Input Parameters:
4465 +  mat - the matrix
4466 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4467 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4468 
4469    Output Parameters:
4470 .  f - the factor matrix used with MatXXFactorSymbolic() calls
4471 
4472    Notes:
4473       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4474      such as pastix, superlu, mumps etc.
4475 
4476       PETSc must have been ./configure to use the external solver, using the option --download-package
4477 
4478    Level: intermediate
4479 
4480 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4481 @*/
4482 PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4483 {
4484   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4485   PetscBool      foundpackage,foundmtype;
4486 
4487   PetscFunctionBegin;
4488   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4489   PetscValidType(mat,1);
4490 
4491   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4492   MatCheckPreallocated(mat,1);
4493 
4494   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);CHKERRQ(ierr);
4495   if (!foundpackage) {
4496     if (type) {
4497       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);
4498     } else {
4499       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);
4500     }
4501   }
4502   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4503   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);
4504 
4505   ierr = (*conv)(mat,ftype,f);CHKERRQ(ierr);
4506   PetscFunctionReturn(0);
4507 }
4508 
4509 /*@C
4510    MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4511 
4512    Not Collective
4513 
4514    Input Parameters:
4515 +  mat - the matrix
4516 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4517 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4518 
4519    Output Parameter:
4520 .    flg - PETSC_TRUE if the factorization is available
4521 
4522    Notes:
4523       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4524      such as pastix, superlu, mumps etc.
4525 
4526       PETSc must have been ./configure to use the external solver, using the option --download-package
4527 
4528    Level: intermediate
4529 
4530 .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4531 @*/
4532 PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4533 {
4534   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4535 
4536   PetscFunctionBegin;
4537   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4538   PetscValidType(mat,1);
4539 
4540   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4541   MatCheckPreallocated(mat,1);
4542 
4543   *flg = PETSC_FALSE;
4544   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);CHKERRQ(ierr);
4545   if (gconv) {
4546     *flg = PETSC_TRUE;
4547   }
4548   PetscFunctionReturn(0);
4549 }
4550 
4551 #include <petscdmtypes.h>
4552 
4553 /*@
4554    MatDuplicate - Duplicates a matrix including the non-zero structure.
4555 
4556    Collective on Mat
4557 
4558    Input Parameters:
4559 +  mat - the matrix
4560 -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4561         See the manual page for MatDuplicateOption for an explanation of these options.
4562 
4563    Output Parameter:
4564 .  M - pointer to place new matrix
4565 
4566    Level: intermediate
4567 
4568    Notes:
4569     You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4570     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.
4571 
4572 .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4573 @*/
4574 PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4575 {
4576   PetscErrorCode ierr;
4577   Mat            B;
4578   PetscInt       i;
4579   DM             dm;
4580   void           (*viewf)(void);
4581 
4582   PetscFunctionBegin;
4583   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4584   PetscValidType(mat,1);
4585   PetscValidPointer(M,3);
4586   if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4587   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4588   MatCheckPreallocated(mat,1);
4589 
4590   *M = 0;
4591   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4592   ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4593   ierr = (*mat->ops->duplicate)(mat,op,M);CHKERRQ(ierr);
4594   B    = *M;
4595 
4596   ierr = MatGetOperation(mat,MATOP_VIEW,&viewf);CHKERRQ(ierr);
4597   if (viewf) {
4598     ierr = MatSetOperation(B,MATOP_VIEW,viewf);CHKERRQ(ierr);
4599   }
4600 
4601   B->stencil.dim = mat->stencil.dim;
4602   B->stencil.noc = mat->stencil.noc;
4603   for (i=0; i<=mat->stencil.dim; i++) {
4604     B->stencil.dims[i]   = mat->stencil.dims[i];
4605     B->stencil.starts[i] = mat->stencil.starts[i];
4606   }
4607 
4608   B->nooffproczerorows = mat->nooffproczerorows;
4609   B->nooffprocentries  = mat->nooffprocentries;
4610 
4611   ierr = PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);CHKERRQ(ierr);
4612   if (dm) {
4613     ierr = PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);CHKERRQ(ierr);
4614   }
4615   ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4616   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4617   PetscFunctionReturn(0);
4618 }
4619 
4620 /*@
4621    MatGetDiagonal - Gets the diagonal of a matrix.
4622 
4623    Logically Collective on Mat
4624 
4625    Input Parameters:
4626 +  mat - the matrix
4627 -  v - the vector for storing the diagonal
4628 
4629    Output Parameter:
4630 .  v - the diagonal of the matrix
4631 
4632    Level: intermediate
4633 
4634    Note:
4635    Currently only correct in parallel for square matrices.
4636 
4637 .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4638 @*/
4639 PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4640 {
4641   PetscErrorCode ierr;
4642 
4643   PetscFunctionBegin;
4644   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4645   PetscValidType(mat,1);
4646   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4647   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4648   if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4649   MatCheckPreallocated(mat,1);
4650 
4651   ierr = (*mat->ops->getdiagonal)(mat,v);CHKERRQ(ierr);
4652   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4653   PetscFunctionReturn(0);
4654 }
4655 
4656 /*@C
4657    MatGetRowMin - Gets the minimum value (of the real part) of each
4658         row of the matrix
4659 
4660    Logically Collective on Mat
4661 
4662    Input Parameters:
4663 .  mat - the matrix
4664 
4665    Output Parameter:
4666 +  v - the vector for storing the maximums
4667 -  idx - the indices of the column found for each row (optional)
4668 
4669    Level: intermediate
4670 
4671    Notes:
4672     The result of this call are the same as if one converted the matrix to dense format
4673       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4674 
4675     This code is only implemented for a couple of matrix formats.
4676 
4677 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4678           MatGetRowMax()
4679 @*/
4680 PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4681 {
4682   PetscErrorCode ierr;
4683 
4684   PetscFunctionBegin;
4685   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4686   PetscValidType(mat,1);
4687   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4688   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4689   if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4690   MatCheckPreallocated(mat,1);
4691 
4692   ierr = (*mat->ops->getrowmin)(mat,v,idx);CHKERRQ(ierr);
4693   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4694   PetscFunctionReturn(0);
4695 }
4696 
4697 /*@C
4698    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4699         row of the matrix
4700 
4701    Logically Collective on Mat
4702 
4703    Input Parameters:
4704 .  mat - the matrix
4705 
4706    Output Parameter:
4707 +  v - the vector for storing the minimums
4708 -  idx - the indices of the column found for each row (or NULL if not needed)
4709 
4710    Level: intermediate
4711 
4712    Notes:
4713     if a row is completely empty or has only 0.0 values then the idx[] value for that
4714     row is 0 (the first column).
4715 
4716     This code is only implemented for a couple of matrix formats.
4717 
4718 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4719 @*/
4720 PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4721 {
4722   PetscErrorCode ierr;
4723 
4724   PetscFunctionBegin;
4725   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4726   PetscValidType(mat,1);
4727   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4728   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4729   if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4730   MatCheckPreallocated(mat,1);
4731   if (idx) {ierr = PetscArrayzero(idx,mat->rmap->n);CHKERRQ(ierr);}
4732 
4733   ierr = (*mat->ops->getrowminabs)(mat,v,idx);CHKERRQ(ierr);
4734   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4735   PetscFunctionReturn(0);
4736 }
4737 
4738 /*@C
4739    MatGetRowMax - Gets the maximum value (of the real part) of each
4740         row of the matrix
4741 
4742    Logically Collective on Mat
4743 
4744    Input Parameters:
4745 .  mat - the matrix
4746 
4747    Output Parameter:
4748 +  v - the vector for storing the maximums
4749 -  idx - the indices of the column found for each row (optional)
4750 
4751    Level: intermediate
4752 
4753    Notes:
4754     The result of this call are the same as if one converted the matrix to dense format
4755       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4756 
4757     This code is only implemented for a couple of matrix formats.
4758 
4759 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4760 @*/
4761 PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4762 {
4763   PetscErrorCode ierr;
4764 
4765   PetscFunctionBegin;
4766   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4767   PetscValidType(mat,1);
4768   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4769   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4770   if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4771   MatCheckPreallocated(mat,1);
4772 
4773   ierr = (*mat->ops->getrowmax)(mat,v,idx);CHKERRQ(ierr);
4774   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4775   PetscFunctionReturn(0);
4776 }
4777 
4778 /*@C
4779    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4780         row of the matrix
4781 
4782    Logically Collective on Mat
4783 
4784    Input Parameters:
4785 .  mat - the matrix
4786 
4787    Output Parameter:
4788 +  v - the vector for storing the maximums
4789 -  idx - the indices of the column found for each row (or NULL if not needed)
4790 
4791    Level: intermediate
4792 
4793    Notes:
4794     if a row is completely empty or has only 0.0 values then the idx[] value for that
4795     row is 0 (the first column).
4796 
4797     This code is only implemented for a couple of matrix formats.
4798 
4799 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4800 @*/
4801 PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4802 {
4803   PetscErrorCode ierr;
4804 
4805   PetscFunctionBegin;
4806   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4807   PetscValidType(mat,1);
4808   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4809   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4810   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4811   MatCheckPreallocated(mat,1);
4812   if (idx) {ierr = PetscArrayzero(idx,mat->rmap->n);CHKERRQ(ierr);}
4813 
4814   ierr = (*mat->ops->getrowmaxabs)(mat,v,idx);CHKERRQ(ierr);
4815   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4816   PetscFunctionReturn(0);
4817 }
4818 
4819 /*@
4820    MatGetRowSum - Gets the sum of each row of the matrix
4821 
4822    Logically or Neighborhood Collective on Mat
4823 
4824    Input Parameters:
4825 .  mat - the matrix
4826 
4827    Output Parameter:
4828 .  v - the vector for storing the sum of rows
4829 
4830    Level: intermediate
4831 
4832    Notes:
4833     This code is slow since it is not currently specialized for different formats
4834 
4835 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4836 @*/
4837 PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4838 {
4839   Vec            ones;
4840   PetscErrorCode ierr;
4841 
4842   PetscFunctionBegin;
4843   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4844   PetscValidType(mat,1);
4845   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4846   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4847   MatCheckPreallocated(mat,1);
4848   ierr = MatCreateVecs(mat,&ones,NULL);CHKERRQ(ierr);
4849   ierr = VecSet(ones,1.);CHKERRQ(ierr);
4850   ierr = MatMult(mat,ones,v);CHKERRQ(ierr);
4851   ierr = VecDestroy(&ones);CHKERRQ(ierr);
4852   PetscFunctionReturn(0);
4853 }
4854 
4855 /*@
4856    MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4857 
4858    Collective on Mat
4859 
4860    Input Parameter:
4861 +  mat - the matrix to transpose
4862 -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
4863 
4864    Output Parameters:
4865 .  B - the transpose
4866 
4867    Notes:
4868      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
4869 
4870      MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
4871 
4872      Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4873 
4874    Level: intermediate
4875 
4876 .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4877 @*/
4878 PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4879 {
4880   PetscErrorCode ierr;
4881 
4882   PetscFunctionBegin;
4883   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4884   PetscValidType(mat,1);
4885   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4886   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4887   if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4888   if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4889   if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4890   MatCheckPreallocated(mat,1);
4891 
4892   ierr = PetscLogEventBegin(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4893   ierr = (*mat->ops->transpose)(mat,reuse,B);CHKERRQ(ierr);
4894   ierr = PetscLogEventEnd(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4895   if (B) {ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);}
4896   PetscFunctionReturn(0);
4897 }
4898 
4899 /*@
4900    MatIsTranspose - Test whether a matrix is another one's transpose,
4901         or its own, in which case it tests symmetry.
4902 
4903    Collective on Mat
4904 
4905    Input Parameter:
4906 +  A - the matrix to test
4907 -  B - the matrix to test against, this can equal the first parameter
4908 
4909    Output Parameters:
4910 .  flg - the result
4911 
4912    Notes:
4913    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4914    has a running time of the order of the number of nonzeros; the parallel
4915    test involves parallel copies of the block-offdiagonal parts of the matrix.
4916 
4917    Level: intermediate
4918 
4919 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4920 @*/
4921 PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4922 {
4923   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4924 
4925   PetscFunctionBegin;
4926   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4927   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4928   PetscValidBoolPointer(flg,3);
4929   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);CHKERRQ(ierr);
4930   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);CHKERRQ(ierr);
4931   *flg = PETSC_FALSE;
4932   if (f && g) {
4933     if (f == g) {
4934       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
4935     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4936   } else {
4937     MatType mattype;
4938     if (!f) {
4939       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
4940     } else {
4941       ierr = MatGetType(B,&mattype);CHKERRQ(ierr);
4942     }
4943     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
4944   }
4945   PetscFunctionReturn(0);
4946 }
4947 
4948 /*@
4949    MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
4950 
4951    Collective on Mat
4952 
4953    Input Parameter:
4954 +  mat - the matrix to transpose and complex conjugate
4955 -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose
4956 
4957    Output Parameters:
4958 .  B - the Hermitian
4959 
4960    Level: intermediate
4961 
4962 .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4963 @*/
4964 PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4965 {
4966   PetscErrorCode ierr;
4967 
4968   PetscFunctionBegin;
4969   ierr = MatTranspose(mat,reuse,B);CHKERRQ(ierr);
4970 #if defined(PETSC_USE_COMPLEX)
4971   ierr = MatConjugate(*B);CHKERRQ(ierr);
4972 #endif
4973   PetscFunctionReturn(0);
4974 }
4975 
4976 /*@
4977    MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
4978 
4979    Collective on Mat
4980 
4981    Input Parameter:
4982 +  A - the matrix to test
4983 -  B - the matrix to test against, this can equal the first parameter
4984 
4985    Output Parameters:
4986 .  flg - the result
4987 
4988    Notes:
4989    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4990    has a running time of the order of the number of nonzeros; the parallel
4991    test involves parallel copies of the block-offdiagonal parts of the matrix.
4992 
4993    Level: intermediate
4994 
4995 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4996 @*/
4997 PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4998 {
4999   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
5000 
5001   PetscFunctionBegin;
5002   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
5003   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
5004   PetscValidBoolPointer(flg,3);
5005   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);CHKERRQ(ierr);
5006   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);CHKERRQ(ierr);
5007   if (f && g) {
5008     if (f==g) {
5009       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
5010     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5011   }
5012   PetscFunctionReturn(0);
5013 }
5014 
5015 /*@
5016    MatPermute - Creates a new matrix with rows and columns permuted from the
5017    original.
5018 
5019    Collective on Mat
5020 
5021    Input Parameters:
5022 +  mat - the matrix to permute
5023 .  row - row permutation, each processor supplies only the permutation for its rows
5024 -  col - column permutation, each processor supplies only the permutation for its columns
5025 
5026    Output Parameters:
5027 .  B - the permuted matrix
5028 
5029    Level: advanced
5030 
5031    Note:
5032    The index sets map from row/col of permuted matrix to row/col of original matrix.
5033    The index sets should be on the same communicator as Mat and have the same local sizes.
5034 
5035 .seealso: MatGetOrdering(), ISAllGather()
5036 
5037 @*/
5038 PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5039 {
5040   PetscErrorCode ierr;
5041 
5042   PetscFunctionBegin;
5043   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5044   PetscValidType(mat,1);
5045   PetscValidHeaderSpecific(row,IS_CLASSID,2);
5046   PetscValidHeaderSpecific(col,IS_CLASSID,3);
5047   PetscValidPointer(B,4);
5048   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5049   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5050   if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
5051   MatCheckPreallocated(mat,1);
5052 
5053   ierr = (*mat->ops->permute)(mat,row,col,B);CHKERRQ(ierr);
5054   ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);
5055   PetscFunctionReturn(0);
5056 }
5057 
5058 /*@
5059    MatEqual - Compares two matrices.
5060 
5061    Collective on Mat
5062 
5063    Input Parameters:
5064 +  A - the first matrix
5065 -  B - the second matrix
5066 
5067    Output Parameter:
5068 .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
5069 
5070    Level: intermediate
5071 
5072 @*/
5073 PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5074 {
5075   PetscErrorCode ierr;
5076 
5077   PetscFunctionBegin;
5078   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
5079   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
5080   PetscValidType(A,1);
5081   PetscValidType(B,2);
5082   PetscValidBoolPointer(flg,3);
5083   PetscCheckSameComm(A,1,B,2);
5084   MatCheckPreallocated(B,2);
5085   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5086   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5087   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);
5088   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5089   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5090   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);
5091   MatCheckPreallocated(A,1);
5092 
5093   ierr = (*A->ops->equal)(A,B,flg);CHKERRQ(ierr);
5094   PetscFunctionReturn(0);
5095 }
5096 
5097 /*@
5098    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5099    matrices that are stored as vectors.  Either of the two scaling
5100    matrices can be NULL.
5101 
5102    Collective on Mat
5103 
5104    Input Parameters:
5105 +  mat - the matrix to be scaled
5106 .  l - the left scaling vector (or NULL)
5107 -  r - the right scaling vector (or NULL)
5108 
5109    Notes:
5110    MatDiagonalScale() computes A = LAR, where
5111    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5112    The L scales the rows of the matrix, the R scales the columns of the matrix.
5113 
5114    Level: intermediate
5115 
5116 
5117 .seealso: MatScale(), MatShift(), MatDiagonalSet()
5118 @*/
5119 PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5120 {
5121   PetscErrorCode ierr;
5122 
5123   PetscFunctionBegin;
5124   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5125   PetscValidType(mat,1);
5126   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5127   if (l) {PetscValidHeaderSpecific(l,VEC_CLASSID,2);PetscCheckSameComm(mat,1,l,2);}
5128   if (r) {PetscValidHeaderSpecific(r,VEC_CLASSID,3);PetscCheckSameComm(mat,1,r,3);}
5129   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5130   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5131   MatCheckPreallocated(mat,1);
5132 
5133   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5134   ierr = (*mat->ops->diagonalscale)(mat,l,r);CHKERRQ(ierr);
5135   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5136   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5137   PetscFunctionReturn(0);
5138 }
5139 
5140 /*@
5141     MatScale - Scales all elements of a matrix by a given number.
5142 
5143     Logically Collective on Mat
5144 
5145     Input Parameters:
5146 +   mat - the matrix to be scaled
5147 -   a  - the scaling value
5148 
5149     Output Parameter:
5150 .   mat - the scaled matrix
5151 
5152     Level: intermediate
5153 
5154 .seealso: MatDiagonalScale()
5155 @*/
5156 PetscErrorCode MatScale(Mat mat,PetscScalar a)
5157 {
5158   PetscErrorCode ierr;
5159 
5160   PetscFunctionBegin;
5161   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5162   PetscValidType(mat,1);
5163   if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5164   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5165   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5166   PetscValidLogicalCollectiveScalar(mat,a,2);
5167   MatCheckPreallocated(mat,1);
5168 
5169   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5170   if (a != (PetscScalar)1.0) {
5171     ierr = (*mat->ops->scale)(mat,a);CHKERRQ(ierr);
5172     ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5173   }
5174   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5175   PetscFunctionReturn(0);
5176 }
5177 
5178 /*@
5179    MatNorm - Calculates various norms of a matrix.
5180 
5181    Collective on Mat
5182 
5183    Input Parameters:
5184 +  mat - the matrix
5185 -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5186 
5187    Output Parameters:
5188 .  nrm - the resulting norm
5189 
5190    Level: intermediate
5191 
5192 @*/
5193 PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5194 {
5195   PetscErrorCode ierr;
5196 
5197   PetscFunctionBegin;
5198   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5199   PetscValidType(mat,1);
5200   PetscValidScalarPointer(nrm,3);
5201 
5202   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5203   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5204   if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5205   MatCheckPreallocated(mat,1);
5206 
5207   ierr = (*mat->ops->norm)(mat,type,nrm);CHKERRQ(ierr);
5208   PetscFunctionReturn(0);
5209 }
5210 
5211 /*
5212      This variable is used to prevent counting of MatAssemblyBegin() that
5213    are called from within a MatAssemblyEnd().
5214 */
5215 static PetscInt MatAssemblyEnd_InUse = 0;
5216 /*@
5217    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5218    be called after completing all calls to MatSetValues().
5219 
5220    Collective on Mat
5221 
5222    Input Parameters:
5223 +  mat - the matrix
5224 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5225 
5226    Notes:
5227    MatSetValues() generally caches the values.  The matrix is ready to
5228    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5229    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5230    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5231    using the matrix.
5232 
5233    ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5234    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
5235    a global collective operation requring all processes that share the matrix.
5236 
5237    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5238    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5239    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5240 
5241    Level: beginner
5242 
5243 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5244 @*/
5245 PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5246 {
5247   PetscErrorCode ierr;
5248 
5249   PetscFunctionBegin;
5250   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5251   PetscValidType(mat,1);
5252   MatCheckPreallocated(mat,1);
5253   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5254   if (mat->assembled) {
5255     mat->was_assembled = PETSC_TRUE;
5256     mat->assembled     = PETSC_FALSE;
5257   }
5258 
5259   if (!MatAssemblyEnd_InUse) {
5260     ierr = PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5261     if (mat->ops->assemblybegin) {ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);}
5262     ierr = PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5263   } else if (mat->ops->assemblybegin) {
5264     ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);
5265   }
5266   PetscFunctionReturn(0);
5267 }
5268 
5269 /*@
5270    MatAssembled - Indicates if a matrix has been assembled and is ready for
5271      use; for example, in matrix-vector product.
5272 
5273    Not Collective
5274 
5275    Input Parameter:
5276 .  mat - the matrix
5277 
5278    Output Parameter:
5279 .  assembled - PETSC_TRUE or PETSC_FALSE
5280 
5281    Level: advanced
5282 
5283 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5284 @*/
5285 PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5286 {
5287   PetscFunctionBegin;
5288   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5289   PetscValidPointer(assembled,2);
5290   *assembled = mat->assembled;
5291   PetscFunctionReturn(0);
5292 }
5293 
5294 /*@
5295    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5296    be called after MatAssemblyBegin().
5297 
5298    Collective on Mat
5299 
5300    Input Parameters:
5301 +  mat - the matrix
5302 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5303 
5304    Options Database Keys:
5305 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5306 .  -mat_view ::ascii_info_detail - Prints more detailed info
5307 .  -mat_view - Prints matrix in ASCII format
5308 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5309 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5310 .  -display <name> - Sets display name (default is host)
5311 .  -draw_pause <sec> - Sets number of seconds to pause after display
5312 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab )
5313 .  -viewer_socket_machine <machine> - Machine to use for socket
5314 .  -viewer_socket_port <port> - Port number to use for socket
5315 -  -mat_view binary:filename[:append] - Save matrix to file in binary format
5316 
5317    Notes:
5318    MatSetValues() generally caches the values.  The matrix is ready to
5319    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5320    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5321    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5322    using the matrix.
5323 
5324    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5325    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5326    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5327 
5328    Level: beginner
5329 
5330 .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5331 @*/
5332 PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5333 {
5334   PetscErrorCode  ierr;
5335   static PetscInt inassm = 0;
5336   PetscBool       flg    = PETSC_FALSE;
5337 
5338   PetscFunctionBegin;
5339   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5340   PetscValidType(mat,1);
5341 
5342   inassm++;
5343   MatAssemblyEnd_InUse++;
5344   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5345     ierr = PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5346     if (mat->ops->assemblyend) {
5347       ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5348     }
5349     ierr = PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5350   } else if (mat->ops->assemblyend) {
5351     ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5352   }
5353 
5354   /* Flush assembly is not a true assembly */
5355   if (type != MAT_FLUSH_ASSEMBLY) {
5356     mat->num_ass++;
5357     mat->assembled        = PETSC_TRUE;
5358     mat->ass_nonzerostate = mat->nonzerostate;
5359   }
5360 
5361   mat->insertmode = NOT_SET_VALUES;
5362   MatAssemblyEnd_InUse--;
5363   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5364   if (!mat->symmetric_eternal) {
5365     mat->symmetric_set              = PETSC_FALSE;
5366     mat->hermitian_set              = PETSC_FALSE;
5367     mat->structurally_symmetric_set = PETSC_FALSE;
5368   }
5369   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5370     ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5371 
5372     if (mat->checksymmetryonassembly) {
5373       ierr = MatIsSymmetric(mat,mat->checksymmetrytol,&flg);CHKERRQ(ierr);
5374       if (flg) {
5375         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5376       } else {
5377         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5378       }
5379     }
5380     if (mat->nullsp && mat->checknullspaceonassembly) {
5381       ierr = MatNullSpaceTest(mat->nullsp,mat,NULL);CHKERRQ(ierr);
5382     }
5383   }
5384   inassm--;
5385   PetscFunctionReturn(0);
5386 }
5387 
5388 /*@
5389    MatSetOption - Sets a parameter option for a matrix. Some options
5390    may be specific to certain storage formats.  Some options
5391    determine how values will be inserted (or added). Sorted,
5392    row-oriented input will generally assemble the fastest. The default
5393    is row-oriented.
5394 
5395    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5396 
5397    Input Parameters:
5398 +  mat - the matrix
5399 .  option - the option, one of those listed below (and possibly others),
5400 -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5401 
5402   Options Describing Matrix Structure:
5403 +    MAT_SPD - symmetric positive definite
5404 .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5405 .    MAT_HERMITIAN - transpose is the complex conjugation
5406 .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5407 -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5408                             you set to be kept with all future use of the matrix
5409                             including after MatAssemblyBegin/End() which could
5410                             potentially change the symmetry structure, i.e. you
5411                             KNOW the matrix will ALWAYS have the property you set.
5412                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5413                             the relevant flags must be set independently.
5414 
5415 
5416    Options For Use with MatSetValues():
5417    Insert a logically dense subblock, which can be
5418 .    MAT_ROW_ORIENTED - row-oriented (default)
5419 
5420    Note these options reflect the data you pass in with MatSetValues(); it has
5421    nothing to do with how the data is stored internally in the matrix
5422    data structure.
5423 
5424    When (re)assembling a matrix, we can restrict the input for
5425    efficiency/debugging purposes.  These options include:
5426 +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5427 .    MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5428 .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5429 .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5430 .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5431 .    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5432         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5433         performance for very large process counts.
5434 -    MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5435         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5436         functions, instead sending only neighbor messages.
5437 
5438    Notes:
5439    Except for MAT_UNUSED_NONZERO_LOCATION_ERR and  MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5440 
5441    Some options are relevant only for particular matrix types and
5442    are thus ignored by others.  Other options are not supported by
5443    certain matrix types and will generate an error message if set.
5444 
5445    If using a Fortran 77 module to compute a matrix, one may need to
5446    use the column-oriented option (or convert to the row-oriented
5447    format).
5448 
5449    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5450    that would generate a new entry in the nonzero structure is instead
5451    ignored.  Thus, if memory has not alredy been allocated for this particular
5452    data, then the insertion is ignored. For dense matrices, in which
5453    the entire array is allocated, no entries are ever ignored.
5454    Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5455 
5456    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5457    that would generate a new entry in the nonzero structure instead produces
5458    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
5459 
5460    MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5461    that would generate a new entry that has not been preallocated will
5462    instead produce an error. (Currently supported for AIJ and BAIJ formats
5463    only.) This is a useful flag when debugging matrix memory preallocation.
5464    If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5465 
5466    MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5467    other processors should be dropped, rather than stashed.
5468    This is useful if you know that the "owning" processor is also
5469    always generating the correct matrix entries, so that PETSc need
5470    not transfer duplicate entries generated on another processor.
5471 
5472    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5473    searches during matrix assembly. When this flag is set, the hash table
5474    is created during the first Matrix Assembly. This hash table is
5475    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5476    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5477    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5478    supported by MATMPIBAIJ format only.
5479 
5480    MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5481    are kept in the nonzero structure
5482 
5483    MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5484    a zero location in the matrix
5485 
5486    MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5487 
5488    MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5489         zero row routines and thus improves performance for very large process counts.
5490 
5491    MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5492         part of the matrix (since they should match the upper triangular part).
5493 
5494    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5495                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5496                      with finite difference schemes with non-periodic boundary conditions.
5497    Notes:
5498     Can only be called after MatSetSizes() and MatSetType() have been set.
5499 
5500    Level: intermediate
5501 
5502 .seealso:  MatOption, Mat
5503 
5504 @*/
5505 PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5506 {
5507   PetscErrorCode ierr;
5508 
5509   PetscFunctionBegin;
5510   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5511   PetscValidType(mat,1);
5512   if (op > 0) {
5513     PetscValidLogicalCollectiveEnum(mat,op,2);
5514     PetscValidLogicalCollectiveBool(mat,flg,3);
5515   }
5516 
5517   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);
5518   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()");
5519 
5520   switch (op) {
5521   case MAT_NO_OFF_PROC_ENTRIES:
5522     mat->nooffprocentries = flg;
5523     PetscFunctionReturn(0);
5524     break;
5525   case MAT_SUBSET_OFF_PROC_ENTRIES:
5526     mat->assembly_subset = flg;
5527     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5528 #if !defined(PETSC_HAVE_MPIUNI)
5529       ierr = MatStashScatterDestroy_BTS(&mat->stash);CHKERRQ(ierr);
5530 #endif
5531       mat->stash.first_assembly_done = PETSC_FALSE;
5532     }
5533     PetscFunctionReturn(0);
5534   case MAT_NO_OFF_PROC_ZERO_ROWS:
5535     mat->nooffproczerorows = flg;
5536     PetscFunctionReturn(0);
5537     break;
5538   case MAT_SPD:
5539     mat->spd_set = PETSC_TRUE;
5540     mat->spd     = flg;
5541     if (flg) {
5542       mat->symmetric                  = PETSC_TRUE;
5543       mat->structurally_symmetric     = PETSC_TRUE;
5544       mat->symmetric_set              = PETSC_TRUE;
5545       mat->structurally_symmetric_set = PETSC_TRUE;
5546     }
5547     break;
5548   case MAT_SYMMETRIC:
5549     mat->symmetric = flg;
5550     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5551     mat->symmetric_set              = PETSC_TRUE;
5552     mat->structurally_symmetric_set = flg;
5553 #if !defined(PETSC_USE_COMPLEX)
5554     mat->hermitian     = flg;
5555     mat->hermitian_set = PETSC_TRUE;
5556 #endif
5557     break;
5558   case MAT_HERMITIAN:
5559     mat->hermitian = flg;
5560     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5561     mat->hermitian_set              = PETSC_TRUE;
5562     mat->structurally_symmetric_set = flg;
5563 #if !defined(PETSC_USE_COMPLEX)
5564     mat->symmetric     = flg;
5565     mat->symmetric_set = PETSC_TRUE;
5566 #endif
5567     break;
5568   case MAT_STRUCTURALLY_SYMMETRIC:
5569     mat->structurally_symmetric     = flg;
5570     mat->structurally_symmetric_set = PETSC_TRUE;
5571     break;
5572   case MAT_SYMMETRY_ETERNAL:
5573     mat->symmetric_eternal = flg;
5574     break;
5575   case MAT_STRUCTURE_ONLY:
5576     mat->structure_only = flg;
5577     break;
5578   case MAT_SORTED_FULL:
5579     mat->sortedfull = flg;
5580     break;
5581   default:
5582     break;
5583   }
5584   if (mat->ops->setoption) {
5585     ierr = (*mat->ops->setoption)(mat,op,flg);CHKERRQ(ierr);
5586   }
5587   PetscFunctionReturn(0);
5588 }
5589 
5590 /*@
5591    MatGetOption - Gets a parameter option that has been set for a matrix.
5592 
5593    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5594 
5595    Input Parameters:
5596 +  mat - the matrix
5597 -  option - the option, this only responds to certain options, check the code for which ones
5598 
5599    Output Parameter:
5600 .  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5601 
5602     Notes:
5603     Can only be called after MatSetSizes() and MatSetType() have been set.
5604 
5605    Level: intermediate
5606 
5607 .seealso:  MatOption, MatSetOption()
5608 
5609 @*/
5610 PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5611 {
5612   PetscFunctionBegin;
5613   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5614   PetscValidType(mat,1);
5615 
5616   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);
5617   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()");
5618 
5619   switch (op) {
5620   case MAT_NO_OFF_PROC_ENTRIES:
5621     *flg = mat->nooffprocentries;
5622     break;
5623   case MAT_NO_OFF_PROC_ZERO_ROWS:
5624     *flg = mat->nooffproczerorows;
5625     break;
5626   case MAT_SYMMETRIC:
5627     *flg = mat->symmetric;
5628     break;
5629   case MAT_HERMITIAN:
5630     *flg = mat->hermitian;
5631     break;
5632   case MAT_STRUCTURALLY_SYMMETRIC:
5633     *flg = mat->structurally_symmetric;
5634     break;
5635   case MAT_SYMMETRY_ETERNAL:
5636     *flg = mat->symmetric_eternal;
5637     break;
5638   case MAT_SPD:
5639     *flg = mat->spd;
5640     break;
5641   default:
5642     break;
5643   }
5644   PetscFunctionReturn(0);
5645 }
5646 
5647 /*@
5648    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5649    this routine retains the old nonzero structure.
5650 
5651    Logically Collective on Mat
5652 
5653    Input Parameters:
5654 .  mat - the matrix
5655 
5656    Level: intermediate
5657 
5658    Notes:
5659     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.
5660    See the Performance chapter of the users manual for information on preallocating matrices.
5661 
5662 .seealso: MatZeroRows()
5663 @*/
5664 PetscErrorCode MatZeroEntries(Mat mat)
5665 {
5666   PetscErrorCode ierr;
5667 
5668   PetscFunctionBegin;
5669   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5670   PetscValidType(mat,1);
5671   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5672   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");
5673   if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5674   MatCheckPreallocated(mat,1);
5675 
5676   ierr = PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5677   ierr = (*mat->ops->zeroentries)(mat);CHKERRQ(ierr);
5678   ierr = PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5679   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5680   PetscFunctionReturn(0);
5681 }
5682 
5683 /*@
5684    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5685    of a set of rows and columns of a matrix.
5686 
5687    Collective on Mat
5688 
5689    Input Parameters:
5690 +  mat - the matrix
5691 .  numRows - the number of rows to remove
5692 .  rows - the global row indices
5693 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5694 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5695 -  b - optional vector of right hand side, that will be adjusted by provided solution
5696 
5697    Notes:
5698    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5699 
5700    The user can set a value in the diagonal entry (or for the AIJ and
5701    row formats can optionally remove the main diagonal entry from the
5702    nonzero structure as well, by passing 0.0 as the final argument).
5703 
5704    For the parallel case, all processes that share the matrix (i.e.,
5705    those in the communicator used for matrix creation) MUST call this
5706    routine, regardless of whether any rows being zeroed are owned by
5707    them.
5708 
5709    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5710    list only rows local to itself).
5711 
5712    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5713 
5714    Level: intermediate
5715 
5716 .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5717           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5718 @*/
5719 PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5720 {
5721   PetscErrorCode ierr;
5722 
5723   PetscFunctionBegin;
5724   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5725   PetscValidType(mat,1);
5726   if (numRows) PetscValidIntPointer(rows,3);
5727   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5728   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5729   if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5730   MatCheckPreallocated(mat,1);
5731 
5732   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5733   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5734   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5735   PetscFunctionReturn(0);
5736 }
5737 
5738 /*@
5739    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5740    of a set of rows and columns of a matrix.
5741 
5742    Collective on Mat
5743 
5744    Input Parameters:
5745 +  mat - the matrix
5746 .  is - the rows to zero
5747 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5748 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5749 -  b - optional vector of right hand side, that will be adjusted by provided solution
5750 
5751    Notes:
5752    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5753 
5754    The user can set a value in the diagonal entry (or for the AIJ and
5755    row formats can optionally remove the main diagonal entry from the
5756    nonzero structure as well, by passing 0.0 as the final argument).
5757 
5758    For the parallel case, all processes that share the matrix (i.e.,
5759    those in the communicator used for matrix creation) MUST call this
5760    routine, regardless of whether any rows being zeroed are owned by
5761    them.
5762 
5763    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5764    list only rows local to itself).
5765 
5766    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5767 
5768    Level: intermediate
5769 
5770 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5771           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5772 @*/
5773 PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5774 {
5775   PetscErrorCode ierr;
5776   PetscInt       numRows;
5777   const PetscInt *rows;
5778 
5779   PetscFunctionBegin;
5780   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5781   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5782   PetscValidType(mat,1);
5783   PetscValidType(is,2);
5784   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5785   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5786   ierr = MatZeroRowsColumns(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5787   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5788   PetscFunctionReturn(0);
5789 }
5790 
5791 /*@
5792    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5793    of a set of rows of a matrix.
5794 
5795    Collective on Mat
5796 
5797    Input Parameters:
5798 +  mat - the matrix
5799 .  numRows - the number of rows to remove
5800 .  rows - the global row indices
5801 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5802 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5803 -  b - optional vector of right hand side, that will be adjusted by provided solution
5804 
5805    Notes:
5806    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5807    but does not release memory.  For the dense and block diagonal
5808    formats this does not alter the nonzero structure.
5809 
5810    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5811    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5812    merely zeroed.
5813 
5814    The user can set a value in the diagonal entry (or for the AIJ and
5815    row formats can optionally remove the main diagonal entry from the
5816    nonzero structure as well, by passing 0.0 as the final argument).
5817 
5818    For the parallel case, all processes that share the matrix (i.e.,
5819    those in the communicator used for matrix creation) MUST call this
5820    routine, regardless of whether any rows being zeroed are owned by
5821    them.
5822 
5823    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5824    list only rows local to itself).
5825 
5826    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5827    owns that are to be zeroed. This saves a global synchronization in the implementation.
5828 
5829    Level: intermediate
5830 
5831 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5832           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5833 @*/
5834 PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5835 {
5836   PetscErrorCode ierr;
5837 
5838   PetscFunctionBegin;
5839   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5840   PetscValidType(mat,1);
5841   if (numRows) PetscValidIntPointer(rows,3);
5842   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5843   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5844   if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5845   MatCheckPreallocated(mat,1);
5846 
5847   ierr = (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5848   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5849   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5850   PetscFunctionReturn(0);
5851 }
5852 
5853 /*@
5854    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5855    of a set of rows of a matrix.
5856 
5857    Collective on Mat
5858 
5859    Input Parameters:
5860 +  mat - the matrix
5861 .  is - index set of rows to remove
5862 .  diag - value put in all diagonals of eliminated rows
5863 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5864 -  b - optional vector of right hand side, that will be adjusted by provided solution
5865 
5866    Notes:
5867    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5868    but does not release memory.  For the dense and block diagonal
5869    formats this does not alter the nonzero structure.
5870 
5871    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5872    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5873    merely zeroed.
5874 
5875    The user can set a value in the diagonal entry (or for the AIJ and
5876    row formats can optionally remove the main diagonal entry from the
5877    nonzero structure as well, by passing 0.0 as the final argument).
5878 
5879    For the parallel case, all processes that share the matrix (i.e.,
5880    those in the communicator used for matrix creation) MUST call this
5881    routine, regardless of whether any rows being zeroed are owned by
5882    them.
5883 
5884    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5885    list only rows local to itself).
5886 
5887    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5888    owns that are to be zeroed. This saves a global synchronization in the implementation.
5889 
5890    Level: intermediate
5891 
5892 .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5893           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5894 @*/
5895 PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5896 {
5897   PetscInt       numRows;
5898   const PetscInt *rows;
5899   PetscErrorCode ierr;
5900 
5901   PetscFunctionBegin;
5902   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5903   PetscValidType(mat,1);
5904   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5905   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5906   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5907   ierr = MatZeroRows(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5908   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5909   PetscFunctionReturn(0);
5910 }
5911 
5912 /*@
5913    MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5914    of a set of rows of a matrix. These rows must be local to the process.
5915 
5916    Collective on Mat
5917 
5918    Input Parameters:
5919 +  mat - the matrix
5920 .  numRows - the number of rows to remove
5921 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5922 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5923 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5924 -  b - optional vector of right hand side, that will be adjusted by provided solution
5925 
5926    Notes:
5927    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5928    but does not release memory.  For the dense and block diagonal
5929    formats this does not alter the nonzero structure.
5930 
5931    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5932    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5933    merely zeroed.
5934 
5935    The user can set a value in the diagonal entry (or for the AIJ and
5936    row formats can optionally remove the main diagonal entry from the
5937    nonzero structure as well, by passing 0.0 as the final argument).
5938 
5939    For the parallel case, all processes that share the matrix (i.e.,
5940    those in the communicator used for matrix creation) MUST call this
5941    routine, regardless of whether any rows being zeroed are owned by
5942    them.
5943 
5944    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5945    list only rows local to itself).
5946 
5947    The grid coordinates are across the entire grid, not just the local portion
5948 
5949    In Fortran idxm and idxn should be declared as
5950 $     MatStencil idxm(4,m)
5951    and the values inserted using
5952 $    idxm(MatStencil_i,1) = i
5953 $    idxm(MatStencil_j,1) = j
5954 $    idxm(MatStencil_k,1) = k
5955 $    idxm(MatStencil_c,1) = c
5956    etc
5957 
5958    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5959    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5960    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5961    DM_BOUNDARY_PERIODIC boundary type.
5962 
5963    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
5964    a single value per point) you can skip filling those indices.
5965 
5966    Level: intermediate
5967 
5968 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5969           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5970 @*/
5971 PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5972 {
5973   PetscInt       dim     = mat->stencil.dim;
5974   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5975   PetscInt       *dims   = mat->stencil.dims+1;
5976   PetscInt       *starts = mat->stencil.starts;
5977   PetscInt       *dxm    = (PetscInt*) rows;
5978   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
5979   PetscErrorCode ierr;
5980 
5981   PetscFunctionBegin;
5982   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5983   PetscValidType(mat,1);
5984   if (numRows) PetscValidIntPointer(rows,3);
5985 
5986   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
5987   for (i = 0; i < numRows; ++i) {
5988     /* Skip unused dimensions (they are ordered k, j, i, c) */
5989     for (j = 0; j < 3-sdim; ++j) dxm++;
5990     /* Local index in X dir */
5991     tmp = *dxm++ - starts[0];
5992     /* Loop over remaining dimensions */
5993     for (j = 0; j < dim-1; ++j) {
5994       /* If nonlocal, set index to be negative */
5995       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5996       /* Update local index */
5997       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5998     }
5999     /* Skip component slot if necessary */
6000     if (mat->stencil.noc) dxm++;
6001     /* Local row number */
6002     if (tmp >= 0) {
6003       jdxm[numNewRows++] = tmp;
6004     }
6005   }
6006   ierr = MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
6007   ierr = PetscFree(jdxm);CHKERRQ(ierr);
6008   PetscFunctionReturn(0);
6009 }
6010 
6011 /*@
6012    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6013    of a set of rows and columns of a matrix.
6014 
6015    Collective on Mat
6016 
6017    Input Parameters:
6018 +  mat - the matrix
6019 .  numRows - the number of rows/columns to remove
6020 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
6021 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6022 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6023 -  b - optional vector of right hand side, that will be adjusted by provided solution
6024 
6025    Notes:
6026    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6027    but does not release memory.  For the dense and block diagonal
6028    formats this does not alter the nonzero structure.
6029 
6030    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6031    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6032    merely zeroed.
6033 
6034    The user can set a value in the diagonal entry (or for the AIJ and
6035    row formats can optionally remove the main diagonal entry from the
6036    nonzero structure as well, by passing 0.0 as the final argument).
6037 
6038    For the parallel case, all processes that share the matrix (i.e.,
6039    those in the communicator used for matrix creation) MUST call this
6040    routine, regardless of whether any rows being zeroed are owned by
6041    them.
6042 
6043    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6044    list only rows local to itself, but the row/column numbers are given in local numbering).
6045 
6046    The grid coordinates are across the entire grid, not just the local portion
6047 
6048    In Fortran idxm and idxn should be declared as
6049 $     MatStencil idxm(4,m)
6050    and the values inserted using
6051 $    idxm(MatStencil_i,1) = i
6052 $    idxm(MatStencil_j,1) = j
6053 $    idxm(MatStencil_k,1) = k
6054 $    idxm(MatStencil_c,1) = c
6055    etc
6056 
6057    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6058    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6059    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6060    DM_BOUNDARY_PERIODIC boundary type.
6061 
6062    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
6063    a single value per point) you can skip filling those indices.
6064 
6065    Level: intermediate
6066 
6067 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6068           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6069 @*/
6070 PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6071 {
6072   PetscInt       dim     = mat->stencil.dim;
6073   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6074   PetscInt       *dims   = mat->stencil.dims+1;
6075   PetscInt       *starts = mat->stencil.starts;
6076   PetscInt       *dxm    = (PetscInt*) rows;
6077   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
6078   PetscErrorCode ierr;
6079 
6080   PetscFunctionBegin;
6081   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6082   PetscValidType(mat,1);
6083   if (numRows) PetscValidIntPointer(rows,3);
6084 
6085   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
6086   for (i = 0; i < numRows; ++i) {
6087     /* Skip unused dimensions (they are ordered k, j, i, c) */
6088     for (j = 0; j < 3-sdim; ++j) dxm++;
6089     /* Local index in X dir */
6090     tmp = *dxm++ - starts[0];
6091     /* Loop over remaining dimensions */
6092     for (j = 0; j < dim-1; ++j) {
6093       /* If nonlocal, set index to be negative */
6094       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6095       /* Update local index */
6096       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6097     }
6098     /* Skip component slot if necessary */
6099     if (mat->stencil.noc) dxm++;
6100     /* Local row number */
6101     if (tmp >= 0) {
6102       jdxm[numNewRows++] = tmp;
6103     }
6104   }
6105   ierr = MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
6106   ierr = PetscFree(jdxm);CHKERRQ(ierr);
6107   PetscFunctionReturn(0);
6108 }
6109 
6110 /*@C
6111    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6112    of a set of rows of a matrix; using local numbering of rows.
6113 
6114    Collective on Mat
6115 
6116    Input Parameters:
6117 +  mat - the matrix
6118 .  numRows - the number of rows to remove
6119 .  rows - the global row indices
6120 .  diag - value put in all diagonals of eliminated rows
6121 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6122 -  b - optional vector of right hand side, that will be adjusted by provided solution
6123 
6124    Notes:
6125    Before calling MatZeroRowsLocal(), the user must first set the
6126    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6127 
6128    For the AIJ matrix formats this removes the old nonzero structure,
6129    but does not release memory.  For the dense and block diagonal
6130    formats this does not alter the nonzero structure.
6131 
6132    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6133    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6134    merely zeroed.
6135 
6136    The user can set a value in the diagonal entry (or for the AIJ and
6137    row formats can optionally remove the main diagonal entry from the
6138    nonzero structure as well, by passing 0.0 as the final argument).
6139 
6140    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6141    owns that are to be zeroed. This saves a global synchronization in the implementation.
6142 
6143    Level: intermediate
6144 
6145 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6146           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6147 @*/
6148 PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6149 {
6150   PetscErrorCode ierr;
6151 
6152   PetscFunctionBegin;
6153   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6154   PetscValidType(mat,1);
6155   if (numRows) PetscValidIntPointer(rows,3);
6156   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6157   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6158   MatCheckPreallocated(mat,1);
6159 
6160   if (mat->ops->zerorowslocal) {
6161     ierr = (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6162   } else {
6163     IS             is, newis;
6164     const PetscInt *newRows;
6165 
6166     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6167     ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6168     ierr = ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);CHKERRQ(ierr);
6169     ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6170     ierr = (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6171     ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6172     ierr = ISDestroy(&newis);CHKERRQ(ierr);
6173     ierr = ISDestroy(&is);CHKERRQ(ierr);
6174   }
6175   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6176   PetscFunctionReturn(0);
6177 }
6178 
6179 /*@
6180    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6181    of a set of rows of a matrix; using local numbering of rows.
6182 
6183    Collective on Mat
6184 
6185    Input Parameters:
6186 +  mat - the matrix
6187 .  is - index set of rows to remove
6188 .  diag - value put in all diagonals of eliminated rows
6189 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6190 -  b - optional vector of right hand side, that will be adjusted by provided solution
6191 
6192    Notes:
6193    Before calling MatZeroRowsLocalIS(), the user must first set the
6194    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6195 
6196    For the AIJ matrix formats this removes the old nonzero structure,
6197    but does not release memory.  For the dense and block diagonal
6198    formats this does not alter the nonzero structure.
6199 
6200    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6201    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6202    merely zeroed.
6203 
6204    The user can set a value in the diagonal entry (or for the AIJ and
6205    row formats can optionally remove the main diagonal entry from the
6206    nonzero structure as well, by passing 0.0 as the final argument).
6207 
6208    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6209    owns that are to be zeroed. This saves a global synchronization in the implementation.
6210 
6211    Level: intermediate
6212 
6213 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6214           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6215 @*/
6216 PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6217 {
6218   PetscErrorCode ierr;
6219   PetscInt       numRows;
6220   const PetscInt *rows;
6221 
6222   PetscFunctionBegin;
6223   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6224   PetscValidType(mat,1);
6225   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6226   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6227   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6228   MatCheckPreallocated(mat,1);
6229 
6230   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6231   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6232   ierr = MatZeroRowsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6233   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6234   PetscFunctionReturn(0);
6235 }
6236 
6237 /*@
6238    MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6239    of a set of rows and columns of a matrix; using local numbering of rows.
6240 
6241    Collective on Mat
6242 
6243    Input Parameters:
6244 +  mat - the matrix
6245 .  numRows - the number of rows to remove
6246 .  rows - the global row indices
6247 .  diag - value put in all diagonals of eliminated rows
6248 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6249 -  b - optional vector of right hand side, that will be adjusted by provided solution
6250 
6251    Notes:
6252    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6253    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6254 
6255    The user can set a value in the diagonal entry (or for the AIJ and
6256    row formats can optionally remove the main diagonal entry from the
6257    nonzero structure as well, by passing 0.0 as the final argument).
6258 
6259    Level: intermediate
6260 
6261 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6262           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6263 @*/
6264 PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6265 {
6266   PetscErrorCode ierr;
6267   IS             is, newis;
6268   const PetscInt *newRows;
6269 
6270   PetscFunctionBegin;
6271   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6272   PetscValidType(mat,1);
6273   if (numRows) PetscValidIntPointer(rows,3);
6274   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6275   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6276   MatCheckPreallocated(mat,1);
6277 
6278   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6279   ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6280   ierr = ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);CHKERRQ(ierr);
6281   ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6282   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6283   ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6284   ierr = ISDestroy(&newis);CHKERRQ(ierr);
6285   ierr = ISDestroy(&is);CHKERRQ(ierr);
6286   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6287   PetscFunctionReturn(0);
6288 }
6289 
6290 /*@
6291    MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6292    of a set of rows and columns of a matrix; using local numbering of rows.
6293 
6294    Collective on Mat
6295 
6296    Input Parameters:
6297 +  mat - the matrix
6298 .  is - index set of rows to remove
6299 .  diag - value put in all diagonals of eliminated rows
6300 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6301 -  b - optional vector of right hand side, that will be adjusted by provided solution
6302 
6303    Notes:
6304    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6305    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6306 
6307    The user can set a value in the diagonal entry (or for the AIJ and
6308    row formats can optionally remove the main diagonal entry from the
6309    nonzero structure as well, by passing 0.0 as the final argument).
6310 
6311    Level: intermediate
6312 
6313 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6314           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6315 @*/
6316 PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6317 {
6318   PetscErrorCode ierr;
6319   PetscInt       numRows;
6320   const PetscInt *rows;
6321 
6322   PetscFunctionBegin;
6323   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6324   PetscValidType(mat,1);
6325   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6326   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6327   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6328   MatCheckPreallocated(mat,1);
6329 
6330   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6331   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6332   ierr = MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6333   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6334   PetscFunctionReturn(0);
6335 }
6336 
6337 /*@C
6338    MatGetSize - Returns the numbers of rows and columns in a matrix.
6339 
6340    Not Collective
6341 
6342    Input Parameter:
6343 .  mat - the matrix
6344 
6345    Output Parameters:
6346 +  m - the number of global rows
6347 -  n - the number of global columns
6348 
6349    Note: both output parameters can be NULL on input.
6350 
6351    Level: beginner
6352 
6353 .seealso: MatGetLocalSize()
6354 @*/
6355 PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6356 {
6357   PetscFunctionBegin;
6358   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6359   if (m) *m = mat->rmap->N;
6360   if (n) *n = mat->cmap->N;
6361   PetscFunctionReturn(0);
6362 }
6363 
6364 /*@C
6365    MatGetLocalSize - Returns the number of rows and columns in a matrix
6366    stored locally.  This information may be implementation dependent, so
6367    use with care.
6368 
6369    Not Collective
6370 
6371    Input Parameters:
6372 .  mat - the matrix
6373 
6374    Output Parameters:
6375 +  m - the number of local rows
6376 -  n - the number of local columns
6377 
6378    Note: both output parameters can be NULL on input.
6379 
6380    Level: beginner
6381 
6382 .seealso: MatGetSize()
6383 @*/
6384 PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6385 {
6386   PetscFunctionBegin;
6387   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6388   if (m) PetscValidIntPointer(m,2);
6389   if (n) PetscValidIntPointer(n,3);
6390   if (m) *m = mat->rmap->n;
6391   if (n) *n = mat->cmap->n;
6392   PetscFunctionReturn(0);
6393 }
6394 
6395 /*@C
6396    MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6397    this processor. (The columns of the "diagonal block")
6398 
6399    Not Collective, unless matrix has not been allocated, then collective on Mat
6400 
6401    Input Parameters:
6402 .  mat - the matrix
6403 
6404    Output Parameters:
6405 +  m - the global index of the first local column
6406 -  n - one more than the global index of the last local column
6407 
6408    Notes:
6409     both output parameters can be NULL on input.
6410 
6411    Level: developer
6412 
6413 .seealso:  MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6414 
6415 @*/
6416 PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6417 {
6418   PetscFunctionBegin;
6419   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6420   PetscValidType(mat,1);
6421   if (m) PetscValidIntPointer(m,2);
6422   if (n) PetscValidIntPointer(n,3);
6423   MatCheckPreallocated(mat,1);
6424   if (m) *m = mat->cmap->rstart;
6425   if (n) *n = mat->cmap->rend;
6426   PetscFunctionReturn(0);
6427 }
6428 
6429 /*@C
6430    MatGetOwnershipRange - Returns the range of matrix rows owned by
6431    this processor, assuming that the matrix is laid out with the first
6432    n1 rows on the first processor, the next n2 rows on the second, etc.
6433    For certain parallel layouts this range may not be well defined.
6434 
6435    Not Collective
6436 
6437    Input Parameters:
6438 .  mat - the matrix
6439 
6440    Output Parameters:
6441 +  m - the global index of the first local row
6442 -  n - one more than the global index of the last local row
6443 
6444    Note: Both output parameters can be NULL on input.
6445 $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6446 $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6447 $  and then MPI_Scan() to calculate prefix sums of the local sizes.
6448 
6449    Level: beginner
6450 
6451 .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6452 
6453 @*/
6454 PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6455 {
6456   PetscFunctionBegin;
6457   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6458   PetscValidType(mat,1);
6459   if (m) PetscValidIntPointer(m,2);
6460   if (n) PetscValidIntPointer(n,3);
6461   MatCheckPreallocated(mat,1);
6462   if (m) *m = mat->rmap->rstart;
6463   if (n) *n = mat->rmap->rend;
6464   PetscFunctionReturn(0);
6465 }
6466 
6467 /*@C
6468    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6469    each process
6470 
6471    Not Collective, unless matrix has not been allocated, then collective on Mat
6472 
6473    Input Parameters:
6474 .  mat - the matrix
6475 
6476    Output Parameters:
6477 .  ranges - start of each processors portion plus one more than the total length at the end
6478 
6479    Level: beginner
6480 
6481 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6482 
6483 @*/
6484 PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6485 {
6486   PetscErrorCode ierr;
6487 
6488   PetscFunctionBegin;
6489   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6490   PetscValidType(mat,1);
6491   MatCheckPreallocated(mat,1);
6492   ierr = PetscLayoutGetRanges(mat->rmap,ranges);CHKERRQ(ierr);
6493   PetscFunctionReturn(0);
6494 }
6495 
6496 /*@C
6497    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6498    this processor. (The columns of the "diagonal blocks" for each process)
6499 
6500    Not Collective, unless matrix has not been allocated, then collective on Mat
6501 
6502    Input Parameters:
6503 .  mat - the matrix
6504 
6505    Output Parameters:
6506 .  ranges - start of each processors portion plus one more then the total length at the end
6507 
6508    Level: beginner
6509 
6510 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6511 
6512 @*/
6513 PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6514 {
6515   PetscErrorCode ierr;
6516 
6517   PetscFunctionBegin;
6518   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6519   PetscValidType(mat,1);
6520   MatCheckPreallocated(mat,1);
6521   ierr = PetscLayoutGetRanges(mat->cmap,ranges);CHKERRQ(ierr);
6522   PetscFunctionReturn(0);
6523 }
6524 
6525 /*@C
6526    MatGetOwnershipIS - Get row and column ownership as index sets
6527 
6528    Not Collective
6529 
6530    Input Arguments:
6531 .  A - matrix of type Elemental
6532 
6533    Output Arguments:
6534 +  rows - rows in which this process owns elements
6535 -  cols - columns in which this process owns elements
6536 
6537    Level: intermediate
6538 
6539 .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6540 @*/
6541 PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6542 {
6543   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6544 
6545   PetscFunctionBegin;
6546   MatCheckPreallocated(A,1);
6547   ierr = PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);CHKERRQ(ierr);
6548   if (f) {
6549     ierr = (*f)(A,rows,cols);CHKERRQ(ierr);
6550   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6551     if (rows) {ierr = ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);CHKERRQ(ierr);}
6552     if (cols) {ierr = ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);CHKERRQ(ierr);}
6553   }
6554   PetscFunctionReturn(0);
6555 }
6556 
6557 /*@C
6558    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6559    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6560    to complete the factorization.
6561 
6562    Collective on Mat
6563 
6564    Input Parameters:
6565 +  mat - the matrix
6566 .  row - row permutation
6567 .  column - column permutation
6568 -  info - structure containing
6569 $      levels - number of levels of fill.
6570 $      expected fill - as ratio of original fill.
6571 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6572                 missing diagonal entries)
6573 
6574    Output Parameters:
6575 .  fact - new matrix that has been symbolically factored
6576 
6577    Notes:
6578     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6579 
6580    Most users should employ the simplified KSP interface for linear solvers
6581    instead of working directly with matrix algebra routines such as this.
6582    See, e.g., KSPCreate().
6583 
6584    Level: developer
6585 
6586 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6587           MatGetOrdering(), MatFactorInfo
6588 
6589     Note: this uses the definition of level of fill as in Y. Saad, 2003
6590 
6591     Developer Note: fortran interface is not autogenerated as the f90
6592     interface defintion cannot be generated correctly [due to MatFactorInfo]
6593 
6594    References:
6595      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6596 @*/
6597 PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6598 {
6599   PetscErrorCode ierr;
6600 
6601   PetscFunctionBegin;
6602   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6603   PetscValidType(mat,1);
6604   PetscValidHeaderSpecific(row,IS_CLASSID,2);
6605   PetscValidHeaderSpecific(col,IS_CLASSID,3);
6606   PetscValidPointer(info,4);
6607   PetscValidPointer(fact,5);
6608   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6609   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6610   if (!(fact)->ops->ilufactorsymbolic) {
6611     MatSolverType spackage;
6612     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
6613     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6614   }
6615   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6616   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6617   MatCheckPreallocated(mat,2);
6618 
6619   ierr = PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6620   ierr = (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
6621   ierr = PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6622   PetscFunctionReturn(0);
6623 }
6624 
6625 /*@C
6626    MatICCFactorSymbolic - Performs symbolic incomplete
6627    Cholesky factorization for a symmetric matrix.  Use
6628    MatCholeskyFactorNumeric() to complete the factorization.
6629 
6630    Collective on Mat
6631 
6632    Input Parameters:
6633 +  mat - the matrix
6634 .  perm - row and column permutation
6635 -  info - structure containing
6636 $      levels - number of levels of fill.
6637 $      expected fill - as ratio of original fill.
6638 
6639    Output Parameter:
6640 .  fact - the factored matrix
6641 
6642    Notes:
6643    Most users should employ the KSP interface for linear solvers
6644    instead of working directly with matrix algebra routines such as this.
6645    See, e.g., KSPCreate().
6646 
6647    Level: developer
6648 
6649 .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6650 
6651     Note: this uses the definition of level of fill as in Y. Saad, 2003
6652 
6653     Developer Note: fortran interface is not autogenerated as the f90
6654     interface defintion cannot be generated correctly [due to MatFactorInfo]
6655 
6656    References:
6657      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6658 @*/
6659 PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6660 {
6661   PetscErrorCode ierr;
6662 
6663   PetscFunctionBegin;
6664   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6665   PetscValidType(mat,1);
6666   PetscValidHeaderSpecific(perm,IS_CLASSID,2);
6667   PetscValidPointer(info,3);
6668   PetscValidPointer(fact,4);
6669   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6670   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6671   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6672   if (!(fact)->ops->iccfactorsymbolic) {
6673     MatSolverType spackage;
6674     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
6675     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6676   }
6677   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6678   MatCheckPreallocated(mat,2);
6679 
6680   ierr = PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6681   ierr = (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
6682   ierr = PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6683   PetscFunctionReturn(0);
6684 }
6685 
6686 /*@C
6687    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6688    points to an array of valid matrices, they may be reused to store the new
6689    submatrices.
6690 
6691    Collective on Mat
6692 
6693    Input Parameters:
6694 +  mat - the matrix
6695 .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6696 .  irow, icol - index sets of rows and columns to extract
6697 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6698 
6699    Output Parameter:
6700 .  submat - the array of submatrices
6701 
6702    Notes:
6703    MatCreateSubMatrices() can extract ONLY sequential submatrices
6704    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6705    to extract a parallel submatrix.
6706 
6707    Some matrix types place restrictions on the row and column
6708    indices, such as that they be sorted or that they be equal to each other.
6709 
6710    The index sets may not have duplicate entries.
6711 
6712    When extracting submatrices from a parallel matrix, each processor can
6713    form a different submatrix by setting the rows and columns of its
6714    individual index sets according to the local submatrix desired.
6715 
6716    When finished using the submatrices, the user should destroy
6717    them with MatDestroySubMatrices().
6718 
6719    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6720    original matrix has not changed from that last call to MatCreateSubMatrices().
6721 
6722    This routine creates the matrices in submat; you should NOT create them before
6723    calling it. It also allocates the array of matrix pointers submat.
6724 
6725    For BAIJ matrices the index sets must respect the block structure, that is if they
6726    request one row/column in a block, they must request all rows/columns that are in
6727    that block. For example, if the block size is 2 you cannot request just row 0 and
6728    column 0.
6729 
6730    Fortran Note:
6731    The Fortran interface is slightly different from that given below; it
6732    requires one to pass in  as submat a Mat (integer) array of size at least n+1.
6733 
6734    Level: advanced
6735 
6736 
6737 .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6738 @*/
6739 PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6740 {
6741   PetscErrorCode ierr;
6742   PetscInt       i;
6743   PetscBool      eq;
6744 
6745   PetscFunctionBegin;
6746   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6747   PetscValidType(mat,1);
6748   if (n) {
6749     PetscValidPointer(irow,3);
6750     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6751     PetscValidPointer(icol,4);
6752     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6753   }
6754   PetscValidPointer(submat,6);
6755   if (n && scall == MAT_REUSE_MATRIX) {
6756     PetscValidPointer(*submat,6);
6757     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6758   }
6759   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6760   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6761   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6762   MatCheckPreallocated(mat,1);
6763 
6764   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6765   ierr = (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6766   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6767   for (i=0; i<n; i++) {
6768     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6769     ierr = ISEqualUnsorted(irow[i],icol[i],&eq);CHKERRQ(ierr);
6770     if (eq) {
6771       ierr = MatPropagateSymmetryOptions(mat,(*submat)[i]);CHKERRQ(ierr);
6772     }
6773   }
6774   PetscFunctionReturn(0);
6775 }
6776 
6777 /*@C
6778    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
6779 
6780    Collective on Mat
6781 
6782    Input Parameters:
6783 +  mat - the matrix
6784 .  n   - the number of submatrixes to be extracted
6785 .  irow, icol - index sets of rows and columns to extract
6786 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6787 
6788    Output Parameter:
6789 .  submat - the array of submatrices
6790 
6791    Level: advanced
6792 
6793 
6794 .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6795 @*/
6796 PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6797 {
6798   PetscErrorCode ierr;
6799   PetscInt       i;
6800   PetscBool      eq;
6801 
6802   PetscFunctionBegin;
6803   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6804   PetscValidType(mat,1);
6805   if (n) {
6806     PetscValidPointer(irow,3);
6807     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6808     PetscValidPointer(icol,4);
6809     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6810   }
6811   PetscValidPointer(submat,6);
6812   if (n && scall == MAT_REUSE_MATRIX) {
6813     PetscValidPointer(*submat,6);
6814     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6815   }
6816   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6817   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6818   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6819   MatCheckPreallocated(mat,1);
6820 
6821   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6822   ierr = (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6823   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6824   for (i=0; i<n; i++) {
6825     ierr = ISEqualUnsorted(irow[i],icol[i],&eq);CHKERRQ(ierr);
6826     if (eq) {
6827       ierr = MatPropagateSymmetryOptions(mat,(*submat)[i]);CHKERRQ(ierr);
6828     }
6829   }
6830   PetscFunctionReturn(0);
6831 }
6832 
6833 /*@C
6834    MatDestroyMatrices - Destroys an array of matrices.
6835 
6836    Collective on Mat
6837 
6838    Input Parameters:
6839 +  n - the number of local matrices
6840 -  mat - the matrices (note that this is a pointer to the array of matrices)
6841 
6842    Level: advanced
6843 
6844     Notes:
6845     Frees not only the matrices, but also the array that contains the matrices
6846            In Fortran will not free the array.
6847 
6848 .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6849 @*/
6850 PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6851 {
6852   PetscErrorCode ierr;
6853   PetscInt       i;
6854 
6855   PetscFunctionBegin;
6856   if (!*mat) PetscFunctionReturn(0);
6857   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6858   PetscValidPointer(mat,2);
6859 
6860   for (i=0; i<n; i++) {
6861     ierr = MatDestroy(&(*mat)[i]);CHKERRQ(ierr);
6862   }
6863 
6864   /* memory is allocated even if n = 0 */
6865   ierr = PetscFree(*mat);CHKERRQ(ierr);
6866   PetscFunctionReturn(0);
6867 }
6868 
6869 /*@C
6870    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
6871 
6872    Collective on Mat
6873 
6874    Input Parameters:
6875 +  n - the number of local matrices
6876 -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6877                        sequence of MatCreateSubMatrices())
6878 
6879    Level: advanced
6880 
6881     Notes:
6882     Frees not only the matrices, but also the array that contains the matrices
6883            In Fortran will not free the array.
6884 
6885 .seealso: MatCreateSubMatrices()
6886 @*/
6887 PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6888 {
6889   PetscErrorCode ierr;
6890   Mat            mat0;
6891 
6892   PetscFunctionBegin;
6893   if (!*mat) PetscFunctionReturn(0);
6894   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6895   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6896   PetscValidPointer(mat,2);
6897 
6898   mat0 = (*mat)[0];
6899   if (mat0 && mat0->ops->destroysubmatrices) {
6900     ierr = (mat0->ops->destroysubmatrices)(n,mat);CHKERRQ(ierr);
6901   } else {
6902     ierr = MatDestroyMatrices(n,mat);CHKERRQ(ierr);
6903   }
6904   PetscFunctionReturn(0);
6905 }
6906 
6907 /*@C
6908    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
6909 
6910    Collective on Mat
6911 
6912    Input Parameters:
6913 .  mat - the matrix
6914 
6915    Output Parameter:
6916 .  matstruct - the sequential matrix with the nonzero structure of mat
6917 
6918   Level: intermediate
6919 
6920 .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6921 @*/
6922 PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6923 {
6924   PetscErrorCode ierr;
6925 
6926   PetscFunctionBegin;
6927   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6928   PetscValidPointer(matstruct,2);
6929 
6930   PetscValidType(mat,1);
6931   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6932   MatCheckPreallocated(mat,1);
6933 
6934   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6935   ierr = PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
6936   ierr = (*mat->ops->getseqnonzerostructure)(mat,matstruct);CHKERRQ(ierr);
6937   ierr = PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
6938   PetscFunctionReturn(0);
6939 }
6940 
6941 /*@C
6942    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
6943 
6944    Collective on Mat
6945 
6946    Input Parameters:
6947 .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6948                        sequence of MatGetSequentialNonzeroStructure())
6949 
6950    Level: advanced
6951 
6952     Notes:
6953     Frees not only the matrices, but also the array that contains the matrices
6954 
6955 .seealso: MatGetSeqNonzeroStructure()
6956 @*/
6957 PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6958 {
6959   PetscErrorCode ierr;
6960 
6961   PetscFunctionBegin;
6962   PetscValidPointer(mat,1);
6963   ierr = MatDestroy(mat);CHKERRQ(ierr);
6964   PetscFunctionReturn(0);
6965 }
6966 
6967 /*@
6968    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6969    replaces the index sets by larger ones that represent submatrices with
6970    additional overlap.
6971 
6972    Collective on Mat
6973 
6974    Input Parameters:
6975 +  mat - the matrix
6976 .  n   - the number of index sets
6977 .  is  - the array of index sets (these index sets will changed during the call)
6978 -  ov  - the additional overlap requested
6979 
6980    Options Database:
6981 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6982 
6983    Level: developer
6984 
6985 
6986 .seealso: MatCreateSubMatrices()
6987 @*/
6988 PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6989 {
6990   PetscErrorCode ierr;
6991 
6992   PetscFunctionBegin;
6993   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6994   PetscValidType(mat,1);
6995   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6996   if (n) {
6997     PetscValidPointer(is,3);
6998     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
6999   }
7000   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7001   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7002   MatCheckPreallocated(mat,1);
7003 
7004   if (!ov) PetscFunctionReturn(0);
7005   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7006   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7007   ierr = (*mat->ops->increaseoverlap)(mat,n,is,ov);CHKERRQ(ierr);
7008   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7009   PetscFunctionReturn(0);
7010 }
7011 
7012 
7013 PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
7014 
7015 /*@
7016    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7017    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7018    additional overlap.
7019 
7020    Collective on Mat
7021 
7022    Input Parameters:
7023 +  mat - the matrix
7024 .  n   - the number of index sets
7025 .  is  - the array of index sets (these index sets will changed during the call)
7026 -  ov  - the additional overlap requested
7027 
7028    Options Database:
7029 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7030 
7031    Level: developer
7032 
7033 
7034 .seealso: MatCreateSubMatrices()
7035 @*/
7036 PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7037 {
7038   PetscInt       i;
7039   PetscErrorCode ierr;
7040 
7041   PetscFunctionBegin;
7042   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7043   PetscValidType(mat,1);
7044   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7045   if (n) {
7046     PetscValidPointer(is,3);
7047     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
7048   }
7049   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7050   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7051   MatCheckPreallocated(mat,1);
7052   if (!ov) PetscFunctionReturn(0);
7053   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7054   for(i=0; i<n; i++){
7055 	ierr =  MatIncreaseOverlapSplit_Single(mat,&is[i],ov);CHKERRQ(ierr);
7056   }
7057   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7058   PetscFunctionReturn(0);
7059 }
7060 
7061 
7062 
7063 
7064 /*@
7065    MatGetBlockSize - Returns the matrix block size.
7066 
7067    Not Collective
7068 
7069    Input Parameter:
7070 .  mat - the matrix
7071 
7072    Output Parameter:
7073 .  bs - block size
7074 
7075    Notes:
7076     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7077 
7078    If the block size has not been set yet this routine returns 1.
7079 
7080    Level: intermediate
7081 
7082 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7083 @*/
7084 PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7085 {
7086   PetscFunctionBegin;
7087   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7088   PetscValidIntPointer(bs,2);
7089   *bs = PetscAbs(mat->rmap->bs);
7090   PetscFunctionReturn(0);
7091 }
7092 
7093 /*@
7094    MatGetBlockSizes - Returns the matrix block row and column sizes.
7095 
7096    Not Collective
7097 
7098    Input Parameter:
7099 .  mat - the matrix
7100 
7101    Output Parameter:
7102 +  rbs - row block size
7103 -  cbs - column block size
7104 
7105    Notes:
7106     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7107     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7108 
7109    If a block size has not been set yet this routine returns 1.
7110 
7111    Level: intermediate
7112 
7113 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7114 @*/
7115 PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7116 {
7117   PetscFunctionBegin;
7118   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7119   if (rbs) PetscValidIntPointer(rbs,2);
7120   if (cbs) PetscValidIntPointer(cbs,3);
7121   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7122   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7123   PetscFunctionReturn(0);
7124 }
7125 
7126 /*@
7127    MatSetBlockSize - Sets the matrix block size.
7128 
7129    Logically Collective on Mat
7130 
7131    Input Parameters:
7132 +  mat - the matrix
7133 -  bs - block size
7134 
7135    Notes:
7136     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7137     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7138 
7139     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7140     is compatible with the matrix local sizes.
7141 
7142    Level: intermediate
7143 
7144 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7145 @*/
7146 PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7147 {
7148   PetscErrorCode ierr;
7149 
7150   PetscFunctionBegin;
7151   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7152   PetscValidLogicalCollectiveInt(mat,bs,2);
7153   ierr = MatSetBlockSizes(mat,bs,bs);CHKERRQ(ierr);
7154   PetscFunctionReturn(0);
7155 }
7156 
7157 /*@
7158    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7159 
7160    Logically Collective on Mat
7161 
7162    Input Parameters:
7163 +  mat - the matrix
7164 .  nblocks - the number of blocks on this process
7165 -  bsizes - the block sizes
7166 
7167    Notes:
7168     Currently used by PCVPBJACOBI for SeqAIJ matrices
7169 
7170    Level: intermediate
7171 
7172 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7173 @*/
7174 PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7175 {
7176   PetscErrorCode ierr;
7177   PetscInt       i,ncnt = 0, nlocal;
7178 
7179   PetscFunctionBegin;
7180   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7181   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7182   ierr = MatGetLocalSize(mat,&nlocal,NULL);CHKERRQ(ierr);
7183   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7184   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);
7185   ierr = PetscFree(mat->bsizes);CHKERRQ(ierr);
7186   mat->nblocks = nblocks;
7187   ierr = PetscMalloc1(nblocks,&mat->bsizes);CHKERRQ(ierr);
7188   ierr = PetscArraycpy(mat->bsizes,bsizes,nblocks);CHKERRQ(ierr);
7189   PetscFunctionReturn(0);
7190 }
7191 
7192 /*@C
7193    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7194 
7195    Logically Collective on Mat
7196 
7197    Input Parameters:
7198 .  mat - the matrix
7199 
7200    Output Parameters:
7201 +  nblocks - the number of blocks on this process
7202 -  bsizes - the block sizes
7203 
7204    Notes: Currently not supported from Fortran
7205 
7206    Level: intermediate
7207 
7208 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7209 @*/
7210 PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7211 {
7212   PetscFunctionBegin;
7213   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7214   *nblocks = mat->nblocks;
7215   *bsizes  = mat->bsizes;
7216   PetscFunctionReturn(0);
7217 }
7218 
7219 /*@
7220    MatSetBlockSizes - Sets the matrix block row and column sizes.
7221 
7222    Logically Collective on Mat
7223 
7224    Input Parameters:
7225 +  mat - the matrix
7226 .  rbs - row block size
7227 -  cbs - column block size
7228 
7229    Notes:
7230     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7231     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7232     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7233 
7234     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7235     are compatible with the matrix local sizes.
7236 
7237     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7238 
7239    Level: intermediate
7240 
7241 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7242 @*/
7243 PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7244 {
7245   PetscErrorCode ierr;
7246 
7247   PetscFunctionBegin;
7248   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7249   PetscValidLogicalCollectiveInt(mat,rbs,2);
7250   PetscValidLogicalCollectiveInt(mat,cbs,3);
7251   if (mat->ops->setblocksizes) {
7252     ierr = (*mat->ops->setblocksizes)(mat,rbs,cbs);CHKERRQ(ierr);
7253   }
7254   if (mat->rmap->refcnt) {
7255     ISLocalToGlobalMapping l2g = NULL;
7256     PetscLayout            nmap = NULL;
7257 
7258     ierr = PetscLayoutDuplicate(mat->rmap,&nmap);CHKERRQ(ierr);
7259     if (mat->rmap->mapping) {
7260       ierr = ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);CHKERRQ(ierr);
7261     }
7262     ierr = PetscLayoutDestroy(&mat->rmap);CHKERRQ(ierr);
7263     mat->rmap = nmap;
7264     mat->rmap->mapping = l2g;
7265   }
7266   if (mat->cmap->refcnt) {
7267     ISLocalToGlobalMapping l2g = NULL;
7268     PetscLayout            nmap = NULL;
7269 
7270     ierr = PetscLayoutDuplicate(mat->cmap,&nmap);CHKERRQ(ierr);
7271     if (mat->cmap->mapping) {
7272       ierr = ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);CHKERRQ(ierr);
7273     }
7274     ierr = PetscLayoutDestroy(&mat->cmap);CHKERRQ(ierr);
7275     mat->cmap = nmap;
7276     mat->cmap->mapping = l2g;
7277   }
7278   ierr = PetscLayoutSetBlockSize(mat->rmap,rbs);CHKERRQ(ierr);
7279   ierr = PetscLayoutSetBlockSize(mat->cmap,cbs);CHKERRQ(ierr);
7280   PetscFunctionReturn(0);
7281 }
7282 
7283 /*@
7284    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7285 
7286    Logically Collective on Mat
7287 
7288    Input Parameters:
7289 +  mat - the matrix
7290 .  fromRow - matrix from which to copy row block size
7291 -  fromCol - matrix from which to copy column block size (can be same as fromRow)
7292 
7293    Level: developer
7294 
7295 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7296 @*/
7297 PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7298 {
7299   PetscErrorCode ierr;
7300 
7301   PetscFunctionBegin;
7302   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7303   PetscValidHeaderSpecific(fromRow,MAT_CLASSID,2);
7304   PetscValidHeaderSpecific(fromCol,MAT_CLASSID,3);
7305   if (fromRow->rmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);CHKERRQ(ierr);}
7306   if (fromCol->cmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);CHKERRQ(ierr);}
7307   PetscFunctionReturn(0);
7308 }
7309 
7310 /*@
7311    MatResidual - Default routine to calculate the residual.
7312 
7313    Collective on Mat
7314 
7315    Input Parameters:
7316 +  mat - the matrix
7317 .  b   - the right-hand-side
7318 -  x   - the approximate solution
7319 
7320    Output Parameter:
7321 .  r - location to store the residual
7322 
7323    Level: developer
7324 
7325 .seealso: PCMGSetResidual()
7326 @*/
7327 PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7328 {
7329   PetscErrorCode ierr;
7330 
7331   PetscFunctionBegin;
7332   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7333   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
7334   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
7335   PetscValidHeaderSpecific(r,VEC_CLASSID,4);
7336   PetscValidType(mat,1);
7337   MatCheckPreallocated(mat,1);
7338   ierr  = PetscLogEventBegin(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7339   if (!mat->ops->residual) {
7340     ierr = MatMult(mat,x,r);CHKERRQ(ierr);
7341     ierr = VecAYPX(r,-1.0,b);CHKERRQ(ierr);
7342   } else {
7343     ierr  = (*mat->ops->residual)(mat,b,x,r);CHKERRQ(ierr);
7344   }
7345   ierr  = PetscLogEventEnd(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7346   PetscFunctionReturn(0);
7347 }
7348 
7349 /*@C
7350     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7351 
7352    Collective on Mat
7353 
7354     Input Parameters:
7355 +   mat - the matrix
7356 .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7357 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7358 -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7359                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7360                  always used.
7361 
7362     Output Parameters:
7363 +   n - number of rows in the (possibly compressed) matrix
7364 .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7365 .   ja - the column indices
7366 -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7367            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7368 
7369     Level: developer
7370 
7371     Notes:
7372     You CANNOT change any of the ia[] or ja[] values.
7373 
7374     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7375 
7376     Fortran Notes:
7377     In Fortran use
7378 $
7379 $      PetscInt ia(1), ja(1)
7380 $      PetscOffset iia, jja
7381 $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7382 $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7383 
7384      or
7385 $
7386 $    PetscInt, pointer :: ia(:),ja(:)
7387 $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7388 $    ! Access the ith and jth entries via ia(i) and ja(j)
7389 
7390 .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7391 @*/
7392 PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7393 {
7394   PetscErrorCode ierr;
7395 
7396   PetscFunctionBegin;
7397   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7398   PetscValidType(mat,1);
7399   PetscValidIntPointer(n,5);
7400   if (ia) PetscValidIntPointer(ia,6);
7401   if (ja) PetscValidIntPointer(ja,7);
7402   PetscValidIntPointer(done,8);
7403   MatCheckPreallocated(mat,1);
7404   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7405   else {
7406     *done = PETSC_TRUE;
7407     ierr  = PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7408     ierr  = (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7409     ierr  = PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7410   }
7411   PetscFunctionReturn(0);
7412 }
7413 
7414 /*@C
7415     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7416 
7417     Collective on Mat
7418 
7419     Input Parameters:
7420 +   mat - the matrix
7421 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7422 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7423                 symmetrized
7424 .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7425                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7426                  always used.
7427 .   n - number of columns in the (possibly compressed) matrix
7428 .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7429 -   ja - the row indices
7430 
7431     Output Parameters:
7432 .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7433 
7434     Level: developer
7435 
7436 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7437 @*/
7438 PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7439 {
7440   PetscErrorCode ierr;
7441 
7442   PetscFunctionBegin;
7443   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7444   PetscValidType(mat,1);
7445   PetscValidIntPointer(n,4);
7446   if (ia) PetscValidIntPointer(ia,5);
7447   if (ja) PetscValidIntPointer(ja,6);
7448   PetscValidIntPointer(done,7);
7449   MatCheckPreallocated(mat,1);
7450   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7451   else {
7452     *done = PETSC_TRUE;
7453     ierr  = (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7454   }
7455   PetscFunctionReturn(0);
7456 }
7457 
7458 /*@C
7459     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7460     MatGetRowIJ().
7461 
7462     Collective on Mat
7463 
7464     Input Parameters:
7465 +   mat - the matrix
7466 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7467 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7468                 symmetrized
7469 .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7470                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7471                  always used.
7472 .   n - size of (possibly compressed) matrix
7473 .   ia - the row pointers
7474 -   ja - the column indices
7475 
7476     Output Parameters:
7477 .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7478 
7479     Note:
7480     This routine zeros out n, ia, and ja. This is to prevent accidental
7481     us of the array after it has been restored. If you pass NULL, it will
7482     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.
7483 
7484     Level: developer
7485 
7486 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7487 @*/
7488 PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7489 {
7490   PetscErrorCode ierr;
7491 
7492   PetscFunctionBegin;
7493   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7494   PetscValidType(mat,1);
7495   if (ia) PetscValidIntPointer(ia,6);
7496   if (ja) PetscValidIntPointer(ja,7);
7497   PetscValidIntPointer(done,8);
7498   MatCheckPreallocated(mat,1);
7499 
7500   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7501   else {
7502     *done = PETSC_TRUE;
7503     ierr  = (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7504     if (n)  *n = 0;
7505     if (ia) *ia = NULL;
7506     if (ja) *ja = NULL;
7507   }
7508   PetscFunctionReturn(0);
7509 }
7510 
7511 /*@C
7512     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7513     MatGetColumnIJ().
7514 
7515     Collective on Mat
7516 
7517     Input Parameters:
7518 +   mat - the matrix
7519 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7520 -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7521                 symmetrized
7522 -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7523                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7524                  always used.
7525 
7526     Output Parameters:
7527 +   n - size of (possibly compressed) matrix
7528 .   ia - the column pointers
7529 .   ja - the row indices
7530 -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7531 
7532     Level: developer
7533 
7534 .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7535 @*/
7536 PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7537 {
7538   PetscErrorCode ierr;
7539 
7540   PetscFunctionBegin;
7541   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7542   PetscValidType(mat,1);
7543   if (ia) PetscValidIntPointer(ia,5);
7544   if (ja) PetscValidIntPointer(ja,6);
7545   PetscValidIntPointer(done,7);
7546   MatCheckPreallocated(mat,1);
7547 
7548   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7549   else {
7550     *done = PETSC_TRUE;
7551     ierr  = (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7552     if (n)  *n = 0;
7553     if (ia) *ia = NULL;
7554     if (ja) *ja = NULL;
7555   }
7556   PetscFunctionReturn(0);
7557 }
7558 
7559 /*@C
7560     MatColoringPatch -Used inside matrix coloring routines that
7561     use MatGetRowIJ() and/or MatGetColumnIJ().
7562 
7563     Collective on Mat
7564 
7565     Input Parameters:
7566 +   mat - the matrix
7567 .   ncolors - max color value
7568 .   n   - number of entries in colorarray
7569 -   colorarray - array indicating color for each column
7570 
7571     Output Parameters:
7572 .   iscoloring - coloring generated using colorarray information
7573 
7574     Level: developer
7575 
7576 .seealso: MatGetRowIJ(), MatGetColumnIJ()
7577 
7578 @*/
7579 PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7580 {
7581   PetscErrorCode ierr;
7582 
7583   PetscFunctionBegin;
7584   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7585   PetscValidType(mat,1);
7586   PetscValidIntPointer(colorarray,4);
7587   PetscValidPointer(iscoloring,5);
7588   MatCheckPreallocated(mat,1);
7589 
7590   if (!mat->ops->coloringpatch) {
7591     ierr = ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);CHKERRQ(ierr);
7592   } else {
7593     ierr = (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);CHKERRQ(ierr);
7594   }
7595   PetscFunctionReturn(0);
7596 }
7597 
7598 
7599 /*@
7600    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7601 
7602    Logically Collective on Mat
7603 
7604    Input Parameter:
7605 .  mat - the factored matrix to be reset
7606 
7607    Notes:
7608    This routine should be used only with factored matrices formed by in-place
7609    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7610    format).  This option can save memory, for example, when solving nonlinear
7611    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7612    ILU(0) preconditioner.
7613 
7614    Note that one can specify in-place ILU(0) factorization by calling
7615 .vb
7616      PCType(pc,PCILU);
7617      PCFactorSeUseInPlace(pc);
7618 .ve
7619    or by using the options -pc_type ilu -pc_factor_in_place
7620 
7621    In-place factorization ILU(0) can also be used as a local
7622    solver for the blocks within the block Jacobi or additive Schwarz
7623    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7624    for details on setting local solver options.
7625 
7626    Most users should employ the simplified KSP interface for linear solvers
7627    instead of working directly with matrix algebra routines such as this.
7628    See, e.g., KSPCreate().
7629 
7630    Level: developer
7631 
7632 .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7633 
7634 @*/
7635 PetscErrorCode MatSetUnfactored(Mat mat)
7636 {
7637   PetscErrorCode ierr;
7638 
7639   PetscFunctionBegin;
7640   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7641   PetscValidType(mat,1);
7642   MatCheckPreallocated(mat,1);
7643   mat->factortype = MAT_FACTOR_NONE;
7644   if (!mat->ops->setunfactored) PetscFunctionReturn(0);
7645   ierr = (*mat->ops->setunfactored)(mat);CHKERRQ(ierr);
7646   PetscFunctionReturn(0);
7647 }
7648 
7649 /*MC
7650     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7651 
7652     Synopsis:
7653     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7654 
7655     Not collective
7656 
7657     Input Parameter:
7658 .   x - matrix
7659 
7660     Output Parameters:
7661 +   xx_v - the Fortran90 pointer to the array
7662 -   ierr - error code
7663 
7664     Example of Usage:
7665 .vb
7666       PetscScalar, pointer xx_v(:,:)
7667       ....
7668       call MatDenseGetArrayF90(x,xx_v,ierr)
7669       a = xx_v(3)
7670       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7671 .ve
7672 
7673     Level: advanced
7674 
7675 .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7676 
7677 M*/
7678 
7679 /*MC
7680     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7681     accessed with MatDenseGetArrayF90().
7682 
7683     Synopsis:
7684     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7685 
7686     Not collective
7687 
7688     Input Parameters:
7689 +   x - matrix
7690 -   xx_v - the Fortran90 pointer to the array
7691 
7692     Output Parameter:
7693 .   ierr - error code
7694 
7695     Example of Usage:
7696 .vb
7697        PetscScalar, pointer xx_v(:,:)
7698        ....
7699        call MatDenseGetArrayF90(x,xx_v,ierr)
7700        a = xx_v(3)
7701        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7702 .ve
7703 
7704     Level: advanced
7705 
7706 .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7707 
7708 M*/
7709 
7710 
7711 /*MC
7712     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7713 
7714     Synopsis:
7715     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7716 
7717     Not collective
7718 
7719     Input Parameter:
7720 .   x - matrix
7721 
7722     Output Parameters:
7723 +   xx_v - the Fortran90 pointer to the array
7724 -   ierr - error code
7725 
7726     Example of Usage:
7727 .vb
7728       PetscScalar, pointer xx_v(:)
7729       ....
7730       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7731       a = xx_v(3)
7732       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7733 .ve
7734 
7735     Level: advanced
7736 
7737 .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7738 
7739 M*/
7740 
7741 /*MC
7742     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7743     accessed with MatSeqAIJGetArrayF90().
7744 
7745     Synopsis:
7746     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7747 
7748     Not collective
7749 
7750     Input Parameters:
7751 +   x - matrix
7752 -   xx_v - the Fortran90 pointer to the array
7753 
7754     Output Parameter:
7755 .   ierr - error code
7756 
7757     Example of Usage:
7758 .vb
7759        PetscScalar, pointer xx_v(:)
7760        ....
7761        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7762        a = xx_v(3)
7763        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7764 .ve
7765 
7766     Level: advanced
7767 
7768 .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7769 
7770 M*/
7771 
7772 
7773 /*@
7774     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7775                       as the original matrix.
7776 
7777     Collective on Mat
7778 
7779     Input Parameters:
7780 +   mat - the original matrix
7781 .   isrow - parallel IS containing the rows this processor should obtain
7782 .   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.
7783 -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7784 
7785     Output Parameter:
7786 .   newmat - the new submatrix, of the same type as the old
7787 
7788     Level: advanced
7789 
7790     Notes:
7791     The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7792 
7793     Some matrix types place restrictions on the row and column indices, such
7794     as that they be sorted or that they be equal to each other.
7795 
7796     The index sets may not have duplicate entries.
7797 
7798       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7799    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7800    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7801    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7802    you are finished using it.
7803 
7804     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7805     the input matrix.
7806 
7807     If iscol is NULL then all columns are obtained (not supported in Fortran).
7808 
7809    Example usage:
7810    Consider the following 8x8 matrix with 34 non-zero values, that is
7811    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7812    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7813    as follows:
7814 
7815 .vb
7816             1  2  0  |  0  3  0  |  0  4
7817     Proc0   0  5  6  |  7  0  0  |  8  0
7818             9  0 10  | 11  0  0  | 12  0
7819     -------------------------------------
7820            13  0 14  | 15 16 17  |  0  0
7821     Proc1   0 18  0  | 19 20 21  |  0  0
7822             0  0  0  | 22 23  0  | 24  0
7823     -------------------------------------
7824     Proc2  25 26 27  |  0  0 28  | 29  0
7825            30  0  0  | 31 32 33  |  0 34
7826 .ve
7827 
7828     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is
7829 
7830 .vb
7831             2  0  |  0  3  0  |  0
7832     Proc0   5  6  |  7  0  0  |  8
7833     -------------------------------
7834     Proc1  18  0  | 19 20 21  |  0
7835     -------------------------------
7836     Proc2  26 27  |  0  0 28  | 29
7837             0  0  | 31 32 33  |  0
7838 .ve
7839 
7840 
7841 .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7842 @*/
7843 PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7844 {
7845   PetscErrorCode ierr;
7846   PetscMPIInt    size;
7847   Mat            *local;
7848   IS             iscoltmp;
7849   PetscBool      flg;
7850 
7851   PetscFunctionBegin;
7852   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7853   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
7854   if (iscol) PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
7855   PetscValidPointer(newmat,5);
7856   if (cll == MAT_REUSE_MATRIX) PetscValidHeaderSpecific(*newmat,MAT_CLASSID,5);
7857   PetscValidType(mat,1);
7858   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7859   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
7860 
7861   MatCheckPreallocated(mat,1);
7862   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
7863 
7864   if (!iscol || isrow == iscol) {
7865     PetscBool   stride;
7866     PetscMPIInt grabentirematrix = 0,grab;
7867     ierr = PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);CHKERRQ(ierr);
7868     if (stride) {
7869       PetscInt first,step,n,rstart,rend;
7870       ierr = ISStrideGetInfo(isrow,&first,&step);CHKERRQ(ierr);
7871       if (step == 1) {
7872         ierr = MatGetOwnershipRange(mat,&rstart,&rend);CHKERRQ(ierr);
7873         if (rstart == first) {
7874           ierr = ISGetLocalSize(isrow,&n);CHKERRQ(ierr);
7875           if (n == rend-rstart) {
7876             grabentirematrix = 1;
7877           }
7878         }
7879       }
7880     }
7881     ierr = MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
7882     if (grab) {
7883       ierr = PetscInfo(mat,"Getting entire matrix as submatrix\n");CHKERRQ(ierr);
7884       if (cll == MAT_INITIAL_MATRIX) {
7885         *newmat = mat;
7886         ierr    = PetscObjectReference((PetscObject)mat);CHKERRQ(ierr);
7887       }
7888       PetscFunctionReturn(0);
7889     }
7890   }
7891 
7892   if (!iscol) {
7893     ierr = ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);CHKERRQ(ierr);
7894   } else {
7895     iscoltmp = iscol;
7896   }
7897 
7898   /* if original matrix is on just one processor then use submatrix generated */
7899   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7900     ierr = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);CHKERRQ(ierr);
7901     goto setproperties;
7902   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7903     ierr    = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);CHKERRQ(ierr);
7904     *newmat = *local;
7905     ierr    = PetscFree(local);CHKERRQ(ierr);
7906     goto setproperties;
7907   } else if (!mat->ops->createsubmatrix) {
7908     /* Create a new matrix type that implements the operation using the full matrix */
7909     ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7910     switch (cll) {
7911     case MAT_INITIAL_MATRIX:
7912       ierr = MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);CHKERRQ(ierr);
7913       break;
7914     case MAT_REUSE_MATRIX:
7915       ierr = MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);CHKERRQ(ierr);
7916       break;
7917     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7918     }
7919     ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7920     goto setproperties;
7921   }
7922 
7923   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7924   ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7925   ierr = (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);CHKERRQ(ierr);
7926   ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7927 
7928 setproperties:
7929   ierr = ISEqualUnsorted(isrow,iscoltmp,&flg);CHKERRQ(ierr);
7930   if (flg) {
7931     ierr = MatPropagateSymmetryOptions(mat,*newmat);CHKERRQ(ierr);
7932   }
7933   if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
7934   if (*newmat && cll == MAT_INITIAL_MATRIX) {ierr = PetscObjectStateIncrease((PetscObject)*newmat);CHKERRQ(ierr);}
7935   PetscFunctionReturn(0);
7936 }
7937 
7938 /*@
7939    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix
7940 
7941    Not Collective
7942 
7943    Input Parameters:
7944 +  A - the matrix we wish to propagate options from
7945 -  B - the matrix we wish to propagate options to
7946 
7947    Level: beginner
7948 
7949    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC
7950 
7951 .seealso: MatSetOption()
7952 @*/
7953 PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7954 {
7955   PetscErrorCode ierr;
7956 
7957   PetscFunctionBegin;
7958   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
7959   PetscValidHeaderSpecific(B,MAT_CLASSID,1);
7960   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7961     ierr = MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);CHKERRQ(ierr);
7962   }
7963   if (A->structurally_symmetric_set) {
7964     ierr = MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);CHKERRQ(ierr);
7965   }
7966   if (A->hermitian_set) {
7967     ierr = MatSetOption(B,MAT_HERMITIAN,A->hermitian);CHKERRQ(ierr);
7968   }
7969   if (A->spd_set) {
7970     ierr = MatSetOption(B,MAT_SPD,A->spd);CHKERRQ(ierr);
7971   }
7972   if (A->symmetric_set) {
7973     ierr = MatSetOption(B,MAT_SYMMETRIC,A->symmetric);CHKERRQ(ierr);
7974   }
7975   PetscFunctionReturn(0);
7976 }
7977 
7978 /*@
7979    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7980    used during the assembly process to store values that belong to
7981    other processors.
7982 
7983    Not Collective
7984 
7985    Input Parameters:
7986 +  mat   - the matrix
7987 .  size  - the initial size of the stash.
7988 -  bsize - the initial size of the block-stash(if used).
7989 
7990    Options Database Keys:
7991 +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7992 -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>
7993 
7994    Level: intermediate
7995 
7996    Notes:
7997      The block-stash is used for values set with MatSetValuesBlocked() while
7998      the stash is used for values set with MatSetValues()
7999 
8000      Run with the option -info and look for output of the form
8001      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8002      to determine the appropriate value, MM, to use for size and
8003      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8004      to determine the value, BMM to use for bsize
8005 
8006 
8007 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
8008 
8009 @*/
8010 PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8011 {
8012   PetscErrorCode ierr;
8013 
8014   PetscFunctionBegin;
8015   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8016   PetscValidType(mat,1);
8017   ierr = MatStashSetInitialSize_Private(&mat->stash,size);CHKERRQ(ierr);
8018   ierr = MatStashSetInitialSize_Private(&mat->bstash,bsize);CHKERRQ(ierr);
8019   PetscFunctionReturn(0);
8020 }
8021 
8022 /*@
8023    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8024      the matrix
8025 
8026    Neighbor-wise Collective on Mat
8027 
8028    Input Parameters:
8029 +  mat   - the matrix
8030 .  x,y - the vectors
8031 -  w - where the result is stored
8032 
8033    Level: intermediate
8034 
8035    Notes:
8036     w may be the same vector as y.
8037 
8038     This allows one to use either the restriction or interpolation (its transpose)
8039     matrix to do the interpolation
8040 
8041 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8042 
8043 @*/
8044 PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8045 {
8046   PetscErrorCode ierr;
8047   PetscInt       M,N,Ny;
8048 
8049   PetscFunctionBegin;
8050   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8051   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8052   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8053   PetscValidHeaderSpecific(w,VEC_CLASSID,4);
8054   PetscValidType(A,1);
8055   MatCheckPreallocated(A,1);
8056   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8057   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8058   if (M == Ny) {
8059     ierr = MatMultAdd(A,x,y,w);CHKERRQ(ierr);
8060   } else {
8061     ierr = MatMultTransposeAdd(A,x,y,w);CHKERRQ(ierr);
8062   }
8063   PetscFunctionReturn(0);
8064 }
8065 
8066 /*@
8067    MatInterpolate - y = A*x or A'*x depending on the shape of
8068      the matrix
8069 
8070    Neighbor-wise Collective on Mat
8071 
8072    Input Parameters:
8073 +  mat   - the matrix
8074 -  x,y - the vectors
8075 
8076    Level: intermediate
8077 
8078    Notes:
8079     This allows one to use either the restriction or interpolation (its transpose)
8080     matrix to do the interpolation
8081 
8082 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8083 
8084 @*/
8085 PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8086 {
8087   PetscErrorCode ierr;
8088   PetscInt       M,N,Ny;
8089 
8090   PetscFunctionBegin;
8091   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8092   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8093   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8094   PetscValidType(A,1);
8095   MatCheckPreallocated(A,1);
8096   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8097   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8098   if (M == Ny) {
8099     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8100   } else {
8101     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8102   }
8103   PetscFunctionReturn(0);
8104 }
8105 
8106 /*@
8107    MatRestrict - y = A*x or A'*x
8108 
8109    Neighbor-wise Collective on Mat
8110 
8111    Input Parameters:
8112 +  mat   - the matrix
8113 -  x,y - the vectors
8114 
8115    Level: intermediate
8116 
8117    Notes:
8118     This allows one to use either the restriction or interpolation (its transpose)
8119     matrix to do the restriction
8120 
8121 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8122 
8123 @*/
8124 PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8125 {
8126   PetscErrorCode ierr;
8127   PetscInt       M,N,Ny;
8128 
8129   PetscFunctionBegin;
8130   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8131   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8132   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8133   PetscValidType(A,1);
8134   MatCheckPreallocated(A,1);
8135 
8136   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8137   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8138   if (M == Ny) {
8139     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8140   } else {
8141     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8142   }
8143   PetscFunctionReturn(0);
8144 }
8145 
8146 /*@
8147    MatGetNullSpace - retrieves the null space of a matrix.
8148 
8149    Logically Collective on Mat
8150 
8151    Input Parameters:
8152 +  mat - the matrix
8153 -  nullsp - the null space object
8154 
8155    Level: developer
8156 
8157 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8158 @*/
8159 PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8160 {
8161   PetscFunctionBegin;
8162   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8163   PetscValidPointer(nullsp,2);
8164   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8165   PetscFunctionReturn(0);
8166 }
8167 
8168 /*@
8169    MatSetNullSpace - attaches a null space to a matrix.
8170 
8171    Logically Collective on Mat
8172 
8173    Input Parameters:
8174 +  mat - the matrix
8175 -  nullsp - the null space object
8176 
8177    Level: advanced
8178 
8179    Notes:
8180       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8181 
8182       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8183       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8184 
8185       You can remove the null space by calling this routine with an nullsp of NULL
8186 
8187 
8188       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8189    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).
8190    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
8191    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
8192    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).
8193 
8194       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8195 
8196     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
8197     routine also automatically calls MatSetTransposeNullSpace().
8198 
8199 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8200 @*/
8201 PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8202 {
8203   PetscErrorCode ierr;
8204 
8205   PetscFunctionBegin;
8206   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8207   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8208   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8209   ierr = MatNullSpaceDestroy(&mat->nullsp);CHKERRQ(ierr);
8210   mat->nullsp = nullsp;
8211   if (mat->symmetric_set && mat->symmetric) {
8212     ierr = MatSetTransposeNullSpace(mat,nullsp);CHKERRQ(ierr);
8213   }
8214   PetscFunctionReturn(0);
8215 }
8216 
8217 /*@
8218    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8219 
8220    Logically Collective on Mat
8221 
8222    Input Parameters:
8223 +  mat - the matrix
8224 -  nullsp - the null space object
8225 
8226    Level: developer
8227 
8228 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8229 @*/
8230 PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8231 {
8232   PetscFunctionBegin;
8233   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8234   PetscValidType(mat,1);
8235   PetscValidPointer(nullsp,2);
8236   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8237   PetscFunctionReturn(0);
8238 }
8239 
8240 /*@
8241    MatSetTransposeNullSpace - attaches a null space to a matrix.
8242 
8243    Logically Collective on Mat
8244 
8245    Input Parameters:
8246 +  mat - the matrix
8247 -  nullsp - the null space object
8248 
8249    Level: advanced
8250 
8251    Notes:
8252       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.
8253       You must also call MatSetNullSpace()
8254 
8255 
8256       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8257    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).
8258    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
8259    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
8260    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).
8261 
8262       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8263 
8264 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8265 @*/
8266 PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8267 {
8268   PetscErrorCode ierr;
8269 
8270   PetscFunctionBegin;
8271   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8272   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8273   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8274   ierr = MatNullSpaceDestroy(&mat->transnullsp);CHKERRQ(ierr);
8275   mat->transnullsp = nullsp;
8276   PetscFunctionReturn(0);
8277 }
8278 
8279 /*@
8280    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8281         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8282 
8283    Logically Collective on Mat
8284 
8285    Input Parameters:
8286 +  mat - the matrix
8287 -  nullsp - the null space object
8288 
8289    Level: advanced
8290 
8291    Notes:
8292       Overwrites any previous near null space that may have been attached
8293 
8294       You can remove the null space by calling this routine with an nullsp of NULL
8295 
8296 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8297 @*/
8298 PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8299 {
8300   PetscErrorCode ierr;
8301 
8302   PetscFunctionBegin;
8303   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8304   PetscValidType(mat,1);
8305   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8306   MatCheckPreallocated(mat,1);
8307   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8308   ierr = MatNullSpaceDestroy(&mat->nearnullsp);CHKERRQ(ierr);
8309   mat->nearnullsp = nullsp;
8310   PetscFunctionReturn(0);
8311 }
8312 
8313 /*@
8314    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()
8315 
8316    Not Collective
8317 
8318    Input Parameter:
8319 .  mat - the matrix
8320 
8321    Output Parameter:
8322 .  nullsp - the null space object, NULL if not set
8323 
8324    Level: developer
8325 
8326 .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8327 @*/
8328 PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8329 {
8330   PetscFunctionBegin;
8331   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8332   PetscValidType(mat,1);
8333   PetscValidPointer(nullsp,2);
8334   MatCheckPreallocated(mat,1);
8335   *nullsp = mat->nearnullsp;
8336   PetscFunctionReturn(0);
8337 }
8338 
8339 /*@C
8340    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8341 
8342    Collective on Mat
8343 
8344    Input Parameters:
8345 +  mat - the matrix
8346 .  row - row/column permutation
8347 .  fill - expected fill factor >= 1.0
8348 -  level - level of fill, for ICC(k)
8349 
8350    Notes:
8351    Probably really in-place only when level of fill is zero, otherwise allocates
8352    new space to store factored matrix and deletes previous memory.
8353 
8354    Most users should employ the simplified KSP interface for linear solvers
8355    instead of working directly with matrix algebra routines such as this.
8356    See, e.g., KSPCreate().
8357 
8358    Level: developer
8359 
8360 
8361 .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8362 
8363     Developer Note: fortran interface is not autogenerated as the f90
8364     interface defintion cannot be generated correctly [due to MatFactorInfo]
8365 
8366 @*/
8367 PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8368 {
8369   PetscErrorCode ierr;
8370 
8371   PetscFunctionBegin;
8372   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8373   PetscValidType(mat,1);
8374   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
8375   PetscValidPointer(info,3);
8376   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8377   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8378   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8379   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8380   MatCheckPreallocated(mat,1);
8381   ierr = (*mat->ops->iccfactor)(mat,row,info);CHKERRQ(ierr);
8382   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8383   PetscFunctionReturn(0);
8384 }
8385 
8386 /*@
8387    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8388          ghosted ones.
8389 
8390    Not Collective
8391 
8392    Input Parameters:
8393 +  mat - the matrix
8394 -  diag = the diagonal values, including ghost ones
8395 
8396    Level: developer
8397 
8398    Notes:
8399     Works only for MPIAIJ and MPIBAIJ matrices
8400 
8401 .seealso: MatDiagonalScale()
8402 @*/
8403 PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8404 {
8405   PetscErrorCode ierr;
8406   PetscMPIInt    size;
8407 
8408   PetscFunctionBegin;
8409   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8410   PetscValidHeaderSpecific(diag,VEC_CLASSID,2);
8411   PetscValidType(mat,1);
8412 
8413   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8414   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8415   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
8416   if (size == 1) {
8417     PetscInt n,m;
8418     ierr = VecGetSize(diag,&n);CHKERRQ(ierr);
8419     ierr = MatGetSize(mat,0,&m);CHKERRQ(ierr);
8420     if (m == n) {
8421       ierr = MatDiagonalScale(mat,0,diag);CHKERRQ(ierr);
8422     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8423   } else {
8424     ierr = PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));CHKERRQ(ierr);
8425   }
8426   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8427   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8428   PetscFunctionReturn(0);
8429 }
8430 
8431 /*@
8432    MatGetInertia - Gets the inertia from a factored matrix
8433 
8434    Collective on Mat
8435 
8436    Input Parameter:
8437 .  mat - the matrix
8438 
8439    Output Parameters:
8440 +   nneg - number of negative eigenvalues
8441 .   nzero - number of zero eigenvalues
8442 -   npos - number of positive eigenvalues
8443 
8444    Level: advanced
8445 
8446    Notes:
8447     Matrix must have been factored by MatCholeskyFactor()
8448 
8449 
8450 @*/
8451 PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8452 {
8453   PetscErrorCode ierr;
8454 
8455   PetscFunctionBegin;
8456   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8457   PetscValidType(mat,1);
8458   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8459   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8460   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8461   ierr = (*mat->ops->getinertia)(mat,nneg,nzero,npos);CHKERRQ(ierr);
8462   PetscFunctionReturn(0);
8463 }
8464 
8465 /* ----------------------------------------------------------------*/
8466 /*@C
8467    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8468 
8469    Neighbor-wise Collective on Mats
8470 
8471    Input Parameters:
8472 +  mat - the factored matrix
8473 -  b - the right-hand-side vectors
8474 
8475    Output Parameter:
8476 .  x - the result vectors
8477 
8478    Notes:
8479    The vectors b and x cannot be the same.  I.e., one cannot
8480    call MatSolves(A,x,x).
8481 
8482    Notes:
8483    Most users should employ the simplified KSP interface for linear solvers
8484    instead of working directly with matrix algebra routines such as this.
8485    See, e.g., KSPCreate().
8486 
8487    Level: developer
8488 
8489 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8490 @*/
8491 PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8492 {
8493   PetscErrorCode ierr;
8494 
8495   PetscFunctionBegin;
8496   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8497   PetscValidType(mat,1);
8498   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8499   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8500   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
8501 
8502   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8503   MatCheckPreallocated(mat,1);
8504   ierr = PetscLogEventBegin(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8505   ierr = (*mat->ops->solves)(mat,b,x);CHKERRQ(ierr);
8506   ierr = PetscLogEventEnd(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8507   PetscFunctionReturn(0);
8508 }
8509 
8510 /*@
8511    MatIsSymmetric - Test whether a matrix is symmetric
8512 
8513    Collective on Mat
8514 
8515    Input Parameter:
8516 +  A - the matrix to test
8517 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8518 
8519    Output Parameters:
8520 .  flg - the result
8521 
8522    Notes:
8523     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8524 
8525    Level: intermediate
8526 
8527 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8528 @*/
8529 PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8530 {
8531   PetscErrorCode ierr;
8532 
8533   PetscFunctionBegin;
8534   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8535   PetscValidBoolPointer(flg,2);
8536 
8537   if (!A->symmetric_set) {
8538     if (!A->ops->issymmetric) {
8539       MatType mattype;
8540       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8541       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8542     }
8543     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8544     if (!tol) {
8545       ierr = MatSetOption(A,MAT_SYMMETRIC,*flg);CHKERRQ(ierr);
8546     }
8547   } else if (A->symmetric) {
8548     *flg = PETSC_TRUE;
8549   } else if (!tol) {
8550     *flg = PETSC_FALSE;
8551   } else {
8552     if (!A->ops->issymmetric) {
8553       MatType mattype;
8554       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8555       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8556     }
8557     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8558   }
8559   PetscFunctionReturn(0);
8560 }
8561 
8562 /*@
8563    MatIsHermitian - Test whether a matrix is Hermitian
8564 
8565    Collective on Mat
8566 
8567    Input Parameter:
8568 +  A - the matrix to test
8569 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8570 
8571    Output Parameters:
8572 .  flg - the result
8573 
8574    Level: intermediate
8575 
8576 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8577           MatIsSymmetricKnown(), MatIsSymmetric()
8578 @*/
8579 PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8580 {
8581   PetscErrorCode ierr;
8582 
8583   PetscFunctionBegin;
8584   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8585   PetscValidBoolPointer(flg,2);
8586 
8587   if (!A->hermitian_set) {
8588     if (!A->ops->ishermitian) {
8589       MatType mattype;
8590       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8591       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8592     }
8593     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8594     if (!tol) {
8595       ierr = MatSetOption(A,MAT_HERMITIAN,*flg);CHKERRQ(ierr);
8596     }
8597   } else if (A->hermitian) {
8598     *flg = PETSC_TRUE;
8599   } else if (!tol) {
8600     *flg = PETSC_FALSE;
8601   } else {
8602     if (!A->ops->ishermitian) {
8603       MatType mattype;
8604       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8605       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8606     }
8607     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8608   }
8609   PetscFunctionReturn(0);
8610 }
8611 
8612 /*@
8613    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8614 
8615    Not Collective
8616 
8617    Input Parameter:
8618 .  A - the matrix to check
8619 
8620    Output Parameters:
8621 +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8622 -  flg - the result
8623 
8624    Level: advanced
8625 
8626    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8627          if you want it explicitly checked
8628 
8629 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8630 @*/
8631 PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8632 {
8633   PetscFunctionBegin;
8634   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8635   PetscValidPointer(set,2);
8636   PetscValidBoolPointer(flg,3);
8637   if (A->symmetric_set) {
8638     *set = PETSC_TRUE;
8639     *flg = A->symmetric;
8640   } else {
8641     *set = PETSC_FALSE;
8642   }
8643   PetscFunctionReturn(0);
8644 }
8645 
8646 /*@
8647    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8648 
8649    Not Collective
8650 
8651    Input Parameter:
8652 .  A - the matrix to check
8653 
8654    Output Parameters:
8655 +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8656 -  flg - the result
8657 
8658    Level: advanced
8659 
8660    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8661          if you want it explicitly checked
8662 
8663 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8664 @*/
8665 PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8666 {
8667   PetscFunctionBegin;
8668   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8669   PetscValidPointer(set,2);
8670   PetscValidBoolPointer(flg,3);
8671   if (A->hermitian_set) {
8672     *set = PETSC_TRUE;
8673     *flg = A->hermitian;
8674   } else {
8675     *set = PETSC_FALSE;
8676   }
8677   PetscFunctionReturn(0);
8678 }
8679 
8680 /*@
8681    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8682 
8683    Collective on Mat
8684 
8685    Input Parameter:
8686 .  A - the matrix to test
8687 
8688    Output Parameters:
8689 .  flg - the result
8690 
8691    Level: intermediate
8692 
8693 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8694 @*/
8695 PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8696 {
8697   PetscErrorCode ierr;
8698 
8699   PetscFunctionBegin;
8700   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8701   PetscValidBoolPointer(flg,2);
8702   if (!A->structurally_symmetric_set) {
8703     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);
8704     ierr = (*A->ops->isstructurallysymmetric)(A,flg);CHKERRQ(ierr);
8705     ierr = MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);CHKERRQ(ierr);
8706   } else *flg = A->structurally_symmetric;
8707   PetscFunctionReturn(0);
8708 }
8709 
8710 /*@
8711    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8712        to be communicated to other processors during the MatAssemblyBegin/End() process
8713 
8714     Not collective
8715 
8716    Input Parameter:
8717 .   vec - the vector
8718 
8719    Output Parameters:
8720 +   nstash   - the size of the stash
8721 .   reallocs - the number of additional mallocs incurred.
8722 .   bnstash   - the size of the block stash
8723 -   breallocs - the number of additional mallocs incurred.in the block stash
8724 
8725    Level: advanced
8726 
8727 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8728 
8729 @*/
8730 PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8731 {
8732   PetscErrorCode ierr;
8733 
8734   PetscFunctionBegin;
8735   ierr = MatStashGetInfo_Private(&mat->stash,nstash,reallocs);CHKERRQ(ierr);
8736   ierr = MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);CHKERRQ(ierr);
8737   PetscFunctionReturn(0);
8738 }
8739 
8740 /*@C
8741    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8742      parallel layout
8743 
8744    Collective on Mat
8745 
8746    Input Parameter:
8747 .  mat - the matrix
8748 
8749    Output Parameter:
8750 +   right - (optional) vector that the matrix can be multiplied against
8751 -   left - (optional) vector that the matrix vector product can be stored in
8752 
8753    Notes:
8754     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().
8755 
8756   Notes:
8757     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8758 
8759   Level: advanced
8760 
8761 .seealso: MatCreate(), VecDestroy()
8762 @*/
8763 PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8764 {
8765   PetscErrorCode ierr;
8766 
8767   PetscFunctionBegin;
8768   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8769   PetscValidType(mat,1);
8770   if (mat->ops->getvecs) {
8771     ierr = (*mat->ops->getvecs)(mat,right,left);CHKERRQ(ierr);
8772   } else {
8773     PetscInt rbs,cbs;
8774     ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
8775     if (right) {
8776       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8777       ierr = VecCreate(PetscObjectComm((PetscObject)mat),right);CHKERRQ(ierr);
8778       ierr = VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8779       ierr = VecSetBlockSize(*right,cbs);CHKERRQ(ierr);
8780       ierr = VecSetType(*right,mat->defaultvectype);CHKERRQ(ierr);
8781       ierr = PetscLayoutReference(mat->cmap,&(*right)->map);CHKERRQ(ierr);
8782     }
8783     if (left) {
8784       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8785       ierr = VecCreate(PetscObjectComm((PetscObject)mat),left);CHKERRQ(ierr);
8786       ierr = VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8787       ierr = VecSetBlockSize(*left,rbs);CHKERRQ(ierr);
8788       ierr = VecSetType(*left,mat->defaultvectype);CHKERRQ(ierr);
8789       ierr = PetscLayoutReference(mat->rmap,&(*left)->map);CHKERRQ(ierr);
8790     }
8791   }
8792   PetscFunctionReturn(0);
8793 }
8794 
8795 /*@C
8796    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8797      with default values.
8798 
8799    Not Collective
8800 
8801    Input Parameters:
8802 .    info - the MatFactorInfo data structure
8803 
8804 
8805    Notes:
8806     The solvers are generally used through the KSP and PC objects, for example
8807           PCLU, PCILU, PCCHOLESKY, PCICC
8808 
8809    Level: developer
8810 
8811 .seealso: MatFactorInfo
8812 
8813     Developer Note: fortran interface is not autogenerated as the f90
8814     interface defintion cannot be generated correctly [due to MatFactorInfo]
8815 
8816 @*/
8817 
8818 PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8819 {
8820   PetscErrorCode ierr;
8821 
8822   PetscFunctionBegin;
8823   ierr = PetscMemzero(info,sizeof(MatFactorInfo));CHKERRQ(ierr);
8824   PetscFunctionReturn(0);
8825 }
8826 
8827 /*@
8828    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
8829 
8830    Collective on Mat
8831 
8832    Input Parameters:
8833 +  mat - the factored matrix
8834 -  is - the index set defining the Schur indices (0-based)
8835 
8836    Notes:
8837     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
8838 
8839    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
8840 
8841    Level: developer
8842 
8843 .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8844           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
8845 
8846 @*/
8847 PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8848 {
8849   PetscErrorCode ierr,(*f)(Mat,IS);
8850 
8851   PetscFunctionBegin;
8852   PetscValidType(mat,1);
8853   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8854   PetscValidType(is,2);
8855   PetscValidHeaderSpecific(is,IS_CLASSID,2);
8856   PetscCheckSameComm(mat,1,is,2);
8857   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8858   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);CHKERRQ(ierr);
8859   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");
8860   ierr = MatDestroy(&mat->schur);CHKERRQ(ierr);
8861   ierr = (*f)(mat,is);CHKERRQ(ierr);
8862   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8863   PetscFunctionReturn(0);
8864 }
8865 
8866 /*@
8867   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
8868 
8869    Logically Collective on Mat
8870 
8871    Input Parameters:
8872 +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8873 .  S - location where to return the Schur complement, can be NULL
8874 -  status - the status of the Schur complement matrix, can be NULL
8875 
8876    Notes:
8877    You must call MatFactorSetSchurIS() before calling this routine.
8878 
8879    The routine provides a copy of the Schur matrix stored within the solver data structures.
8880    The caller must destroy the object when it is no longer needed.
8881    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
8882 
8883    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)
8884 
8885    Developer Notes:
8886     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8887    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
8888 
8889    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8890 
8891    Level: advanced
8892 
8893    References:
8894 
8895 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8896 @*/
8897 PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8898 {
8899   PetscErrorCode ierr;
8900 
8901   PetscFunctionBegin;
8902   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8903   if (S) PetscValidPointer(S,2);
8904   if (status) PetscValidPointer(status,3);
8905   if (S) {
8906     PetscErrorCode (*f)(Mat,Mat*);
8907 
8908     ierr = PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);CHKERRQ(ierr);
8909     if (f) {
8910       ierr = (*f)(F,S);CHKERRQ(ierr);
8911     } else {
8912       ierr = MatDuplicate(F->schur,MAT_COPY_VALUES,S);CHKERRQ(ierr);
8913     }
8914   }
8915   if (status) *status = F->schur_status;
8916   PetscFunctionReturn(0);
8917 }
8918 
8919 /*@
8920   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
8921 
8922    Logically Collective on Mat
8923 
8924    Input Parameters:
8925 +  F - the factored matrix obtained by calling MatGetFactor()
8926 .  *S - location where to return the Schur complement, can be NULL
8927 -  status - the status of the Schur complement matrix, can be NULL
8928 
8929    Notes:
8930    You must call MatFactorSetSchurIS() before calling this routine.
8931 
8932    Schur complement mode is currently implemented for sequential matrices.
8933    The routine returns a the Schur Complement stored within the data strutures of the solver.
8934    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8935    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
8936 
8937    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
8938 
8939    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8940 
8941    Level: advanced
8942 
8943    References:
8944 
8945 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8946 @*/
8947 PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8948 {
8949   PetscFunctionBegin;
8950   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8951   if (S) PetscValidPointer(S,2);
8952   if (status) PetscValidPointer(status,3);
8953   if (S) *S = F->schur;
8954   if (status) *status = F->schur_status;
8955   PetscFunctionReturn(0);
8956 }
8957 
8958 /*@
8959   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
8960 
8961    Logically Collective on Mat
8962 
8963    Input Parameters:
8964 +  F - the factored matrix obtained by calling MatGetFactor()
8965 .  *S - location where the Schur complement is stored
8966 -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)
8967 
8968    Notes:
8969 
8970    Level: advanced
8971 
8972    References:
8973 
8974 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8975 @*/
8976 PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8977 {
8978   PetscErrorCode ierr;
8979 
8980   PetscFunctionBegin;
8981   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8982   if (S) {
8983     PetscValidHeaderSpecific(*S,MAT_CLASSID,2);
8984     *S = NULL;
8985   }
8986   F->schur_status = status;
8987   ierr = MatFactorUpdateSchurStatus_Private(F);CHKERRQ(ierr);
8988   PetscFunctionReturn(0);
8989 }
8990 
8991 /*@
8992   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
8993 
8994    Logically Collective on Mat
8995 
8996    Input Parameters:
8997 +  F - the factored matrix obtained by calling MatGetFactor()
8998 .  rhs - location where the right hand side of the Schur complement system is stored
8999 -  sol - location where the solution of the Schur complement system has to be returned
9000 
9001    Notes:
9002    The sizes of the vectors should match the size of the Schur complement
9003 
9004    Must be called after MatFactorSetSchurIS()
9005 
9006    Level: advanced
9007 
9008    References:
9009 
9010 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9011 @*/
9012 PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9013 {
9014   PetscErrorCode ierr;
9015 
9016   PetscFunctionBegin;
9017   PetscValidType(F,1);
9018   PetscValidType(rhs,2);
9019   PetscValidType(sol,3);
9020   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9021   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
9022   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
9023   PetscCheckSameComm(F,1,rhs,2);
9024   PetscCheckSameComm(F,1,sol,3);
9025   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9026   switch (F->schur_status) {
9027   case MAT_FACTOR_SCHUR_FACTORED:
9028     ierr = MatSolveTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
9029     break;
9030   case MAT_FACTOR_SCHUR_INVERTED:
9031     ierr = MatMultTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
9032     break;
9033   default:
9034     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9035     break;
9036   }
9037   PetscFunctionReturn(0);
9038 }
9039 
9040 /*@
9041   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
9042 
9043    Logically Collective on Mat
9044 
9045    Input Parameters:
9046 +  F - the factored matrix obtained by calling MatGetFactor()
9047 .  rhs - location where the right hand side of the Schur complement system is stored
9048 -  sol - location where the solution of the Schur complement system has to be returned
9049 
9050    Notes:
9051    The sizes of the vectors should match the size of the Schur complement
9052 
9053    Must be called after MatFactorSetSchurIS()
9054 
9055    Level: advanced
9056 
9057    References:
9058 
9059 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9060 @*/
9061 PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9062 {
9063   PetscErrorCode ierr;
9064 
9065   PetscFunctionBegin;
9066   PetscValidType(F,1);
9067   PetscValidType(rhs,2);
9068   PetscValidType(sol,3);
9069   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9070   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
9071   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
9072   PetscCheckSameComm(F,1,rhs,2);
9073   PetscCheckSameComm(F,1,sol,3);
9074   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9075   switch (F->schur_status) {
9076   case MAT_FACTOR_SCHUR_FACTORED:
9077     ierr = MatSolve(F->schur,rhs,sol);CHKERRQ(ierr);
9078     break;
9079   case MAT_FACTOR_SCHUR_INVERTED:
9080     ierr = MatMult(F->schur,rhs,sol);CHKERRQ(ierr);
9081     break;
9082   default:
9083     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9084     break;
9085   }
9086   PetscFunctionReturn(0);
9087 }
9088 
9089 /*@
9090   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9091 
9092    Logically Collective on Mat
9093 
9094    Input Parameters:
9095 .  F - the factored matrix obtained by calling MatGetFactor()
9096 
9097    Notes:
9098     Must be called after MatFactorSetSchurIS().
9099 
9100    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9101 
9102    Level: advanced
9103 
9104    References:
9105 
9106 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9107 @*/
9108 PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9109 {
9110   PetscErrorCode ierr;
9111 
9112   PetscFunctionBegin;
9113   PetscValidType(F,1);
9114   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9115   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(0);
9116   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9117   ierr = MatFactorInvertSchurComplement_Private(F);CHKERRQ(ierr);
9118   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9119   PetscFunctionReturn(0);
9120 }
9121 
9122 /*@
9123   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9124 
9125    Logically Collective on Mat
9126 
9127    Input Parameters:
9128 .  F - the factored matrix obtained by calling MatGetFactor()
9129 
9130    Notes:
9131     Must be called after MatFactorSetSchurIS().
9132 
9133    Level: advanced
9134 
9135    References:
9136 
9137 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9138 @*/
9139 PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9140 {
9141   PetscErrorCode ierr;
9142 
9143   PetscFunctionBegin;
9144   PetscValidType(F,1);
9145   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9146   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(0);
9147   ierr = MatFactorFactorizeSchurComplement_Private(F);CHKERRQ(ierr);
9148   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9149   PetscFunctionReturn(0);
9150 }
9151 
9152 /*@
9153    MatPtAP - Creates the matrix product C = P^T * A * P
9154 
9155    Neighbor-wise Collective on Mat
9156 
9157    Input Parameters:
9158 +  A - the matrix
9159 .  P - the projection matrix
9160 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9161 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9162           if the result is a dense matrix this is irrelevent
9163 
9164    Output Parameters:
9165 .  C - the product matrix
9166 
9167    Notes:
9168    C will be created and must be destroyed by the user with MatDestroy().
9169 
9170    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().
9171 
9172    Level: intermediate
9173 
9174 .seealso: MatMatMult(), MatRARt()
9175 @*/
9176 PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9177 {
9178   PetscErrorCode ierr;
9179 
9180   PetscFunctionBegin;
9181   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9182 
9183   if (scall == MAT_INITIAL_MATRIX) {
9184     ierr = MatProductCreate(A,P,NULL,C);CHKERRQ(ierr);
9185     ierr = MatProductSetType(*C,MATPRODUCT_PtAP);CHKERRQ(ierr);
9186     ierr = MatProductSetAlgorithm(*C,"default");CHKERRQ(ierr);
9187     ierr = MatProductSetFill(*C,fill);CHKERRQ(ierr);
9188 
9189     (*C)->product->api_user = PETSC_TRUE;
9190     ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9191     ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9192   } else {
9193     Mat_Product *product = (*C)->product;
9194     if (product) { /* user may chage input matrices A or B when REUSE */
9195       ierr = MatProductReplaceMats(A,P,NULL,*C);CHKERRQ(ierr);
9196     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9197   }
9198 
9199   ierr = MatProductNumeric(*C);CHKERRQ(ierr);
9200   if (A->symmetric_set && A->symmetric) {
9201     ierr = MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
9202   }
9203   PetscFunctionReturn(0);
9204 }
9205 
9206 /*@
9207    MatRARt - Creates the matrix product C = R * A * R^T
9208 
9209    Neighbor-wise Collective on Mat
9210 
9211    Input Parameters:
9212 +  A - the matrix
9213 .  R - the projection matrix
9214 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9215 -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9216           if the result is a dense matrix this is irrelevent
9217 
9218    Output Parameters:
9219 .  C - the product matrix
9220 
9221    Notes:
9222    C will be created and must be destroyed by the user with MatDestroy().
9223 
9224    This routine is currently only implemented for pairs of AIJ matrices and classes
9225    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9226    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9227    We recommend using MatPtAP().
9228 
9229    Level: intermediate
9230 
9231 .seealso: MatMatMult(), MatPtAP()
9232 @*/
9233 PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9234 {
9235   PetscErrorCode ierr;
9236 
9237   PetscFunctionBegin;
9238   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9239 
9240   if (scall == MAT_INITIAL_MATRIX) {
9241     ierr = MatProductCreate(A,R,NULL,C);CHKERRQ(ierr);
9242     ierr = MatProductSetType(*C,MATPRODUCT_RARt);CHKERRQ(ierr);
9243     ierr = MatProductSetAlgorithm(*C,"default");CHKERRQ(ierr);
9244     ierr = MatProductSetFill(*C,fill);CHKERRQ(ierr);
9245 
9246     (*C)->product->api_user = PETSC_TRUE;
9247     ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9248     ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9249   } else { /* scall == MAT_REUSE_MATRIX */
9250     Mat_Product *product = (*C)->product;
9251     if (product) {
9252       /* user may chage input matrices A or R when REUSE */
9253       ierr = MatProductReplaceMats(A,R,NULL,*C);CHKERRQ(ierr);
9254     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9255   }
9256 
9257   ierr = MatProductNumeric(*C);CHKERRQ(ierr);
9258   PetscFunctionReturn(0);
9259 }
9260 
9261 
9262 static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
9263 {
9264   PetscBool      clearproduct = PETSC_FALSE;
9265   PetscErrorCode ierr;
9266 
9267   PetscFunctionBegin;
9268   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9269 
9270   if (scall == MAT_INITIAL_MATRIX) {
9271     ierr = MatProductCreate(A,B,NULL,C);CHKERRQ(ierr);
9272     ierr = MatProductSetType(*C,ptype);CHKERRQ(ierr);
9273     ierr = MatProductSetAlgorithm(*C,"default");CHKERRQ(ierr);
9274     ierr = MatProductSetFill(*C,fill);CHKERRQ(ierr);
9275 
9276     (*C)->product->api_user = PETSC_TRUE;
9277     ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9278     ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9279   } else { /* scall == MAT_REUSE_MATRIX */
9280     Mat_Product *product = (*C)->product;
9281     if (!product) {
9282       /* user provide the dense matrix *C without calling MatProductCreate() */
9283       PetscBool seqdense,mpidense,dense;
9284 #if defined(PETSC_HAVE_CUDA)
9285       PetscBool seqdensecuda;
9286 #endif
9287       ierr = PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);CHKERRQ(ierr);
9288       ierr = PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);CHKERRQ(ierr);
9289       ierr = PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);CHKERRQ(ierr);
9290 #if defined(PETSC_HAVE_CUDA)
9291       ierr = PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSECUDA,&seqdensecuda);CHKERRQ(ierr);
9292       if (seqdense || mpidense || dense || seqdensecuda) {
9293 #else
9294       if (seqdense || mpidense || dense) {
9295 #endif
9296         /* user wants to reuse an assembled dense matrix */
9297         /* Create product -- see MatCreateProduct() */
9298         ierr = MatProductCreate_Private(A,B,NULL,*C);CHKERRQ(ierr);
9299         product = (*C)->product;
9300         product->fill     = fill;
9301         product->api_user = PETSC_TRUE;
9302 
9303         ierr = MatProductSetType(*C,ptype);CHKERRQ(ierr);
9304         ierr = MatProductSetFromOptions(*C);CHKERRQ(ierr);
9305         ierr = MatProductSymbolic(*C);CHKERRQ(ierr);
9306       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9307       clearproduct = PETSC_TRUE;
9308     } else { /* user may chage input matrices A or B when REUSE */
9309       ierr = MatProductReplaceMats(A,B,NULL,*C);CHKERRQ(ierr);
9310     }
9311   }
9312   ierr = MatProductNumeric(*C);CHKERRQ(ierr);
9313   if (clearproduct) {
9314     ierr = MatProductClear(*C);CHKERRQ(ierr);
9315   }
9316   PetscFunctionReturn(0);
9317 }
9318 
9319 /*@
9320    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
9321 
9322    Neighbor-wise Collective on Mat
9323 
9324    Input Parameters:
9325 +  A - the left matrix
9326 .  B - the right matrix
9327 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9328 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9329           if the result is a dense matrix this is irrelevent
9330 
9331    Output Parameters:
9332 .  C - the product matrix
9333 
9334    Notes:
9335    Unless scall is MAT_REUSE_MATRIX C will be created.
9336 
9337    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
9338    call to this function with MAT_INITIAL_MATRIX.
9339 
9340    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.
9341 
9342    If you have many matrices with the same non-zero structure to multiply, you should use MatProductCreate()/MatProductSymbolic(C)/ReplaceMats(), and call MatProductNumeric() repeatedly.
9343 
9344    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.
9345 
9346    Level: intermediate
9347 
9348 .seealso: MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
9349 @*/
9350 PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9351 {
9352   PetscErrorCode ierr;
9353 
9354   PetscFunctionBegin;
9355   ierr = MatProduct_Private(A,B,scall,fill,MATPRODUCT_AB,C);CHKERRQ(ierr);
9356   PetscFunctionReturn(0);
9357 }
9358 
9359 /*@
9360    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9361 
9362    Neighbor-wise Collective on Mat
9363 
9364    Input Parameters:
9365 +  A - the left matrix
9366 .  B - the right matrix
9367 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9368 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9369 
9370    Output Parameters:
9371 .  C - the product matrix
9372 
9373    Notes:
9374    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9375 
9376    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9377 
9378   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9379    actually needed.
9380 
9381    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9382    and for pairs of MPIDense matrices.
9383 
9384    Options Database Keys:
9385 .  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9386                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9387                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.
9388 
9389    Level: intermediate
9390 
9391 .seealso: MatMatMult(), MatTransposeMatMult() MatPtAP()
9392 @*/
9393 PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9394 {
9395   PetscErrorCode ierr;
9396 
9397   PetscFunctionBegin;
9398   ierr = MatProduct_Private(A,B,scall,fill,MATPRODUCT_ABt,C);CHKERRQ(ierr);
9399   PetscFunctionReturn(0);
9400 }
9401 
9402 /*@
9403    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
9404 
9405    Neighbor-wise Collective on Mat
9406 
9407    Input Parameters:
9408 +  A - the left matrix
9409 .  B - the right matrix
9410 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9411 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9412 
9413    Output Parameters:
9414 .  C - the product matrix
9415 
9416    Notes:
9417    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9418 
9419    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call.
9420 
9421   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9422    actually needed.
9423 
9424    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9425    which inherit from SeqAIJ.  C will be of same type as the input matrices.
9426 
9427    Level: intermediate
9428 
9429 .seealso: MatMatMult(), MatMatTransposeMult(), MatPtAP()
9430 @*/
9431 PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9432 {
9433   PetscErrorCode ierr;
9434 
9435   PetscFunctionBegin;
9436   ierr = MatProduct_Private(A,B,scall,fill,MATPRODUCT_AtB,C);CHKERRQ(ierr);
9437   PetscFunctionReturn(0);
9438 }
9439 
9440 /*@
9441    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
9442 
9443    Neighbor-wise Collective on Mat
9444 
9445    Input Parameters:
9446 +  A - the left matrix
9447 .  B - the middle matrix
9448 .  C - the right matrix
9449 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9450 -  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
9451           if the result is a dense matrix this is irrelevent
9452 
9453    Output Parameters:
9454 .  D - the product matrix
9455 
9456    Notes:
9457    Unless scall is MAT_REUSE_MATRIX D will be created.
9458 
9459    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
9460 
9461    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9462    actually needed.
9463 
9464    If you have many matrices with the same non-zero structure to multiply, you
9465    should use MAT_REUSE_MATRIX in all calls but the first or
9466 
9467    Level: intermediate
9468 
9469 .seealso: MatMatMult, MatPtAP()
9470 @*/
9471 PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9472 {
9473   PetscErrorCode ierr;
9474 
9475   PetscFunctionBegin;
9476   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9477 
9478   if (scall == MAT_INITIAL_MATRIX) {
9479     ierr = MatProductCreate(A,B,C,D);CHKERRQ(ierr);
9480     ierr = MatProductSetType(*D,MATPRODUCT_ABC);CHKERRQ(ierr);
9481     ierr = MatProductSetAlgorithm(*D,"default");CHKERRQ(ierr);
9482     ierr = MatProductSetFill(*D,fill);CHKERRQ(ierr);
9483 
9484     (*D)->product->api_user = PETSC_TRUE;
9485     ierr = MatProductSetFromOptions(*D);CHKERRQ(ierr);
9486 
9487     ierr = MatProductSymbolic(*D);CHKERRQ(ierr);
9488   } else { /* user may chage input matrices when REUSE */
9489     ierr = MatProductReplaceMats(A,B,C,*D);CHKERRQ(ierr);
9490   }
9491 
9492   ierr = MatProductNumeric(*D);CHKERRQ(ierr);
9493   PetscFunctionReturn(0);
9494 }
9495 
9496 /*@
9497    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
9498 
9499    Collective on Mat
9500 
9501    Input Parameters:
9502 +  mat - the matrix
9503 .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9504 .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9505 -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9506 
9507    Output Parameter:
9508 .  matredundant - redundant matrix
9509 
9510    Notes:
9511    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9512    original matrix has not changed from that last call to MatCreateRedundantMatrix().
9513 
9514    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9515    calling it.
9516 
9517    Level: advanced
9518 
9519 
9520 .seealso: MatDestroy()
9521 @*/
9522 PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9523 {
9524   PetscErrorCode ierr;
9525   MPI_Comm       comm;
9526   PetscMPIInt    size;
9527   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9528   Mat_Redundant  *redund=NULL;
9529   PetscSubcomm   psubcomm=NULL;
9530   MPI_Comm       subcomm_in=subcomm;
9531   Mat            *matseq;
9532   IS             isrow,iscol;
9533   PetscBool      newsubcomm=PETSC_FALSE;
9534 
9535   PetscFunctionBegin;
9536   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9537   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9538     PetscValidPointer(*matredundant,5);
9539     PetscValidHeaderSpecific(*matredundant,MAT_CLASSID,5);
9540   }
9541 
9542   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
9543   if (size == 1 || nsubcomm == 1) {
9544     if (reuse == MAT_INITIAL_MATRIX) {
9545       ierr = MatDuplicate(mat,MAT_COPY_VALUES,matredundant);CHKERRQ(ierr);
9546     } else {
9547       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");
9548       ierr = MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
9549     }
9550     PetscFunctionReturn(0);
9551   }
9552 
9553   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9554   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9555   MatCheckPreallocated(mat,1);
9556 
9557   ierr = PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
9558   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9559     /* create psubcomm, then get subcomm */
9560     ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
9561     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
9562     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
9563 
9564     ierr = PetscSubcommCreate(comm,&psubcomm);CHKERRQ(ierr);
9565     ierr = PetscSubcommSetNumber(psubcomm,nsubcomm);CHKERRQ(ierr);
9566     ierr = PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);CHKERRQ(ierr);
9567     ierr = PetscSubcommSetFromOptions(psubcomm);CHKERRQ(ierr);
9568     ierr = PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);CHKERRQ(ierr);
9569     newsubcomm = PETSC_TRUE;
9570     ierr = PetscSubcommDestroy(&psubcomm);CHKERRQ(ierr);
9571   }
9572 
9573   /* get isrow, iscol and a local sequential matrix matseq[0] */
9574   if (reuse == MAT_INITIAL_MATRIX) {
9575     mloc_sub = PETSC_DECIDE;
9576     nloc_sub = PETSC_DECIDE;
9577     if (bs < 1) {
9578       ierr = PetscSplitOwnership(subcomm,&mloc_sub,&M);CHKERRQ(ierr);
9579       ierr = PetscSplitOwnership(subcomm,&nloc_sub,&N);CHKERRQ(ierr);
9580     } else {
9581       ierr = PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);CHKERRQ(ierr);
9582       ierr = PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);CHKERRQ(ierr);
9583     }
9584     ierr = MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);CHKERRQ(ierr);
9585     rstart = rend - mloc_sub;
9586     ierr = ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);CHKERRQ(ierr);
9587     ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);CHKERRQ(ierr);
9588   } else { /* reuse == MAT_REUSE_MATRIX */
9589     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");
9590     /* retrieve subcomm */
9591     ierr = PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);CHKERRQ(ierr);
9592     redund = (*matredundant)->redundant;
9593     isrow  = redund->isrow;
9594     iscol  = redund->iscol;
9595     matseq = redund->matseq;
9596   }
9597   ierr = MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);CHKERRQ(ierr);
9598 
9599   /* get matredundant over subcomm */
9600   if (reuse == MAT_INITIAL_MATRIX) {
9601     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);CHKERRQ(ierr);
9602 
9603     /* create a supporting struct and attach it to C for reuse */
9604     ierr = PetscNewLog(*matredundant,&redund);CHKERRQ(ierr);
9605     (*matredundant)->redundant = redund;
9606     redund->isrow              = isrow;
9607     redund->iscol              = iscol;
9608     redund->matseq             = matseq;
9609     if (newsubcomm) {
9610       redund->subcomm          = subcomm;
9611     } else {
9612       redund->subcomm          = MPI_COMM_NULL;
9613     }
9614   } else {
9615     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);CHKERRQ(ierr);
9616   }
9617   ierr = PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
9618   PetscFunctionReturn(0);
9619 }
9620 
9621 /*@C
9622    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
9623    a given 'mat' object. Each submatrix can span multiple procs.
9624 
9625    Collective on Mat
9626 
9627    Input Parameters:
9628 +  mat - the matrix
9629 .  subcomm - the subcommunicator obtained by com_split(comm)
9630 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9631 
9632    Output Parameter:
9633 .  subMat - 'parallel submatrices each spans a given subcomm
9634 
9635   Notes:
9636   The submatrix partition across processors is dictated by 'subComm' a
9637   communicator obtained by com_split(comm). The comm_split
9638   is not restriced to be grouped with consecutive original ranks.
9639 
9640   Due the comm_split() usage, the parallel layout of the submatrices
9641   map directly to the layout of the original matrix [wrt the local
9642   row,col partitioning]. So the original 'DiagonalMat' naturally maps
9643   into the 'DiagonalMat' of the subMat, hence it is used directly from
9644   the subMat. However the offDiagMat looses some columns - and this is
9645   reconstructed with MatSetValues()
9646 
9647   Level: advanced
9648 
9649 
9650 .seealso: MatCreateSubMatrices()
9651 @*/
9652 PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
9653 {
9654   PetscErrorCode ierr;
9655   PetscMPIInt    commsize,subCommSize;
9656 
9657   PetscFunctionBegin;
9658   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);CHKERRQ(ierr);
9659   ierr = MPI_Comm_size(subComm,&subCommSize);CHKERRQ(ierr);
9660   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
9661 
9662   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");
9663   ierr = PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
9664   ierr = (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);CHKERRQ(ierr);
9665   ierr = PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
9666   PetscFunctionReturn(0);
9667 }
9668 
9669 /*@
9670    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
9671 
9672    Not Collective
9673 
9674    Input Arguments:
9675 +  mat - matrix to extract local submatrix from
9676 .  isrow - local row indices for submatrix
9677 -  iscol - local column indices for submatrix
9678 
9679    Output Arguments:
9680 .  submat - the submatrix
9681 
9682    Level: intermediate
9683 
9684    Notes:
9685    The submat should be returned with MatRestoreLocalSubMatrix().
9686 
9687    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
9688    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
9689 
9690    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
9691    MatSetValuesBlockedLocal() will also be implemented.
9692 
9693    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
9694    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.
9695 
9696 .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
9697 @*/
9698 PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9699 {
9700   PetscErrorCode ierr;
9701 
9702   PetscFunctionBegin;
9703   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9704   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
9705   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
9706   PetscCheckSameComm(isrow,2,iscol,3);
9707   PetscValidPointer(submat,4);
9708   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");
9709 
9710   if (mat->ops->getlocalsubmatrix) {
9711     ierr = (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
9712   } else {
9713     ierr = MatCreateLocalRef(mat,isrow,iscol,submat);CHKERRQ(ierr);
9714   }
9715   PetscFunctionReturn(0);
9716 }
9717 
9718 /*@
9719    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
9720 
9721    Not Collective
9722 
9723    Input Arguments:
9724    mat - matrix to extract local submatrix from
9725    isrow - local row indices for submatrix
9726    iscol - local column indices for submatrix
9727    submat - the submatrix
9728 
9729    Level: intermediate
9730 
9731 .seealso: MatGetLocalSubMatrix()
9732 @*/
9733 PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9734 {
9735   PetscErrorCode ierr;
9736 
9737   PetscFunctionBegin;
9738   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9739   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
9740   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
9741   PetscCheckSameComm(isrow,2,iscol,3);
9742   PetscValidPointer(submat,4);
9743   if (*submat) {
9744     PetscValidHeaderSpecific(*submat,MAT_CLASSID,4);
9745   }
9746 
9747   if (mat->ops->restorelocalsubmatrix) {
9748     ierr = (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
9749   } else {
9750     ierr = MatDestroy(submat);CHKERRQ(ierr);
9751   }
9752   *submat = NULL;
9753   PetscFunctionReturn(0);
9754 }
9755 
9756 /* --------------------------------------------------------*/
9757 /*@
9758    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
9759 
9760    Collective on Mat
9761 
9762    Input Parameter:
9763 .  mat - the matrix
9764 
9765    Output Parameter:
9766 .  is - if any rows have zero diagonals this contains the list of them
9767 
9768    Level: developer
9769 
9770 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9771 @*/
9772 PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
9773 {
9774   PetscErrorCode ierr;
9775 
9776   PetscFunctionBegin;
9777   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9778   PetscValidType(mat,1);
9779   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9780   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9781 
9782   if (!mat->ops->findzerodiagonals) {
9783     Vec                diag;
9784     const PetscScalar *a;
9785     PetscInt          *rows;
9786     PetscInt           rStart, rEnd, r, nrow = 0;
9787 
9788     ierr = MatCreateVecs(mat, &diag, NULL);CHKERRQ(ierr);
9789     ierr = MatGetDiagonal(mat, diag);CHKERRQ(ierr);
9790     ierr = MatGetOwnershipRange(mat, &rStart, &rEnd);CHKERRQ(ierr);
9791     ierr = VecGetArrayRead(diag, &a);CHKERRQ(ierr);
9792     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
9793     ierr = PetscMalloc1(nrow, &rows);CHKERRQ(ierr);
9794     nrow = 0;
9795     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
9796     ierr = VecRestoreArrayRead(diag, &a);CHKERRQ(ierr);
9797     ierr = VecDestroy(&diag);CHKERRQ(ierr);
9798     ierr = ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);CHKERRQ(ierr);
9799   } else {
9800     ierr = (*mat->ops->findzerodiagonals)(mat, is);CHKERRQ(ierr);
9801   }
9802   PetscFunctionReturn(0);
9803 }
9804 
9805 /*@
9806    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
9807 
9808    Collective on Mat
9809 
9810    Input Parameter:
9811 .  mat - the matrix
9812 
9813    Output Parameter:
9814 .  is - contains the list of rows with off block diagonal entries
9815 
9816    Level: developer
9817 
9818 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9819 @*/
9820 PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
9821 {
9822   PetscErrorCode ierr;
9823 
9824   PetscFunctionBegin;
9825   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9826   PetscValidType(mat,1);
9827   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9828   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9829 
9830   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);
9831   ierr = (*mat->ops->findoffblockdiagonalentries)(mat,is);CHKERRQ(ierr);
9832   PetscFunctionReturn(0);
9833 }
9834 
9835 /*@C
9836   MatInvertBlockDiagonal - Inverts the block diagonal entries.
9837 
9838   Collective on Mat
9839 
9840   Input Parameters:
9841 . mat - the matrix
9842 
9843   Output Parameters:
9844 . values - the block inverses in column major order (FORTRAN-like)
9845 
9846    Note:
9847    This routine is not available from Fortran.
9848 
9849   Level: advanced
9850 
9851 .seealso: MatInvertBockDiagonalMat
9852 @*/
9853 PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
9854 {
9855   PetscErrorCode ierr;
9856 
9857   PetscFunctionBegin;
9858   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9859   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9860   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9861   if (!mat->ops->invertblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type %s",((PetscObject)mat)->type_name);
9862   ierr = (*mat->ops->invertblockdiagonal)(mat,values);CHKERRQ(ierr);
9863   PetscFunctionReturn(0);
9864 }
9865 
9866 /*@C
9867   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.
9868 
9869   Collective on Mat
9870 
9871   Input Parameters:
9872 + mat - the matrix
9873 . nblocks - the number of blocks
9874 - bsizes - the size of each block
9875 
9876   Output Parameters:
9877 . values - the block inverses in column major order (FORTRAN-like)
9878 
9879    Note:
9880    This routine is not available from Fortran.
9881 
9882   Level: advanced
9883 
9884 .seealso: MatInvertBockDiagonal()
9885 @*/
9886 PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
9887 {
9888   PetscErrorCode ierr;
9889 
9890   PetscFunctionBegin;
9891   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9892   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9893   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9894   if (!mat->ops->invertvariableblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type",((PetscObject)mat)->type_name);
9895   ierr = (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);CHKERRQ(ierr);
9896   PetscFunctionReturn(0);
9897 }
9898 
9899 /*@
9900   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A
9901 
9902   Collective on Mat
9903 
9904   Input Parameters:
9905 . A - the matrix
9906 
9907   Output Parameters:
9908 . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.
9909 
9910   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C
9911 
9912   Level: advanced
9913 
9914 .seealso: MatInvertBockDiagonal()
9915 @*/
9916 PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
9917 {
9918   PetscErrorCode     ierr;
9919   const PetscScalar *vals;
9920   PetscInt          *dnnz;
9921   PetscInt           M,N,m,n,rstart,rend,bs,i,j;
9922 
9923   PetscFunctionBegin;
9924   ierr = MatInvertBlockDiagonal(A,&vals);CHKERRQ(ierr);
9925   ierr = MatGetBlockSize(A,&bs);CHKERRQ(ierr);
9926   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
9927   ierr = MatGetLocalSize(A,&m,&n);CHKERRQ(ierr);
9928   ierr = MatSetSizes(C,m,n,M,N);CHKERRQ(ierr);
9929   ierr = MatSetBlockSize(C,bs);CHKERRQ(ierr);
9930   ierr = PetscMalloc1(m/bs,&dnnz);CHKERRQ(ierr);
9931   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
9932   ierr = MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);CHKERRQ(ierr);
9933   ierr = PetscFree(dnnz);CHKERRQ(ierr);
9934   ierr = MatGetOwnershipRange(C,&rstart,&rend);CHKERRQ(ierr);
9935   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);CHKERRQ(ierr);
9936   for (i = rstart/bs; i < rend/bs; i++) {
9937     ierr = MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);CHKERRQ(ierr);
9938   }
9939   ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
9940   ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
9941   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);CHKERRQ(ierr);
9942   PetscFunctionReturn(0);
9943 }
9944 
9945 /*@C
9946     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
9947     via MatTransposeColoringCreate().
9948 
9949     Collective on MatTransposeColoring
9950 
9951     Input Parameter:
9952 .   c - coloring context
9953 
9954     Level: intermediate
9955 
9956 .seealso: MatTransposeColoringCreate()
9957 @*/
9958 PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
9959 {
9960   PetscErrorCode       ierr;
9961   MatTransposeColoring matcolor=*c;
9962 
9963   PetscFunctionBegin;
9964   if (!matcolor) PetscFunctionReturn(0);
9965   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; PetscFunctionReturn(0);}
9966 
9967   ierr = PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);CHKERRQ(ierr);
9968   ierr = PetscFree(matcolor->rows);CHKERRQ(ierr);
9969   ierr = PetscFree(matcolor->den2sp);CHKERRQ(ierr);
9970   ierr = PetscFree(matcolor->colorforcol);CHKERRQ(ierr);
9971   ierr = PetscFree(matcolor->columns);CHKERRQ(ierr);
9972   if (matcolor->brows>0) {
9973     ierr = PetscFree(matcolor->lstart);CHKERRQ(ierr);
9974   }
9975   ierr = PetscHeaderDestroy(c);CHKERRQ(ierr);
9976   PetscFunctionReturn(0);
9977 }
9978 
9979 /*@C
9980     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
9981     a MatTransposeColoring context has been created, computes a dense B^T by Apply
9982     MatTransposeColoring to sparse B.
9983 
9984     Collective on MatTransposeColoring
9985 
9986     Input Parameters:
9987 +   B - sparse matrix B
9988 .   Btdense - symbolic dense matrix B^T
9989 -   coloring - coloring context created with MatTransposeColoringCreate()
9990 
9991     Output Parameter:
9992 .   Btdense - dense matrix B^T
9993 
9994     Level: advanced
9995 
9996      Notes:
9997     These are used internally for some implementations of MatRARt()
9998 
9999 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()
10000 
10001 @*/
10002 PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10003 {
10004   PetscErrorCode ierr;
10005 
10006   PetscFunctionBegin;
10007   PetscValidHeaderSpecific(B,MAT_CLASSID,1);
10008   PetscValidHeaderSpecific(Btdense,MAT_CLASSID,2);
10009   PetscValidHeaderSpecific(coloring,MAT_TRANSPOSECOLORING_CLASSID,3);
10010 
10011   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10012   ierr = (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);CHKERRQ(ierr);
10013   PetscFunctionReturn(0);
10014 }
10015 
10016 /*@C
10017     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10018     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10019     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10020     Csp from Cden.
10021 
10022     Collective on MatTransposeColoring
10023 
10024     Input Parameters:
10025 +   coloring - coloring context created with MatTransposeColoringCreate()
10026 -   Cden - matrix product of a sparse matrix and a dense matrix Btdense
10027 
10028     Output Parameter:
10029 .   Csp - sparse matrix
10030 
10031     Level: advanced
10032 
10033      Notes:
10034     These are used internally for some implementations of MatRARt()
10035 
10036 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
10037 
10038 @*/
10039 PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10040 {
10041   PetscErrorCode ierr;
10042 
10043   PetscFunctionBegin;
10044   PetscValidHeaderSpecific(matcoloring,MAT_TRANSPOSECOLORING_CLASSID,1);
10045   PetscValidHeaderSpecific(Cden,MAT_CLASSID,2);
10046   PetscValidHeaderSpecific(Csp,MAT_CLASSID,3);
10047 
10048   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10049   ierr = (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);CHKERRQ(ierr);
10050   ierr = MatAssemblyBegin(Csp,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10051   ierr = MatAssemblyEnd(Csp,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10052   PetscFunctionReturn(0);
10053 }
10054 
10055 /*@C
10056    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
10057 
10058    Collective on Mat
10059 
10060    Input Parameters:
10061 +  mat - the matrix product C
10062 -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
10063 
10064     Output Parameter:
10065 .   color - the new coloring context
10066 
10067     Level: intermediate
10068 
10069 .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
10070            MatTransColoringApplyDenToSp()
10071 @*/
10072 PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10073 {
10074   MatTransposeColoring c;
10075   MPI_Comm             comm;
10076   PetscErrorCode       ierr;
10077 
10078   PetscFunctionBegin;
10079   ierr = PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10080   ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
10081   ierr = PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);CHKERRQ(ierr);
10082 
10083   c->ctype = iscoloring->ctype;
10084   if (mat->ops->transposecoloringcreate) {
10085     ierr = (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);CHKERRQ(ierr);
10086   } else SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for matrix type %s",((PetscObject)mat)->type_name);
10087 
10088   *color = c;
10089   ierr   = PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10090   PetscFunctionReturn(0);
10091 }
10092 
10093 /*@
10094       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10095         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10096         same, otherwise it will be larger
10097 
10098      Not Collective
10099 
10100   Input Parameter:
10101 .    A  - the matrix
10102 
10103   Output Parameter:
10104 .    state - the current state
10105 
10106   Notes:
10107     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10108          different matrices
10109 
10110   Level: intermediate
10111 
10112 @*/
10113 PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10114 {
10115   PetscFunctionBegin;
10116   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10117   *state = mat->nonzerostate;
10118   PetscFunctionReturn(0);
10119 }
10120 
10121 /*@
10122       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10123                  matrices from each processor
10124 
10125     Collective
10126 
10127    Input Parameters:
10128 +    comm - the communicators the parallel matrix will live on
10129 .    seqmat - the input sequential matrices
10130 .    n - number of local columns (or PETSC_DECIDE)
10131 -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10132 
10133    Output Parameter:
10134 .    mpimat - the parallel matrix generated
10135 
10136     Level: advanced
10137 
10138    Notes:
10139     The number of columns of the matrix in EACH processor MUST be the same.
10140 
10141 @*/
10142 PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10143 {
10144   PetscErrorCode ierr;
10145 
10146   PetscFunctionBegin;
10147   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10148   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");
10149 
10150   ierr = PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10151   ierr = (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);CHKERRQ(ierr);
10152   ierr = PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10153   PetscFunctionReturn(0);
10154 }
10155 
10156 /*@
10157      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10158                  ranks' ownership ranges.
10159 
10160     Collective on A
10161 
10162    Input Parameters:
10163 +    A   - the matrix to create subdomains from
10164 -    N   - requested number of subdomains
10165 
10166 
10167    Output Parameters:
10168 +    n   - number of subdomains resulting on this rank
10169 -    iss - IS list with indices of subdomains on this rank
10170 
10171     Level: advanced
10172 
10173     Notes:
10174     number of subdomains must be smaller than the communicator size
10175 @*/
10176 PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10177 {
10178   MPI_Comm        comm,subcomm;
10179   PetscMPIInt     size,rank,color;
10180   PetscInt        rstart,rend,k;
10181   PetscErrorCode  ierr;
10182 
10183   PetscFunctionBegin;
10184   ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr);
10185   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
10186   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
10187   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);
10188   *n = 1;
10189   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10190   color = rank/k;
10191   ierr = MPI_Comm_split(comm,color,rank,&subcomm);CHKERRQ(ierr);
10192   ierr = PetscMalloc1(1,iss);CHKERRQ(ierr);
10193   ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
10194   ierr = ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);CHKERRQ(ierr);
10195   ierr = MPI_Comm_free(&subcomm);CHKERRQ(ierr);
10196   PetscFunctionReturn(0);
10197 }
10198 
10199 /*@
10200    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.
10201 
10202    If the interpolation and restriction operators are the same, uses MatPtAP.
10203    If they are not the same, use MatMatMatMult.
10204 
10205    Once the coarse grid problem is constructed, correct for interpolation operators
10206    that are not of full rank, which can legitimately happen in the case of non-nested
10207    geometric multigrid.
10208 
10209    Input Parameters:
10210 +  restrct - restriction operator
10211 .  dA - fine grid matrix
10212 .  interpolate - interpolation operator
10213 .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10214 -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate
10215 
10216    Output Parameters:
10217 .  A - the Galerkin coarse matrix
10218 
10219    Options Database Key:
10220 .  -pc_mg_galerkin <both,pmat,mat,none>
10221 
10222    Level: developer
10223 
10224 .seealso: MatPtAP(), MatMatMatMult()
10225 @*/
10226 PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10227 {
10228   PetscErrorCode ierr;
10229   IS             zerorows;
10230   Vec            diag;
10231 
10232   PetscFunctionBegin;
10233   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10234   /* Construct the coarse grid matrix */
10235   if (interpolate == restrct) {
10236     ierr = MatPtAP(dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10237   } else {
10238     ierr = MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10239   }
10240 
10241   /* If the interpolation matrix is not of full rank, A will have zero rows.
10242      This can legitimately happen in the case of non-nested geometric multigrid.
10243      In that event, we set the rows of the matrix to the rows of the identity,
10244      ignoring the equations (as the RHS will also be zero). */
10245 
10246   ierr = MatFindZeroRows(*A, &zerorows);CHKERRQ(ierr);
10247 
10248   if (zerorows != NULL) { /* if there are any zero rows */
10249     ierr = MatCreateVecs(*A, &diag, NULL);CHKERRQ(ierr);
10250     ierr = MatGetDiagonal(*A, diag);CHKERRQ(ierr);
10251     ierr = VecISSet(diag, zerorows, 1.0);CHKERRQ(ierr);
10252     ierr = MatDiagonalSet(*A, diag, INSERT_VALUES);CHKERRQ(ierr);
10253     ierr = VecDestroy(&diag);CHKERRQ(ierr);
10254     ierr = ISDestroy(&zerorows);CHKERRQ(ierr);
10255   }
10256   PetscFunctionReturn(0);
10257 }
10258 
10259 /*@C
10260     MatSetOperation - Allows user to set a matrix operation for any matrix type
10261 
10262    Logically Collective on Mat
10263 
10264     Input Parameters:
10265 +   mat - the matrix
10266 .   op - the name of the operation
10267 -   f - the function that provides the operation
10268 
10269    Level: developer
10270 
10271     Usage:
10272 $      extern PetscErrorCode usermult(Mat,Vec,Vec);
10273 $      ierr = MatCreateXXX(comm,...&A);
10274 $      ierr = MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
10275 
10276     Notes:
10277     See the file include/petscmat.h for a complete list of matrix
10278     operations, which all have the form MATOP_<OPERATION>, where
10279     <OPERATION> is the name (in all capital letters) of the
10280     user interface routine (e.g., MatMult() -> MATOP_MULT).
10281 
10282     All user-provided functions (except for MATOP_DESTROY) should have the same calling
10283     sequence as the usual matrix interface routines, since they
10284     are intended to be accessed via the usual matrix interface
10285     routines, e.g.,
10286 $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)
10287 
10288     In particular each function MUST return an error code of 0 on success and
10289     nonzero on failure.
10290 
10291     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.
10292 
10293 .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10294 @*/
10295 PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10296 {
10297   PetscFunctionBegin;
10298   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10299   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10300     mat->ops->viewnative = mat->ops->view;
10301   }
10302   (((void(**)(void))mat->ops)[op]) = f;
10303   PetscFunctionReturn(0);
10304 }
10305 
10306 /*@C
10307     MatGetOperation - Gets a matrix operation for any matrix type.
10308 
10309     Not Collective
10310 
10311     Input Parameters:
10312 +   mat - the matrix
10313 -   op - the name of the operation
10314 
10315     Output Parameter:
10316 .   f - the function that provides the operation
10317 
10318     Level: developer
10319 
10320     Usage:
10321 $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
10322 $      ierr = MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);
10323 
10324     Notes:
10325     See the file include/petscmat.h for a complete list of matrix
10326     operations, which all have the form MATOP_<OPERATION>, where
10327     <OPERATION> is the name (in all capital letters) of the
10328     user interface routine (e.g., MatMult() -> MATOP_MULT).
10329 
10330     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.
10331 
10332 .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
10333 @*/
10334 PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
10335 {
10336   PetscFunctionBegin;
10337   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10338   *f = (((void (**)(void))mat->ops)[op]);
10339   PetscFunctionReturn(0);
10340 }
10341 
10342 /*@
10343     MatHasOperation - Determines whether the given matrix supports the particular
10344     operation.
10345 
10346    Not Collective
10347 
10348    Input Parameters:
10349 +  mat - the matrix
10350 -  op - the operation, for example, MATOP_GET_DIAGONAL
10351 
10352    Output Parameter:
10353 .  has - either PETSC_TRUE or PETSC_FALSE
10354 
10355    Level: advanced
10356 
10357    Notes:
10358    See the file include/petscmat.h for a complete list of matrix
10359    operations, which all have the form MATOP_<OPERATION>, where
10360    <OPERATION> is the name (in all capital letters) of the
10361    user-level routine.  E.g., MatNorm() -> MATOP_NORM.
10362 
10363 .seealso: MatCreateShell()
10364 @*/
10365 PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
10366 {
10367   PetscErrorCode ierr;
10368 
10369   PetscFunctionBegin;
10370   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10371   PetscValidType(mat,1);
10372   PetscValidPointer(has,3);
10373   if (mat->ops->hasoperation) {
10374     ierr = (*mat->ops->hasoperation)(mat,op,has);CHKERRQ(ierr);
10375   } else {
10376     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
10377     else {
10378       *has = PETSC_FALSE;
10379       if (op == MATOP_CREATE_SUBMATRIX) {
10380         PetscMPIInt size;
10381 
10382         ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
10383         if (size == 1) {
10384           ierr = MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);CHKERRQ(ierr);
10385         }
10386       }
10387     }
10388   }
10389   PetscFunctionReturn(0);
10390 }
10391 
10392 /*@
10393     MatHasCongruentLayouts - Determines whether the rows and columns layouts
10394     of the matrix are congruent
10395 
10396    Collective on mat
10397 
10398    Input Parameters:
10399 .  mat - the matrix
10400 
10401    Output Parameter:
10402 .  cong - either PETSC_TRUE or PETSC_FALSE
10403 
10404    Level: beginner
10405 
10406    Notes:
10407 
10408 .seealso: MatCreate(), MatSetSizes()
10409 @*/
10410 PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
10411 {
10412   PetscErrorCode ierr;
10413 
10414   PetscFunctionBegin;
10415   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10416   PetscValidType(mat,1);
10417   PetscValidPointer(cong,2);
10418   if (!mat->rmap || !mat->cmap) {
10419     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
10420     PetscFunctionReturn(0);
10421   }
10422   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
10423     ierr = PetscLayoutCompare(mat->rmap,mat->cmap,cong);CHKERRQ(ierr);
10424     if (*cong) mat->congruentlayouts = 1;
10425     else       mat->congruentlayouts = 0;
10426   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
10427   PetscFunctionReturn(0);
10428 }
10429 
10430 /*@
10431     MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
10432     e.g., matrx product of MatPtAP.
10433 
10434    Collective on mat
10435 
10436    Input Parameters:
10437 .  mat - the matrix
10438 
10439    Output Parameter:
10440 .  mat - the matrix with intermediate data structures released
10441 
10442    Level: advanced
10443 
10444    Notes:
10445 
10446 .seealso: MatPtAP(), MatMatMult()
10447 @*/
10448 PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
10449 {
10450   PetscErrorCode ierr;
10451 
10452   PetscFunctionBegin;
10453   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10454   PetscValidType(mat,1);
10455   if (mat->ops->freeintermediatedatastructures) {
10456     ierr = (*mat->ops->freeintermediatedatastructures)(mat);CHKERRQ(ierr);
10457   }
10458   PetscFunctionReturn(0);
10459 }
10460