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