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