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