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