xref: /petsc/src/mat/interface/matrix.c (revision 8fcddce65efd55a8fe3f87d4c08c15577ce4cbef)
1 
2 /*
3    This is where the abstract matrix operations are defined
4 */
5 
6 #include <petsc/private/matimpl.h>        /*I "petscmat.h" I*/
7 #include <petsc/private/isimpl.h>
8 #include <petsc/private/vecimpl.h>
9 
10 /* Logging support */
11 PetscClassId MAT_CLASSID;
12 PetscClassId MAT_COLORING_CLASSID;
13 PetscClassId MAT_FDCOLORING_CLASSID;
14 PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
15 
16 PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
17 PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve,MAT_MatTrSolve;
18 PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
19 PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
20 PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
21 PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
22 PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
23 PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
24 PetscLogEvent MAT_TransposeColoringCreate;
25 PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
26 PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
27 PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
28 PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
29 PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
30 PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
31 PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_Transpose_SeqAIJ, MAT_GetBrowsOfAcols;
32 PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
33 PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
34 PetscLogEvent MAT_GetMultiProcBlock;
35 PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_SetValuesBatch;
36 PetscLogEvent MAT_ViennaCLCopyToGPU;
37 PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
38 PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;
39 
40 const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","MatFactorType","MAT_FACTOR_",0};
41 
42 /*@
43    MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated it randomly selects appropriate locations
44 
45    Logically Collective on Mat
46 
47    Input Parameters:
48 +  x  - the matrix
49 -  rctx - the random number context, formed by PetscRandomCreate(), or NULL and
50           it will create one internally.
51 
52    Output Parameter:
53 .  x  - the matrix
54 
55    Example of Usage:
56 .vb
57      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
58      MatSetRandom(x,rctx);
59      PetscRandomDestroy(rctx);
60 .ve
61 
62    Level: intermediate
63 
64    Concepts: matrix^setting to random
65    Concepts: random^matrix
66 
67 .seealso: MatZeroEntries(), MatSetValues(), PetscRandomCreate(), PetscRandomDestroy()
68 @*/
69 PetscErrorCode MatSetRandom(Mat x,PetscRandom rctx)
70 {
71   PetscErrorCode ierr;
72   PetscRandom    randObj = NULL;
73 
74   PetscFunctionBegin;
75   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
76   if (rctx) PetscValidHeaderSpecific(rctx,PETSC_RANDOM_CLASSID,2);
77   PetscValidType(x,1);
78 
79   if (!x->ops->setrandom) SETERRQ1(PetscObjectComm((PetscObject)x),PETSC_ERR_SUP,"Mat type %s",((PetscObject)x)->type_name);
80 
81   if (!rctx) {
82     MPI_Comm comm;
83     ierr = PetscObjectGetComm((PetscObject)x,&comm);CHKERRQ(ierr);
84     ierr = PetscRandomCreate(comm,&randObj);CHKERRQ(ierr);
85     ierr = PetscRandomSetFromOptions(randObj);CHKERRQ(ierr);
86     rctx = randObj;
87   }
88 
89   ierr = PetscLogEventBegin(MAT_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
90   ierr = (*x->ops->setrandom)(x,rctx);CHKERRQ(ierr);
91   ierr = PetscLogEventEnd(MAT_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
92 
93   ierr = MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
94   ierr = MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
95   ierr = PetscRandomDestroy(&randObj);CHKERRQ(ierr);
96   PetscFunctionReturn(0);
97 }
98 
99 /*@
100    MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
101 
102    Logically Collective on Mat
103 
104    Input Parameters:
105 .  mat - the factored matrix
106 
107    Output Parameter:
108 +  pivot - the pivot value computed
109 -  row - the row that the zero pivot occurred. Note that this row must be interpreted carefully due to row reorderings and which processes
110          the share the matrix
111 
112    Level: advanced
113 
114    Notes:
115     This routine does not work for factorizations done with external packages.
116    This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT
117 
118    This can be called on non-factored matrices that come from, for example, matrices used in SOR.
119 
120 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
121 @*/
122 PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat,PetscReal *pivot,PetscInt *row)
123 {
124   PetscFunctionBegin;
125   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
126   *pivot = mat->factorerror_zeropivot_value;
127   *row   = mat->factorerror_zeropivot_row;
128   PetscFunctionReturn(0);
129 }
130 
131 /*@
132    MatFactorGetError - gets the error code from a factorization
133 
134    Logically Collective on Mat
135 
136    Input Parameters:
137 .  mat - the factored matrix
138 
139    Output Parameter:
140 .  err  - the error code
141 
142    Level: advanced
143 
144    Notes:
145     This can be called on non-factored matrices that come from, for example, matrices used in SOR.
146 
147 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
148 @*/
149 PetscErrorCode MatFactorGetError(Mat mat,MatFactorError *err)
150 {
151   PetscFunctionBegin;
152   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
153   *err = mat->factorerrortype;
154   PetscFunctionReturn(0);
155 }
156 
157 /*@
158    MatFactorClearError - clears the error code in a factorization
159 
160    Logically Collective on Mat
161 
162    Input Parameter:
163 .  mat - the factored matrix
164 
165    Level: developer
166 
167    Notes:
168     This can be called on non-factored matrices that come from, for example, matrices used in SOR.
169 
170 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorGetError(), MatFactorGetErrorZeroPivot()
171 @*/
172 PetscErrorCode MatFactorClearError(Mat mat)
173 {
174   PetscFunctionBegin;
175   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
176   mat->factorerrortype             = MAT_FACTOR_NOERROR;
177   mat->factorerror_zeropivot_value = 0.0;
178   mat->factorerror_zeropivot_row   = 0;
179   PetscFunctionReturn(0);
180 }
181 
182 PETSC_INTERN PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat,PetscBool cols,PetscReal tol,IS *nonzero)
183 {
184   PetscErrorCode    ierr;
185   Vec               r,l;
186   const PetscScalar *al;
187   PetscInt          i,nz,gnz,N,n;
188 
189   PetscFunctionBegin;
190   ierr = MatCreateVecs(mat,&r,&l);CHKERRQ(ierr);
191   if (!cols) { /* nonzero rows */
192     ierr = MatGetSize(mat,&N,NULL);CHKERRQ(ierr);
193     ierr = MatGetLocalSize(mat,&n,NULL);CHKERRQ(ierr);
194     ierr = VecSet(l,0.0);CHKERRQ(ierr);
195     ierr = VecSetRandom(r,NULL);CHKERRQ(ierr);
196     ierr = MatMult(mat,r,l);CHKERRQ(ierr);
197     ierr = VecGetArrayRead(l,&al);CHKERRQ(ierr);
198   } else { /* nonzero columns */
199     ierr = MatGetSize(mat,NULL,&N);CHKERRQ(ierr);
200     ierr = MatGetLocalSize(mat,NULL,&n);CHKERRQ(ierr);
201     ierr = VecSet(r,0.0);CHKERRQ(ierr);
202     ierr = VecSetRandom(l,NULL);CHKERRQ(ierr);
203     ierr = MatMultTranspose(mat,l,r);CHKERRQ(ierr);
204     ierr = VecGetArrayRead(r,&al);CHKERRQ(ierr);
205   }
206   if (tol <= 0.0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nz++; }
207   else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nz++; }
208   ierr = MPIU_Allreduce(&nz,&gnz,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
209   if (gnz != N) {
210     PetscInt *nzr;
211     ierr = PetscMalloc1(nz,&nzr);CHKERRQ(ierr);
212     if (nz) {
213       if (tol < 0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nzr[nz++] = i; }
214       else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i; }
215     }
216     ierr = ISCreateGeneral(PetscObjectComm((PetscObject)mat),nz,nzr,PETSC_OWN_POINTER,nonzero);CHKERRQ(ierr);
217   } else *nonzero = NULL;
218   if (!cols) { /* nonzero rows */
219     ierr = VecRestoreArrayRead(l,&al);CHKERRQ(ierr);
220   } else {
221     ierr = VecRestoreArrayRead(r,&al);CHKERRQ(ierr);
222   }
223   ierr = VecDestroy(&l);CHKERRQ(ierr);
224   ierr = VecDestroy(&r);CHKERRQ(ierr);
225   PetscFunctionReturn(0);
226 }
227 
228 /*@
229       MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
230 
231   Input Parameter:
232 .    A  - the matrix
233 
234   Output Parameter:
235 .    keptrows - the rows that are not completely zero
236 
237   Notes:
238     keptrows is set to NULL if all rows are nonzero.
239 
240   Level: intermediate
241 
242  @*/
243 PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
244 {
245   PetscErrorCode ierr;
246 
247   PetscFunctionBegin;
248   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
249   PetscValidType(mat,1);
250   PetscValidPointer(keptrows,2);
251   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
252   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
253   if (!mat->ops->findnonzerorows) {
254     ierr = MatFindNonzeroRowsOrCols_Basic(mat,PETSC_FALSE,0.0,keptrows);CHKERRQ(ierr);
255   } else {
256     ierr = (*mat->ops->findnonzerorows)(mat,keptrows);CHKERRQ(ierr);
257   }
258   PetscFunctionReturn(0);
259 }
260 
261 /*@
262       MatFindZeroRows - Locate all rows that are completely zero in the matrix
263 
264   Input Parameter:
265 .    A  - the matrix
266 
267   Output Parameter:
268 .    zerorows - the rows that are completely zero
269 
270   Notes:
271     zerorows is set to NULL if no rows are zero.
272 
273   Level: intermediate
274 
275  @*/
276 PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
277 {
278   PetscErrorCode ierr;
279   IS keptrows;
280   PetscInt m, n;
281 
282   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
283   PetscValidType(mat,1);
284 
285   ierr = MatFindNonzeroRows(mat, &keptrows);CHKERRQ(ierr);
286   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
287      In keeping with this convention, we set zerorows to NULL if there are no zero
288      rows. */
289   if (keptrows == NULL) {
290     *zerorows = NULL;
291   } else {
292     ierr = MatGetOwnershipRange(mat,&m,&n);CHKERRQ(ierr);
293     ierr = ISComplement(keptrows,m,n,zerorows);CHKERRQ(ierr);
294     ierr = ISDestroy(&keptrows);CHKERRQ(ierr);
295   }
296   PetscFunctionReturn(0);
297 }
298 
299 /*@
300    MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
301 
302    Not Collective
303 
304    Input Parameters:
305 .   A - the matrix
306 
307    Output Parameters:
308 .   a - the diagonal part (which is a SEQUENTIAL matrix)
309 
310    Notes:
311     see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.
312           Use caution, as the reference count on the returned matrix is not incremented and it is used as
313 	  part of the containing MPI Mat's normal operation.
314 
315    Level: advanced
316 
317 @*/
318 PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
319 {
320   PetscErrorCode ierr;
321 
322   PetscFunctionBegin;
323   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
324   PetscValidType(A,1);
325   PetscValidPointer(a,3);
326   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
327   if (!A->ops->getdiagonalblock) {
328     PetscMPIInt size;
329     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRQ(ierr);
330     if (size == 1) {
331       *a = A;
332       PetscFunctionReturn(0);
333     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Not coded for this matrix type");
334   }
335   ierr = (*A->ops->getdiagonalblock)(A,a);CHKERRQ(ierr);
336   PetscFunctionReturn(0);
337 }
338 
339 /*@
340    MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
341 
342    Collective on Mat
343 
344    Input Parameters:
345 .  mat - the matrix
346 
347    Output Parameter:
348 .   trace - the sum of the diagonal entries
349 
350    Level: advanced
351 
352 @*/
353 PetscErrorCode MatGetTrace(Mat mat,PetscScalar *trace)
354 {
355   PetscErrorCode ierr;
356   Vec            diag;
357 
358   PetscFunctionBegin;
359   ierr = MatCreateVecs(mat,&diag,NULL);CHKERRQ(ierr);
360   ierr = MatGetDiagonal(mat,diag);CHKERRQ(ierr);
361   ierr = VecSum(diag,trace);CHKERRQ(ierr);
362   ierr = VecDestroy(&diag);CHKERRQ(ierr);
363   PetscFunctionReturn(0);
364 }
365 
366 /*@
367    MatRealPart - Zeros out the imaginary part of the matrix
368 
369    Logically Collective on Mat
370 
371    Input Parameters:
372 .  mat - the matrix
373 
374    Level: advanced
375 
376 
377 .seealso: MatImaginaryPart()
378 @*/
379 PetscErrorCode MatRealPart(Mat mat)
380 {
381   PetscErrorCode ierr;
382 
383   PetscFunctionBegin;
384   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
385   PetscValidType(mat,1);
386   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
387   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
388   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
389   MatCheckPreallocated(mat,1);
390   ierr = (*mat->ops->realpart)(mat);CHKERRQ(ierr);
391 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
392   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
393     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
394   }
395 #endif
396   PetscFunctionReturn(0);
397 }
398 
399 /*@C
400    MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix
401 
402    Collective on Mat
403 
404    Input Parameter:
405 .  mat - the matrix
406 
407    Output Parameters:
408 +   nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
409 -   ghosts - the global indices of the ghost points
410 
411    Notes:
412     the nghosts and ghosts are suitable to pass into VecCreateGhost()
413 
414    Level: advanced
415 
416 @*/
417 PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
418 {
419   PetscErrorCode ierr;
420 
421   PetscFunctionBegin;
422   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
423   PetscValidType(mat,1);
424   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
425   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
426   if (!mat->ops->getghosts) {
427     if (nghosts) *nghosts = 0;
428     if (ghosts) *ghosts = 0;
429   } else {
430     ierr = (*mat->ops->getghosts)(mat,nghosts,ghosts);CHKERRQ(ierr);
431   }
432   PetscFunctionReturn(0);
433 }
434 
435 
436 /*@
437    MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
438 
439    Logically Collective on Mat
440 
441    Input Parameters:
442 .  mat - the matrix
443 
444    Level: advanced
445 
446 
447 .seealso: MatRealPart()
448 @*/
449 PetscErrorCode MatImaginaryPart(Mat mat)
450 {
451   PetscErrorCode ierr;
452 
453   PetscFunctionBegin;
454   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
455   PetscValidType(mat,1);
456   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
457   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
458   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
459   MatCheckPreallocated(mat,1);
460   ierr = (*mat->ops->imaginarypart)(mat);CHKERRQ(ierr);
461 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
462   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
463     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
464   }
465 #endif
466   PetscFunctionReturn(0);
467 }
468 
469 /*@
470    MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)
471 
472    Not Collective
473 
474    Input Parameter:
475 .  mat - the matrix
476 
477    Output Parameters:
478 +  missing - is any diagonal missing
479 -  dd - first diagonal entry that is missing (optional) on this process
480 
481    Level: advanced
482 
483 
484 .seealso: MatRealPart()
485 @*/
486 PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
487 {
488   PetscErrorCode ierr;
489 
490   PetscFunctionBegin;
491   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
492   PetscValidType(mat,1);
493   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
494   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
495   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
496   ierr = (*mat->ops->missingdiagonal)(mat,missing,dd);CHKERRQ(ierr);
497   PetscFunctionReturn(0);
498 }
499 
500 /*@C
501    MatGetRow - Gets a row of a matrix.  You MUST call MatRestoreRow()
502    for each row that you get to ensure that your application does
503    not bleed memory.
504 
505    Not Collective
506 
507    Input Parameters:
508 +  mat - the matrix
509 -  row - the row to get
510 
511    Output Parameters:
512 +  ncols -  if not NULL, the number of nonzeros in the row
513 .  cols - if not NULL, the column numbers
514 -  vals - if not NULL, the values
515 
516    Notes:
517    This routine is provided for people who need to have direct access
518    to the structure of a matrix.  We hope that we provide enough
519    high-level matrix routines that few users will need it.
520 
521    MatGetRow() always returns 0-based column indices, regardless of
522    whether the internal representation is 0-based (default) or 1-based.
523 
524    For better efficiency, set cols and/or vals to NULL if you do
525    not wish to extract these quantities.
526 
527    The user can only examine the values extracted with MatGetRow();
528    the values cannot be altered.  To change the matrix entries, one
529    must use MatSetValues().
530 
531    You can only have one call to MatGetRow() outstanding for a particular
532    matrix at a time, per processor. MatGetRow() can only obtain rows
533    associated with the given processor, it cannot get rows from the
534    other processors; for that we suggest using MatCreateSubMatrices(), then
535    MatGetRow() on the submatrix. The row index passed to MatGetRow()
536    is in the global number of rows.
537 
538    Fortran Notes:
539    The calling sequence from Fortran is
540 .vb
541    MatGetRow(matrix,row,ncols,cols,values,ierr)
542          Mat     matrix (input)
543          integer row    (input)
544          integer ncols  (output)
545          integer cols(maxcols) (output)
546          double precision (or double complex) values(maxcols) output
547 .ve
548    where maxcols >= maximum nonzeros in any row of the matrix.
549 
550 
551    Caution:
552    Do not try to change the contents of the output arrays (cols and vals).
553    In some cases, this may corrupt the matrix.
554 
555    Level: advanced
556 
557    Concepts: matrices^row access
558 
559 .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
560 @*/
561 PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
562 {
563   PetscErrorCode ierr;
564   PetscInt       incols;
565 
566   PetscFunctionBegin;
567   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
568   PetscValidType(mat,1);
569   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
570   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
571   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
572   MatCheckPreallocated(mat,1);
573   ierr = PetscLogEventBegin(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
574   ierr = (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);CHKERRQ(ierr);
575   if (ncols) *ncols = incols;
576   ierr = PetscLogEventEnd(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
577   PetscFunctionReturn(0);
578 }
579 
580 /*@
581    MatConjugate - replaces the matrix values with their complex conjugates
582 
583    Logically Collective on Mat
584 
585    Input Parameters:
586 .  mat - the matrix
587 
588    Level: advanced
589 
590 .seealso:  VecConjugate()
591 @*/
592 PetscErrorCode MatConjugate(Mat mat)
593 {
594 #if defined(PETSC_USE_COMPLEX)
595   PetscErrorCode ierr;
596 
597   PetscFunctionBegin;
598   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
599   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
600   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");
601   ierr = (*mat->ops->conjugate)(mat);CHKERRQ(ierr);
602 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
603   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
604     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
605   }
606 #endif
607   PetscFunctionReturn(0);
608 #else
609   return 0;
610 #endif
611 }
612 
613 /*@C
614    MatRestoreRow - Frees any temporary space allocated by MatGetRow().
615 
616    Not Collective
617 
618    Input Parameters:
619 +  mat - the matrix
620 .  row - the row to get
621 .  ncols, cols - the number of nonzeros and their columns
622 -  vals - if nonzero the column values
623 
624    Notes:
625    This routine should be called after you have finished examining the entries.
626 
627    This routine zeros out ncols, cols, and vals. This is to prevent accidental
628    us of the array after it has been restored. If you pass NULL, it will
629    not zero the pointers.  Use of cols or vals after MatRestoreRow is invalid.
630 
631    Fortran Notes:
632    The calling sequence from Fortran is
633 .vb
634    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
635       Mat     matrix (input)
636       integer row    (input)
637       integer ncols  (output)
638       integer cols(maxcols) (output)
639       double precision (or double complex) values(maxcols) output
640 .ve
641    Where maxcols >= maximum nonzeros in any row of the matrix.
642 
643    In Fortran MatRestoreRow() MUST be called after MatGetRow()
644    before another call to MatGetRow() can be made.
645 
646    Level: advanced
647 
648 .seealso:  MatGetRow()
649 @*/
650 PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
651 {
652   PetscErrorCode ierr;
653 
654   PetscFunctionBegin;
655   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
656   if (ncols) PetscValidIntPointer(ncols,3);
657   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
658   if (!mat->ops->restorerow) PetscFunctionReturn(0);
659   ierr = (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);CHKERRQ(ierr);
660   if (ncols) *ncols = 0;
661   if (cols)  *cols = NULL;
662   if (vals)  *vals = NULL;
663   PetscFunctionReturn(0);
664 }
665 
666 /*@
667    MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
668    You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.
669 
670    Not Collective
671 
672    Input Parameters:
673 +  mat - the matrix
674 
675    Notes:
676    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.
677 
678    Level: advanced
679 
680    Concepts: matrices^row access
681 
682 .seealso: MatRestoreRowRowUpperTriangular()
683 @*/
684 PetscErrorCode MatGetRowUpperTriangular(Mat mat)
685 {
686   PetscErrorCode ierr;
687 
688   PetscFunctionBegin;
689   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
690   PetscValidType(mat,1);
691   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
692   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
693   if (!mat->ops->getrowuppertriangular) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
694   MatCheckPreallocated(mat,1);
695   ierr = (*mat->ops->getrowuppertriangular)(mat);CHKERRQ(ierr);
696   PetscFunctionReturn(0);
697 }
698 
699 /*@
700    MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.
701 
702    Not Collective
703 
704    Input Parameters:
705 +  mat - the matrix
706 
707    Notes:
708    This routine should be called after you have finished MatGetRow/MatRestoreRow().
709 
710 
711    Level: advanced
712 
713 .seealso:  MatGetRowUpperTriangular()
714 @*/
715 PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
716 {
717   PetscErrorCode ierr;
718 
719   PetscFunctionBegin;
720   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
721   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
722   if (!mat->ops->restorerowuppertriangular) PetscFunctionReturn(0);
723   ierr = (*mat->ops->restorerowuppertriangular)(mat);CHKERRQ(ierr);
724   PetscFunctionReturn(0);
725 }
726 
727 /*@C
728    MatSetOptionsPrefix - Sets the prefix used for searching for all
729    Mat options in the database.
730 
731    Logically Collective on Mat
732 
733    Input Parameter:
734 +  A - the Mat context
735 -  prefix - the prefix to prepend to all option names
736 
737    Notes:
738    A hyphen (-) must NOT be given at the beginning of the prefix name.
739    The first character of all runtime options is AUTOMATICALLY the hyphen.
740 
741    Level: advanced
742 
743 .keywords: Mat, set, options, prefix, database
744 
745 .seealso: MatSetFromOptions()
746 @*/
747 PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
748 {
749   PetscErrorCode ierr;
750 
751   PetscFunctionBegin;
752   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
753   ierr = PetscObjectSetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
754   PetscFunctionReturn(0);
755 }
756 
757 /*@C
758    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
759    Mat options in the database.
760 
761    Logically Collective on Mat
762 
763    Input Parameters:
764 +  A - the Mat context
765 -  prefix - the prefix to prepend to all option names
766 
767    Notes:
768    A hyphen (-) must NOT be given at the beginning of the prefix name.
769    The first character of all runtime options is AUTOMATICALLY the hyphen.
770 
771    Level: advanced
772 
773 .keywords: Mat, append, options, prefix, database
774 
775 .seealso: MatGetOptionsPrefix()
776 @*/
777 PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
778 {
779   PetscErrorCode ierr;
780 
781   PetscFunctionBegin;
782   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
783   ierr = PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
784   PetscFunctionReturn(0);
785 }
786 
787 /*@C
788    MatGetOptionsPrefix - Sets the prefix used for searching for all
789    Mat options in the database.
790 
791    Not Collective
792 
793    Input Parameter:
794 .  A - the Mat context
795 
796    Output Parameter:
797 .  prefix - pointer to the prefix string used
798 
799    Notes:
800     On the fortran side, the user should pass in a string 'prefix' of
801    sufficient length to hold the prefix.
802 
803    Level: advanced
804 
805 .keywords: Mat, get, options, prefix, database
806 
807 .seealso: MatAppendOptionsPrefix()
808 @*/
809 PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
810 {
811   PetscErrorCode ierr;
812 
813   PetscFunctionBegin;
814   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
815   ierr = PetscObjectGetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
816   PetscFunctionReturn(0);
817 }
818 
819 /*@
820    MatResetPreallocation - Reset mat to use the original nonzero pattern provided by users.
821 
822    Collective on Mat
823 
824    Input Parameters:
825 .  A - the Mat context
826 
827    Notes:
828    The allocated memory will be shrunk after calling MatAssembly with MAT_FINAL_ASSEMBLY. Users can reset the preallocation to access the original memory.
829    Currently support MPIAIJ and SEQAIJ.
830 
831    Level: beginner
832 
833 .keywords: Mat, ResetPreallocation
834 
835 .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
836 @*/
837 PetscErrorCode MatResetPreallocation(Mat A)
838 {
839   PetscErrorCode ierr;
840 
841   PetscFunctionBegin;
842   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
843   PetscValidType(A,1);
844   ierr = PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));CHKERRQ(ierr);
845   PetscFunctionReturn(0);
846 }
847 
848 
849 /*@
850    MatSetUp - Sets up the internal matrix data structures for the later use.
851 
852    Collective on Mat
853 
854    Input Parameters:
855 .  A - the Mat context
856 
857    Notes:
858    If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.
859 
860    If a suitable preallocation routine is used, this function does not need to be called.
861 
862    See the Performance chapter of the PETSc users manual for how to preallocate matrices
863 
864    Level: beginner
865 
866 .keywords: Mat, setup
867 
868 .seealso: MatCreate(), MatDestroy()
869 @*/
870 PetscErrorCode MatSetUp(Mat A)
871 {
872   PetscMPIInt    size;
873   PetscErrorCode ierr;
874 
875   PetscFunctionBegin;
876   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
877   if (!((PetscObject)A)->type_name) {
878     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);CHKERRQ(ierr);
879     if (size == 1) {
880       ierr = MatSetType(A, MATSEQAIJ);CHKERRQ(ierr);
881     } else {
882       ierr = MatSetType(A, MATMPIAIJ);CHKERRQ(ierr);
883     }
884   }
885   if (!A->preallocated && A->ops->setup) {
886     ierr = PetscInfo(A,"Warning not preallocating matrix storage\n");CHKERRQ(ierr);
887     ierr = (*A->ops->setup)(A);CHKERRQ(ierr);
888   }
889   ierr = PetscLayoutSetUp(A->rmap);CHKERRQ(ierr);
890   ierr = PetscLayoutSetUp(A->cmap);CHKERRQ(ierr);
891   A->preallocated = PETSC_TRUE;
892   PetscFunctionReturn(0);
893 }
894 
895 #if defined(PETSC_HAVE_SAWS)
896 #include <petscviewersaws.h>
897 #endif
898 /*@C
899    MatView - Visualizes a matrix object.
900 
901    Collective on Mat
902 
903    Input Parameters:
904 +  mat - the matrix
905 -  viewer - visualization context
906 
907   Notes:
908   The available visualization contexts include
909 +    PETSC_VIEWER_STDOUT_SELF - for sequential matrices
910 .    PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
911 .    PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
912 -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
913 
914    The user can open alternative visualization contexts with
915 +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
916 .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
917          specified file; corresponding input uses MatLoad()
918 .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
919          an X window display
920 -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
921          Currently only the sequential dense and AIJ
922          matrix types support the Socket viewer.
923 
924    The user can call PetscViewerPushFormat() to specify the output
925    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
926    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
927 +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
928 .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
929 .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
930 .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
931          format common among all matrix types
932 .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
933          format (which is in many cases the same as the default)
934 .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
935          size and structure (not the matrix entries)
936 -    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
937          the matrix structure
938 
939    Options Database Keys:
940 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
941 .  -mat_view ::ascii_info_detail - Prints more detailed info
942 .  -mat_view - Prints matrix in ASCII format
943 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
944 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
945 .  -display <name> - Sets display name (default is host)
946 .  -draw_pause <sec> - Sets number of seconds to pause after display
947 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: ch_matlab for details)
948 .  -viewer_socket_machine <machine> -
949 .  -viewer_socket_port <port> -
950 .  -mat_view binary - save matrix to file in binary format
951 -  -viewer_binary_filename <name> -
952    Level: beginner
953 
954    Notes:
955     See the manual page for MatLoad() for the exact format of the binary file when the binary
956       viewer is used.
957 
958       See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
959       viewer is used.
960 
961       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
962       and then use the following mouse functions.
963 + left mouse: zoom in
964 . middle mouse: zoom out
965 - right mouse: continue with the simulation
966 
967    Concepts: matrices^viewing
968    Concepts: matrices^plotting
969    Concepts: matrices^printing
970 
971 .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
972           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
973 @*/
974 PetscErrorCode MatView(Mat mat,PetscViewer viewer)
975 {
976   PetscErrorCode    ierr;
977   PetscInt          rows,cols,rbs,cbs;
978   PetscBool         iascii,ibinary;
979   PetscViewerFormat format;
980   PetscMPIInt       size;
981 #if defined(PETSC_HAVE_SAWS)
982   PetscBool         issaws;
983 #endif
984 
985   PetscFunctionBegin;
986   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
987   PetscValidType(mat,1);
988   if (!viewer) {
989     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);CHKERRQ(ierr);
990   }
991   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
992   PetscCheckSameComm(mat,1,viewer,2);
993   MatCheckPreallocated(mat,1);
994   ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
995   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
996   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(0);
997   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);CHKERRQ(ierr);
998   if (ibinary) {
999     PetscBool mpiio;
1000     ierr = PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);CHKERRQ(ierr);
1001     if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
1002   }
1003 
1004   ierr = PetscLogEventBegin(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
1005   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
1006   if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
1007     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
1008   }
1009 
1010 #if defined(PETSC_HAVE_SAWS)
1011   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);CHKERRQ(ierr);
1012 #endif
1013   if (iascii) {
1014     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1015     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);CHKERRQ(ierr);
1016     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1017       MatNullSpace nullsp,transnullsp;
1018 
1019       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1020       ierr = MatGetSize(mat,&rows,&cols);CHKERRQ(ierr);
1021       ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
1022       if (rbs != 1 || cbs != 1) {
1023         if (rbs != cbs) {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs = %D\n",rows,cols,rbs,cbs);CHKERRQ(ierr);}
1024         else            {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);CHKERRQ(ierr);}
1025       } else {
1026         ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);CHKERRQ(ierr);
1027       }
1028       if (mat->factortype) {
1029         MatSolverType solver;
1030         ierr = MatFactorGetSolverType(mat,&solver);CHKERRQ(ierr);
1031         ierr = PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);CHKERRQ(ierr);
1032       }
1033       if (mat->ops->getinfo) {
1034         MatInfo info;
1035         ierr = MatGetInfo(mat,MAT_GLOBAL_SUM,&info);CHKERRQ(ierr);
1036         ierr = PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);CHKERRQ(ierr);
1037         ierr = PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls =%D\n",(PetscInt)info.mallocs);CHKERRQ(ierr);
1038       }
1039       ierr = MatGetNullSpace(mat,&nullsp);CHKERRQ(ierr);
1040       ierr = MatGetTransposeNullSpace(mat,&transnullsp);CHKERRQ(ierr);
1041       if (nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached null space\n");CHKERRQ(ierr);}
1042       if (transnullsp && transnullsp != nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached transposed null space\n");CHKERRQ(ierr);}
1043       ierr = MatGetNearNullSpace(mat,&nullsp);CHKERRQ(ierr);
1044       if (nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");CHKERRQ(ierr);}
1045     }
1046 #if defined(PETSC_HAVE_SAWS)
1047   } else if (issaws) {
1048     PetscMPIInt rank;
1049 
1050     ierr = PetscObjectName((PetscObject)mat);CHKERRQ(ierr);
1051     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
1052     if (!((PetscObject)mat)->amsmem && !rank) {
1053       ierr = PetscObjectViewSAWs((PetscObject)mat,viewer);CHKERRQ(ierr);
1054     }
1055 #endif
1056   }
1057   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1058     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1059     ierr = (*mat->ops->viewnative)(mat,viewer);CHKERRQ(ierr);
1060     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1061   } else if (mat->ops->view) {
1062     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1063     ierr = (*mat->ops->view)(mat,viewer);CHKERRQ(ierr);
1064     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1065   }
1066   if (iascii) {
1067     ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
1068     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1069       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1070     }
1071   }
1072   ierr = PetscLogEventEnd(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
1073   PetscFunctionReturn(0);
1074 }
1075 
1076 #if defined(PETSC_USE_DEBUG)
1077 #include <../src/sys/totalview/tv_data_display.h>
1078 PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1079 {
1080   TV_add_row("Local rows", "int", &mat->rmap->n);
1081   TV_add_row("Local columns", "int", &mat->cmap->n);
1082   TV_add_row("Global rows", "int", &mat->rmap->N);
1083   TV_add_row("Global columns", "int", &mat->cmap->N);
1084   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1085   return TV_format_OK;
1086 }
1087 #endif
1088 
1089 /*@C
1090    MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1091    with MatView().  The matrix format is determined from the options database.
1092    Generates a parallel MPI matrix if the communicator has more than one
1093    processor.  The default matrix type is AIJ.
1094 
1095    Collective on PetscViewer
1096 
1097    Input Parameters:
1098 +  newmat - the newly loaded matrix, this needs to have been created with MatCreate()
1099             or some related function before a call to MatLoad()
1100 -  viewer - binary/HDF5 file viewer
1101 
1102    Options Database Keys:
1103    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1104    block size
1105 .    -matload_block_size <bs>
1106 
1107    Level: beginner
1108 
1109    Notes:
1110    If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1111    Mat before calling this routine if you wish to set it from the options database.
1112 
1113    MatLoad() automatically loads into the options database any options
1114    given in the file filename.info where filename is the name of the file
1115    that was passed to the PetscViewerBinaryOpen(). The options in the info
1116    file will be ignored if you use the -viewer_binary_skip_info option.
1117 
1118    If the type or size of newmat is not set before a call to MatLoad, PETSc
1119    sets the default matrix type AIJ and sets the local and global sizes.
1120    If type and/or size is already set, then the same are used.
1121 
1122    In parallel, each processor can load a subset of rows (or the
1123    entire matrix).  This routine is especially useful when a large
1124    matrix is stored on disk and only part of it is desired on each
1125    processor.  For example, a parallel solver may access only some of
1126    the rows from each processor.  The algorithm used here reads
1127    relatively small blocks of data rather than reading the entire
1128    matrix and then subsetting it.
1129 
1130    Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1131    Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1132    or the sequence like
1133 $    PetscViewer v;
1134 $    PetscViewerCreate(PETSC_COMM_WORLD,&v);
1135 $    PetscViewerSetType(v,PETSCVIEWERBINARY);
1136 $    PetscViewerSetFromOptions(v);
1137 $    PetscViewerFileSetMode(v,FILE_MODE_READ);
1138 $    PetscViewerFileSetName(v,"datafile");
1139    The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1140 $ -viewer_type {binary,hdf5}
1141 
1142    See the example src/ksp/ksp/examples/tutorials/ex27.c with the first approach,
1143    and src/mat/examples/tutorials/ex10.c with the second approach.
1144 
1145    Notes about the PETSc binary format:
1146    In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1147    is read onto rank 0 and then shipped to its destination rank, one after another.
1148    Multiple objects, both matrices and vectors, can be stored within the same file.
1149    Their PetscObject name is ignored; they are loaded in the order of their storage.
1150 
1151    Most users should not need to know the details of the binary storage
1152    format, since MatLoad() and MatView() completely hide these details.
1153    But for anyone who's interested, the standard binary matrix storage
1154    format is
1155 
1156 $    int    MAT_FILE_CLASSID
1157 $    int    number of rows
1158 $    int    number of columns
1159 $    int    total number of nonzeros
1160 $    int    *number nonzeros in each row
1161 $    int    *column indices of all nonzeros (starting index is zero)
1162 $    PetscScalar *values of all nonzeros
1163 
1164    PETSc automatically does the byte swapping for
1165 machines that store the bytes reversed, e.g.  DEC alpha, freebsd,
1166 linux, Windows and the paragon; thus if you write your own binary
1167 read/write routines you have to swap the bytes; see PetscBinaryRead()
1168 and PetscBinaryWrite() to see how this may be done.
1169 
1170    Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1171    In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1172    Each processor's chunk is loaded independently by its owning rank.
1173    Multiple objects, both matrices and vectors, can be stored within the same file.
1174    They are looked up by their PetscObject name.
1175 
1176    As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1177    by default the same structure and naming of the AIJ arrays and column count
1178    (see PetscViewerHDF5SetAIJNames())
1179    within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1180 $    save example.mat A b -v7.3
1181    can be directly read by this routine (see Reference 1 for details).
1182    Note that depending on your MATLAB version, this format might be a default,
1183    otherwise you can set it as default in Preferences.
1184 
1185    Unless -nocompression flag is used to save the file in MATLAB,
1186    PETSc must be configured with ZLIB package.
1187 
1188    Current HDF5 limitations:
1189    This reader currently supports only real MATSEQAIJ and MATMPIAIJ matrices.
1190 
1191    MatView() is not yet implemented.
1192 
1193    References:
1194 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version
1195 
1196 .keywords: matrix, load, binary, input, HDF5
1197 
1198 .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), PetscViewerHDF5SetAIJNames(), MatView(), VecLoad()
1199 
1200  @*/
1201 PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1202 {
1203   PetscErrorCode ierr;
1204   PetscBool      flg;
1205 
1206   PetscFunctionBegin;
1207   PetscValidHeaderSpecific(newmat,MAT_CLASSID,1);
1208   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1209 
1210   if (!((PetscObject)newmat)->type_name) {
1211     ierr = MatSetType(newmat,MATAIJ);CHKERRQ(ierr);
1212   }
1213 
1214   flg  = PETSC_FALSE;
1215   ierr = PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);CHKERRQ(ierr);
1216   if (flg) {
1217     ierr = MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
1218     ierr = MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);CHKERRQ(ierr);
1219   }
1220   flg  = PETSC_FALSE;
1221   ierr = PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);CHKERRQ(ierr);
1222   if (flg) {
1223     ierr = MatSetOption(newmat,MAT_SPD,PETSC_TRUE);CHKERRQ(ierr);
1224   }
1225 
1226   if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
1227   ierr = PetscLogEventBegin(MAT_Load,viewer,0,0,0);CHKERRQ(ierr);
1228   ierr = (*newmat->ops->load)(newmat,viewer);CHKERRQ(ierr);
1229   ierr = PetscLogEventEnd(MAT_Load,viewer,0,0,0);CHKERRQ(ierr);
1230   PetscFunctionReturn(0);
1231 }
1232 
1233 PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1234 {
1235   PetscErrorCode ierr;
1236   Mat_Redundant  *redund = *redundant;
1237   PetscInt       i;
1238 
1239   PetscFunctionBegin;
1240   if (redund){
1241     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1242       ierr = ISDestroy(&redund->isrow);CHKERRQ(ierr);
1243       ierr = ISDestroy(&redund->iscol);CHKERRQ(ierr);
1244       ierr = MatDestroySubMatrices(1,&redund->matseq);CHKERRQ(ierr);
1245     } else {
1246       ierr = PetscFree2(redund->send_rank,redund->recv_rank);CHKERRQ(ierr);
1247       ierr = PetscFree(redund->sbuf_j);CHKERRQ(ierr);
1248       ierr = PetscFree(redund->sbuf_a);CHKERRQ(ierr);
1249       for (i=0; i<redund->nrecvs; i++) {
1250         ierr = PetscFree(redund->rbuf_j[i]);CHKERRQ(ierr);
1251         ierr = PetscFree(redund->rbuf_a[i]);CHKERRQ(ierr);
1252       }
1253       ierr = PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);CHKERRQ(ierr);
1254     }
1255 
1256     if (redund->subcomm) {
1257       ierr = PetscCommDestroy(&redund->subcomm);CHKERRQ(ierr);
1258     }
1259     ierr = PetscFree(redund);CHKERRQ(ierr);
1260   }
1261   PetscFunctionReturn(0);
1262 }
1263 
1264 /*@
1265    MatDestroy - Frees space taken by a matrix.
1266 
1267    Collective on Mat
1268 
1269    Input Parameter:
1270 .  A - the matrix
1271 
1272    Level: beginner
1273 
1274 @*/
1275 PetscErrorCode MatDestroy(Mat *A)
1276 {
1277   PetscErrorCode ierr;
1278 
1279   PetscFunctionBegin;
1280   if (!*A) PetscFunctionReturn(0);
1281   PetscValidHeaderSpecific(*A,MAT_CLASSID,1);
1282   if (--((PetscObject)(*A))->refct > 0) {*A = NULL; PetscFunctionReturn(0);}
1283 
1284   /* if memory was published with SAWs then destroy it */
1285   ierr = PetscObjectSAWsViewOff((PetscObject)*A);CHKERRQ(ierr);
1286   if ((*A)->ops->destroy) {
1287     ierr = (*(*A)->ops->destroy)(*A);CHKERRQ(ierr);
1288   }
1289 
1290   ierr = PetscFree((*A)->defaultvectype);CHKERRQ(ierr);
1291   ierr = PetscFree((*A)->bsizes);CHKERRQ(ierr);
1292   ierr = PetscFree((*A)->solvertype);CHKERRQ(ierr);
1293   ierr = MatDestroy_Redundant(&(*A)->redundant);CHKERRQ(ierr);
1294   ierr = MatNullSpaceDestroy(&(*A)->nullsp);CHKERRQ(ierr);
1295   ierr = MatNullSpaceDestroy(&(*A)->transnullsp);CHKERRQ(ierr);
1296   ierr = MatNullSpaceDestroy(&(*A)->nearnullsp);CHKERRQ(ierr);
1297   ierr = MatDestroy(&(*A)->schur);CHKERRQ(ierr);
1298   ierr = PetscLayoutDestroy(&(*A)->rmap);CHKERRQ(ierr);
1299   ierr = PetscLayoutDestroy(&(*A)->cmap);CHKERRQ(ierr);
1300   ierr = PetscHeaderDestroy(A);CHKERRQ(ierr);
1301   PetscFunctionReturn(0);
1302 }
1303 
1304 /*@C
1305    MatSetValues - Inserts or adds a block of values into a matrix.
1306    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1307    MUST be called after all calls to MatSetValues() have been completed.
1308 
1309    Not Collective
1310 
1311    Input Parameters:
1312 +  mat - the matrix
1313 .  v - a logically two-dimensional array of values
1314 .  m, idxm - the number of rows and their global indices
1315 .  n, idxn - the number of columns and their global indices
1316 -  addv - either ADD_VALUES or INSERT_VALUES, where
1317    ADD_VALUES adds values to any existing entries, and
1318    INSERT_VALUES replaces existing entries with new values
1319 
1320    Notes:
1321    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1322       MatSetUp() before using this routine
1323 
1324    By default the values, v, are row-oriented. See MatSetOption() for other options.
1325 
1326    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1327    options cannot be mixed without intervening calls to the assembly
1328    routines.
1329 
1330    MatSetValues() uses 0-based row and column numbers in Fortran
1331    as well as in C.
1332 
1333    Negative indices may be passed in idxm and idxn, these rows and columns are
1334    simply ignored. This allows easily inserting element stiffness matrices
1335    with homogeneous Dirchlet boundary conditions that you don't want represented
1336    in the matrix.
1337 
1338    Efficiency Alert:
1339    The routine MatSetValuesBlocked() may offer much better efficiency
1340    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1341 
1342    Level: beginner
1343 
1344    Developer Notes:
1345     This is labeled with C so does not automatically generate Fortran stubs and interfaces
1346                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1347 
1348    Concepts: matrices^putting entries in
1349 
1350 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1351           InsertMode, INSERT_VALUES, ADD_VALUES
1352 @*/
1353 PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1354 {
1355   PetscErrorCode ierr;
1356 #if defined(PETSC_USE_DEBUG)
1357   PetscInt       i,j;
1358 #endif
1359 
1360   PetscFunctionBeginHot;
1361   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1362   PetscValidType(mat,1);
1363   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1364   PetscValidIntPointer(idxm,3);
1365   PetscValidIntPointer(idxn,5);
1366   PetscValidScalarPointer(v,6);
1367   MatCheckPreallocated(mat,1);
1368   if (mat->insertmode == NOT_SET_VALUES) {
1369     mat->insertmode = addv;
1370   }
1371 #if defined(PETSC_USE_DEBUG)
1372   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1373   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1374   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1375 
1376   for (i=0; i<m; i++) {
1377     for (j=0; j<n; j++) {
1378       if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1379 #if defined(PETSC_USE_COMPLEX)
1380         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]);
1381 #else
1382         SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1383 #endif
1384     }
1385   }
1386 #endif
1387 
1388   if (mat->assembled) {
1389     mat->was_assembled = PETSC_TRUE;
1390     mat->assembled     = PETSC_FALSE;
1391   }
1392   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1393   ierr = (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);CHKERRQ(ierr);
1394   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1395 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1396   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1397     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1398   }
1399 #endif
1400   PetscFunctionReturn(0);
1401 }
1402 
1403 
1404 /*@
1405    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1406         values into a matrix
1407 
1408    Not Collective
1409 
1410    Input Parameters:
1411 +  mat - the matrix
1412 .  row - the (block) row to set
1413 -  v - a logically two-dimensional array of values
1414 
1415    Notes:
1416    By the values, v, are column-oriented (for the block version) and sorted
1417 
1418    All the nonzeros in the row must be provided
1419 
1420    The matrix must have previously had its column indices set
1421 
1422    The row must belong to this process
1423 
1424    Level: intermediate
1425 
1426    Concepts: matrices^putting entries in
1427 
1428 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1429           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1430 @*/
1431 PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1432 {
1433   PetscErrorCode ierr;
1434   PetscInt       globalrow;
1435 
1436   PetscFunctionBegin;
1437   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1438   PetscValidType(mat,1);
1439   PetscValidScalarPointer(v,2);
1440   ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);CHKERRQ(ierr);
1441   ierr = MatSetValuesRow(mat,globalrow,v);CHKERRQ(ierr);
1442 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
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    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1452         values into a matrix
1453 
1454    Not Collective
1455 
1456    Input Parameters:
1457 +  mat - the matrix
1458 .  row - the (block) row to set
1459 -  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
1460 
1461    Notes:
1462    The values, v, are column-oriented for the block version.
1463 
1464    All the nonzeros in the row must be provided
1465 
1466    THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1467 
1468    The row must belong to this process
1469 
1470    Level: advanced
1471 
1472    Concepts: matrices^putting entries in
1473 
1474 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1475           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1476 @*/
1477 PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1478 {
1479   PetscErrorCode ierr;
1480 
1481   PetscFunctionBeginHot;
1482   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1483   PetscValidType(mat,1);
1484   MatCheckPreallocated(mat,1);
1485   PetscValidScalarPointer(v,2);
1486 #if defined(PETSC_USE_DEBUG)
1487   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1488   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1489 #endif
1490   mat->insertmode = INSERT_VALUES;
1491 
1492   if (mat->assembled) {
1493     mat->was_assembled = PETSC_TRUE;
1494     mat->assembled     = PETSC_FALSE;
1495   }
1496   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1497   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1498   ierr = (*mat->ops->setvaluesrow)(mat,row,v);CHKERRQ(ierr);
1499   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1500 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1501   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1502     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1503   }
1504 #endif
1505   PetscFunctionReturn(0);
1506 }
1507 
1508 /*@
1509    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1510      Using structured grid indexing
1511 
1512    Not Collective
1513 
1514    Input Parameters:
1515 +  mat - the matrix
1516 .  m - number of rows being entered
1517 .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1518 .  n - number of columns being entered
1519 .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1520 .  v - a logically two-dimensional array of values
1521 -  addv - either ADD_VALUES or INSERT_VALUES, where
1522    ADD_VALUES adds values to any existing entries, and
1523    INSERT_VALUES replaces existing entries with new values
1524 
1525    Notes:
1526    By default the values, v, are row-oriented.  See MatSetOption() for other options.
1527 
1528    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1529    options cannot be mixed without intervening calls to the assembly
1530    routines.
1531 
1532    The grid coordinates are across the entire grid, not just the local portion
1533 
1534    MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1535    as well as in C.
1536 
1537    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1538 
1539    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1540    or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1541 
1542    The columns and rows in the stencil passed in MUST be contained within the
1543    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1544    if you create a DMDA with an overlap of one grid level and on a particular process its first
1545    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1546    first i index you can use in your column and row indices in MatSetStencil() is 5.
1547 
1548    In Fortran idxm and idxn should be declared as
1549 $     MatStencil idxm(4,m),idxn(4,n)
1550    and the values inserted using
1551 $    idxm(MatStencil_i,1) = i
1552 $    idxm(MatStencil_j,1) = j
1553 $    idxm(MatStencil_k,1) = k
1554 $    idxm(MatStencil_c,1) = c
1555    etc
1556 
1557    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1558    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1559    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1560    DM_BOUNDARY_PERIODIC boundary type.
1561 
1562    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
1563    a single value per point) you can skip filling those indices.
1564 
1565    Inspired by the structured grid interface to the HYPRE package
1566    (http://www.llnl.gov/CASC/hypre)
1567 
1568    Efficiency Alert:
1569    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1570    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1571 
1572    Level: beginner
1573 
1574    Concepts: matrices^putting entries in
1575 
1576 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1577           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1578 @*/
1579 PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1580 {
1581   PetscErrorCode ierr;
1582   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1583   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1584   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1585 
1586   PetscFunctionBegin;
1587   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1588   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1589   PetscValidType(mat,1);
1590   PetscValidIntPointer(idxm,3);
1591   PetscValidIntPointer(idxn,5);
1592   PetscValidScalarPointer(v,6);
1593 
1594   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1595     jdxm = buf; jdxn = buf+m;
1596   } else {
1597     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1598     jdxm = bufm; jdxn = bufn;
1599   }
1600   for (i=0; i<m; i++) {
1601     for (j=0; j<3-sdim; j++) dxm++;
1602     tmp = *dxm++ - starts[0];
1603     for (j=0; j<dim-1; j++) {
1604       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1605       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1606     }
1607     if (mat->stencil.noc) dxm++;
1608     jdxm[i] = tmp;
1609   }
1610   for (i=0; i<n; i++) {
1611     for (j=0; j<3-sdim; j++) dxn++;
1612     tmp = *dxn++ - starts[0];
1613     for (j=0; j<dim-1; j++) {
1614       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1615       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1616     }
1617     if (mat->stencil.noc) dxn++;
1618     jdxn[i] = tmp;
1619   }
1620   ierr = MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1621   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1622   PetscFunctionReturn(0);
1623 }
1624 
1625 /*@
1626    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1627      Using structured grid indexing
1628 
1629    Not Collective
1630 
1631    Input Parameters:
1632 +  mat - the matrix
1633 .  m - number of rows being entered
1634 .  idxm - grid coordinates for matrix rows being entered
1635 .  n - number of columns being entered
1636 .  idxn - grid coordinates for matrix columns being entered
1637 .  v - a logically two-dimensional array of values
1638 -  addv - either ADD_VALUES or INSERT_VALUES, where
1639    ADD_VALUES adds values to any existing entries, and
1640    INSERT_VALUES replaces existing entries with new values
1641 
1642    Notes:
1643    By default the values, v, are row-oriented and unsorted.
1644    See MatSetOption() for other options.
1645 
1646    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1647    options cannot be mixed without intervening calls to the assembly
1648    routines.
1649 
1650    The grid coordinates are across the entire grid, not just the local portion
1651 
1652    MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1653    as well as in C.
1654 
1655    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1656 
1657    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1658    or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1659 
1660    The columns and rows in the stencil passed in MUST be contained within the
1661    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1662    if you create a DMDA with an overlap of one grid level and on a particular process its first
1663    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1664    first i index you can use in your column and row indices in MatSetStencil() is 5.
1665 
1666    In Fortran idxm and idxn should be declared as
1667 $     MatStencil idxm(4,m),idxn(4,n)
1668    and the values inserted using
1669 $    idxm(MatStencil_i,1) = i
1670 $    idxm(MatStencil_j,1) = j
1671 $    idxm(MatStencil_k,1) = k
1672    etc
1673 
1674    Negative indices may be passed in idxm and idxn, these rows and columns are
1675    simply ignored. This allows easily inserting element stiffness matrices
1676    with homogeneous Dirchlet boundary conditions that you don't want represented
1677    in the matrix.
1678 
1679    Inspired by the structured grid interface to the HYPRE package
1680    (http://www.llnl.gov/CASC/hypre)
1681 
1682    Level: beginner
1683 
1684    Concepts: matrices^putting entries in
1685 
1686 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1687           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1688           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1689 @*/
1690 PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1691 {
1692   PetscErrorCode ierr;
1693   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1694   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1695   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1696 
1697   PetscFunctionBegin;
1698   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1699   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1700   PetscValidType(mat,1);
1701   PetscValidIntPointer(idxm,3);
1702   PetscValidIntPointer(idxn,5);
1703   PetscValidScalarPointer(v,6);
1704 
1705   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1706     jdxm = buf; jdxn = buf+m;
1707   } else {
1708     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1709     jdxm = bufm; jdxn = bufn;
1710   }
1711   for (i=0; i<m; i++) {
1712     for (j=0; j<3-sdim; j++) dxm++;
1713     tmp = *dxm++ - starts[0];
1714     for (j=0; j<sdim-1; j++) {
1715       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1716       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1717     }
1718     dxm++;
1719     jdxm[i] = tmp;
1720   }
1721   for (i=0; i<n; i++) {
1722     for (j=0; j<3-sdim; j++) dxn++;
1723     tmp = *dxn++ - starts[0];
1724     for (j=0; j<sdim-1; j++) {
1725       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1726       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1727     }
1728     dxn++;
1729     jdxn[i] = tmp;
1730   }
1731   ierr = MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1732   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1733 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1734   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1735     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1736   }
1737 #endif
1738   PetscFunctionReturn(0);
1739 }
1740 
1741 /*@
1742    MatSetStencil - Sets the grid information for setting values into a matrix via
1743         MatSetValuesStencil()
1744 
1745    Not Collective
1746 
1747    Input Parameters:
1748 +  mat - the matrix
1749 .  dim - dimension of the grid 1, 2, or 3
1750 .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1751 .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1752 -  dof - number of degrees of freedom per node
1753 
1754 
1755    Inspired by the structured grid interface to the HYPRE package
1756    (www.llnl.gov/CASC/hyper)
1757 
1758    For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1759    user.
1760 
1761    Level: beginner
1762 
1763    Concepts: matrices^putting entries in
1764 
1765 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1766           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1767 @*/
1768 PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1769 {
1770   PetscInt i;
1771 
1772   PetscFunctionBegin;
1773   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1774   PetscValidIntPointer(dims,3);
1775   PetscValidIntPointer(starts,4);
1776 
1777   mat->stencil.dim = dim + (dof > 1);
1778   for (i=0; i<dim; i++) {
1779     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1780     mat->stencil.starts[i] = starts[dim-i-1];
1781   }
1782   mat->stencil.dims[dim]   = dof;
1783   mat->stencil.starts[dim] = 0;
1784   mat->stencil.noc         = (PetscBool)(dof == 1);
1785   PetscFunctionReturn(0);
1786 }
1787 
1788 /*@C
1789    MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1790 
1791    Not Collective
1792 
1793    Input Parameters:
1794 +  mat - the matrix
1795 .  v - a logically two-dimensional array of values
1796 .  m, idxm - the number of block rows and their global block indices
1797 .  n, idxn - the number of block columns and their global block indices
1798 -  addv - either ADD_VALUES or INSERT_VALUES, where
1799    ADD_VALUES adds values to any existing entries, and
1800    INSERT_VALUES replaces existing entries with new values
1801 
1802    Notes:
1803    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1804    MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1805 
1806    The m and n count the NUMBER of blocks in the row direction and column direction,
1807    NOT the total number of rows/columns; for example, if the block size is 2 and
1808    you are passing in values for rows 2,3,4,5  then m would be 2 (not 4).
1809    The values in idxm would be 1 2; that is the first index for each block divided by
1810    the block size.
1811 
1812    Note that you must call MatSetBlockSize() when constructing this matrix (before
1813    preallocating it).
1814 
1815    By default the values, v, are row-oriented, so the layout of
1816    v is the same as for MatSetValues(). See MatSetOption() for other options.
1817 
1818    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1819    options cannot be mixed without intervening calls to the assembly
1820    routines.
1821 
1822    MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1823    as well as in C.
1824 
1825    Negative indices may be passed in idxm and idxn, these rows and columns are
1826    simply ignored. This allows easily inserting element stiffness matrices
1827    with homogeneous Dirchlet boundary conditions that you don't want represented
1828    in the matrix.
1829 
1830    Each time an entry is set within a sparse matrix via MatSetValues(),
1831    internal searching must be done to determine where to place the
1832    data in the matrix storage space.  By instead inserting blocks of
1833    entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1834    reduced.
1835 
1836    Example:
1837 $   Suppose m=n=2 and block size(bs) = 2 The array is
1838 $
1839 $   1  2  | 3  4
1840 $   5  6  | 7  8
1841 $   - - - | - - -
1842 $   9  10 | 11 12
1843 $   13 14 | 15 16
1844 $
1845 $   v[] should be passed in like
1846 $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1847 $
1848 $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1849 $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1850 
1851    Level: intermediate
1852 
1853    Concepts: matrices^putting entries in blocked
1854 
1855 .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1856 @*/
1857 PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1858 {
1859   PetscErrorCode ierr;
1860 
1861   PetscFunctionBeginHot;
1862   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1863   PetscValidType(mat,1);
1864   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1865   PetscValidIntPointer(idxm,3);
1866   PetscValidIntPointer(idxn,5);
1867   PetscValidScalarPointer(v,6);
1868   MatCheckPreallocated(mat,1);
1869   if (mat->insertmode == NOT_SET_VALUES) {
1870     mat->insertmode = addv;
1871   }
1872 #if defined(PETSC_USE_DEBUG)
1873   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1874   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1875   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1876 #endif
1877 
1878   if (mat->assembled) {
1879     mat->was_assembled = PETSC_TRUE;
1880     mat->assembled     = PETSC_FALSE;
1881   }
1882   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1883   if (mat->ops->setvaluesblocked) {
1884     ierr = (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);CHKERRQ(ierr);
1885   } else {
1886     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1887     PetscInt i,j,bs,cbs;
1888     ierr = MatGetBlockSizes(mat,&bs,&cbs);CHKERRQ(ierr);
1889     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1890       iidxm = buf; iidxn = buf + m*bs;
1891     } else {
1892       ierr  = PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);CHKERRQ(ierr);
1893       iidxm = bufr; iidxn = bufc;
1894     }
1895     for (i=0; i<m; i++) {
1896       for (j=0; j<bs; j++) {
1897         iidxm[i*bs+j] = bs*idxm[i] + j;
1898       }
1899     }
1900     for (i=0; i<n; i++) {
1901       for (j=0; j<cbs; j++) {
1902         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1903       }
1904     }
1905     ierr = MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);CHKERRQ(ierr);
1906     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
1907   }
1908   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1909 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1910   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1911     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1912   }
1913 #endif
1914   PetscFunctionReturn(0);
1915 }
1916 
1917 /*@
1918    MatGetValues - Gets a block of values from a matrix.
1919 
1920    Not Collective; currently only returns a local block
1921 
1922    Input Parameters:
1923 +  mat - the matrix
1924 .  v - a logically two-dimensional array for storing the values
1925 .  m, idxm - the number of rows and their global indices
1926 -  n, idxn - the number of columns and their global indices
1927 
1928    Notes:
1929    The user must allocate space (m*n PetscScalars) for the values, v.
1930    The values, v, are then returned in a row-oriented format,
1931    analogous to that used by default in MatSetValues().
1932 
1933    MatGetValues() uses 0-based row and column numbers in
1934    Fortran as well as in C.
1935 
1936    MatGetValues() requires that the matrix has been assembled
1937    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1938    MatSetValues() and MatGetValues() CANNOT be made in succession
1939    without intermediate matrix assembly.
1940 
1941    Negative row or column indices will be ignored and those locations in v[] will be
1942    left unchanged.
1943 
1944    Level: advanced
1945 
1946    Concepts: matrices^accessing values
1947 
1948 .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1949 @*/
1950 PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1951 {
1952   PetscErrorCode ierr;
1953 
1954   PetscFunctionBegin;
1955   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1956   PetscValidType(mat,1);
1957   if (!m || !n) PetscFunctionReturn(0);
1958   PetscValidIntPointer(idxm,3);
1959   PetscValidIntPointer(idxn,5);
1960   PetscValidScalarPointer(v,6);
1961   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1962   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1963   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1964   MatCheckPreallocated(mat,1);
1965 
1966   ierr = PetscLogEventBegin(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1967   ierr = (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);CHKERRQ(ierr);
1968   ierr = PetscLogEventEnd(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1969   PetscFunctionReturn(0);
1970 }
1971 
1972 /*@
1973   MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1974   the same size. Currently, this can only be called once and creates the given matrix.
1975 
1976   Not Collective
1977 
1978   Input Parameters:
1979 + mat - the matrix
1980 . nb - the number of blocks
1981 . bs - the number of rows (and columns) in each block
1982 . rows - a concatenation of the rows for each block
1983 - v - a concatenation of logically two-dimensional arrays of values
1984 
1985   Notes:
1986   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
1987 
1988   Level: advanced
1989 
1990   Concepts: matrices^putting entries in
1991 
1992 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1993           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1994 @*/
1995 PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1996 {
1997   PetscErrorCode ierr;
1998 
1999   PetscFunctionBegin;
2000   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2001   PetscValidType(mat,1);
2002   PetscValidScalarPointer(rows,4);
2003   PetscValidScalarPointer(v,5);
2004 #if defined(PETSC_USE_DEBUG)
2005   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2006 #endif
2007 
2008   ierr = PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
2009   if (mat->ops->setvaluesbatch) {
2010     ierr = (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);CHKERRQ(ierr);
2011   } else {
2012     PetscInt b;
2013     for (b = 0; b < nb; ++b) {
2014       ierr = MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);CHKERRQ(ierr);
2015     }
2016   }
2017   ierr = PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
2018   PetscFunctionReturn(0);
2019 }
2020 
2021 /*@
2022    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2023    the routine MatSetValuesLocal() to allow users to insert matrix entries
2024    using a local (per-processor) numbering.
2025 
2026    Not Collective
2027 
2028    Input Parameters:
2029 +  x - the matrix
2030 .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2031 - cmapping - column mapping
2032 
2033    Level: intermediate
2034 
2035    Concepts: matrices^local to global mapping
2036    Concepts: local to global mapping^for matrices
2037 
2038 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2039 @*/
2040 PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2041 {
2042   PetscErrorCode ierr;
2043 
2044   PetscFunctionBegin;
2045   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
2046   PetscValidType(x,1);
2047   PetscValidHeaderSpecific(rmapping,IS_LTOGM_CLASSID,2);
2048   PetscValidHeaderSpecific(cmapping,IS_LTOGM_CLASSID,3);
2049 
2050   if (x->ops->setlocaltoglobalmapping) {
2051     ierr = (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);CHKERRQ(ierr);
2052   } else {
2053     ierr = PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);CHKERRQ(ierr);
2054     ierr = PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);CHKERRQ(ierr);
2055   }
2056   PetscFunctionReturn(0);
2057 }
2058 
2059 
2060 /*@
2061    MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
2062 
2063    Not Collective
2064 
2065    Input Parameters:
2066 .  A - the matrix
2067 
2068    Output Parameters:
2069 + rmapping - row mapping
2070 - cmapping - column mapping
2071 
2072    Level: advanced
2073 
2074    Concepts: matrices^local to global mapping
2075    Concepts: local to global mapping^for matrices
2076 
2077 .seealso:  MatSetValuesLocal()
2078 @*/
2079 PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2080 {
2081   PetscFunctionBegin;
2082   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
2083   PetscValidType(A,1);
2084   if (rmapping) PetscValidPointer(rmapping,2);
2085   if (cmapping) PetscValidPointer(cmapping,3);
2086   if (rmapping) *rmapping = A->rmap->mapping;
2087   if (cmapping) *cmapping = A->cmap->mapping;
2088   PetscFunctionReturn(0);
2089 }
2090 
2091 /*@
2092    MatGetLayouts - Gets the PetscLayout objects for rows and columns
2093 
2094    Not Collective
2095 
2096    Input Parameters:
2097 .  A - the matrix
2098 
2099    Output Parameters:
2100 + rmap - row layout
2101 - cmap - column layout
2102 
2103    Level: advanced
2104 
2105 .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2106 @*/
2107 PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2108 {
2109   PetscFunctionBegin;
2110   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
2111   PetscValidType(A,1);
2112   if (rmap) PetscValidPointer(rmap,2);
2113   if (cmap) PetscValidPointer(cmap,3);
2114   if (rmap) *rmap = A->rmap;
2115   if (cmap) *cmap = A->cmap;
2116   PetscFunctionReturn(0);
2117 }
2118 
2119 /*@C
2120    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2121    using a local ordering of the nodes.
2122 
2123    Not Collective
2124 
2125    Input Parameters:
2126 +  mat - the matrix
2127 .  nrow, irow - number of rows and their local indices
2128 .  ncol, icol - number of columns and their local indices
2129 .  y -  a logically two-dimensional array of values
2130 -  addv - either INSERT_VALUES or ADD_VALUES, where
2131    ADD_VALUES adds values to any existing entries, and
2132    INSERT_VALUES replaces existing entries with new values
2133 
2134    Notes:
2135    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2136       MatSetUp() before using this routine
2137 
2138    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
2139 
2140    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2141    options cannot be mixed without intervening calls to the assembly
2142    routines.
2143 
2144    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2145    MUST be called after all calls to MatSetValuesLocal() have been completed.
2146 
2147    Level: intermediate
2148 
2149    Concepts: matrices^putting entries in with local numbering
2150 
2151    Developer Notes:
2152     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2153                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2154 
2155 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2156            MatSetValueLocal()
2157 @*/
2158 PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2159 {
2160   PetscErrorCode ierr;
2161 
2162   PetscFunctionBeginHot;
2163   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2164   PetscValidType(mat,1);
2165   MatCheckPreallocated(mat,1);
2166   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
2167   PetscValidIntPointer(irow,3);
2168   PetscValidIntPointer(icol,5);
2169   PetscValidScalarPointer(y,6);
2170   if (mat->insertmode == NOT_SET_VALUES) {
2171     mat->insertmode = addv;
2172   }
2173 #if defined(PETSC_USE_DEBUG)
2174   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2175   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2176   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2177 #endif
2178 
2179   if (mat->assembled) {
2180     mat->was_assembled = PETSC_TRUE;
2181     mat->assembled     = PETSC_FALSE;
2182   }
2183   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2184   if (mat->ops->setvalueslocal) {
2185     ierr = (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2186   } else {
2187     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2188     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2189       irowm = buf; icolm = buf+nrow;
2190     } else {
2191       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2192       irowm = bufr; icolm = bufc;
2193     }
2194     ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2195     ierr = ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2196     ierr = MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2197     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2198   }
2199   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2200 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2201   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2202     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2203   }
2204 #endif
2205   PetscFunctionReturn(0);
2206 }
2207 
2208 /*@C
2209    MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2210    using a local ordering of the nodes a block at a time.
2211 
2212    Not Collective
2213 
2214    Input Parameters:
2215 +  x - the matrix
2216 .  nrow, irow - number of rows and their local indices
2217 .  ncol, icol - number of columns and their local indices
2218 .  y -  a logically two-dimensional array of values
2219 -  addv - either INSERT_VALUES or ADD_VALUES, where
2220    ADD_VALUES adds values to any existing entries, and
2221    INSERT_VALUES replaces existing entries with new values
2222 
2223    Notes:
2224    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2225       MatSetUp() before using this routine
2226 
2227    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2228       before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2229 
2230    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2231    options cannot be mixed without intervening calls to the assembly
2232    routines.
2233 
2234    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2235    MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2236 
2237    Level: intermediate
2238 
2239    Developer Notes:
2240     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2241                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2242 
2243    Concepts: matrices^putting blocked values in with local numbering
2244 
2245 .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2246            MatSetValuesLocal(),  MatSetValuesBlocked()
2247 @*/
2248 PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2249 {
2250   PetscErrorCode ierr;
2251 
2252   PetscFunctionBeginHot;
2253   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2254   PetscValidType(mat,1);
2255   MatCheckPreallocated(mat,1);
2256   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
2257   PetscValidIntPointer(irow,3);
2258   PetscValidIntPointer(icol,5);
2259   PetscValidScalarPointer(y,6);
2260   if (mat->insertmode == NOT_SET_VALUES) {
2261     mat->insertmode = addv;
2262   }
2263 #if defined(PETSC_USE_DEBUG)
2264   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2265   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2266   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);
2267 #endif
2268 
2269   if (mat->assembled) {
2270     mat->was_assembled = PETSC_TRUE;
2271     mat->assembled     = PETSC_FALSE;
2272   }
2273   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2274   if (mat->ops->setvaluesblockedlocal) {
2275     ierr = (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2276   } else {
2277     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2278     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2279       irowm = buf; icolm = buf + nrow;
2280     } else {
2281       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2282       irowm = bufr; icolm = bufc;
2283     }
2284     ierr = ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2285     ierr = ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2286     ierr = MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2287     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2288   }
2289   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2290 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2291   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2292     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2293   }
2294 #endif
2295   PetscFunctionReturn(0);
2296 }
2297 
2298 /*@
2299    MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2300 
2301    Collective on Mat and Vec
2302 
2303    Input Parameters:
2304 +  mat - the matrix
2305 -  x   - the vector to be multiplied
2306 
2307    Output Parameters:
2308 .  y - the result
2309 
2310    Notes:
2311    The vectors x and y cannot be the same.  I.e., one cannot
2312    call MatMult(A,y,y).
2313 
2314    Level: developer
2315 
2316    Concepts: matrix-vector product
2317 
2318 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2319 @*/
2320 PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2321 {
2322   PetscErrorCode ierr;
2323 
2324   PetscFunctionBegin;
2325   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2326   PetscValidType(mat,1);
2327   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2328   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2329 
2330   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2331   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2332   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2333   MatCheckPreallocated(mat,1);
2334 
2335   if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2336   ierr = (*mat->ops->multdiagonalblock)(mat,x,y);CHKERRQ(ierr);
2337   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2338   PetscFunctionReturn(0);
2339 }
2340 
2341 /* --------------------------------------------------------*/
2342 /*@
2343    MatMult - Computes the matrix-vector product, y = Ax.
2344 
2345    Neighbor-wise Collective on Mat and Vec
2346 
2347    Input Parameters:
2348 +  mat - the matrix
2349 -  x   - the vector to be multiplied
2350 
2351    Output Parameters:
2352 .  y - the result
2353 
2354    Notes:
2355    The vectors x and y cannot be the same.  I.e., one cannot
2356    call MatMult(A,y,y).
2357 
2358    Level: beginner
2359 
2360    Concepts: matrix-vector product
2361 
2362 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2363 @*/
2364 PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2365 {
2366   PetscErrorCode ierr;
2367 
2368   PetscFunctionBegin;
2369   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2370   PetscValidType(mat,1);
2371   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2372   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2373   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2374   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2375   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2376 #if !defined(PETSC_HAVE_CONSTRAINTS)
2377   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);
2378   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);
2379   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);
2380 #endif
2381   ierr = VecSetErrorIfLocked(y,3);CHKERRQ(ierr);
2382   if (mat->erroriffailure) {ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);}
2383   MatCheckPreallocated(mat,1);
2384 
2385   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2386   if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2387   ierr = PetscLogEventBegin(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2388   ierr = (*mat->ops->mult)(mat,x,y);CHKERRQ(ierr);
2389   ierr = PetscLogEventEnd(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2390   if (mat->erroriffailure) {ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);}
2391   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2392   PetscFunctionReturn(0);
2393 }
2394 
2395 /*@
2396    MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.
2397 
2398    Neighbor-wise Collective on Mat and Vec
2399 
2400    Input Parameters:
2401 +  mat - the matrix
2402 -  x   - the vector to be multiplied
2403 
2404    Output Parameters:
2405 .  y - the result
2406 
2407    Notes:
2408    The vectors x and y cannot be the same.  I.e., one cannot
2409    call MatMultTranspose(A,y,y).
2410 
2411    For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2412    use MatMultHermitianTranspose()
2413 
2414    Level: beginner
2415 
2416    Concepts: matrix vector product^transpose
2417 
2418 .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2419 @*/
2420 PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2421 {
2422   PetscErrorCode ierr;
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   if (mat->erroriffailure) {ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);}
2438   MatCheckPreallocated(mat,1);
2439 
2440   if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2441   ierr = PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2442   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2443   ierr = (*mat->ops->multtranspose)(mat,x,y);CHKERRQ(ierr);
2444   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2445   ierr = PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2446   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2447   if (mat->erroriffailure) {ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);}
2448   PetscFunctionReturn(0);
2449 }
2450 
2451 /*@
2452    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2453 
2454    Neighbor-wise Collective on Mat and Vec
2455 
2456    Input Parameters:
2457 +  mat - the matrix
2458 -  x   - the vector to be multilplied
2459 
2460    Output Parameters:
2461 .  y - the result
2462 
2463    Notes:
2464    The vectors x and y cannot be the same.  I.e., one cannot
2465    call MatMultHermitianTranspose(A,y,y).
2466 
2467    Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2468 
2469    For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2470 
2471    Level: beginner
2472 
2473    Concepts: matrix vector product^transpose
2474 
2475 .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2476 @*/
2477 PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2478 {
2479   PetscErrorCode ierr;
2480   Vec            w;
2481 
2482   PetscFunctionBegin;
2483   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2484   PetscValidType(mat,1);
2485   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2486   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2487 
2488   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2489   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2490   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2491 #if !defined(PETSC_HAVE_CONSTRAINTS)
2492   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);
2493   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);
2494 #endif
2495   MatCheckPreallocated(mat,1);
2496 
2497   ierr = PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2498   if (mat->ops->multhermitiantranspose) {
2499     ierr = VecLockReadPush(x);CHKERRQ(ierr);
2500     ierr = (*mat->ops->multhermitiantranspose)(mat,x,y);CHKERRQ(ierr);
2501     ierr = VecLockReadPop(x);CHKERRQ(ierr);
2502   } else {
2503     ierr = VecDuplicate(x,&w);CHKERRQ(ierr);
2504     ierr = VecCopy(x,w);CHKERRQ(ierr);
2505     ierr = VecConjugate(w);CHKERRQ(ierr);
2506     ierr = MatMultTranspose(mat,w,y);CHKERRQ(ierr);
2507     ierr = VecDestroy(&w);CHKERRQ(ierr);
2508     ierr = VecConjugate(y);CHKERRQ(ierr);
2509   }
2510   ierr = PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2511   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2512   PetscFunctionReturn(0);
2513 }
2514 
2515 /*@
2516     MatMultAdd -  Computes v3 = v2 + A * v1.
2517 
2518     Neighbor-wise Collective on Mat and Vec
2519 
2520     Input Parameters:
2521 +   mat - the matrix
2522 -   v1, v2 - the vectors
2523 
2524     Output Parameters:
2525 .   v3 - the result
2526 
2527     Notes:
2528     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2529     call MatMultAdd(A,v1,v2,v1).
2530 
2531     Level: beginner
2532 
2533     Concepts: matrix vector product^addition
2534 
2535 .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2536 @*/
2537 PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2538 {
2539   PetscErrorCode ierr;
2540 
2541   PetscFunctionBegin;
2542   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2543   PetscValidType(mat,1);
2544   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2545   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2546   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2547 
2548   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2549   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2550   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);
2551   /* 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);
2552      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); */
2553   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);
2554   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);
2555   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2556   MatCheckPreallocated(mat,1);
2557 
2558   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2559   ierr = PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2560   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2561   ierr = (*mat->ops->multadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2562   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2563   ierr = PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2564   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2565   PetscFunctionReturn(0);
2566 }
2567 
2568 /*@
2569    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2570 
2571    Neighbor-wise Collective on Mat and Vec
2572 
2573    Input Parameters:
2574 +  mat - the matrix
2575 -  v1, v2 - the vectors
2576 
2577    Output Parameters:
2578 .  v3 - the result
2579 
2580    Notes:
2581    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2582    call MatMultTransposeAdd(A,v1,v2,v1).
2583 
2584    Level: beginner
2585 
2586    Concepts: matrix vector product^transpose and addition
2587 
2588 .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2589 @*/
2590 PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2591 {
2592   PetscErrorCode ierr;
2593 
2594   PetscFunctionBegin;
2595   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2596   PetscValidType(mat,1);
2597   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2598   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2599   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2600 
2601   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2602   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2603   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2604   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2605   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);
2606   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);
2607   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);
2608   MatCheckPreallocated(mat,1);
2609 
2610   ierr = PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2611   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2612   ierr = (*mat->ops->multtransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2613   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2614   ierr = PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2615   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2616   PetscFunctionReturn(0);
2617 }
2618 
2619 /*@
2620    MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2621 
2622    Neighbor-wise Collective on Mat and Vec
2623 
2624    Input Parameters:
2625 +  mat - the matrix
2626 -  v1, v2 - the vectors
2627 
2628    Output Parameters:
2629 .  v3 - the result
2630 
2631    Notes:
2632    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2633    call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2634 
2635    Level: beginner
2636 
2637    Concepts: matrix vector product^transpose and addition
2638 
2639 .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2640 @*/
2641 PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2642 {
2643   PetscErrorCode ierr;
2644 
2645   PetscFunctionBegin;
2646   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2647   PetscValidType(mat,1);
2648   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2649   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2650   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2651 
2652   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2653   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2654   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2655   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);
2656   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);
2657   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);
2658   MatCheckPreallocated(mat,1);
2659 
2660   ierr = PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2661   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2662   if (mat->ops->multhermitiantransposeadd) {
2663     ierr = (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2664   } else {
2665     Vec w,z;
2666     ierr = VecDuplicate(v1,&w);CHKERRQ(ierr);
2667     ierr = VecCopy(v1,w);CHKERRQ(ierr);
2668     ierr = VecConjugate(w);CHKERRQ(ierr);
2669     ierr = VecDuplicate(v3,&z);CHKERRQ(ierr);
2670     ierr = MatMultTranspose(mat,w,z);CHKERRQ(ierr);
2671     ierr = VecDestroy(&w);CHKERRQ(ierr);
2672     ierr = VecConjugate(z);CHKERRQ(ierr);
2673     if (v2 != v3) {
2674       ierr = VecWAXPY(v3,1.0,v2,z);CHKERRQ(ierr);
2675     } else {
2676       ierr = VecAXPY(v3,1.0,z);CHKERRQ(ierr);
2677     }
2678     ierr = VecDestroy(&z);CHKERRQ(ierr);
2679   }
2680   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2681   ierr = PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2682   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2683   PetscFunctionReturn(0);
2684 }
2685 
2686 /*@
2687    MatMultConstrained - The inner multiplication routine for a
2688    constrained matrix P^T A P.
2689 
2690    Neighbor-wise Collective on Mat and Vec
2691 
2692    Input Parameters:
2693 +  mat - the matrix
2694 -  x   - the vector to be multilplied
2695 
2696    Output Parameters:
2697 .  y - the result
2698 
2699    Notes:
2700    The vectors x and y cannot be the same.  I.e., one cannot
2701    call MatMult(A,y,y).
2702 
2703    Level: beginner
2704 
2705 .keywords: matrix, multiply, matrix-vector product, constraint
2706 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2707 @*/
2708 PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2709 {
2710   PetscErrorCode ierr;
2711 
2712   PetscFunctionBegin;
2713   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2714   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2715   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2716   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2717   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2718   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2719   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);
2720   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);
2721   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);
2722 
2723   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2724   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2725   ierr = (*mat->ops->multconstrained)(mat,x,y);CHKERRQ(ierr);
2726   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2727   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2728   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2729   PetscFunctionReturn(0);
2730 }
2731 
2732 /*@
2733    MatMultTransposeConstrained - The inner multiplication routine for a
2734    constrained matrix P^T A^T P.
2735 
2736    Neighbor-wise Collective on Mat and Vec
2737 
2738    Input Parameters:
2739 +  mat - the matrix
2740 -  x   - the vector to be multilplied
2741 
2742    Output Parameters:
2743 .  y - the result
2744 
2745    Notes:
2746    The vectors x and y cannot be the same.  I.e., one cannot
2747    call MatMult(A,y,y).
2748 
2749    Level: beginner
2750 
2751 .keywords: matrix, multiply, matrix-vector product, constraint
2752 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2753 @*/
2754 PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2755 {
2756   PetscErrorCode ierr;
2757 
2758   PetscFunctionBegin;
2759   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2760   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2761   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2762   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2763   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2764   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2765   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);
2766   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);
2767 
2768   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2769   ierr = (*mat->ops->multtransposeconstrained)(mat,x,y);CHKERRQ(ierr);
2770   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2771   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2772   PetscFunctionReturn(0);
2773 }
2774 
2775 /*@C
2776    MatGetFactorType - gets the type of factorization it is
2777 
2778    Not Collective
2779 
2780    Input Parameters:
2781 .  mat - the matrix
2782 
2783    Output Parameters:
2784 .  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2785 
2786    Level: intermediate
2787 
2788 .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2789 @*/
2790 PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2791 {
2792   PetscFunctionBegin;
2793   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2794   PetscValidType(mat,1);
2795   PetscValidPointer(t,2);
2796   *t = mat->factortype;
2797   PetscFunctionReturn(0);
2798 }
2799 
2800 /*@C
2801    MatSetFactorType - sets the type of factorization it is
2802 
2803    Logically Collective on Mat
2804 
2805    Input Parameters:
2806 +  mat - the matrix
2807 -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2808 
2809    Level: intermediate
2810 
2811 .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2812 @*/
2813 PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2814 {
2815   PetscFunctionBegin;
2816   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2817   PetscValidType(mat,1);
2818   mat->factortype = t;
2819   PetscFunctionReturn(0);
2820 }
2821 
2822 /* ------------------------------------------------------------*/
2823 /*@C
2824    MatGetInfo - Returns information about matrix storage (number of
2825    nonzeros, memory, etc.).
2826 
2827    Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2828 
2829    Input Parameters:
2830 .  mat - the matrix
2831 
2832    Output Parameters:
2833 +  flag - flag indicating the type of parameters to be returned
2834    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2835    MAT_GLOBAL_SUM - sum over all processors)
2836 -  info - matrix information context
2837 
2838    Notes:
2839    The MatInfo context contains a variety of matrix data, including
2840    number of nonzeros allocated and used, number of mallocs during
2841    matrix assembly, etc.  Additional information for factored matrices
2842    is provided (such as the fill ratio, number of mallocs during
2843    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2844    when using the runtime options
2845 $       -info -mat_view ::ascii_info
2846 
2847    Example for C/C++ Users:
2848    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2849    data within the MatInfo context.  For example,
2850 .vb
2851       MatInfo info;
2852       Mat     A;
2853       double  mal, nz_a, nz_u;
2854 
2855       MatGetInfo(A,MAT_LOCAL,&info);
2856       mal  = info.mallocs;
2857       nz_a = info.nz_allocated;
2858 .ve
2859 
2860    Example for Fortran Users:
2861    Fortran users should declare info as a double precision
2862    array of dimension MAT_INFO_SIZE, and then extract the parameters
2863    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2864    a complete list of parameter names.
2865 .vb
2866       double  precision info(MAT_INFO_SIZE)
2867       double  precision mal, nz_a
2868       Mat     A
2869       integer ierr
2870 
2871       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2872       mal = info(MAT_INFO_MALLOCS)
2873       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2874 .ve
2875 
2876     Level: intermediate
2877 
2878     Concepts: matrices^getting information on
2879 
2880     Developer Note: fortran interface is not autogenerated as the f90
2881     interface defintion cannot be generated correctly [due to MatInfo]
2882 
2883 .seealso: MatStashGetInfo()
2884 
2885 @*/
2886 PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2887 {
2888   PetscErrorCode ierr;
2889 
2890   PetscFunctionBegin;
2891   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2892   PetscValidType(mat,1);
2893   PetscValidPointer(info,3);
2894   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2895   MatCheckPreallocated(mat,1);
2896   ierr = (*mat->ops->getinfo)(mat,flag,info);CHKERRQ(ierr);
2897   PetscFunctionReturn(0);
2898 }
2899 
2900 /*
2901    This is used by external packages where it is not easy to get the info from the actual
2902    matrix factorization.
2903 */
2904 PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2905 {
2906   PetscErrorCode ierr;
2907 
2908   PetscFunctionBegin;
2909   ierr = PetscMemzero(info,sizeof(MatInfo));CHKERRQ(ierr);
2910   PetscFunctionReturn(0);
2911 }
2912 
2913 /* ----------------------------------------------------------*/
2914 
2915 /*@C
2916    MatLUFactor - Performs in-place LU factorization of matrix.
2917 
2918    Collective on Mat
2919 
2920    Input Parameters:
2921 +  mat - the matrix
2922 .  row - row permutation
2923 .  col - column permutation
2924 -  info - options for factorization, includes
2925 $          fill - expected fill as ratio of original fill.
2926 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2927 $                   Run with the option -info to determine an optimal value to use
2928 
2929    Notes:
2930    Most users should employ the simplified KSP interface for linear solvers
2931    instead of working directly with matrix algebra routines such as this.
2932    See, e.g., KSPCreate().
2933 
2934    This changes the state of the matrix to a factored matrix; it cannot be used
2935    for example with MatSetValues() unless one first calls MatSetUnfactored().
2936 
2937    Level: developer
2938 
2939    Concepts: matrices^LU factorization
2940 
2941 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2942           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2943 
2944     Developer Note: fortran interface is not autogenerated as the f90
2945     interface defintion cannot be generated correctly [due to MatFactorInfo]
2946 
2947 @*/
2948 PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2949 {
2950   PetscErrorCode ierr;
2951   MatFactorInfo  tinfo;
2952 
2953   PetscFunctionBegin;
2954   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2955   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2956   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2957   if (info) PetscValidPointer(info,4);
2958   PetscValidType(mat,1);
2959   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2960   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2961   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2962   MatCheckPreallocated(mat,1);
2963   if (!info) {
2964     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
2965     info = &tinfo;
2966   }
2967 
2968   ierr = PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2969   ierr = (*mat->ops->lufactor)(mat,row,col,info);CHKERRQ(ierr);
2970   ierr = PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2971   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
2972   PetscFunctionReturn(0);
2973 }
2974 
2975 /*@C
2976    MatILUFactor - Performs in-place ILU factorization of matrix.
2977 
2978    Collective on Mat
2979 
2980    Input Parameters:
2981 +  mat - the matrix
2982 .  row - row permutation
2983 .  col - column permutation
2984 -  info - structure containing
2985 $      levels - number of levels of fill.
2986 $      expected fill - as ratio of original fill.
2987 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2988                 missing diagonal entries)
2989 
2990    Notes:
2991    Probably really in-place only when level of fill is zero, otherwise allocates
2992    new space to store factored matrix and deletes previous memory.
2993 
2994    Most users should employ the simplified KSP interface for linear solvers
2995    instead of working directly with matrix algebra routines such as this.
2996    See, e.g., KSPCreate().
2997 
2998    Level: developer
2999 
3000    Concepts: matrices^ILU factorization
3001 
3002 .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
3003 
3004     Developer Note: fortran interface is not autogenerated as the f90
3005     interface defintion cannot be generated correctly [due to MatFactorInfo]
3006 
3007 @*/
3008 PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3009 {
3010   PetscErrorCode ierr;
3011 
3012   PetscFunctionBegin;
3013   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3014   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
3015   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
3016   PetscValidPointer(info,4);
3017   PetscValidType(mat,1);
3018   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
3019   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3020   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3021   if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3022   MatCheckPreallocated(mat,1);
3023 
3024   ierr = PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
3025   ierr = (*mat->ops->ilufactor)(mat,row,col,info);CHKERRQ(ierr);
3026   ierr = PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
3027   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3028   PetscFunctionReturn(0);
3029 }
3030 
3031 /*@C
3032    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3033    Call this routine before calling MatLUFactorNumeric().
3034 
3035    Collective on Mat
3036 
3037    Input Parameters:
3038 +  fact - the factor matrix obtained with MatGetFactor()
3039 .  mat - the matrix
3040 .  row, col - row and column permutations
3041 -  info - options for factorization, includes
3042 $          fill - expected fill as ratio of original fill.
3043 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3044 $                   Run with the option -info to determine an optimal value to use
3045 
3046 
3047    Notes:
3048     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
3049 
3050    Most users should employ the simplified KSP interface for linear solvers
3051    instead of working directly with matrix algebra routines such as this.
3052    See, e.g., KSPCreate().
3053 
3054    Level: developer
3055 
3056    Concepts: matrices^LU symbolic factorization
3057 
3058 .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
3059 
3060     Developer Note: fortran interface is not autogenerated as the f90
3061     interface defintion cannot be generated correctly [due to MatFactorInfo]
3062 
3063 @*/
3064 PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3065 {
3066   PetscErrorCode ierr;
3067 
3068   PetscFunctionBegin;
3069   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3070   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
3071   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
3072   if (info) PetscValidPointer(info,4);
3073   PetscValidType(mat,1);
3074   PetscValidPointer(fact,5);
3075   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3076   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3077   if (!(fact)->ops->lufactorsymbolic) {
3078     MatSolverType spackage;
3079     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
3080     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3081   }
3082   MatCheckPreallocated(mat,2);
3083 
3084   ierr = PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
3085   ierr = (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
3086   ierr = PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
3087   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3088   PetscFunctionReturn(0);
3089 }
3090 
3091 /*@C
3092    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3093    Call this routine after first calling MatLUFactorSymbolic().
3094 
3095    Collective on Mat
3096 
3097    Input Parameters:
3098 +  fact - the factor matrix obtained with MatGetFactor()
3099 .  mat - the matrix
3100 -  info - options for factorization
3101 
3102    Notes:
3103    See MatLUFactor() for in-place factorization.  See
3104    MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3105 
3106    Most users should employ the simplified KSP interface for linear solvers
3107    instead of working directly with matrix algebra routines such as this.
3108    See, e.g., KSPCreate().
3109 
3110    Level: developer
3111 
3112    Concepts: matrices^LU numeric factorization
3113 
3114 .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3115 
3116     Developer Note: fortran interface is not autogenerated as the f90
3117     interface defintion cannot be generated correctly [due to MatFactorInfo]
3118 
3119 @*/
3120 PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3121 {
3122   PetscErrorCode ierr;
3123 
3124   PetscFunctionBegin;
3125   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3126   PetscValidType(mat,1);
3127   PetscValidPointer(fact,2);
3128   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
3129   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3130   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);
3131 
3132   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3133   MatCheckPreallocated(mat,2);
3134   ierr = PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3135   ierr = (fact->ops->lufactornumeric)(fact,mat,info);CHKERRQ(ierr);
3136   ierr = PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3137   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3138   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3139   PetscFunctionReturn(0);
3140 }
3141 
3142 /*@C
3143    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3144    symmetric matrix.
3145 
3146    Collective on Mat
3147 
3148    Input Parameters:
3149 +  mat - the matrix
3150 .  perm - row and column permutations
3151 -  f - expected fill as ratio of original fill
3152 
3153    Notes:
3154    See MatLUFactor() for the nonsymmetric case.  See also
3155    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3156 
3157    Most users should employ the simplified KSP interface for linear solvers
3158    instead of working directly with matrix algebra routines such as this.
3159    See, e.g., KSPCreate().
3160 
3161    Level: developer
3162 
3163    Concepts: matrices^Cholesky factorization
3164 
3165 .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3166           MatGetOrdering()
3167 
3168     Developer Note: fortran interface is not autogenerated as the f90
3169     interface defintion cannot be generated correctly [due to MatFactorInfo]
3170 
3171 @*/
3172 PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3173 {
3174   PetscErrorCode ierr;
3175 
3176   PetscFunctionBegin;
3177   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3178   PetscValidType(mat,1);
3179   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3180   if (info) PetscValidPointer(info,3);
3181   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3182   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3183   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3184   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);
3185   MatCheckPreallocated(mat,1);
3186 
3187   ierr = PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3188   ierr = (*mat->ops->choleskyfactor)(mat,perm,info);CHKERRQ(ierr);
3189   ierr = PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3190   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3191   PetscFunctionReturn(0);
3192 }
3193 
3194 /*@C
3195    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3196    of a symmetric matrix.
3197 
3198    Collective on Mat
3199 
3200    Input Parameters:
3201 +  fact - the factor matrix obtained with MatGetFactor()
3202 .  mat - the matrix
3203 .  perm - row and column permutations
3204 -  info - options for factorization, includes
3205 $          fill - expected fill as ratio of original fill.
3206 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3207 $                   Run with the option -info to determine an optimal value to use
3208 
3209    Notes:
3210    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3211    MatCholeskyFactor() and MatCholeskyFactorNumeric().
3212 
3213    Most users should employ the simplified KSP interface for linear solvers
3214    instead of working directly with matrix algebra routines such as this.
3215    See, e.g., KSPCreate().
3216 
3217    Level: developer
3218 
3219    Concepts: matrices^Cholesky symbolic factorization
3220 
3221 .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3222           MatGetOrdering()
3223 
3224     Developer Note: fortran interface is not autogenerated as the f90
3225     interface defintion cannot be generated correctly [due to MatFactorInfo]
3226 
3227 @*/
3228 PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3229 {
3230   PetscErrorCode ierr;
3231 
3232   PetscFunctionBegin;
3233   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3234   PetscValidType(mat,1);
3235   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3236   if (info) PetscValidPointer(info,3);
3237   PetscValidPointer(fact,4);
3238   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3239   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3240   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3241   if (!(fact)->ops->choleskyfactorsymbolic) {
3242     MatSolverType spackage;
3243     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
3244     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3245   }
3246   MatCheckPreallocated(mat,2);
3247 
3248   ierr = PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3249   ierr = (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
3250   ierr = PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3251   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3252   PetscFunctionReturn(0);
3253 }
3254 
3255 /*@C
3256    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3257    of a symmetric matrix. Call this routine after first calling
3258    MatCholeskyFactorSymbolic().
3259 
3260    Collective on Mat
3261 
3262    Input Parameters:
3263 +  fact - the factor matrix obtained with MatGetFactor()
3264 .  mat - the initial matrix
3265 .  info - options for factorization
3266 -  fact - the symbolic factor of mat
3267 
3268 
3269    Notes:
3270    Most users should employ the simplified KSP interface for linear solvers
3271    instead of working directly with matrix algebra routines such as this.
3272    See, e.g., KSPCreate().
3273 
3274    Level: developer
3275 
3276    Concepts: matrices^Cholesky numeric factorization
3277 
3278 .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3279 
3280     Developer Note: fortran interface is not autogenerated as the f90
3281     interface defintion cannot be generated correctly [due to MatFactorInfo]
3282 
3283 @*/
3284 PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3285 {
3286   PetscErrorCode ierr;
3287 
3288   PetscFunctionBegin;
3289   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3290   PetscValidType(mat,1);
3291   PetscValidPointer(fact,2);
3292   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
3293   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3294   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3295   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);
3296   MatCheckPreallocated(mat,2);
3297 
3298   ierr = PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3299   ierr = (fact->ops->choleskyfactornumeric)(fact,mat,info);CHKERRQ(ierr);
3300   ierr = PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3301   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3302   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3303   PetscFunctionReturn(0);
3304 }
3305 
3306 /* ----------------------------------------------------------------*/
3307 /*@
3308    MatSolve - Solves A x = b, given a factored matrix.
3309 
3310    Neighbor-wise Collective on Mat and Vec
3311 
3312    Input Parameters:
3313 +  mat - the factored matrix
3314 -  b - the right-hand-side vector
3315 
3316    Output Parameter:
3317 .  x - the result vector
3318 
3319    Notes:
3320    The vectors b and x cannot be the same.  I.e., one cannot
3321    call MatSolve(A,x,x).
3322 
3323    Notes:
3324    Most users should employ the simplified KSP interface for linear solvers
3325    instead of working directly with matrix algebra routines such as this.
3326    See, e.g., KSPCreate().
3327 
3328    Level: developer
3329 
3330    Concepts: matrices^triangular solves
3331 
3332 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3333 @*/
3334 PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3335 {
3336   PetscErrorCode ierr;
3337 
3338   PetscFunctionBegin;
3339   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3340   PetscValidType(mat,1);
3341   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3342   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3343   PetscCheckSameComm(mat,1,b,2);
3344   PetscCheckSameComm(mat,1,x,3);
3345   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3346   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);
3347   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);
3348   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);
3349   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3350   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3351   MatCheckPreallocated(mat,1);
3352 
3353   ierr = PetscLogEventBegin(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3354   if (mat->factorerrortype) {
3355     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3356     ierr = VecSetInf(x);CHKERRQ(ierr);
3357   } else {
3358     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3359     ierr = (*mat->ops->solve)(mat,b,x);CHKERRQ(ierr);
3360   }
3361   ierr = PetscLogEventEnd(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3362   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3363   PetscFunctionReturn(0);
3364 }
3365 
3366 static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X, PetscBool trans)
3367 {
3368   PetscErrorCode ierr;
3369   Vec            b,x;
3370   PetscInt       m,N,i;
3371   PetscScalar    *bb,*xx;
3372   PetscBool      flg;
3373 
3374   PetscFunctionBegin;
3375   ierr = PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQDENSE,MATMPIDENSE,NULL);CHKERRQ(ierr);
3376   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
3377   ierr = PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);CHKERRQ(ierr);
3378   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");
3379 
3380   ierr = MatDenseGetArray(B,&bb);CHKERRQ(ierr);
3381   ierr = MatDenseGetArray(X,&xx);CHKERRQ(ierr);
3382   ierr = MatGetLocalSize(B,&m,NULL);CHKERRQ(ierr);  /* number local rows */
3383   ierr = MatGetSize(B,NULL,&N);CHKERRQ(ierr);       /* total columns in dense matrix */
3384   ierr = MatCreateVecs(A,&x,&b);CHKERRQ(ierr);
3385   for (i=0; i<N; i++) {
3386     ierr = VecPlaceArray(b,bb + i*m);CHKERRQ(ierr);
3387     ierr = VecPlaceArray(x,xx + i*m);CHKERRQ(ierr);
3388     if (trans) {
3389       ierr = MatSolveTranspose(A,b,x);CHKERRQ(ierr);
3390     } else {
3391       ierr = MatSolve(A,b,x);CHKERRQ(ierr);
3392     }
3393     ierr = VecResetArray(x);CHKERRQ(ierr);
3394     ierr = VecResetArray(b);CHKERRQ(ierr);
3395   }
3396   ierr = VecDestroy(&b);CHKERRQ(ierr);
3397   ierr = VecDestroy(&x);CHKERRQ(ierr);
3398   ierr = MatDenseRestoreArray(B,&bb);CHKERRQ(ierr);
3399   ierr = MatDenseRestoreArray(X,&xx);CHKERRQ(ierr);
3400   PetscFunctionReturn(0);
3401 }
3402 
3403 /*@
3404    MatMatSolve - Solves A X = B, given a factored matrix.
3405 
3406    Neighbor-wise Collective on Mat
3407 
3408    Input Parameters:
3409 +  A - the factored matrix
3410 -  B - the right-hand-side matrix  (dense matrix)
3411 
3412    Output Parameter:
3413 .  X - the result matrix (dense matrix)
3414 
3415    Notes:
3416    The matrices b and x cannot be the same.  I.e., one cannot
3417    call MatMatSolve(A,x,x).
3418 
3419    Notes:
3420    Most users should usually employ the simplified KSP interface for linear solvers
3421    instead of working directly with matrix algebra routines such as this.
3422    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3423    at a time.
3424 
3425    When using SuperLU_Dist as a parallel solver PETSc will use the SuperLU_Dist functionality to solve multiple right hand sides simultaneously. For MUMPS
3426    it calls a separate solve for each right hand side since MUMPS does not yet support distributed right hand sides.
3427 
3428    Since the resulting matrix X must always be dense we do not support sparse representation of the matrix B.
3429 
3430    Level: developer
3431 
3432    Concepts: matrices^triangular solves
3433 
3434 .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3435 @*/
3436 PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3437 {
3438   PetscErrorCode ierr;
3439 
3440   PetscFunctionBegin;
3441   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3442   PetscValidType(A,1);
3443   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3444   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3445   PetscCheckSameComm(A,1,B,2);
3446   PetscCheckSameComm(A,1,X,3);
3447   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3448   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);
3449   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);
3450   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");
3451   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3452   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3453   MatCheckPreallocated(A,1);
3454 
3455   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3456   if (!A->ops->matsolve) {
3457     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3458     ierr = MatMatSolve_Basic(A,B,X,PETSC_FALSE);CHKERRQ(ierr);
3459   } else {
3460     ierr = (*A->ops->matsolve)(A,B,X);CHKERRQ(ierr);
3461   }
3462   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3463   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3464   PetscFunctionReturn(0);
3465 }
3466 
3467 /*@
3468    MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3469 
3470    Neighbor-wise Collective on Mat
3471 
3472    Input Parameters:
3473 +  A - the factored matrix
3474 -  B - the right-hand-side matrix  (dense matrix)
3475 
3476    Output Parameter:
3477 .  X - the result matrix (dense matrix)
3478 
3479    Notes:
3480    The matrices B and X cannot be the same.  I.e., one cannot
3481    call MatMatSolveTranspose(A,X,X).
3482 
3483    Notes:
3484    Most users should usually employ the simplified KSP interface for linear solvers
3485    instead of working directly with matrix algebra routines such as this.
3486    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3487    at a time.
3488 
3489    When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3490 
3491    Level: developer
3492 
3493    Concepts: matrices^triangular solves
3494 
3495 .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3496 @*/
3497 PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3498 {
3499   PetscErrorCode ierr;
3500 
3501   PetscFunctionBegin;
3502   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3503   PetscValidType(A,1);
3504   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3505   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3506   PetscCheckSameComm(A,1,B,2);
3507   PetscCheckSameComm(A,1,X,3);
3508   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3509   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);
3510   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);
3511   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);
3512   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");
3513   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3514   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3515   MatCheckPreallocated(A,1);
3516 
3517   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3518   if (!A->ops->matsolvetranspose) {
3519     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3520     ierr = MatMatSolve_Basic(A,B,X,PETSC_TRUE);CHKERRQ(ierr);
3521   } else {
3522     ierr = (*A->ops->matsolvetranspose)(A,B,X);CHKERRQ(ierr);
3523   }
3524   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3525   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3526   PetscFunctionReturn(0);
3527 }
3528 
3529 /*@
3530    MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3531 
3532    Neighbor-wise Collective on Mat
3533 
3534    Input Parameters:
3535 +  A - the factored matrix
3536 -  Bt - the transpose of right-hand-side matrix
3537 
3538    Output Parameter:
3539 .  X - the result matrix (dense matrix)
3540 
3541    Notes:
3542    Most users should usually employ the simplified KSP interface for linear solvers
3543    instead of working directly with matrix algebra routines such as this.
3544    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3545    at a time.
3546 
3547    For MUMPS, it only supports centralized sparse compressed column format on the host processor for right hand side matrix. User must create B^T in sparse compressed row format on the host processor and call MatMatTransposeSolve() to implement MUMPS' MatMatSolve().
3548 
3549    Level: developer
3550 
3551    Concepts: matrices^triangular solves
3552 
3553 .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3554 @*/
3555 PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3556 {
3557   PetscErrorCode ierr;
3558 
3559   PetscFunctionBegin;
3560   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3561   PetscValidType(A,1);
3562   PetscValidHeaderSpecific(Bt,MAT_CLASSID,2);
3563   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3564   PetscCheckSameComm(A,1,Bt,2);
3565   PetscCheckSameComm(A,1,X,3);
3566 
3567   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3568   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);
3569   if (A->rmap->N != Bt->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat Bt: global dim %D %D",A->rmap->N,Bt->cmap->N);
3570   if (X->cmap->N < Bt->rmap->N) SETERRQ(PetscObjectComm((PetscObject)X),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as row number of the rhs matrix");
3571   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3572   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3573   MatCheckPreallocated(A,1);
3574 
3575   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3576   ierr = PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3577   ierr = (*A->ops->mattransposesolve)(A,Bt,X);CHKERRQ(ierr);
3578   ierr = PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3579   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3580   PetscFunctionReturn(0);
3581 }
3582 
3583 /*@
3584    MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3585                             U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3586 
3587    Neighbor-wise Collective on Mat and Vec
3588 
3589    Input Parameters:
3590 +  mat - the factored matrix
3591 -  b - the right-hand-side vector
3592 
3593    Output Parameter:
3594 .  x - the result vector
3595 
3596    Notes:
3597    MatSolve() should be used for most applications, as it performs
3598    a forward solve followed by a backward solve.
3599 
3600    The vectors b and x cannot be the same,  i.e., one cannot
3601    call MatForwardSolve(A,x,x).
3602 
3603    For matrix in seqsbaij format with block size larger than 1,
3604    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3605    MatForwardSolve() solves U^T*D y = b, and
3606    MatBackwardSolve() solves U x = y.
3607    Thus they do not provide a symmetric preconditioner.
3608 
3609    Most users should employ the simplified KSP interface for linear solvers
3610    instead of working directly with matrix algebra routines such as this.
3611    See, e.g., KSPCreate().
3612 
3613    Level: developer
3614 
3615    Concepts: matrices^forward solves
3616 
3617 .seealso: MatSolve(), MatBackwardSolve()
3618 @*/
3619 PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3620 {
3621   PetscErrorCode ierr;
3622 
3623   PetscFunctionBegin;
3624   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3625   PetscValidType(mat,1);
3626   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3627   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3628   PetscCheckSameComm(mat,1,b,2);
3629   PetscCheckSameComm(mat,1,x,3);
3630   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3631   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);
3632   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);
3633   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);
3634   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3635   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3636   MatCheckPreallocated(mat,1);
3637 
3638   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3639   ierr = PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3640   ierr = (*mat->ops->forwardsolve)(mat,b,x);CHKERRQ(ierr);
3641   ierr = PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3642   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3643   PetscFunctionReturn(0);
3644 }
3645 
3646 /*@
3647    MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3648                              D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3649 
3650    Neighbor-wise Collective on Mat and Vec
3651 
3652    Input Parameters:
3653 +  mat - the factored matrix
3654 -  b - the right-hand-side vector
3655 
3656    Output Parameter:
3657 .  x - the result vector
3658 
3659    Notes:
3660    MatSolve() should be used for most applications, as it performs
3661    a forward solve followed by a backward solve.
3662 
3663    The vectors b and x cannot be the same.  I.e., one cannot
3664    call MatBackwardSolve(A,x,x).
3665 
3666    For matrix in seqsbaij format with block size larger than 1,
3667    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3668    MatForwardSolve() solves U^T*D y = b, and
3669    MatBackwardSolve() solves U x = y.
3670    Thus they do not provide a symmetric preconditioner.
3671 
3672    Most users should employ the simplified KSP interface for linear solvers
3673    instead of working directly with matrix algebra routines such as this.
3674    See, e.g., KSPCreate().
3675 
3676    Level: developer
3677 
3678    Concepts: matrices^backward solves
3679 
3680 .seealso: MatSolve(), MatForwardSolve()
3681 @*/
3682 PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3683 {
3684   PetscErrorCode ierr;
3685 
3686   PetscFunctionBegin;
3687   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3688   PetscValidType(mat,1);
3689   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3690   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3691   PetscCheckSameComm(mat,1,b,2);
3692   PetscCheckSameComm(mat,1,x,3);
3693   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3694   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);
3695   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);
3696   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);
3697   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3698   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3699   MatCheckPreallocated(mat,1);
3700 
3701   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3702   ierr = PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3703   ierr = (*mat->ops->backwardsolve)(mat,b,x);CHKERRQ(ierr);
3704   ierr = PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3705   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3706   PetscFunctionReturn(0);
3707 }
3708 
3709 /*@
3710    MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3711 
3712    Neighbor-wise Collective on Mat and Vec
3713 
3714    Input Parameters:
3715 +  mat - the factored matrix
3716 .  b - the right-hand-side vector
3717 -  y - the vector to be added to
3718 
3719    Output Parameter:
3720 .  x - the result vector
3721 
3722    Notes:
3723    The vectors b and x cannot be the same.  I.e., one cannot
3724    call MatSolveAdd(A,x,y,x).
3725 
3726    Most users should employ the simplified KSP interface for linear solvers
3727    instead of working directly with matrix algebra routines such as this.
3728    See, e.g., KSPCreate().
3729 
3730    Level: developer
3731 
3732    Concepts: matrices^triangular solves
3733 
3734 .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3735 @*/
3736 PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3737 {
3738   PetscScalar    one = 1.0;
3739   Vec            tmp;
3740   PetscErrorCode ierr;
3741 
3742   PetscFunctionBegin;
3743   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3744   PetscValidType(mat,1);
3745   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3746   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3747   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3748   PetscCheckSameComm(mat,1,b,2);
3749   PetscCheckSameComm(mat,1,y,2);
3750   PetscCheckSameComm(mat,1,x,3);
3751   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3752   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);
3753   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);
3754   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);
3755   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);
3756   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);
3757   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3758   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3759   MatCheckPreallocated(mat,1);
3760 
3761   ierr = PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3762   if (mat->ops->solveadd) {
3763     ierr = (*mat->ops->solveadd)(mat,b,y,x);CHKERRQ(ierr);
3764   } else {
3765     /* do the solve then the add manually */
3766     if (x != y) {
3767       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3768       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3769     } else {
3770       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3771       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3772       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3773       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3774       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3775       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3776     }
3777   }
3778   ierr = PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3779   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3780   PetscFunctionReturn(0);
3781 }
3782 
3783 /*@
3784    MatSolveTranspose - Solves A' x = b, given a factored matrix.
3785 
3786    Neighbor-wise Collective on Mat and Vec
3787 
3788    Input Parameters:
3789 +  mat - the factored matrix
3790 -  b - the right-hand-side vector
3791 
3792    Output Parameter:
3793 .  x - the result vector
3794 
3795    Notes:
3796    The vectors b and x cannot be the same.  I.e., one cannot
3797    call MatSolveTranspose(A,x,x).
3798 
3799    Most users should employ the simplified KSP interface for linear solvers
3800    instead of working directly with matrix algebra routines such as this.
3801    See, e.g., KSPCreate().
3802 
3803    Level: developer
3804 
3805    Concepts: matrices^triangular solves
3806 
3807 .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3808 @*/
3809 PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3810 {
3811   PetscErrorCode ierr;
3812 
3813   PetscFunctionBegin;
3814   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3815   PetscValidType(mat,1);
3816   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3817   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3818   PetscCheckSameComm(mat,1,b,2);
3819   PetscCheckSameComm(mat,1,x,3);
3820   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3821   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);
3822   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);
3823   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3824   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3825   MatCheckPreallocated(mat,1);
3826   ierr = PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3827   if (mat->factorerrortype) {
3828     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3829     ierr = VecSetInf(x);CHKERRQ(ierr);
3830   } else {
3831     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3832     ierr = (*mat->ops->solvetranspose)(mat,b,x);CHKERRQ(ierr);
3833   }
3834   ierr = PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3835   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3836   PetscFunctionReturn(0);
3837 }
3838 
3839 /*@
3840    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3841                       factored matrix.
3842 
3843    Neighbor-wise Collective on Mat and Vec
3844 
3845    Input Parameters:
3846 +  mat - the factored matrix
3847 .  b - the right-hand-side vector
3848 -  y - the vector to be added to
3849 
3850    Output Parameter:
3851 .  x - the result vector
3852 
3853    Notes:
3854    The vectors b and x cannot be the same.  I.e., one cannot
3855    call MatSolveTransposeAdd(A,x,y,x).
3856 
3857    Most users should employ the simplified KSP interface for linear solvers
3858    instead of working directly with matrix algebra routines such as this.
3859    See, e.g., KSPCreate().
3860 
3861    Level: developer
3862 
3863    Concepts: matrices^triangular solves
3864 
3865 .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3866 @*/
3867 PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3868 {
3869   PetscScalar    one = 1.0;
3870   PetscErrorCode ierr;
3871   Vec            tmp;
3872 
3873   PetscFunctionBegin;
3874   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3875   PetscValidType(mat,1);
3876   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3877   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3878   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3879   PetscCheckSameComm(mat,1,b,2);
3880   PetscCheckSameComm(mat,1,y,3);
3881   PetscCheckSameComm(mat,1,x,4);
3882   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3883   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);
3884   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);
3885   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);
3886   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);
3887   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3888   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3889   MatCheckPreallocated(mat,1);
3890 
3891   ierr = PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3892   if (mat->ops->solvetransposeadd) {
3893     if (mat->factorerrortype) {
3894       ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3895       ierr = VecSetInf(x);CHKERRQ(ierr);
3896     } else {
3897       ierr = (*mat->ops->solvetransposeadd)(mat,b,y,x);CHKERRQ(ierr);
3898     }
3899   } else {
3900     /* do the solve then the add manually */
3901     if (x != y) {
3902       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3903       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3904     } else {
3905       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3906       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3907       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3908       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3909       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3910       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3911     }
3912   }
3913   ierr = PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3914   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3915   PetscFunctionReturn(0);
3916 }
3917 /* ----------------------------------------------------------------*/
3918 
3919 /*@
3920    MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3921 
3922    Neighbor-wise Collective on Mat and Vec
3923 
3924    Input Parameters:
3925 +  mat - the matrix
3926 .  b - the right hand side
3927 .  omega - the relaxation factor
3928 .  flag - flag indicating the type of SOR (see below)
3929 .  shift -  diagonal shift
3930 .  its - the number of iterations
3931 -  lits - the number of local iterations
3932 
3933    Output Parameters:
3934 .  x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3935 
3936    SOR Flags:
3937 .     SOR_FORWARD_SWEEP - forward SOR
3938 .     SOR_BACKWARD_SWEEP - backward SOR
3939 .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3940 .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3941 .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3942 .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3943 .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3944          upper/lower triangular part of matrix to
3945          vector (with omega)
3946 .     SOR_ZERO_INITIAL_GUESS - zero initial guess
3947 
3948    Notes:
3949    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3950    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3951    on each processor.
3952 
3953    Application programmers will not generally use MatSOR() directly,
3954    but instead will employ the KSP/PC interface.
3955 
3956    Notes:
3957     for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3958 
3959    Notes for Advanced Users:
3960    The flags are implemented as bitwise inclusive or operations.
3961    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3962    to specify a zero initial guess for SSOR.
3963 
3964    Most users should employ the simplified KSP interface for linear solvers
3965    instead of working directly with matrix algebra routines such as this.
3966    See, e.g., KSPCreate().
3967 
3968    Vectors x and b CANNOT be the same
3969 
3970    Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3971 
3972    Level: developer
3973 
3974    Concepts: matrices^relaxation
3975    Concepts: matrices^SOR
3976    Concepts: matrices^Gauss-Seidel
3977 
3978 @*/
3979 PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3980 {
3981   PetscErrorCode ierr;
3982 
3983   PetscFunctionBegin;
3984   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3985   PetscValidType(mat,1);
3986   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3987   PetscValidHeaderSpecific(x,VEC_CLASSID,8);
3988   PetscCheckSameComm(mat,1,b,2);
3989   PetscCheckSameComm(mat,1,x,8);
3990   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3991   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3992   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3993   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);
3994   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);
3995   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);
3996   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3997   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3998   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
3999 
4000   MatCheckPreallocated(mat,1);
4001   ierr = PetscLogEventBegin(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
4002   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);CHKERRQ(ierr);
4003   ierr = PetscLogEventEnd(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
4004   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
4005   PetscFunctionReturn(0);
4006 }
4007 
4008 /*
4009       Default matrix copy routine.
4010 */
4011 PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4012 {
4013   PetscErrorCode    ierr;
4014   PetscInt          i,rstart = 0,rend = 0,nz;
4015   const PetscInt    *cwork;
4016   const PetscScalar *vwork;
4017 
4018   PetscFunctionBegin;
4019   if (B->assembled) {
4020     ierr = MatZeroEntries(B);CHKERRQ(ierr);
4021   }
4022   ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
4023   for (i=rstart; i<rend; i++) {
4024     ierr = MatGetRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
4025     ierr = MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);CHKERRQ(ierr);
4026     ierr = MatRestoreRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
4027   }
4028   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4029   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4030   PetscFunctionReturn(0);
4031 }
4032 
4033 /*@
4034    MatCopy - Copys a matrix to another matrix.
4035 
4036    Collective on Mat
4037 
4038    Input Parameters:
4039 +  A - the matrix
4040 -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
4041 
4042    Output Parameter:
4043 .  B - where the copy is put
4044 
4045    Notes:
4046    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4047    same nonzero pattern or the routine will crash.
4048 
4049    MatCopy() copies the matrix entries of a matrix to another existing
4050    matrix (after first zeroing the second matrix).  A related routine is
4051    MatConvert(), which first creates a new matrix and then copies the data.
4052 
4053    Level: intermediate
4054 
4055    Concepts: matrices^copying
4056 
4057 .seealso: MatConvert(), MatDuplicate()
4058 
4059 @*/
4060 PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4061 {
4062   PetscErrorCode ierr;
4063   PetscInt       i;
4064 
4065   PetscFunctionBegin;
4066   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4067   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4068   PetscValidType(A,1);
4069   PetscValidType(B,2);
4070   PetscCheckSameComm(A,1,B,2);
4071   MatCheckPreallocated(B,2);
4072   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4073   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4074   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);
4075   MatCheckPreallocated(A,1);
4076   if (A == B) PetscFunctionReturn(0);
4077 
4078   ierr = PetscLogEventBegin(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
4079   if (A->ops->copy) {
4080     ierr = (*A->ops->copy)(A,B,str);CHKERRQ(ierr);
4081   } else { /* generic conversion */
4082     ierr = MatCopy_Basic(A,B,str);CHKERRQ(ierr);
4083   }
4084 
4085   B->stencil.dim = A->stencil.dim;
4086   B->stencil.noc = A->stencil.noc;
4087   for (i=0; i<=A->stencil.dim; i++) {
4088     B->stencil.dims[i]   = A->stencil.dims[i];
4089     B->stencil.starts[i] = A->stencil.starts[i];
4090   }
4091 
4092   ierr = PetscLogEventEnd(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
4093   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4094   PetscFunctionReturn(0);
4095 }
4096 
4097 /*@C
4098    MatConvert - Converts a matrix to another matrix, either of the same
4099    or different type.
4100 
4101    Collective on Mat
4102 
4103    Input Parameters:
4104 +  mat - the matrix
4105 .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4106    same type as the original matrix.
4107 -  reuse - denotes if the destination matrix is to be created or reused.
4108    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
4109    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).
4110 
4111    Output Parameter:
4112 .  M - pointer to place new matrix
4113 
4114    Notes:
4115    MatConvert() first creates a new matrix and then copies the data from
4116    the first matrix.  A related routine is MatCopy(), which copies the matrix
4117    entries of one matrix to another already existing matrix context.
4118 
4119    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4120    the MPI communicator of the generated matrix is always the same as the communicator
4121    of the input matrix.
4122 
4123    Level: intermediate
4124 
4125    Concepts: matrices^converting between storage formats
4126 
4127 .seealso: MatCopy(), MatDuplicate()
4128 @*/
4129 PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4130 {
4131   PetscErrorCode ierr;
4132   PetscBool      sametype,issame,flg;
4133   char           convname[256],mtype[256];
4134   Mat            B;
4135 
4136   PetscFunctionBegin;
4137   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4138   PetscValidType(mat,1);
4139   PetscValidPointer(M,3);
4140   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4141   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4142   MatCheckPreallocated(mat,1);
4143 
4144   ierr = PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);CHKERRQ(ierr);
4145   if (flg) {
4146     newtype = mtype;
4147   }
4148   ierr = PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);CHKERRQ(ierr);
4149   ierr = PetscStrcmp(newtype,"same",&issame);CHKERRQ(ierr);
4150   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4151   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");
4152 
4153   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) PetscFunctionReturn(0);
4154 
4155   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4156     ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4157   } else {
4158     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4159     const char     *prefix[3] = {"seq","mpi",""};
4160     PetscInt       i;
4161     /*
4162        Order of precedence:
4163        0) See if newtype is a superclass of the current matrix.
4164        1) See if a specialized converter is known to the current matrix.
4165        2) See if a specialized converter is known to the desired matrix class.
4166        3) See if a good general converter is registered for the desired class
4167           (as of 6/27/03 only MATMPIADJ falls into this category).
4168        4) See if a good general converter is known for the current matrix.
4169        5) Use a really basic converter.
4170     */
4171 
4172     /* 0) See if newtype is a superclass of the current matrix.
4173           i.e mat is mpiaij and newtype is aij */
4174     for (i=0; i<2; i++) {
4175       ierr = PetscStrncpy(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4176       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4177       ierr = PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);CHKERRQ(ierr);
4178       if (flg) {
4179         if (reuse == MAT_INPLACE_MATRIX) {
4180           PetscFunctionReturn(0);
4181         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4182           ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4183           PetscFunctionReturn(0);
4184         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4185           ierr = MatCopy(mat,*M,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
4186           PetscFunctionReturn(0);
4187         }
4188       }
4189     }
4190     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4191     for (i=0; i<3; i++) {
4192       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4193       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4194       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4195       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4196       ierr = PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));CHKERRQ(ierr);
4197       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4198       ierr = PetscObjectQueryFunction((PetscObject)mat,convname,&conv);CHKERRQ(ierr);
4199       if (conv) goto foundconv;
4200     }
4201 
4202     /* 2)  See if a specialized converter is known to the desired matrix class. */
4203     ierr = MatCreate(PetscObjectComm((PetscObject)mat),&B);CHKERRQ(ierr);
4204     ierr = MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);CHKERRQ(ierr);
4205     ierr = MatSetType(B,newtype);CHKERRQ(ierr);
4206     for (i=0; i<3; i++) {
4207       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4208       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4209       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4210       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4211       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4212       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4213       ierr = PetscObjectQueryFunction((PetscObject)B,convname,&conv);CHKERRQ(ierr);
4214       if (conv) {
4215         ierr = MatDestroy(&B);CHKERRQ(ierr);
4216         goto foundconv;
4217       }
4218     }
4219 
4220     /* 3) See if a good general converter is registered for the desired class */
4221     conv = B->ops->convertfrom;
4222     ierr = MatDestroy(&B);CHKERRQ(ierr);
4223     if (conv) goto foundconv;
4224 
4225     /* 4) See if a good general converter is known for the current matrix */
4226     if (mat->ops->convert) {
4227       conv = mat->ops->convert;
4228     }
4229     if (conv) goto foundconv;
4230 
4231     /* 5) Use a really basic converter. */
4232     conv = MatConvert_Basic;
4233 
4234 foundconv:
4235     ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4236     ierr = (*conv)(mat,newtype,reuse,M);CHKERRQ(ierr);
4237     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4238       /* the block sizes must be same if the mappings are copied over */
4239       (*M)->rmap->bs = mat->rmap->bs;
4240       (*M)->cmap->bs = mat->cmap->bs;
4241       ierr = PetscObjectReference((PetscObject)mat->rmap->mapping);CHKERRQ(ierr);
4242       ierr = PetscObjectReference((PetscObject)mat->cmap->mapping);CHKERRQ(ierr);
4243       (*M)->rmap->mapping = mat->rmap->mapping;
4244       (*M)->cmap->mapping = mat->cmap->mapping;
4245     }
4246     (*M)->stencil.dim = mat->stencil.dim;
4247     (*M)->stencil.noc = mat->stencil.noc;
4248     for (i=0; i<=mat->stencil.dim; i++) {
4249       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4250       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4251     }
4252     ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4253   }
4254   ierr = PetscObjectStateIncrease((PetscObject)*M);CHKERRQ(ierr);
4255 
4256   /* Copy Mat options */
4257   if (mat->symmetric) {ierr = MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);}
4258   if (mat->hermitian) {ierr = MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);}
4259   PetscFunctionReturn(0);
4260 }
4261 
4262 /*@C
4263    MatFactorGetSolverType - Returns name of the package providing the factorization routines
4264 
4265    Not Collective
4266 
4267    Input Parameter:
4268 .  mat - the matrix, must be a factored matrix
4269 
4270    Output Parameter:
4271 .   type - the string name of the package (do not free this string)
4272 
4273    Notes:
4274       In Fortran you pass in a empty string and the package name will be copied into it.
4275     (Make sure the string is long enough)
4276 
4277    Level: intermediate
4278 
4279 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4280 @*/
4281 PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4282 {
4283   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4284 
4285   PetscFunctionBegin;
4286   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4287   PetscValidType(mat,1);
4288   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4289   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);CHKERRQ(ierr);
4290   if (!conv) {
4291     *type = MATSOLVERPETSC;
4292   } else {
4293     ierr = (*conv)(mat,type);CHKERRQ(ierr);
4294   }
4295   PetscFunctionReturn(0);
4296 }
4297 
4298 typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4299 struct _MatSolverTypeForSpecifcType {
4300   MatType                        mtype;
4301   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4302   MatSolverTypeForSpecifcType next;
4303 };
4304 
4305 typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4306 struct _MatSolverTypeHolder {
4307   char                           *name;
4308   MatSolverTypeForSpecifcType handlers;
4309   MatSolverTypeHolder         next;
4310 };
4311 
4312 static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4313 
4314 /*@C
4315    MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type
4316 
4317    Input Parameters:
4318 +    package - name of the package, for example petsc or superlu
4319 .    mtype - the matrix type that works with this package
4320 .    ftype - the type of factorization supported by the package
4321 -    getfactor - routine that will create the factored matrix ready to be used
4322 
4323     Level: intermediate
4324 
4325 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4326 @*/
4327 PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4328 {
4329   PetscErrorCode              ierr;
4330   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4331   PetscBool                   flg;
4332   MatSolverTypeForSpecifcType inext,iprev = NULL;
4333 
4334   PetscFunctionBegin;
4335   ierr = MatInitializePackage();CHKERRQ(ierr);
4336   if (!next) {
4337     ierr = PetscNew(&MatSolverTypeHolders);CHKERRQ(ierr);
4338     ierr = PetscStrallocpy(package,&MatSolverTypeHolders->name);CHKERRQ(ierr);
4339     ierr = PetscNew(&MatSolverTypeHolders->handlers);CHKERRQ(ierr);
4340     ierr = PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);CHKERRQ(ierr);
4341     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4342     PetscFunctionReturn(0);
4343   }
4344   while (next) {
4345     ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4346     if (flg) {
4347       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4348       inext = next->handlers;
4349       while (inext) {
4350         ierr = PetscStrcasecmp(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4351         if (flg) {
4352           inext->getfactor[(int)ftype-1] = getfactor;
4353           PetscFunctionReturn(0);
4354         }
4355         iprev = inext;
4356         inext = inext->next;
4357       }
4358       ierr = PetscNew(&iprev->next);CHKERRQ(ierr);
4359       ierr = PetscStrallocpy(mtype,(char **)&iprev->next->mtype);CHKERRQ(ierr);
4360       iprev->next->getfactor[(int)ftype-1] = getfactor;
4361       PetscFunctionReturn(0);
4362     }
4363     prev = next;
4364     next = next->next;
4365   }
4366   ierr = PetscNew(&prev->next);CHKERRQ(ierr);
4367   ierr = PetscStrallocpy(package,&prev->next->name);CHKERRQ(ierr);
4368   ierr = PetscNew(&prev->next->handlers);CHKERRQ(ierr);
4369   ierr = PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);CHKERRQ(ierr);
4370   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4371   PetscFunctionReturn(0);
4372 }
4373 
4374 /*@C
4375    MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4376 
4377    Input Parameters:
4378 +    package - name of the package, for example petsc or superlu
4379 .    ftype - the type of factorization supported by the package
4380 -    mtype - the matrix type that works with this package
4381 
4382    Output Parameters:
4383 +   foundpackage - PETSC_TRUE if the package was registered
4384 .   foundmtype - PETSC_TRUE if the package supports the requested mtype
4385 -   getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4386 
4387     Level: intermediate
4388 
4389 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4390 @*/
4391 PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4392 {
4393   PetscErrorCode                 ierr;
4394   MatSolverTypeHolder         next = MatSolverTypeHolders;
4395   PetscBool                      flg;
4396   MatSolverTypeForSpecifcType inext;
4397 
4398   PetscFunctionBegin;
4399   if (foundpackage) *foundpackage = PETSC_FALSE;
4400   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4401   if (getfactor)    *getfactor    = NULL;
4402 
4403   if (package) {
4404     while (next) {
4405       ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4406       if (flg) {
4407         if (foundpackage) *foundpackage = PETSC_TRUE;
4408         inext = next->handlers;
4409         while (inext) {
4410           ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4411           if (flg) {
4412             if (foundmtype) *foundmtype = PETSC_TRUE;
4413             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4414             PetscFunctionReturn(0);
4415           }
4416           inext = inext->next;
4417         }
4418       }
4419       next = next->next;
4420     }
4421   } else {
4422     while (next) {
4423       inext = next->handlers;
4424       while (inext) {
4425         ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4426         if (flg && inext->getfactor[(int)ftype-1]) {
4427           if (foundpackage) *foundpackage = PETSC_TRUE;
4428           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4429           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
4430           PetscFunctionReturn(0);
4431         }
4432         inext = inext->next;
4433       }
4434       next = next->next;
4435     }
4436   }
4437   PetscFunctionReturn(0);
4438 }
4439 
4440 PetscErrorCode MatSolverTypeDestroy(void)
4441 {
4442   PetscErrorCode              ierr;
4443   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4444   MatSolverTypeForSpecifcType inext,iprev;
4445 
4446   PetscFunctionBegin;
4447   while (next) {
4448     ierr = PetscFree(next->name);CHKERRQ(ierr);
4449     inext = next->handlers;
4450     while (inext) {
4451       ierr = PetscFree(inext->mtype);CHKERRQ(ierr);
4452       iprev = inext;
4453       inext = inext->next;
4454       ierr = PetscFree(iprev);CHKERRQ(ierr);
4455     }
4456     prev = next;
4457     next = next->next;
4458     ierr = PetscFree(prev);CHKERRQ(ierr);
4459   }
4460   MatSolverTypeHolders = NULL;
4461   PetscFunctionReturn(0);
4462 }
4463 
4464 /*@C
4465    MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4466 
4467    Collective on Mat
4468 
4469    Input Parameters:
4470 +  mat - the matrix
4471 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4472 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4473 
4474    Output Parameters:
4475 .  f - the factor matrix used with MatXXFactorSymbolic() calls
4476 
4477    Notes:
4478       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4479      such as pastix, superlu, mumps etc.
4480 
4481       PETSc must have been ./configure to use the external solver, using the option --download-package
4482 
4483    Level: intermediate
4484 
4485 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4486 @*/
4487 PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4488 {
4489   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4490   PetscBool      foundpackage,foundmtype;
4491 
4492   PetscFunctionBegin;
4493   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4494   PetscValidType(mat,1);
4495 
4496   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4497   MatCheckPreallocated(mat,1);
4498 
4499   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);CHKERRQ(ierr);
4500   if (!foundpackage) {
4501     if (type) {
4502       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4503     } else {
4504       SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4505     }
4506   }
4507 
4508   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4509   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);
4510 
4511 #if defined(PETSC_USE_COMPLEX)
4512   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");
4513 #endif
4514 
4515   ierr = (*conv)(mat,ftype,f);CHKERRQ(ierr);
4516   PetscFunctionReturn(0);
4517 }
4518 
4519 /*@C
4520    MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4521 
4522    Not Collective
4523 
4524    Input Parameters:
4525 +  mat - the matrix
4526 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4527 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4528 
4529    Output Parameter:
4530 .    flg - PETSC_TRUE if the factorization is available
4531 
4532    Notes:
4533       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4534      such as pastix, superlu, mumps etc.
4535 
4536       PETSc must have been ./configure to use the external solver, using the option --download-package
4537 
4538    Level: intermediate
4539 
4540 .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4541 @*/
4542 PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4543 {
4544   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4545 
4546   PetscFunctionBegin;
4547   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4548   PetscValidType(mat,1);
4549 
4550   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4551   MatCheckPreallocated(mat,1);
4552 
4553   *flg = PETSC_FALSE;
4554   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);CHKERRQ(ierr);
4555   if (gconv) {
4556     *flg = PETSC_TRUE;
4557   }
4558   PetscFunctionReturn(0);
4559 }
4560 
4561 #include <petscdmtypes.h>
4562 
4563 /*@
4564    MatDuplicate - Duplicates a matrix including the non-zero structure.
4565 
4566    Collective on Mat
4567 
4568    Input Parameters:
4569 +  mat - the matrix
4570 -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4571         See the manual page for MatDuplicateOption for an explanation of these options.
4572 
4573    Output Parameter:
4574 .  M - pointer to place new matrix
4575 
4576    Level: intermediate
4577 
4578    Concepts: matrices^duplicating
4579 
4580    Notes:
4581     You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4582     When original mat is a product of matrix operation, e.g., an output of MatMatMult() or MatCreateSubMatrix(), only the simple matrix data structure of mat is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated. User should not use MatDuplicate() to create new matrix M if M is intended to be reused as the product of matrix operation.
4583 
4584 .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4585 @*/
4586 PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4587 {
4588   PetscErrorCode ierr;
4589   Mat            B;
4590   PetscInt       i;
4591   DM             dm;
4592   void           (*viewf)(void);
4593 
4594   PetscFunctionBegin;
4595   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4596   PetscValidType(mat,1);
4597   PetscValidPointer(M,3);
4598   if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4599   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4600   MatCheckPreallocated(mat,1);
4601 
4602   *M = 0;
4603   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4604   ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4605   ierr = (*mat->ops->duplicate)(mat,op,M);CHKERRQ(ierr);
4606   B    = *M;
4607 
4608   ierr = MatGetOperation(mat,MATOP_VIEW,&viewf);CHKERRQ(ierr);
4609   if (viewf) {
4610     ierr = MatSetOperation(B,MATOP_VIEW,viewf);CHKERRQ(ierr);
4611   }
4612 
4613   B->stencil.dim = mat->stencil.dim;
4614   B->stencil.noc = mat->stencil.noc;
4615   for (i=0; i<=mat->stencil.dim; i++) {
4616     B->stencil.dims[i]   = mat->stencil.dims[i];
4617     B->stencil.starts[i] = mat->stencil.starts[i];
4618   }
4619 
4620   B->nooffproczerorows = mat->nooffproczerorows;
4621   B->nooffprocentries  = mat->nooffprocentries;
4622 
4623   ierr = PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);CHKERRQ(ierr);
4624   if (dm) {
4625     ierr = PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);CHKERRQ(ierr);
4626   }
4627   ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4628   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4629   PetscFunctionReturn(0);
4630 }
4631 
4632 /*@
4633    MatGetDiagonal - Gets the diagonal of a matrix.
4634 
4635    Logically Collective on Mat and Vec
4636 
4637    Input Parameters:
4638 +  mat - the matrix
4639 -  v - the vector for storing the diagonal
4640 
4641    Output Parameter:
4642 .  v - the diagonal of the matrix
4643 
4644    Level: intermediate
4645 
4646    Note:
4647    Currently only correct in parallel for square matrices.
4648 
4649    Concepts: matrices^accessing diagonals
4650 
4651 .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4652 @*/
4653 PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4654 {
4655   PetscErrorCode ierr;
4656 
4657   PetscFunctionBegin;
4658   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4659   PetscValidType(mat,1);
4660   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4661   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4662   if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4663   MatCheckPreallocated(mat,1);
4664 
4665   ierr = (*mat->ops->getdiagonal)(mat,v);CHKERRQ(ierr);
4666   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4667   PetscFunctionReturn(0);
4668 }
4669 
4670 /*@C
4671    MatGetRowMin - Gets the minimum value (of the real part) of each
4672         row of the matrix
4673 
4674    Logically Collective on Mat and Vec
4675 
4676    Input Parameters:
4677 .  mat - the matrix
4678 
4679    Output Parameter:
4680 +  v - the vector for storing the maximums
4681 -  idx - the indices of the column found for each row (optional)
4682 
4683    Level: intermediate
4684 
4685    Notes:
4686     The result of this call are the same as if one converted the matrix to dense format
4687       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4688 
4689     This code is only implemented for a couple of matrix formats.
4690 
4691    Concepts: matrices^getting row maximums
4692 
4693 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4694           MatGetRowMax()
4695 @*/
4696 PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4697 {
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   if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4706   MatCheckPreallocated(mat,1);
4707 
4708   ierr = (*mat->ops->getrowmin)(mat,v,idx);CHKERRQ(ierr);
4709   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4710   PetscFunctionReturn(0);
4711 }
4712 
4713 /*@C
4714    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4715         row of the matrix
4716 
4717    Logically Collective on Mat and Vec
4718 
4719    Input Parameters:
4720 .  mat - the matrix
4721 
4722    Output Parameter:
4723 +  v - the vector for storing the minimums
4724 -  idx - the indices of the column found for each row (or NULL if not needed)
4725 
4726    Level: intermediate
4727 
4728    Notes:
4729     if a row is completely empty or has only 0.0 values then the idx[] value for that
4730     row is 0 (the first column).
4731 
4732     This code is only implemented for a couple of matrix formats.
4733 
4734    Concepts: matrices^getting row maximums
4735 
4736 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4737 @*/
4738 PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4739 {
4740   PetscErrorCode ierr;
4741 
4742   PetscFunctionBegin;
4743   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4744   PetscValidType(mat,1);
4745   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4746   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4747   if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4748   MatCheckPreallocated(mat,1);
4749   if (idx) {ierr = PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));CHKERRQ(ierr);}
4750 
4751   ierr = (*mat->ops->getrowminabs)(mat,v,idx);CHKERRQ(ierr);
4752   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4753   PetscFunctionReturn(0);
4754 }
4755 
4756 /*@C
4757    MatGetRowMax - Gets the maximum value (of the real part) of each
4758         row of the matrix
4759 
4760    Logically Collective on Mat and Vec
4761 
4762    Input Parameters:
4763 .  mat - the matrix
4764 
4765    Output Parameter:
4766 +  v - the vector for storing the maximums
4767 -  idx - the indices of the column found for each row (optional)
4768 
4769    Level: intermediate
4770 
4771    Notes:
4772     The result of this call are the same as if one converted the matrix to dense format
4773       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4774 
4775     This code is only implemented for a couple of matrix formats.
4776 
4777    Concepts: matrices^getting row maximums
4778 
4779 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4780 @*/
4781 PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4782 {
4783   PetscErrorCode ierr;
4784 
4785   PetscFunctionBegin;
4786   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4787   PetscValidType(mat,1);
4788   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4789   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4790   if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4791   MatCheckPreallocated(mat,1);
4792 
4793   ierr = (*mat->ops->getrowmax)(mat,v,idx);CHKERRQ(ierr);
4794   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4795   PetscFunctionReturn(0);
4796 }
4797 
4798 /*@C
4799    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4800         row of the matrix
4801 
4802    Logically Collective on Mat and Vec
4803 
4804    Input Parameters:
4805 .  mat - the matrix
4806 
4807    Output Parameter:
4808 +  v - the vector for storing the maximums
4809 -  idx - the indices of the column found for each row (or NULL if not needed)
4810 
4811    Level: intermediate
4812 
4813    Notes:
4814     if a row is completely empty or has only 0.0 values then the idx[] value for that
4815     row is 0 (the first column).
4816 
4817     This code is only implemented for a couple of matrix formats.
4818 
4819    Concepts: matrices^getting row maximums
4820 
4821 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4822 @*/
4823 PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4824 {
4825   PetscErrorCode ierr;
4826 
4827   PetscFunctionBegin;
4828   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4829   PetscValidType(mat,1);
4830   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4831   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4832   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4833   MatCheckPreallocated(mat,1);
4834   if (idx) {ierr = PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));CHKERRQ(ierr);}
4835 
4836   ierr = (*mat->ops->getrowmaxabs)(mat,v,idx);CHKERRQ(ierr);
4837   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4838   PetscFunctionReturn(0);
4839 }
4840 
4841 /*@
4842    MatGetRowSum - Gets the sum of each row of the matrix
4843 
4844    Logically or Neighborhood Collective on Mat and Vec
4845 
4846    Input Parameters:
4847 .  mat - the matrix
4848 
4849    Output Parameter:
4850 .  v - the vector for storing the sum of rows
4851 
4852    Level: intermediate
4853 
4854    Notes:
4855     This code is slow since it is not currently specialized for different formats
4856 
4857    Concepts: matrices^getting row sums
4858 
4859 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4860 @*/
4861 PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4862 {
4863   Vec            ones;
4864   PetscErrorCode ierr;
4865 
4866   PetscFunctionBegin;
4867   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4868   PetscValidType(mat,1);
4869   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4870   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4871   MatCheckPreallocated(mat,1);
4872   ierr = MatCreateVecs(mat,&ones,NULL);CHKERRQ(ierr);
4873   ierr = VecSet(ones,1.);CHKERRQ(ierr);
4874   ierr = MatMult(mat,ones,v);CHKERRQ(ierr);
4875   ierr = VecDestroy(&ones);CHKERRQ(ierr);
4876   PetscFunctionReturn(0);
4877 }
4878 
4879 /*@
4880    MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4881 
4882    Collective on Mat
4883 
4884    Input Parameter:
4885 +  mat - the matrix to transpose
4886 -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
4887 
4888    Output Parameters:
4889 .  B - the transpose
4890 
4891    Notes:
4892      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
4893 
4894      MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
4895 
4896      Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4897 
4898    Level: intermediate
4899 
4900    Concepts: matrices^transposing
4901 
4902 .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4903 @*/
4904 PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4905 {
4906   PetscErrorCode ierr;
4907 
4908   PetscFunctionBegin;
4909   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4910   PetscValidType(mat,1);
4911   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4912   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4913   if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4914   if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4915   if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4916   MatCheckPreallocated(mat,1);
4917 
4918   ierr = PetscLogEventBegin(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4919   ierr = (*mat->ops->transpose)(mat,reuse,B);CHKERRQ(ierr);
4920   ierr = PetscLogEventEnd(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4921   if (B) {ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);}
4922   PetscFunctionReturn(0);
4923 }
4924 
4925 /*@
4926    MatIsTranspose - Test whether a matrix is another one's transpose,
4927         or its own, in which case it tests symmetry.
4928 
4929    Collective on Mat
4930 
4931    Input Parameter:
4932 +  A - the matrix to test
4933 -  B - the matrix to test against, this can equal the first parameter
4934 
4935    Output Parameters:
4936 .  flg - the result
4937 
4938    Notes:
4939    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4940    has a running time of the order of the number of nonzeros; the parallel
4941    test involves parallel copies of the block-offdiagonal parts of the matrix.
4942 
4943    Level: intermediate
4944 
4945    Concepts: matrices^transposing, matrix^symmetry
4946 
4947 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4948 @*/
4949 PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4950 {
4951   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4952 
4953   PetscFunctionBegin;
4954   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4955   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4956   PetscValidPointer(flg,3);
4957   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);CHKERRQ(ierr);
4958   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);CHKERRQ(ierr);
4959   *flg = PETSC_FALSE;
4960   if (f && g) {
4961     if (f == g) {
4962       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
4963     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4964   } else {
4965     MatType mattype;
4966     if (!f) {
4967       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
4968     } else {
4969       ierr = MatGetType(B,&mattype);CHKERRQ(ierr);
4970     }
4971     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4972   }
4973   PetscFunctionReturn(0);
4974 }
4975 
4976 /*@
4977    MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
4978 
4979    Collective on Mat
4980 
4981    Input Parameter:
4982 +  mat - the matrix to transpose and complex conjugate
4983 -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose
4984 
4985    Output Parameters:
4986 .  B - the Hermitian
4987 
4988    Level: intermediate
4989 
4990    Concepts: matrices^transposing, complex conjugatex
4991 
4992 .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4993 @*/
4994 PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4995 {
4996   PetscErrorCode ierr;
4997 
4998   PetscFunctionBegin;
4999   ierr = MatTranspose(mat,reuse,B);CHKERRQ(ierr);
5000 #if defined(PETSC_USE_COMPLEX)
5001   ierr = MatConjugate(*B);CHKERRQ(ierr);
5002 #endif
5003   PetscFunctionReturn(0);
5004 }
5005 
5006 /*@
5007    MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
5008 
5009    Collective on Mat
5010 
5011    Input Parameter:
5012 +  A - the matrix to test
5013 -  B - the matrix to test against, this can equal the first parameter
5014 
5015    Output Parameters:
5016 .  flg - the result
5017 
5018    Notes:
5019    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
5020    has a running time of the order of the number of nonzeros; the parallel
5021    test involves parallel copies of the block-offdiagonal parts of the matrix.
5022 
5023    Level: intermediate
5024 
5025    Concepts: matrices^transposing, matrix^symmetry
5026 
5027 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5028 @*/
5029 PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5030 {
5031   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
5032 
5033   PetscFunctionBegin;
5034   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
5035   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
5036   PetscValidPointer(flg,3);
5037   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);CHKERRQ(ierr);
5038   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);CHKERRQ(ierr);
5039   if (f && g) {
5040     if (f==g) {
5041       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
5042     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5043   }
5044   PetscFunctionReturn(0);
5045 }
5046 
5047 /*@
5048    MatPermute - Creates a new matrix with rows and columns permuted from the
5049    original.
5050 
5051    Collective on Mat
5052 
5053    Input Parameters:
5054 +  mat - the matrix to permute
5055 .  row - row permutation, each processor supplies only the permutation for its rows
5056 -  col - column permutation, each processor supplies only the permutation for its columns
5057 
5058    Output Parameters:
5059 .  B - the permuted matrix
5060 
5061    Level: advanced
5062 
5063    Note:
5064    The index sets map from row/col of permuted matrix to row/col of original matrix.
5065    The index sets should be on the same communicator as Mat and have the same local sizes.
5066 
5067    Concepts: matrices^permuting
5068 
5069 .seealso: MatGetOrdering(), ISAllGather()
5070 
5071 @*/
5072 PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5073 {
5074   PetscErrorCode ierr;
5075 
5076   PetscFunctionBegin;
5077   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5078   PetscValidType(mat,1);
5079   PetscValidHeaderSpecific(row,IS_CLASSID,2);
5080   PetscValidHeaderSpecific(col,IS_CLASSID,3);
5081   PetscValidPointer(B,4);
5082   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5083   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5084   if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
5085   MatCheckPreallocated(mat,1);
5086 
5087   ierr = (*mat->ops->permute)(mat,row,col,B);CHKERRQ(ierr);
5088   ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);
5089   PetscFunctionReturn(0);
5090 }
5091 
5092 /*@
5093    MatEqual - Compares two matrices.
5094 
5095    Collective on Mat
5096 
5097    Input Parameters:
5098 +  A - the first matrix
5099 -  B - the second matrix
5100 
5101    Output Parameter:
5102 .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
5103 
5104    Level: intermediate
5105 
5106    Concepts: matrices^equality between
5107 @*/
5108 PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5109 {
5110   PetscErrorCode ierr;
5111 
5112   PetscFunctionBegin;
5113   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
5114   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
5115   PetscValidType(A,1);
5116   PetscValidType(B,2);
5117   PetscValidIntPointer(flg,3);
5118   PetscCheckSameComm(A,1,B,2);
5119   MatCheckPreallocated(B,2);
5120   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5121   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5122   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);
5123   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5124   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5125   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);
5126   MatCheckPreallocated(A,1);
5127 
5128   ierr = (*A->ops->equal)(A,B,flg);CHKERRQ(ierr);
5129   PetscFunctionReturn(0);
5130 }
5131 
5132 /*@
5133    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5134    matrices that are stored as vectors.  Either of the two scaling
5135    matrices can be NULL.
5136 
5137    Collective on Mat
5138 
5139    Input Parameters:
5140 +  mat - the matrix to be scaled
5141 .  l - the left scaling vector (or NULL)
5142 -  r - the right scaling vector (or NULL)
5143 
5144    Notes:
5145    MatDiagonalScale() computes A = LAR, where
5146    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5147    The L scales the rows of the matrix, the R scales the columns of the matrix.
5148 
5149    Level: intermediate
5150 
5151    Concepts: matrices^diagonal scaling
5152    Concepts: diagonal scaling of matrices
5153 
5154 .seealso: MatScale(), MatShift(), MatDiagonalSet()
5155 @*/
5156 PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5157 {
5158   PetscErrorCode ierr;
5159 
5160   PetscFunctionBegin;
5161   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5162   PetscValidType(mat,1);
5163   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5164   if (l) {PetscValidHeaderSpecific(l,VEC_CLASSID,2);PetscCheckSameComm(mat,1,l,2);}
5165   if (r) {PetscValidHeaderSpecific(r,VEC_CLASSID,3);PetscCheckSameComm(mat,1,r,3);}
5166   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5167   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5168   MatCheckPreallocated(mat,1);
5169 
5170   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5171   ierr = (*mat->ops->diagonalscale)(mat,l,r);CHKERRQ(ierr);
5172   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5173   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5174 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5175   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5176     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5177   }
5178 #endif
5179   PetscFunctionReturn(0);
5180 }
5181 
5182 /*@
5183     MatScale - Scales all elements of a matrix by a given number.
5184 
5185     Logically Collective on Mat
5186 
5187     Input Parameters:
5188 +   mat - the matrix to be scaled
5189 -   a  - the scaling value
5190 
5191     Output Parameter:
5192 .   mat - the scaled matrix
5193 
5194     Level: intermediate
5195 
5196     Concepts: matrices^scaling all entries
5197 
5198 .seealso: MatDiagonalScale()
5199 @*/
5200 PetscErrorCode MatScale(Mat mat,PetscScalar a)
5201 {
5202   PetscErrorCode ierr;
5203 
5204   PetscFunctionBegin;
5205   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5206   PetscValidType(mat,1);
5207   if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5208   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5209   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5210   PetscValidLogicalCollectiveScalar(mat,a,2);
5211   MatCheckPreallocated(mat,1);
5212 
5213   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5214   if (a != (PetscScalar)1.0) {
5215     ierr = (*mat->ops->scale)(mat,a);CHKERRQ(ierr);
5216     ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5217 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5218     if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5219       mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5220     }
5221 #endif
5222   }
5223   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5224   PetscFunctionReturn(0);
5225 }
5226 
5227 /*@
5228    MatNorm - Calculates various norms of a matrix.
5229 
5230    Collective on Mat
5231 
5232    Input Parameters:
5233 +  mat - the matrix
5234 -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5235 
5236    Output Parameters:
5237 .  nrm - the resulting norm
5238 
5239    Level: intermediate
5240 
5241    Concepts: matrices^norm
5242    Concepts: norm^of matrix
5243 @*/
5244 PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5245 {
5246   PetscErrorCode ierr;
5247 
5248   PetscFunctionBegin;
5249   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5250   PetscValidType(mat,1);
5251   PetscValidScalarPointer(nrm,3);
5252 
5253   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5254   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5255   if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5256   MatCheckPreallocated(mat,1);
5257 
5258   ierr = (*mat->ops->norm)(mat,type,nrm);CHKERRQ(ierr);
5259   PetscFunctionReturn(0);
5260 }
5261 
5262 /*
5263      This variable is used to prevent counting of MatAssemblyBegin() that
5264    are called from within a MatAssemblyEnd().
5265 */
5266 static PetscInt MatAssemblyEnd_InUse = 0;
5267 /*@
5268    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5269    be called after completing all calls to MatSetValues().
5270 
5271    Collective on Mat
5272 
5273    Input Parameters:
5274 +  mat - the matrix
5275 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5276 
5277    Notes:
5278    MatSetValues() generally caches the values.  The matrix is ready to
5279    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5280    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5281    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5282    using the matrix.
5283 
5284    ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5285    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
5286    a global collective operation requring all processes that share the matrix.
5287 
5288    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5289    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5290    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5291 
5292    Level: beginner
5293 
5294    Concepts: matrices^assembling
5295 
5296 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5297 @*/
5298 PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5299 {
5300   PetscErrorCode ierr;
5301 
5302   PetscFunctionBegin;
5303   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5304   PetscValidType(mat,1);
5305   MatCheckPreallocated(mat,1);
5306   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5307   if (mat->assembled) {
5308     mat->was_assembled = PETSC_TRUE;
5309     mat->assembled     = PETSC_FALSE;
5310   }
5311   if (!MatAssemblyEnd_InUse) {
5312     ierr = PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5313     if (mat->ops->assemblybegin) {ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);}
5314     ierr = PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5315   } else if (mat->ops->assemblybegin) {
5316     ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);
5317   }
5318   PetscFunctionReturn(0);
5319 }
5320 
5321 /*@
5322    MatAssembled - Indicates if a matrix has been assembled and is ready for
5323      use; for example, in matrix-vector product.
5324 
5325    Not Collective
5326 
5327    Input Parameter:
5328 .  mat - the matrix
5329 
5330    Output Parameter:
5331 .  assembled - PETSC_TRUE or PETSC_FALSE
5332 
5333    Level: advanced
5334 
5335    Concepts: matrices^assembled?
5336 
5337 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5338 @*/
5339 PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5340 {
5341   PetscFunctionBegin;
5342   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5343   PetscValidType(mat,1);
5344   PetscValidPointer(assembled,2);
5345   *assembled = mat->assembled;
5346   PetscFunctionReturn(0);
5347 }
5348 
5349 /*@
5350    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5351    be called after MatAssemblyBegin().
5352 
5353    Collective on Mat
5354 
5355    Input Parameters:
5356 +  mat - the matrix
5357 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5358 
5359    Options Database Keys:
5360 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5361 .  -mat_view ::ascii_info_detail - Prints more detailed info
5362 .  -mat_view - Prints matrix in ASCII format
5363 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5364 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5365 .  -display <name> - Sets display name (default is host)
5366 .  -draw_pause <sec> - Sets number of seconds to pause after display
5367 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab )
5368 .  -viewer_socket_machine <machine> - Machine to use for socket
5369 .  -viewer_socket_port <port> - Port number to use for socket
5370 -  -mat_view binary:filename[:append] - Save matrix to file in binary format
5371 
5372    Notes:
5373    MatSetValues() generally caches the values.  The matrix is ready to
5374    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5375    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5376    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5377    using the matrix.
5378 
5379    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5380    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5381    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5382 
5383    Level: beginner
5384 
5385 .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5386 @*/
5387 PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5388 {
5389   PetscErrorCode  ierr;
5390   static PetscInt inassm = 0;
5391   PetscBool       flg    = PETSC_FALSE;
5392 
5393   PetscFunctionBegin;
5394   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5395   PetscValidType(mat,1);
5396 
5397   inassm++;
5398   MatAssemblyEnd_InUse++;
5399   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5400     ierr = PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5401     if (mat->ops->assemblyend) {
5402       ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5403     }
5404     ierr = PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5405   } else if (mat->ops->assemblyend) {
5406     ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5407   }
5408 
5409   /* Flush assembly is not a true assembly */
5410   if (type != MAT_FLUSH_ASSEMBLY) {
5411     mat->assembled = PETSC_TRUE; mat->num_ass++;
5412   }
5413   mat->insertmode = NOT_SET_VALUES;
5414   MatAssemblyEnd_InUse--;
5415   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5416   if (!mat->symmetric_eternal) {
5417     mat->symmetric_set              = PETSC_FALSE;
5418     mat->hermitian_set              = PETSC_FALSE;
5419     mat->structurally_symmetric_set = PETSC_FALSE;
5420   }
5421 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5422   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5423     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5424   }
5425 #endif
5426   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5427     ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5428 
5429     if (mat->checksymmetryonassembly) {
5430       ierr = MatIsSymmetric(mat,mat->checksymmetrytol,&flg);CHKERRQ(ierr);
5431       if (flg) {
5432         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5433       } else {
5434         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5435       }
5436     }
5437     if (mat->nullsp && mat->checknullspaceonassembly) {
5438       ierr = MatNullSpaceTest(mat->nullsp,mat,NULL);CHKERRQ(ierr);
5439     }
5440   }
5441   inassm--;
5442   PetscFunctionReturn(0);
5443 }
5444 
5445 /*@
5446    MatSetOption - Sets a parameter option for a matrix. Some options
5447    may be specific to certain storage formats.  Some options
5448    determine how values will be inserted (or added). Sorted,
5449    row-oriented input will generally assemble the fastest. The default
5450    is row-oriented.
5451 
5452    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5453 
5454    Input Parameters:
5455 +  mat - the matrix
5456 .  option - the option, one of those listed below (and possibly others),
5457 -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5458 
5459   Options Describing Matrix Structure:
5460 +    MAT_SPD - symmetric positive definite
5461 .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5462 .    MAT_HERMITIAN - transpose is the complex conjugation
5463 .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5464 -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5465                             you set to be kept with all future use of the matrix
5466                             including after MatAssemblyBegin/End() which could
5467                             potentially change the symmetry structure, i.e. you
5468                             KNOW the matrix will ALWAYS have the property you set.
5469 
5470 
5471    Options For Use with MatSetValues():
5472    Insert a logically dense subblock, which can be
5473 .    MAT_ROW_ORIENTED - row-oriented (default)
5474 
5475    Note these options reflect the data you pass in with MatSetValues(); it has
5476    nothing to do with how the data is stored internally in the matrix
5477    data structure.
5478 
5479    When (re)assembling a matrix, we can restrict the input for
5480    efficiency/debugging purposes.  These options include:
5481 +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5482 .    MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5483 .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5484 .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5485 .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5486 .    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5487         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5488         performance for very large process counts.
5489 -    MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5490         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5491         functions, instead sending only neighbor messages.
5492 
5493    Notes:
5494    Except for MAT_UNUSED_NONZERO_LOCATION_ERR and  MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5495 
5496    Some options are relevant only for particular matrix types and
5497    are thus ignored by others.  Other options are not supported by
5498    certain matrix types and will generate an error message if set.
5499 
5500    If using a Fortran 77 module to compute a matrix, one may need to
5501    use the column-oriented option (or convert to the row-oriented
5502    format).
5503 
5504    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5505    that would generate a new entry in the nonzero structure is instead
5506    ignored.  Thus, if memory has not alredy been allocated for this particular
5507    data, then the insertion is ignored. For dense matrices, in which
5508    the entire array is allocated, no entries are ever ignored.
5509    Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5510 
5511    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5512    that would generate a new entry in the nonzero structure instead produces
5513    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
5514 
5515    MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5516    that would generate a new entry that has not been preallocated will
5517    instead produce an error. (Currently supported for AIJ and BAIJ formats
5518    only.) This is a useful flag when debugging matrix memory preallocation.
5519    If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5520 
5521    MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5522    other processors should be dropped, rather than stashed.
5523    This is useful if you know that the "owning" processor is also
5524    always generating the correct matrix entries, so that PETSc need
5525    not transfer duplicate entries generated on another processor.
5526 
5527    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5528    searches during matrix assembly. When this flag is set, the hash table
5529    is created during the first Matrix Assembly. This hash table is
5530    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5531    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5532    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5533    supported by MATMPIBAIJ format only.
5534 
5535    MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5536    are kept in the nonzero structure
5537 
5538    MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5539    a zero location in the matrix
5540 
5541    MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5542 
5543    MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5544         zero row routines and thus improves performance for very large process counts.
5545 
5546    MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5547         part of the matrix (since they should match the upper triangular part).
5548 
5549    Notes:
5550     Can only be called after MatSetSizes() and MatSetType() have been set.
5551 
5552    Level: intermediate
5553 
5554    Concepts: matrices^setting options
5555 
5556 .seealso:  MatOption, Mat
5557 
5558 @*/
5559 PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5560 {
5561   PetscErrorCode ierr;
5562 
5563   PetscFunctionBegin;
5564   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5565   PetscValidType(mat,1);
5566   if (op > 0) {
5567     PetscValidLogicalCollectiveEnum(mat,op,2);
5568     PetscValidLogicalCollectiveBool(mat,flg,3);
5569   }
5570 
5571   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);
5572   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()");
5573 
5574   switch (op) {
5575   case MAT_NO_OFF_PROC_ENTRIES:
5576     mat->nooffprocentries = flg;
5577     PetscFunctionReturn(0);
5578     break;
5579   case MAT_SUBSET_OFF_PROC_ENTRIES:
5580     mat->subsetoffprocentries = flg;
5581     PetscFunctionReturn(0);
5582   case MAT_NO_OFF_PROC_ZERO_ROWS:
5583     mat->nooffproczerorows = flg;
5584     PetscFunctionReturn(0);
5585     break;
5586   case MAT_SPD:
5587     mat->spd_set = PETSC_TRUE;
5588     mat->spd     = flg;
5589     if (flg) {
5590       mat->symmetric                  = PETSC_TRUE;
5591       mat->structurally_symmetric     = PETSC_TRUE;
5592       mat->symmetric_set              = PETSC_TRUE;
5593       mat->structurally_symmetric_set = PETSC_TRUE;
5594     }
5595     break;
5596   case MAT_SYMMETRIC:
5597     mat->symmetric = flg;
5598     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5599     mat->symmetric_set              = PETSC_TRUE;
5600     mat->structurally_symmetric_set = flg;
5601 #if !defined(PETSC_USE_COMPLEX)
5602     mat->hermitian     = flg;
5603     mat->hermitian_set = PETSC_TRUE;
5604 #endif
5605     break;
5606   case MAT_HERMITIAN:
5607     mat->hermitian = flg;
5608     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5609     mat->hermitian_set              = PETSC_TRUE;
5610     mat->structurally_symmetric_set = flg;
5611 #if !defined(PETSC_USE_COMPLEX)
5612     mat->symmetric     = flg;
5613     mat->symmetric_set = PETSC_TRUE;
5614 #endif
5615     break;
5616   case MAT_STRUCTURALLY_SYMMETRIC:
5617     mat->structurally_symmetric     = flg;
5618     mat->structurally_symmetric_set = PETSC_TRUE;
5619     break;
5620   case MAT_SYMMETRY_ETERNAL:
5621     mat->symmetric_eternal = flg;
5622     break;
5623   case MAT_STRUCTURE_ONLY:
5624     mat->structure_only = flg;
5625     break;
5626   default:
5627     break;
5628   }
5629   if (mat->ops->setoption) {
5630     ierr = (*mat->ops->setoption)(mat,op,flg);CHKERRQ(ierr);
5631   }
5632   PetscFunctionReturn(0);
5633 }
5634 
5635 /*@
5636    MatGetOption - Gets a parameter option that has been set for a matrix.
5637 
5638    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5639 
5640    Input Parameters:
5641 +  mat - the matrix
5642 -  option - the option, this only responds to certain options, check the code for which ones
5643 
5644    Output Parameter:
5645 .  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5646 
5647     Notes:
5648     Can only be called after MatSetSizes() and MatSetType() have been set.
5649 
5650    Level: intermediate
5651 
5652    Concepts: matrices^setting options
5653 
5654 .seealso:  MatOption, MatSetOption()
5655 
5656 @*/
5657 PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5658 {
5659   PetscFunctionBegin;
5660   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5661   PetscValidType(mat,1);
5662 
5663   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);
5664   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()");
5665 
5666   switch (op) {
5667   case MAT_NO_OFF_PROC_ENTRIES:
5668     *flg = mat->nooffprocentries;
5669     break;
5670   case MAT_NO_OFF_PROC_ZERO_ROWS:
5671     *flg = mat->nooffproczerorows;
5672     break;
5673   case MAT_SYMMETRIC:
5674     *flg = mat->symmetric;
5675     break;
5676   case MAT_HERMITIAN:
5677     *flg = mat->hermitian;
5678     break;
5679   case MAT_STRUCTURALLY_SYMMETRIC:
5680     *flg = mat->structurally_symmetric;
5681     break;
5682   case MAT_SYMMETRY_ETERNAL:
5683     *flg = mat->symmetric_eternal;
5684     break;
5685   case MAT_SPD:
5686     *flg = mat->spd;
5687     break;
5688   default:
5689     break;
5690   }
5691   PetscFunctionReturn(0);
5692 }
5693 
5694 /*@
5695    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5696    this routine retains the old nonzero structure.
5697 
5698    Logically Collective on Mat
5699 
5700    Input Parameters:
5701 .  mat - the matrix
5702 
5703    Level: intermediate
5704 
5705    Notes:
5706     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.
5707    See the Performance chapter of the users manual for information on preallocating matrices.
5708 
5709    Concepts: matrices^zeroing
5710 
5711 .seealso: MatZeroRows()
5712 @*/
5713 PetscErrorCode MatZeroEntries(Mat mat)
5714 {
5715   PetscErrorCode ierr;
5716 
5717   PetscFunctionBegin;
5718   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5719   PetscValidType(mat,1);
5720   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5721   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");
5722   if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5723   MatCheckPreallocated(mat,1);
5724 
5725   ierr = PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5726   ierr = (*mat->ops->zeroentries)(mat);CHKERRQ(ierr);
5727   ierr = PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5728   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5729 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5730   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5731     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5732   }
5733 #endif
5734   PetscFunctionReturn(0);
5735 }
5736 
5737 /*@
5738    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5739    of a set of rows and columns of a matrix.
5740 
5741    Collective on Mat
5742 
5743    Input Parameters:
5744 +  mat - the matrix
5745 .  numRows - the number of rows to remove
5746 .  rows - the global row indices
5747 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5748 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5749 -  b - optional vector of right hand side, that will be adjusted by provided solution
5750 
5751    Notes:
5752    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5753 
5754    The user can set a value in the diagonal entry (or for the AIJ and
5755    row formats can optionally remove the main diagonal entry from the
5756    nonzero structure as well, by passing 0.0 as the final argument).
5757 
5758    For the parallel case, all processes that share the matrix (i.e.,
5759    those in the communicator used for matrix creation) MUST call this
5760    routine, regardless of whether any rows being zeroed are owned by
5761    them.
5762 
5763    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5764    list only rows local to itself).
5765 
5766    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5767 
5768    Level: intermediate
5769 
5770    Concepts: matrices^zeroing rows
5771 
5772 .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5773           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5774 @*/
5775 PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5776 {
5777   PetscErrorCode ierr;
5778 
5779   PetscFunctionBegin;
5780   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5781   PetscValidType(mat,1);
5782   if (numRows) PetscValidIntPointer(rows,3);
5783   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5784   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5785   if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5786   MatCheckPreallocated(mat,1);
5787 
5788   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5789   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5790   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5791 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5792   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5793     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5794   }
5795 #endif
5796   PetscFunctionReturn(0);
5797 }
5798 
5799 /*@
5800    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5801    of a set of rows and columns of a matrix.
5802 
5803    Collective on Mat
5804 
5805    Input Parameters:
5806 +  mat - the matrix
5807 .  is - the rows to zero
5808 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5809 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5810 -  b - optional vector of right hand side, that will be adjusted by provided solution
5811 
5812    Notes:
5813    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5814 
5815    The user can set a value in the diagonal entry (or for the AIJ and
5816    row formats can optionally remove the main diagonal entry from the
5817    nonzero structure as well, by passing 0.0 as the final argument).
5818 
5819    For the parallel case, all processes that share the matrix (i.e.,
5820    those in the communicator used for matrix creation) MUST call this
5821    routine, regardless of whether any rows being zeroed are owned by
5822    them.
5823 
5824    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5825    list only rows local to itself).
5826 
5827    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5828 
5829    Level: intermediate
5830 
5831    Concepts: matrices^zeroing rows
5832 
5833 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5834           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5835 @*/
5836 PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5837 {
5838   PetscErrorCode ierr;
5839   PetscInt       numRows;
5840   const PetscInt *rows;
5841 
5842   PetscFunctionBegin;
5843   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5844   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5845   PetscValidType(mat,1);
5846   PetscValidType(is,2);
5847   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5848   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5849   ierr = MatZeroRowsColumns(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5850   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5851   PetscFunctionReturn(0);
5852 }
5853 
5854 /*@
5855    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5856    of a set of rows of a matrix.
5857 
5858    Collective on Mat
5859 
5860    Input Parameters:
5861 +  mat - the matrix
5862 .  numRows - the number of rows to remove
5863 .  rows - the global row indices
5864 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5865 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5866 -  b - optional vector of right hand side, that will be adjusted by provided solution
5867 
5868    Notes:
5869    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5870    but does not release memory.  For the dense and block diagonal
5871    formats this does not alter the nonzero structure.
5872 
5873    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5874    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5875    merely zeroed.
5876 
5877    The user can set a value in the diagonal entry (or for the AIJ and
5878    row formats can optionally remove the main diagonal entry from the
5879    nonzero structure as well, by passing 0.0 as the final argument).
5880 
5881    For the parallel case, all processes that share the matrix (i.e.,
5882    those in the communicator used for matrix creation) MUST call this
5883    routine, regardless of whether any rows being zeroed are owned by
5884    them.
5885 
5886    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5887    list only rows local to itself).
5888 
5889    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5890    owns that are to be zeroed. This saves a global synchronization in the implementation.
5891 
5892    Level: intermediate
5893 
5894    Concepts: matrices^zeroing rows
5895 
5896 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5897           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5898 @*/
5899 PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5900 {
5901   PetscErrorCode ierr;
5902 
5903   PetscFunctionBegin;
5904   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5905   PetscValidType(mat,1);
5906   if (numRows) PetscValidIntPointer(rows,3);
5907   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5908   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5909   if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5910   MatCheckPreallocated(mat,1);
5911 
5912   ierr = (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5913   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5914   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5915 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5916   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5917     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5918   }
5919 #endif
5920   PetscFunctionReturn(0);
5921 }
5922 
5923 /*@
5924    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5925    of a set of rows of a matrix.
5926 
5927    Collective on Mat
5928 
5929    Input Parameters:
5930 +  mat - the matrix
5931 .  is - index set of rows to remove
5932 .  diag - value put in all diagonals of eliminated rows
5933 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5934 -  b - optional vector of right hand side, that will be adjusted by provided solution
5935 
5936    Notes:
5937    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5938    but does not release memory.  For the dense and block diagonal
5939    formats this does not alter the nonzero structure.
5940 
5941    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5942    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5943    merely zeroed.
5944 
5945    The user can set a value in the diagonal entry (or for the AIJ and
5946    row formats can optionally remove the main diagonal entry from the
5947    nonzero structure as well, by passing 0.0 as the final argument).
5948 
5949    For the parallel case, all processes that share the matrix (i.e.,
5950    those in the communicator used for matrix creation) MUST call this
5951    routine, regardless of whether any rows being zeroed are owned by
5952    them.
5953 
5954    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5955    list only rows local to itself).
5956 
5957    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5958    owns that are to be zeroed. This saves a global synchronization in the implementation.
5959 
5960    Level: intermediate
5961 
5962    Concepts: matrices^zeroing rows
5963 
5964 .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5965           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5966 @*/
5967 PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5968 {
5969   PetscInt       numRows;
5970   const PetscInt *rows;
5971   PetscErrorCode ierr;
5972 
5973   PetscFunctionBegin;
5974   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5975   PetscValidType(mat,1);
5976   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5977   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5978   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5979   ierr = MatZeroRows(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5980   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5981   PetscFunctionReturn(0);
5982 }
5983 
5984 /*@
5985    MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5986    of a set of rows of a matrix. These rows must be local to the process.
5987 
5988    Collective on Mat
5989 
5990    Input Parameters:
5991 +  mat - the matrix
5992 .  numRows - the number of rows to remove
5993 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5994 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5995 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5996 -  b - optional vector of right hand side, that will be adjusted by provided solution
5997 
5998    Notes:
5999    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6000    but does not release memory.  For the dense and block diagonal
6001    formats this does not alter the nonzero structure.
6002 
6003    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6004    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6005    merely zeroed.
6006 
6007    The user can set a value in the diagonal entry (or for the AIJ and
6008    row formats can optionally remove the main diagonal entry from the
6009    nonzero structure as well, by passing 0.0 as the final argument).
6010 
6011    For the parallel case, all processes that share the matrix (i.e.,
6012    those in the communicator used for matrix creation) MUST call this
6013    routine, regardless of whether any rows being zeroed are owned by
6014    them.
6015 
6016    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6017    list only rows local to itself).
6018 
6019    The grid coordinates are across the entire grid, not just the local portion
6020 
6021    In Fortran idxm and idxn should be declared as
6022 $     MatStencil idxm(4,m)
6023    and the values inserted using
6024 $    idxm(MatStencil_i,1) = i
6025 $    idxm(MatStencil_j,1) = j
6026 $    idxm(MatStencil_k,1) = k
6027 $    idxm(MatStencil_c,1) = c
6028    etc
6029 
6030    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6031    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6032    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6033    DM_BOUNDARY_PERIODIC boundary type.
6034 
6035    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
6036    a single value per point) you can skip filling those indices.
6037 
6038    Level: intermediate
6039 
6040    Concepts: matrices^zeroing rows
6041 
6042 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6043           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6044 @*/
6045 PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6046 {
6047   PetscInt       dim     = mat->stencil.dim;
6048   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6049   PetscInt       *dims   = mat->stencil.dims+1;
6050   PetscInt       *starts = mat->stencil.starts;
6051   PetscInt       *dxm    = (PetscInt*) rows;
6052   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
6053   PetscErrorCode ierr;
6054 
6055   PetscFunctionBegin;
6056   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6057   PetscValidType(mat,1);
6058   if (numRows) PetscValidIntPointer(rows,3);
6059 
6060   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
6061   for (i = 0; i < numRows; ++i) {
6062     /* Skip unused dimensions (they are ordered k, j, i, c) */
6063     for (j = 0; j < 3-sdim; ++j) dxm++;
6064     /* Local index in X dir */
6065     tmp = *dxm++ - starts[0];
6066     /* Loop over remaining dimensions */
6067     for (j = 0; j < dim-1; ++j) {
6068       /* If nonlocal, set index to be negative */
6069       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6070       /* Update local index */
6071       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6072     }
6073     /* Skip component slot if necessary */
6074     if (mat->stencil.noc) dxm++;
6075     /* Local row number */
6076     if (tmp >= 0) {
6077       jdxm[numNewRows++] = tmp;
6078     }
6079   }
6080   ierr = MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
6081   ierr = PetscFree(jdxm);CHKERRQ(ierr);
6082   PetscFunctionReturn(0);
6083 }
6084 
6085 /*@
6086    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6087    of a set of rows and columns of a matrix.
6088 
6089    Collective on Mat
6090 
6091    Input Parameters:
6092 +  mat - the matrix
6093 .  numRows - the number of rows/columns to remove
6094 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
6095 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6096 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6097 -  b - optional vector of right hand side, that will be adjusted by provided solution
6098 
6099    Notes:
6100    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6101    but does not release memory.  For the dense and block diagonal
6102    formats this does not alter the nonzero structure.
6103 
6104    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6105    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6106    merely zeroed.
6107 
6108    The user can set a value in the diagonal entry (or for the AIJ and
6109    row formats can optionally remove the main diagonal entry from the
6110    nonzero structure as well, by passing 0.0 as the final argument).
6111 
6112    For the parallel case, all processes that share the matrix (i.e.,
6113    those in the communicator used for matrix creation) MUST call this
6114    routine, regardless of whether any rows being zeroed are owned by
6115    them.
6116 
6117    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6118    list only rows local to itself, but the row/column numbers are given in local numbering).
6119 
6120    The grid coordinates are across the entire grid, not just the local portion
6121 
6122    In Fortran idxm and idxn should be declared as
6123 $     MatStencil idxm(4,m)
6124    and the values inserted using
6125 $    idxm(MatStencil_i,1) = i
6126 $    idxm(MatStencil_j,1) = j
6127 $    idxm(MatStencil_k,1) = k
6128 $    idxm(MatStencil_c,1) = c
6129    etc
6130 
6131    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6132    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6133    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6134    DM_BOUNDARY_PERIODIC boundary type.
6135 
6136    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
6137    a single value per point) you can skip filling those indices.
6138 
6139    Level: intermediate
6140 
6141    Concepts: matrices^zeroing rows
6142 
6143 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6144           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6145 @*/
6146 PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6147 {
6148   PetscInt       dim     = mat->stencil.dim;
6149   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6150   PetscInt       *dims   = mat->stencil.dims+1;
6151   PetscInt       *starts = mat->stencil.starts;
6152   PetscInt       *dxm    = (PetscInt*) rows;
6153   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
6154   PetscErrorCode ierr;
6155 
6156   PetscFunctionBegin;
6157   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6158   PetscValidType(mat,1);
6159   if (numRows) PetscValidIntPointer(rows,3);
6160 
6161   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
6162   for (i = 0; i < numRows; ++i) {
6163     /* Skip unused dimensions (they are ordered k, j, i, c) */
6164     for (j = 0; j < 3-sdim; ++j) dxm++;
6165     /* Local index in X dir */
6166     tmp = *dxm++ - starts[0];
6167     /* Loop over remaining dimensions */
6168     for (j = 0; j < dim-1; ++j) {
6169       /* If nonlocal, set index to be negative */
6170       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6171       /* Update local index */
6172       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6173     }
6174     /* Skip component slot if necessary */
6175     if (mat->stencil.noc) dxm++;
6176     /* Local row number */
6177     if (tmp >= 0) {
6178       jdxm[numNewRows++] = tmp;
6179     }
6180   }
6181   ierr = MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
6182   ierr = PetscFree(jdxm);CHKERRQ(ierr);
6183   PetscFunctionReturn(0);
6184 }
6185 
6186 /*@C
6187    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6188    of a set of rows of a matrix; using local numbering of rows.
6189 
6190    Collective on Mat
6191 
6192    Input Parameters:
6193 +  mat - the matrix
6194 .  numRows - the number of rows to remove
6195 .  rows - the global row indices
6196 .  diag - value put in all diagonals of eliminated rows
6197 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6198 -  b - optional vector of right hand side, that will be adjusted by provided solution
6199 
6200    Notes:
6201    Before calling MatZeroRowsLocal(), the user must first set the
6202    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6203 
6204    For the AIJ matrix formats this removes the old nonzero structure,
6205    but does not release memory.  For the dense and block diagonal
6206    formats this does not alter the nonzero structure.
6207 
6208    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6209    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6210    merely zeroed.
6211 
6212    The user can set a value in the diagonal entry (or for the AIJ and
6213    row formats can optionally remove the main diagonal entry from the
6214    nonzero structure as well, by passing 0.0 as the final argument).
6215 
6216    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6217    owns that are to be zeroed. This saves a global synchronization in the implementation.
6218 
6219    Level: intermediate
6220 
6221    Concepts: matrices^zeroing
6222 
6223 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6224           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6225 @*/
6226 PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6227 {
6228   PetscErrorCode ierr;
6229 
6230   PetscFunctionBegin;
6231   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6232   PetscValidType(mat,1);
6233   if (numRows) PetscValidIntPointer(rows,3);
6234   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6235   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6236   MatCheckPreallocated(mat,1);
6237 
6238   if (mat->ops->zerorowslocal) {
6239     ierr = (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6240   } else {
6241     IS             is, newis;
6242     const PetscInt *newRows;
6243 
6244     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6245     ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6246     ierr = ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);CHKERRQ(ierr);
6247     ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6248     ierr = (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6249     ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6250     ierr = ISDestroy(&newis);CHKERRQ(ierr);
6251     ierr = ISDestroy(&is);CHKERRQ(ierr);
6252   }
6253   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6254 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6255   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6256     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6257   }
6258 #endif
6259   PetscFunctionReturn(0);
6260 }
6261 
6262 /*@
6263    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6264    of a set of rows of a matrix; using local numbering of rows.
6265 
6266    Collective on Mat
6267 
6268    Input Parameters:
6269 +  mat - the matrix
6270 .  is - index set of rows to remove
6271 .  diag - value put in all diagonals of eliminated rows
6272 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6273 -  b - optional vector of right hand side, that will be adjusted by provided solution
6274 
6275    Notes:
6276    Before calling MatZeroRowsLocalIS(), the user must first set the
6277    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6278 
6279    For the AIJ matrix formats this removes the old nonzero structure,
6280    but does not release memory.  For the dense and block diagonal
6281    formats this does not alter the nonzero structure.
6282 
6283    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6284    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6285    merely zeroed.
6286 
6287    The user can set a value in the diagonal entry (or for the AIJ and
6288    row formats can optionally remove the main diagonal entry from the
6289    nonzero structure as well, by passing 0.0 as the final argument).
6290 
6291    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6292    owns that are to be zeroed. This saves a global synchronization in the implementation.
6293 
6294    Level: intermediate
6295 
6296    Concepts: matrices^zeroing
6297 
6298 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6299           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6300 @*/
6301 PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6302 {
6303   PetscErrorCode ierr;
6304   PetscInt       numRows;
6305   const PetscInt *rows;
6306 
6307   PetscFunctionBegin;
6308   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6309   PetscValidType(mat,1);
6310   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6311   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6312   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6313   MatCheckPreallocated(mat,1);
6314 
6315   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6316   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6317   ierr = MatZeroRowsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6318   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6319   PetscFunctionReturn(0);
6320 }
6321 
6322 /*@
6323    MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6324    of a set of rows and columns of a matrix; using local numbering of rows.
6325 
6326    Collective on Mat
6327 
6328    Input Parameters:
6329 +  mat - the matrix
6330 .  numRows - the number of rows to remove
6331 .  rows - the global row indices
6332 .  diag - value put in all diagonals of eliminated rows
6333 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6334 -  b - optional vector of right hand side, that will be adjusted by provided solution
6335 
6336    Notes:
6337    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6338    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6339 
6340    The user can set a value in the diagonal entry (or for the AIJ and
6341    row formats can optionally remove the main diagonal entry from the
6342    nonzero structure as well, by passing 0.0 as the final argument).
6343 
6344    Level: intermediate
6345 
6346    Concepts: matrices^zeroing
6347 
6348 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6349           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6350 @*/
6351 PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6352 {
6353   PetscErrorCode ierr;
6354   IS             is, newis;
6355   const PetscInt *newRows;
6356 
6357   PetscFunctionBegin;
6358   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6359   PetscValidType(mat,1);
6360   if (numRows) PetscValidIntPointer(rows,3);
6361   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6362   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6363   MatCheckPreallocated(mat,1);
6364 
6365   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6366   ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6367   ierr = ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);CHKERRQ(ierr);
6368   ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6369   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6370   ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6371   ierr = ISDestroy(&newis);CHKERRQ(ierr);
6372   ierr = ISDestroy(&is);CHKERRQ(ierr);
6373   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6374 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6375   if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6376     mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6377   }
6378 #endif
6379   PetscFunctionReturn(0);
6380 }
6381 
6382 /*@
6383    MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6384    of a set of rows and columns of a matrix; using local numbering of rows.
6385 
6386    Collective on Mat
6387 
6388    Input Parameters:
6389 +  mat - the matrix
6390 .  is - index set of rows to remove
6391 .  diag - value put in all diagonals of eliminated rows
6392 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6393 -  b - optional vector of right hand side, that will be adjusted by provided solution
6394 
6395    Notes:
6396    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6397    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6398 
6399    The user can set a value in the diagonal entry (or for the AIJ and
6400    row formats can optionally remove the main diagonal entry from the
6401    nonzero structure as well, by passing 0.0 as the final argument).
6402 
6403    Level: intermediate
6404 
6405    Concepts: matrices^zeroing
6406 
6407 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6408           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6409 @*/
6410 PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6411 {
6412   PetscErrorCode ierr;
6413   PetscInt       numRows;
6414   const PetscInt *rows;
6415 
6416   PetscFunctionBegin;
6417   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6418   PetscValidType(mat,1);
6419   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6420   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6421   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6422   MatCheckPreallocated(mat,1);
6423 
6424   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6425   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6426   ierr = MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6427   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6428   PetscFunctionReturn(0);
6429 }
6430 
6431 /*@C
6432    MatGetSize - Returns the numbers of rows and columns in a matrix.
6433 
6434    Not Collective
6435 
6436    Input Parameter:
6437 .  mat - the matrix
6438 
6439    Output Parameters:
6440 +  m - the number of global rows
6441 -  n - the number of global columns
6442 
6443    Note: both output parameters can be NULL on input.
6444 
6445    Level: beginner
6446 
6447    Concepts: matrices^size
6448 
6449 .seealso: MatGetLocalSize()
6450 @*/
6451 PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6452 {
6453   PetscFunctionBegin;
6454   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6455   if (m) *m = mat->rmap->N;
6456   if (n) *n = mat->cmap->N;
6457   PetscFunctionReturn(0);
6458 }
6459 
6460 /*@C
6461    MatGetLocalSize - Returns the number of rows and columns in a matrix
6462    stored locally.  This information may be implementation dependent, so
6463    use with care.
6464 
6465    Not Collective
6466 
6467    Input Parameters:
6468 .  mat - the matrix
6469 
6470    Output Parameters:
6471 +  m - the number of local rows
6472 -  n - the number of local columns
6473 
6474    Note: both output parameters can be NULL on input.
6475 
6476    Level: beginner
6477 
6478    Concepts: matrices^local size
6479 
6480 .seealso: MatGetSize()
6481 @*/
6482 PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6483 {
6484   PetscFunctionBegin;
6485   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6486   if (m) PetscValidIntPointer(m,2);
6487   if (n) PetscValidIntPointer(n,3);
6488   if (m) *m = mat->rmap->n;
6489   if (n) *n = mat->cmap->n;
6490   PetscFunctionReturn(0);
6491 }
6492 
6493 /*@C
6494    MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6495    this processor. (The columns of the "diagonal block")
6496 
6497    Not Collective, unless matrix has not been allocated, then collective on Mat
6498 
6499    Input Parameters:
6500 .  mat - the matrix
6501 
6502    Output Parameters:
6503 +  m - the global index of the first local column
6504 -  n - one more than the global index of the last local column
6505 
6506    Notes:
6507     both output parameters can be NULL on input.
6508 
6509    Level: developer
6510 
6511    Concepts: matrices^column ownership
6512 
6513 .seealso:  MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6514 
6515 @*/
6516 PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6517 {
6518   PetscFunctionBegin;
6519   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6520   PetscValidType(mat,1);
6521   if (m) PetscValidIntPointer(m,2);
6522   if (n) PetscValidIntPointer(n,3);
6523   MatCheckPreallocated(mat,1);
6524   if (m) *m = mat->cmap->rstart;
6525   if (n) *n = mat->cmap->rend;
6526   PetscFunctionReturn(0);
6527 }
6528 
6529 /*@C
6530    MatGetOwnershipRange - Returns the range of matrix rows owned by
6531    this processor, assuming that the matrix is laid out with the first
6532    n1 rows on the first processor, the next n2 rows on the second, etc.
6533    For certain parallel layouts this range may not be well defined.
6534 
6535    Not Collective
6536 
6537    Input Parameters:
6538 .  mat - the matrix
6539 
6540    Output Parameters:
6541 +  m - the global index of the first local row
6542 -  n - one more than the global index of the last local row
6543 
6544    Note: Both output parameters can be NULL on input.
6545 $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6546 $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6547 $  and then MPI_Scan() to calculate prefix sums of the local sizes.
6548 
6549    Level: beginner
6550 
6551    Concepts: matrices^row ownership
6552 
6553 .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6554 
6555 @*/
6556 PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6557 {
6558   PetscFunctionBegin;
6559   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6560   PetscValidType(mat,1);
6561   if (m) PetscValidIntPointer(m,2);
6562   if (n) PetscValidIntPointer(n,3);
6563   MatCheckPreallocated(mat,1);
6564   if (m) *m = mat->rmap->rstart;
6565   if (n) *n = mat->rmap->rend;
6566   PetscFunctionReturn(0);
6567 }
6568 
6569 /*@C
6570    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6571    each process
6572 
6573    Not Collective, unless matrix has not been allocated, then collective on Mat
6574 
6575    Input Parameters:
6576 .  mat - the matrix
6577 
6578    Output Parameters:
6579 .  ranges - start of each processors portion plus one more than the total length at the end
6580 
6581    Level: beginner
6582 
6583    Concepts: matrices^row ownership
6584 
6585 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6586 
6587 @*/
6588 PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6589 {
6590   PetscErrorCode ierr;
6591 
6592   PetscFunctionBegin;
6593   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6594   PetscValidType(mat,1);
6595   MatCheckPreallocated(mat,1);
6596   ierr = PetscLayoutGetRanges(mat->rmap,ranges);CHKERRQ(ierr);
6597   PetscFunctionReturn(0);
6598 }
6599 
6600 /*@C
6601    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6602    this processor. (The columns of the "diagonal blocks" for each process)
6603 
6604    Not Collective, unless matrix has not been allocated, then collective on Mat
6605 
6606    Input Parameters:
6607 .  mat - the matrix
6608 
6609    Output Parameters:
6610 .  ranges - start of each processors portion plus one more then the total length at the end
6611 
6612    Level: beginner
6613 
6614    Concepts: matrices^column ownership
6615 
6616 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6617 
6618 @*/
6619 PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6620 {
6621   PetscErrorCode ierr;
6622 
6623   PetscFunctionBegin;
6624   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6625   PetscValidType(mat,1);
6626   MatCheckPreallocated(mat,1);
6627   ierr = PetscLayoutGetRanges(mat->cmap,ranges);CHKERRQ(ierr);
6628   PetscFunctionReturn(0);
6629 }
6630 
6631 /*@C
6632    MatGetOwnershipIS - Get row and column ownership as index sets
6633 
6634    Not Collective
6635 
6636    Input Arguments:
6637 .  A - matrix of type Elemental
6638 
6639    Output Arguments:
6640 +  rows - rows in which this process owns elements
6641 .  cols - columns in which this process owns elements
6642 
6643    Level: intermediate
6644 
6645 .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6646 @*/
6647 PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6648 {
6649   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6650 
6651   PetscFunctionBegin;
6652   MatCheckPreallocated(A,1);
6653   ierr = PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);CHKERRQ(ierr);
6654   if (f) {
6655     ierr = (*f)(A,rows,cols);CHKERRQ(ierr);
6656   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6657     if (rows) {ierr = ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);CHKERRQ(ierr);}
6658     if (cols) {ierr = ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);CHKERRQ(ierr);}
6659   }
6660   PetscFunctionReturn(0);
6661 }
6662 
6663 /*@C
6664    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6665    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6666    to complete the factorization.
6667 
6668    Collective on Mat
6669 
6670    Input Parameters:
6671 +  mat - the matrix
6672 .  row - row permutation
6673 .  column - column permutation
6674 -  info - structure containing
6675 $      levels - number of levels of fill.
6676 $      expected fill - as ratio of original fill.
6677 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6678                 missing diagonal entries)
6679 
6680    Output Parameters:
6681 .  fact - new matrix that has been symbolically factored
6682 
6683    Notes:
6684     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6685 
6686    Most users should employ the simplified KSP interface for linear solvers
6687    instead of working directly with matrix algebra routines such as this.
6688    See, e.g., KSPCreate().
6689 
6690    Level: developer
6691 
6692   Concepts: matrices^symbolic LU factorization
6693   Concepts: matrices^factorization
6694   Concepts: LU^symbolic factorization
6695 
6696 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6697           MatGetOrdering(), MatFactorInfo
6698 
6699     Note: this uses the definition of level of fill as in Y. Saad, 2003
6700 
6701     Developer Note: fortran interface is not autogenerated as the f90
6702     interface defintion cannot be generated correctly [due to MatFactorInfo]
6703 
6704    References:
6705      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6706 @*/
6707 PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6708 {
6709   PetscErrorCode ierr;
6710 
6711   PetscFunctionBegin;
6712   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6713   PetscValidType(mat,1);
6714   PetscValidHeaderSpecific(row,IS_CLASSID,2);
6715   PetscValidHeaderSpecific(col,IS_CLASSID,3);
6716   PetscValidPointer(info,4);
6717   PetscValidPointer(fact,5);
6718   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6719   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6720   if (!(fact)->ops->ilufactorsymbolic) {
6721     MatSolverType spackage;
6722     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
6723     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6724   }
6725   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6726   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6727   MatCheckPreallocated(mat,2);
6728 
6729   ierr = PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6730   ierr = (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
6731   ierr = PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6732   PetscFunctionReturn(0);
6733 }
6734 
6735 /*@C
6736    MatICCFactorSymbolic - Performs symbolic incomplete
6737    Cholesky factorization for a symmetric matrix.  Use
6738    MatCholeskyFactorNumeric() to complete the factorization.
6739 
6740    Collective on Mat
6741 
6742    Input Parameters:
6743 +  mat - the matrix
6744 .  perm - row and column permutation
6745 -  info - structure containing
6746 $      levels - number of levels of fill.
6747 $      expected fill - as ratio of original fill.
6748 
6749    Output Parameter:
6750 .  fact - the factored matrix
6751 
6752    Notes:
6753    Most users should employ the KSP interface for linear solvers
6754    instead of working directly with matrix algebra routines such as this.
6755    See, e.g., KSPCreate().
6756 
6757    Level: developer
6758 
6759   Concepts: matrices^symbolic incomplete Cholesky factorization
6760   Concepts: matrices^factorization
6761   Concepts: Cholsky^symbolic factorization
6762 
6763 .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6764 
6765     Note: this uses the definition of level of fill as in Y. Saad, 2003
6766 
6767     Developer Note: fortran interface is not autogenerated as the f90
6768     interface defintion cannot be generated correctly [due to MatFactorInfo]
6769 
6770    References:
6771      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6772 @*/
6773 PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6774 {
6775   PetscErrorCode ierr;
6776 
6777   PetscFunctionBegin;
6778   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6779   PetscValidType(mat,1);
6780   PetscValidHeaderSpecific(perm,IS_CLASSID,2);
6781   PetscValidPointer(info,3);
6782   PetscValidPointer(fact,4);
6783   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6784   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6785   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6786   if (!(fact)->ops->iccfactorsymbolic) {
6787     MatSolverType spackage;
6788     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
6789     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6790   }
6791   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6792   MatCheckPreallocated(mat,2);
6793 
6794   ierr = PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6795   ierr = (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
6796   ierr = PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6797   PetscFunctionReturn(0);
6798 }
6799 
6800 /*@C
6801    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6802    points to an array of valid matrices, they may be reused to store the new
6803    submatrices.
6804 
6805    Collective on Mat
6806 
6807    Input Parameters:
6808 +  mat - the matrix
6809 .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6810 .  irow, icol - index sets of rows and columns to extract
6811 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6812 
6813    Output Parameter:
6814 .  submat - the array of submatrices
6815 
6816    Notes:
6817    MatCreateSubMatrices() can extract ONLY sequential submatrices
6818    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6819    to extract a parallel submatrix.
6820 
6821    Some matrix types place restrictions on the row and column
6822    indices, such as that they be sorted or that they be equal to each other.
6823 
6824    The index sets may not have duplicate entries.
6825 
6826    When extracting submatrices from a parallel matrix, each processor can
6827    form a different submatrix by setting the rows and columns of its
6828    individual index sets according to the local submatrix desired.
6829 
6830    When finished using the submatrices, the user should destroy
6831    them with MatDestroySubMatrices().
6832 
6833    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6834    original matrix has not changed from that last call to MatCreateSubMatrices().
6835 
6836    This routine creates the matrices in submat; you should NOT create them before
6837    calling it. It also allocates the array of matrix pointers submat.
6838 
6839    For BAIJ matrices the index sets must respect the block structure, that is if they
6840    request one row/column in a block, they must request all rows/columns that are in
6841    that block. For example, if the block size is 2 you cannot request just row 0 and
6842    column 0.
6843 
6844    Fortran Note:
6845    The Fortran interface is slightly different from that given below; it
6846    requires one to pass in  as submat a Mat (integer) array of size at least n+1.
6847 
6848    Level: advanced
6849 
6850    Concepts: matrices^accessing submatrices
6851    Concepts: submatrices
6852 
6853 .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6854 @*/
6855 PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6856 {
6857   PetscErrorCode ierr;
6858   PetscInt       i;
6859   PetscBool      eq;
6860 
6861   PetscFunctionBegin;
6862   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6863   PetscValidType(mat,1);
6864   if (n) {
6865     PetscValidPointer(irow,3);
6866     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6867     PetscValidPointer(icol,4);
6868     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6869   }
6870   PetscValidPointer(submat,6);
6871   if (n && scall == MAT_REUSE_MATRIX) {
6872     PetscValidPointer(*submat,6);
6873     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6874   }
6875   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6876   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6877   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6878   MatCheckPreallocated(mat,1);
6879 
6880   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6881   ierr = (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6882   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6883   for (i=0; i<n; i++) {
6884     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6885     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6886       ierr = ISEqual(irow[i],icol[i],&eq);CHKERRQ(ierr);
6887       if (eq) {
6888         if (mat->symmetric) {
6889           ierr = MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6890         } else if (mat->hermitian) {
6891           ierr = MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
6892         } else if (mat->structurally_symmetric) {
6893           ierr = MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6894         }
6895       }
6896     }
6897   }
6898   PetscFunctionReturn(0);
6899 }
6900 
6901 /*@C
6902    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
6903 
6904    Collective on Mat
6905 
6906    Input Parameters:
6907 +  mat - the matrix
6908 .  n   - the number of submatrixes to be extracted
6909 .  irow, icol - index sets of rows and columns to extract
6910 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6911 
6912    Output Parameter:
6913 .  submat - the array of submatrices
6914 
6915    Level: advanced
6916 
6917    Concepts: matrices^accessing submatrices
6918    Concepts: submatrices
6919 
6920 .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6921 @*/
6922 PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6923 {
6924   PetscErrorCode ierr;
6925   PetscInt       i;
6926   PetscBool      eq;
6927 
6928   PetscFunctionBegin;
6929   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6930   PetscValidType(mat,1);
6931   if (n) {
6932     PetscValidPointer(irow,3);
6933     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6934     PetscValidPointer(icol,4);
6935     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6936   }
6937   PetscValidPointer(submat,6);
6938   if (n && scall == MAT_REUSE_MATRIX) {
6939     PetscValidPointer(*submat,6);
6940     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6941   }
6942   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6943   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6944   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6945   MatCheckPreallocated(mat,1);
6946 
6947   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6948   ierr = (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6949   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6950   for (i=0; i<n; i++) {
6951     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6952       ierr = ISEqual(irow[i],icol[i],&eq);CHKERRQ(ierr);
6953       if (eq) {
6954         if (mat->symmetric) {
6955           ierr = MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6956         } else if (mat->hermitian) {
6957           ierr = MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
6958         } else if (mat->structurally_symmetric) {
6959           ierr = MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6960         }
6961       }
6962     }
6963   }
6964   PetscFunctionReturn(0);
6965 }
6966 
6967 /*@C
6968    MatDestroyMatrices - Destroys an array of matrices.
6969 
6970    Collective on Mat
6971 
6972    Input Parameters:
6973 +  n - the number of local matrices
6974 -  mat - the matrices (note that this is a pointer to the array of matrices)
6975 
6976    Level: advanced
6977 
6978     Notes:
6979     Frees not only the matrices, but also the array that contains the matrices
6980            In Fortran will not free the array.
6981 
6982 .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6983 @*/
6984 PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6985 {
6986   PetscErrorCode ierr;
6987   PetscInt       i;
6988 
6989   PetscFunctionBegin;
6990   if (!*mat) PetscFunctionReturn(0);
6991   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6992   PetscValidPointer(mat,2);
6993 
6994   for (i=0; i<n; i++) {
6995     ierr = MatDestroy(&(*mat)[i]);CHKERRQ(ierr);
6996   }
6997 
6998   /* memory is allocated even if n = 0 */
6999   ierr = PetscFree(*mat);CHKERRQ(ierr);
7000   PetscFunctionReturn(0);
7001 }
7002 
7003 /*@C
7004    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
7005 
7006    Collective on Mat
7007 
7008    Input Parameters:
7009 +  n - the number of local matrices
7010 -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
7011                        sequence of MatCreateSubMatrices())
7012 
7013    Level: advanced
7014 
7015     Notes:
7016     Frees not only the matrices, but also the array that contains the matrices
7017            In Fortran will not free the array.
7018 
7019 .seealso: MatCreateSubMatrices()
7020 @*/
7021 PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
7022 {
7023   PetscErrorCode ierr;
7024   Mat            mat0;
7025 
7026   PetscFunctionBegin;
7027   if (!*mat) PetscFunctionReturn(0);
7028   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7029   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
7030   PetscValidPointer(mat,2);
7031 
7032   mat0 = (*mat)[0];
7033   if (mat0 && mat0->ops->destroysubmatrices) {
7034     ierr = (mat0->ops->destroysubmatrices)(n,mat);CHKERRQ(ierr);
7035   } else {
7036     ierr = MatDestroyMatrices(n,mat);CHKERRQ(ierr);
7037   }
7038   PetscFunctionReturn(0);
7039 }
7040 
7041 /*@C
7042    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
7043 
7044    Collective on Mat
7045 
7046    Input Parameters:
7047 .  mat - the matrix
7048 
7049    Output Parameter:
7050 .  matstruct - the sequential matrix with the nonzero structure of mat
7051 
7052   Level: intermediate
7053 
7054 .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7055 @*/
7056 PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7057 {
7058   PetscErrorCode ierr;
7059 
7060   PetscFunctionBegin;
7061   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7062   PetscValidPointer(matstruct,2);
7063 
7064   PetscValidType(mat,1);
7065   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7066   MatCheckPreallocated(mat,1);
7067 
7068   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7069   ierr = PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
7070   ierr = (*mat->ops->getseqnonzerostructure)(mat,matstruct);CHKERRQ(ierr);
7071   ierr = PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
7072   PetscFunctionReturn(0);
7073 }
7074 
7075 /*@C
7076    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
7077 
7078    Collective on Mat
7079 
7080    Input Parameters:
7081 .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
7082                        sequence of MatGetSequentialNonzeroStructure())
7083 
7084    Level: advanced
7085 
7086     Notes:
7087     Frees not only the matrices, but also the array that contains the matrices
7088 
7089 .seealso: MatGetSeqNonzeroStructure()
7090 @*/
7091 PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7092 {
7093   PetscErrorCode ierr;
7094 
7095   PetscFunctionBegin;
7096   PetscValidPointer(mat,1);
7097   ierr = MatDestroy(mat);CHKERRQ(ierr);
7098   PetscFunctionReturn(0);
7099 }
7100 
7101 /*@
7102    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7103    replaces the index sets by larger ones that represent submatrices with
7104    additional overlap.
7105 
7106    Collective on Mat
7107 
7108    Input Parameters:
7109 +  mat - the matrix
7110 .  n   - the number of index sets
7111 .  is  - the array of index sets (these index sets will changed during the call)
7112 -  ov  - the additional overlap requested
7113 
7114    Options Database:
7115 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7116 
7117    Level: developer
7118 
7119    Concepts: overlap
7120    Concepts: ASM^computing overlap
7121 
7122 .seealso: MatCreateSubMatrices()
7123 @*/
7124 PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7125 {
7126   PetscErrorCode ierr;
7127 
7128   PetscFunctionBegin;
7129   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7130   PetscValidType(mat,1);
7131   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7132   if (n) {
7133     PetscValidPointer(is,3);
7134     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
7135   }
7136   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7137   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7138   MatCheckPreallocated(mat,1);
7139 
7140   if (!ov) PetscFunctionReturn(0);
7141   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7142   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7143   ierr = (*mat->ops->increaseoverlap)(mat,n,is,ov);CHKERRQ(ierr);
7144   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7145   PetscFunctionReturn(0);
7146 }
7147 
7148 
7149 PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
7150 
7151 /*@
7152    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7153    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7154    additional overlap.
7155 
7156    Collective on Mat
7157 
7158    Input Parameters:
7159 +  mat - the matrix
7160 .  n   - the number of index sets
7161 .  is  - the array of index sets (these index sets will changed during the call)
7162 -  ov  - the additional overlap requested
7163 
7164    Options Database:
7165 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7166 
7167    Level: developer
7168 
7169    Concepts: overlap
7170    Concepts: ASM^computing overlap
7171 
7172 .seealso: MatCreateSubMatrices()
7173 @*/
7174 PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7175 {
7176   PetscInt       i;
7177   PetscErrorCode ierr;
7178 
7179   PetscFunctionBegin;
7180   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7181   PetscValidType(mat,1);
7182   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7183   if (n) {
7184     PetscValidPointer(is,3);
7185     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
7186   }
7187   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7188   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7189   MatCheckPreallocated(mat,1);
7190   if (!ov) PetscFunctionReturn(0);
7191   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7192   for(i=0; i<n; i++){
7193 	ierr =  MatIncreaseOverlapSplit_Single(mat,&is[i],ov);CHKERRQ(ierr);
7194   }
7195   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
7196   PetscFunctionReturn(0);
7197 }
7198 
7199 
7200 
7201 
7202 /*@
7203    MatGetBlockSize - Returns the matrix block size.
7204 
7205    Not Collective
7206 
7207    Input Parameter:
7208 .  mat - the matrix
7209 
7210    Output Parameter:
7211 .  bs - block size
7212 
7213    Notes:
7214     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7215 
7216    If the block size has not been set yet this routine returns 1.
7217 
7218    Level: intermediate
7219 
7220    Concepts: matrices^block size
7221 
7222 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7223 @*/
7224 PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7225 {
7226   PetscFunctionBegin;
7227   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7228   PetscValidIntPointer(bs,2);
7229   *bs = PetscAbs(mat->rmap->bs);
7230   PetscFunctionReturn(0);
7231 }
7232 
7233 /*@
7234    MatGetBlockSizes - Returns the matrix block row and column sizes.
7235 
7236    Not Collective
7237 
7238    Input Parameter:
7239 .  mat - the matrix
7240 
7241    Output Parameter:
7242 .  rbs - row block size
7243 .  cbs - column block size
7244 
7245    Notes:
7246     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7247     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7248 
7249    If a block size has not been set yet this routine returns 1.
7250 
7251    Level: intermediate
7252 
7253    Concepts: matrices^block size
7254 
7255 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7256 @*/
7257 PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7258 {
7259   PetscFunctionBegin;
7260   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7261   if (rbs) PetscValidIntPointer(rbs,2);
7262   if (cbs) PetscValidIntPointer(cbs,3);
7263   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7264   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7265   PetscFunctionReturn(0);
7266 }
7267 
7268 /*@
7269    MatSetBlockSize - Sets the matrix block size.
7270 
7271    Logically Collective on Mat
7272 
7273    Input Parameters:
7274 +  mat - the matrix
7275 -  bs - block size
7276 
7277    Notes:
7278     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7279     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7280 
7281     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7282     is compatible with the matrix local sizes.
7283 
7284    Level: intermediate
7285 
7286    Concepts: matrices^block size
7287 
7288 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7289 @*/
7290 PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7291 {
7292   PetscErrorCode ierr;
7293 
7294   PetscFunctionBegin;
7295   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7296   PetscValidLogicalCollectiveInt(mat,bs,2);
7297   ierr = MatSetBlockSizes(mat,bs,bs);CHKERRQ(ierr);
7298   PetscFunctionReturn(0);
7299 }
7300 
7301 /*@
7302    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7303 
7304    Logically Collective on Mat
7305 
7306    Input Parameters:
7307 +  mat - the matrix
7308 .  nblocks - the number of blocks on this process
7309 -  bsizes - the block sizes
7310 
7311    Notes:
7312     Currently used by PCVPBJACOBI for SeqAIJ matrices
7313 
7314    Level: intermediate
7315 
7316    Concepts: matrices^block size
7317 
7318 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7319 @*/
7320 PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7321 {
7322   PetscErrorCode ierr;
7323   PetscInt       i,ncnt = 0, nlocal;
7324 
7325   PetscFunctionBegin;
7326   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7327   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7328   ierr = MatGetLocalSize(mat,&nlocal,NULL);CHKERRQ(ierr);
7329   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7330   if (ncnt != nlocal) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Sum of local block sizes %D does not equal local size of matrix %D",ncnt,nlocal);
7331   ierr = PetscFree(mat->bsizes);CHKERRQ(ierr);
7332   mat->nblocks = nblocks;
7333   ierr = PetscMalloc1(nblocks,&mat->bsizes);CHKERRQ(ierr);
7334   ierr = PetscMemcpy(mat->bsizes,bsizes,nblocks*sizeof(PetscInt));CHKERRQ(ierr);
7335   PetscFunctionReturn(0);
7336 }
7337 
7338 /*@C
7339    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7340 
7341    Logically Collective on Mat
7342 
7343    Input Parameters:
7344 .  mat - the matrix
7345 
7346    Output Parameters:
7347 +  nblocks - the number of blocks on this process
7348 -  bsizes - the block sizes
7349 
7350    Notes: Currently not supported from Fortran
7351 
7352    Level: intermediate
7353 
7354    Concepts: matrices^block size
7355 
7356 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7357 @*/
7358 PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7359 {
7360   PetscFunctionBegin;
7361   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7362   *nblocks = mat->nblocks;
7363   *bsizes  = mat->bsizes;
7364   PetscFunctionReturn(0);
7365 }
7366 
7367 /*@
7368    MatSetBlockSizes - Sets the matrix block row and column sizes.
7369 
7370    Logically Collective on Mat
7371 
7372    Input Parameters:
7373 +  mat - the matrix
7374 -  rbs - row block size
7375 -  cbs - column block size
7376 
7377    Notes:
7378     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7379     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7380     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later
7381 
7382     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7383     are compatible with the matrix local sizes.
7384 
7385     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7386 
7387    Level: intermediate
7388 
7389    Concepts: matrices^block size
7390 
7391 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7392 @*/
7393 PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7394 {
7395   PetscErrorCode ierr;
7396 
7397   PetscFunctionBegin;
7398   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7399   PetscValidLogicalCollectiveInt(mat,rbs,2);
7400   PetscValidLogicalCollectiveInt(mat,cbs,3);
7401   if (mat->ops->setblocksizes) {
7402     ierr = (*mat->ops->setblocksizes)(mat,rbs,cbs);CHKERRQ(ierr);
7403   }
7404   if (mat->rmap->refcnt) {
7405     ISLocalToGlobalMapping l2g = NULL;
7406     PetscLayout            nmap = NULL;
7407 
7408     ierr = PetscLayoutDuplicate(mat->rmap,&nmap);CHKERRQ(ierr);
7409     if (mat->rmap->mapping) {
7410       ierr = ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);CHKERRQ(ierr);
7411     }
7412     ierr = PetscLayoutDestroy(&mat->rmap);CHKERRQ(ierr);
7413     mat->rmap = nmap;
7414     mat->rmap->mapping = l2g;
7415   }
7416   if (mat->cmap->refcnt) {
7417     ISLocalToGlobalMapping l2g = NULL;
7418     PetscLayout            nmap = NULL;
7419 
7420     ierr = PetscLayoutDuplicate(mat->cmap,&nmap);CHKERRQ(ierr);
7421     if (mat->cmap->mapping) {
7422       ierr = ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);CHKERRQ(ierr);
7423     }
7424     ierr = PetscLayoutDestroy(&mat->cmap);CHKERRQ(ierr);
7425     mat->cmap = nmap;
7426     mat->cmap->mapping = l2g;
7427   }
7428   ierr = PetscLayoutSetBlockSize(mat->rmap,rbs);CHKERRQ(ierr);
7429   ierr = PetscLayoutSetBlockSize(mat->cmap,cbs);CHKERRQ(ierr);
7430   PetscFunctionReturn(0);
7431 }
7432 
7433 /*@
7434    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7435 
7436    Logically Collective on Mat
7437 
7438    Input Parameters:
7439 +  mat - the matrix
7440 .  fromRow - matrix from which to copy row block size
7441 -  fromCol - matrix from which to copy column block size (can be same as fromRow)
7442 
7443    Level: developer
7444 
7445    Concepts: matrices^block size
7446 
7447 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7448 @*/
7449 PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7450 {
7451   PetscErrorCode ierr;
7452 
7453   PetscFunctionBegin;
7454   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7455   PetscValidHeaderSpecific(fromRow,MAT_CLASSID,2);
7456   PetscValidHeaderSpecific(fromCol,MAT_CLASSID,3);
7457   if (fromRow->rmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);CHKERRQ(ierr);}
7458   if (fromCol->cmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);CHKERRQ(ierr);}
7459   PetscFunctionReturn(0);
7460 }
7461 
7462 /*@
7463    MatResidual - Default routine to calculate the residual.
7464 
7465    Collective on Mat and Vec
7466 
7467    Input Parameters:
7468 +  mat - the matrix
7469 .  b   - the right-hand-side
7470 -  x   - the approximate solution
7471 
7472    Output Parameter:
7473 .  r - location to store the residual
7474 
7475    Level: developer
7476 
7477 .keywords: MG, default, multigrid, residual
7478 
7479 .seealso: PCMGSetResidual()
7480 @*/
7481 PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7482 {
7483   PetscErrorCode ierr;
7484 
7485   PetscFunctionBegin;
7486   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7487   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
7488   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
7489   PetscValidHeaderSpecific(r,VEC_CLASSID,4);
7490   PetscValidType(mat,1);
7491   MatCheckPreallocated(mat,1);
7492   ierr  = PetscLogEventBegin(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7493   if (!mat->ops->residual) {
7494     ierr = MatMult(mat,x,r);CHKERRQ(ierr);
7495     ierr = VecAYPX(r,-1.0,b);CHKERRQ(ierr);
7496   } else {
7497     ierr  = (*mat->ops->residual)(mat,b,x,r);CHKERRQ(ierr);
7498   }
7499   ierr  = PetscLogEventEnd(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7500   PetscFunctionReturn(0);
7501 }
7502 
7503 /*@C
7504     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7505 
7506    Collective on Mat
7507 
7508     Input Parameters:
7509 +   mat - the matrix
7510 .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7511 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7512 -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7513                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7514                  always used.
7515 
7516     Output Parameters:
7517 +   n - number of rows in the (possibly compressed) matrix
7518 .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7519 .   ja - the column indices
7520 -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7521            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7522 
7523     Level: developer
7524 
7525     Notes:
7526     You CANNOT change any of the ia[] or ja[] values.
7527 
7528     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7529 
7530     Fortran Notes:
7531     In Fortran use
7532 $
7533 $      PetscInt ia(1), ja(1)
7534 $      PetscOffset iia, jja
7535 $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7536 $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7537 
7538      or
7539 $
7540 $    PetscInt, pointer :: ia(:),ja(:)
7541 $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7542 $    ! Access the ith and jth entries via ia(i) and ja(j)
7543 
7544 .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7545 @*/
7546 PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7547 {
7548   PetscErrorCode ierr;
7549 
7550   PetscFunctionBegin;
7551   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7552   PetscValidType(mat,1);
7553   PetscValidIntPointer(n,5);
7554   if (ia) PetscValidIntPointer(ia,6);
7555   if (ja) PetscValidIntPointer(ja,7);
7556   PetscValidIntPointer(done,8);
7557   MatCheckPreallocated(mat,1);
7558   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7559   else {
7560     *done = PETSC_TRUE;
7561     ierr  = PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7562     ierr  = (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7563     ierr  = PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7564   }
7565   PetscFunctionReturn(0);
7566 }
7567 
7568 /*@C
7569     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7570 
7571     Collective on Mat
7572 
7573     Input Parameters:
7574 +   mat - the matrix
7575 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7576 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7577                 symmetrized
7578 .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7579                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7580                  always used.
7581 .   n - number of columns in the (possibly compressed) matrix
7582 .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7583 -   ja - the row indices
7584 
7585     Output Parameters:
7586 .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7587 
7588     Level: developer
7589 
7590 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7591 @*/
7592 PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7593 {
7594   PetscErrorCode ierr;
7595 
7596   PetscFunctionBegin;
7597   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7598   PetscValidType(mat,1);
7599   PetscValidIntPointer(n,4);
7600   if (ia) PetscValidIntPointer(ia,5);
7601   if (ja) PetscValidIntPointer(ja,6);
7602   PetscValidIntPointer(done,7);
7603   MatCheckPreallocated(mat,1);
7604   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7605   else {
7606     *done = PETSC_TRUE;
7607     ierr  = (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7608   }
7609   PetscFunctionReturn(0);
7610 }
7611 
7612 /*@C
7613     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7614     MatGetRowIJ().
7615 
7616     Collective on Mat
7617 
7618     Input Parameters:
7619 +   mat - the matrix
7620 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7621 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7622                 symmetrized
7623 .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7624                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7625                  always used.
7626 .   n - size of (possibly compressed) matrix
7627 .   ia - the row pointers
7628 -   ja - the column indices
7629 
7630     Output Parameters:
7631 .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7632 
7633     Note:
7634     This routine zeros out n, ia, and ja. This is to prevent accidental
7635     us of the array after it has been restored. If you pass NULL, it will
7636     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.
7637 
7638     Level: developer
7639 
7640 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7641 @*/
7642 PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7643 {
7644   PetscErrorCode ierr;
7645 
7646   PetscFunctionBegin;
7647   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7648   PetscValidType(mat,1);
7649   if (ia) PetscValidIntPointer(ia,6);
7650   if (ja) PetscValidIntPointer(ja,7);
7651   PetscValidIntPointer(done,8);
7652   MatCheckPreallocated(mat,1);
7653 
7654   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7655   else {
7656     *done = PETSC_TRUE;
7657     ierr  = (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7658     if (n)  *n = 0;
7659     if (ia) *ia = NULL;
7660     if (ja) *ja = NULL;
7661   }
7662   PetscFunctionReturn(0);
7663 }
7664 
7665 /*@C
7666     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7667     MatGetColumnIJ().
7668 
7669     Collective on Mat
7670 
7671     Input Parameters:
7672 +   mat - the matrix
7673 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7674 -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7675                 symmetrized
7676 -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7677                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7678                  always used.
7679 
7680     Output Parameters:
7681 +   n - size of (possibly compressed) matrix
7682 .   ia - the column pointers
7683 .   ja - the row indices
7684 -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7685 
7686     Level: developer
7687 
7688 .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7689 @*/
7690 PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7691 {
7692   PetscErrorCode ierr;
7693 
7694   PetscFunctionBegin;
7695   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7696   PetscValidType(mat,1);
7697   if (ia) PetscValidIntPointer(ia,5);
7698   if (ja) PetscValidIntPointer(ja,6);
7699   PetscValidIntPointer(done,7);
7700   MatCheckPreallocated(mat,1);
7701 
7702   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7703   else {
7704     *done = PETSC_TRUE;
7705     ierr  = (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7706     if (n)  *n = 0;
7707     if (ia) *ia = NULL;
7708     if (ja) *ja = NULL;
7709   }
7710   PetscFunctionReturn(0);
7711 }
7712 
7713 /*@C
7714     MatColoringPatch -Used inside matrix coloring routines that
7715     use MatGetRowIJ() and/or MatGetColumnIJ().
7716 
7717     Collective on Mat
7718 
7719     Input Parameters:
7720 +   mat - the matrix
7721 .   ncolors - max color value
7722 .   n   - number of entries in colorarray
7723 -   colorarray - array indicating color for each column
7724 
7725     Output Parameters:
7726 .   iscoloring - coloring generated using colorarray information
7727 
7728     Level: developer
7729 
7730 .seealso: MatGetRowIJ(), MatGetColumnIJ()
7731 
7732 @*/
7733 PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7734 {
7735   PetscErrorCode ierr;
7736 
7737   PetscFunctionBegin;
7738   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7739   PetscValidType(mat,1);
7740   PetscValidIntPointer(colorarray,4);
7741   PetscValidPointer(iscoloring,5);
7742   MatCheckPreallocated(mat,1);
7743 
7744   if (!mat->ops->coloringpatch) {
7745     ierr = ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);CHKERRQ(ierr);
7746   } else {
7747     ierr = (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);CHKERRQ(ierr);
7748   }
7749   PetscFunctionReturn(0);
7750 }
7751 
7752 
7753 /*@
7754    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7755 
7756    Logically Collective on Mat
7757 
7758    Input Parameter:
7759 .  mat - the factored matrix to be reset
7760 
7761    Notes:
7762    This routine should be used only with factored matrices formed by in-place
7763    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7764    format).  This option can save memory, for example, when solving nonlinear
7765    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7766    ILU(0) preconditioner.
7767 
7768    Note that one can specify in-place ILU(0) factorization by calling
7769 .vb
7770      PCType(pc,PCILU);
7771      PCFactorSeUseInPlace(pc);
7772 .ve
7773    or by using the options -pc_type ilu -pc_factor_in_place
7774 
7775    In-place factorization ILU(0) can also be used as a local
7776    solver for the blocks within the block Jacobi or additive Schwarz
7777    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7778    for details on setting local solver options.
7779 
7780    Most users should employ the simplified KSP interface for linear solvers
7781    instead of working directly with matrix algebra routines such as this.
7782    See, e.g., KSPCreate().
7783 
7784    Level: developer
7785 
7786 .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7787 
7788    Concepts: matrices^unfactored
7789 
7790 @*/
7791 PetscErrorCode MatSetUnfactored(Mat mat)
7792 {
7793   PetscErrorCode ierr;
7794 
7795   PetscFunctionBegin;
7796   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7797   PetscValidType(mat,1);
7798   MatCheckPreallocated(mat,1);
7799   mat->factortype = MAT_FACTOR_NONE;
7800   if (!mat->ops->setunfactored) PetscFunctionReturn(0);
7801   ierr = (*mat->ops->setunfactored)(mat);CHKERRQ(ierr);
7802   PetscFunctionReturn(0);
7803 }
7804 
7805 /*MC
7806     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7807 
7808     Synopsis:
7809     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7810 
7811     Not collective
7812 
7813     Input Parameter:
7814 .   x - matrix
7815 
7816     Output Parameters:
7817 +   xx_v - the Fortran90 pointer to the array
7818 -   ierr - error code
7819 
7820     Example of Usage:
7821 .vb
7822       PetscScalar, pointer xx_v(:,:)
7823       ....
7824       call MatDenseGetArrayF90(x,xx_v,ierr)
7825       a = xx_v(3)
7826       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7827 .ve
7828 
7829     Level: advanced
7830 
7831 .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7832 
7833     Concepts: matrices^accessing array
7834 
7835 M*/
7836 
7837 /*MC
7838     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7839     accessed with MatDenseGetArrayF90().
7840 
7841     Synopsis:
7842     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7843 
7844     Not collective
7845 
7846     Input Parameters:
7847 +   x - matrix
7848 -   xx_v - the Fortran90 pointer to the array
7849 
7850     Output Parameter:
7851 .   ierr - error code
7852 
7853     Example of Usage:
7854 .vb
7855        PetscScalar, pointer xx_v(:,:)
7856        ....
7857        call MatDenseGetArrayF90(x,xx_v,ierr)
7858        a = xx_v(3)
7859        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7860 .ve
7861 
7862     Level: advanced
7863 
7864 .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7865 
7866 M*/
7867 
7868 
7869 /*MC
7870     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7871 
7872     Synopsis:
7873     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7874 
7875     Not collective
7876 
7877     Input Parameter:
7878 .   x - matrix
7879 
7880     Output Parameters:
7881 +   xx_v - the Fortran90 pointer to the array
7882 -   ierr - error code
7883 
7884     Example of Usage:
7885 .vb
7886       PetscScalar, pointer xx_v(:)
7887       ....
7888       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7889       a = xx_v(3)
7890       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7891 .ve
7892 
7893     Level: advanced
7894 
7895 .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7896 
7897     Concepts: matrices^accessing array
7898 
7899 M*/
7900 
7901 /*MC
7902     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7903     accessed with MatSeqAIJGetArrayF90().
7904 
7905     Synopsis:
7906     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7907 
7908     Not collective
7909 
7910     Input Parameters:
7911 +   x - matrix
7912 -   xx_v - the Fortran90 pointer to the array
7913 
7914     Output Parameter:
7915 .   ierr - error code
7916 
7917     Example of Usage:
7918 .vb
7919        PetscScalar, pointer xx_v(:)
7920        ....
7921        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7922        a = xx_v(3)
7923        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7924 .ve
7925 
7926     Level: advanced
7927 
7928 .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7929 
7930 M*/
7931 
7932 
7933 /*@
7934     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7935                       as the original matrix.
7936 
7937     Collective on Mat
7938 
7939     Input Parameters:
7940 +   mat - the original matrix
7941 .   isrow - parallel IS containing the rows this processor should obtain
7942 .   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.
7943 -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7944 
7945     Output Parameter:
7946 .   newmat - the new submatrix, of the same type as the old
7947 
7948     Level: advanced
7949 
7950     Notes:
7951     The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7952 
7953     Some matrix types place restrictions on the row and column indices, such
7954     as that they be sorted or that they be equal to each other.
7955 
7956     The index sets may not have duplicate entries.
7957 
7958       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7959    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7960    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7961    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7962    you are finished using it.
7963 
7964     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7965     the input matrix.
7966 
7967     If iscol is NULL then all columns are obtained (not supported in Fortran).
7968 
7969    Example usage:
7970    Consider the following 8x8 matrix with 34 non-zero values, that is
7971    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7972    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7973    as follows:
7974 
7975 .vb
7976             1  2  0  |  0  3  0  |  0  4
7977     Proc0   0  5  6  |  7  0  0  |  8  0
7978             9  0 10  | 11  0  0  | 12  0
7979     -------------------------------------
7980            13  0 14  | 15 16 17  |  0  0
7981     Proc1   0 18  0  | 19 20 21  |  0  0
7982             0  0  0  | 22 23  0  | 24  0
7983     -------------------------------------
7984     Proc2  25 26 27  |  0  0 28  | 29  0
7985            30  0  0  | 31 32 33  |  0 34
7986 .ve
7987 
7988     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is
7989 
7990 .vb
7991             2  0  |  0  3  0  |  0
7992     Proc0   5  6  |  7  0  0  |  8
7993     -------------------------------
7994     Proc1  18  0  | 19 20 21  |  0
7995     -------------------------------
7996     Proc2  26 27  |  0  0 28  | 29
7997             0  0  | 31 32 33  |  0
7998 .ve
7999 
8000 
8001     Concepts: matrices^submatrices
8002 
8003 .seealso: MatCreateSubMatrices()
8004 @*/
8005 PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
8006 {
8007   PetscErrorCode ierr;
8008   PetscMPIInt    size;
8009   Mat            *local;
8010   IS             iscoltmp;
8011 
8012   PetscFunctionBegin;
8013   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8014   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
8015   if (iscol) PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
8016   PetscValidPointer(newmat,5);
8017   if (cll == MAT_REUSE_MATRIX) PetscValidHeaderSpecific(*newmat,MAT_CLASSID,5);
8018   PetscValidType(mat,1);
8019   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8020   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
8021 
8022   MatCheckPreallocated(mat,1);
8023   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
8024 
8025   if (!iscol || isrow == iscol) {
8026     PetscBool   stride;
8027     PetscMPIInt grabentirematrix = 0,grab;
8028     ierr = PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);CHKERRQ(ierr);
8029     if (stride) {
8030       PetscInt first,step,n,rstart,rend;
8031       ierr = ISStrideGetInfo(isrow,&first,&step);CHKERRQ(ierr);
8032       if (step == 1) {
8033         ierr = MatGetOwnershipRange(mat,&rstart,&rend);CHKERRQ(ierr);
8034         if (rstart == first) {
8035           ierr = ISGetLocalSize(isrow,&n);CHKERRQ(ierr);
8036           if (n == rend-rstart) {
8037             grabentirematrix = 1;
8038           }
8039         }
8040       }
8041     }
8042     ierr = MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
8043     if (grab) {
8044       ierr = PetscInfo(mat,"Getting entire matrix as submatrix\n");CHKERRQ(ierr);
8045       if (cll == MAT_INITIAL_MATRIX) {
8046         *newmat = mat;
8047         ierr    = PetscObjectReference((PetscObject)mat);CHKERRQ(ierr);
8048       }
8049       PetscFunctionReturn(0);
8050     }
8051   }
8052 
8053   if (!iscol) {
8054     ierr = ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);CHKERRQ(ierr);
8055   } else {
8056     iscoltmp = iscol;
8057   }
8058 
8059   /* if original matrix is on just one processor then use submatrix generated */
8060   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8061     ierr = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);CHKERRQ(ierr);
8062     goto setproperties;
8063   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8064     ierr    = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);CHKERRQ(ierr);
8065     *newmat = *local;
8066     ierr    = PetscFree(local);CHKERRQ(ierr);
8067     goto setproperties;
8068   } else if (!mat->ops->createsubmatrix) {
8069     /* Create a new matrix type that implements the operation using the full matrix */
8070     ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8071     switch (cll) {
8072     case MAT_INITIAL_MATRIX:
8073       ierr = MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);CHKERRQ(ierr);
8074       break;
8075     case MAT_REUSE_MATRIX:
8076       ierr = MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);CHKERRQ(ierr);
8077       break;
8078     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8079     }
8080     ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8081     goto setproperties;
8082   }
8083 
8084   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8085   ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8086   ierr = (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);CHKERRQ(ierr);
8087   ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
8088 
8089   /* Propagate symmetry information for diagonal blocks */
8090 setproperties:
8091   if (isrow == iscoltmp) {
8092     if (mat->symmetric_set && mat->symmetric) {
8093       ierr = MatSetOption(*newmat,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
8094     }
8095     if (mat->structurally_symmetric_set && mat->structurally_symmetric) {
8096       ierr = MatSetOption(*newmat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
8097     }
8098     if (mat->hermitian_set && mat->hermitian) {
8099       ierr = MatSetOption(*newmat,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
8100     }
8101     if (mat->spd_set && mat->spd) {
8102       ierr = MatSetOption(*newmat,MAT_SPD,PETSC_TRUE);CHKERRQ(ierr);
8103     }
8104   }
8105 
8106   if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
8107   if (*newmat && cll == MAT_INITIAL_MATRIX) {ierr = PetscObjectStateIncrease((PetscObject)*newmat);CHKERRQ(ierr);}
8108   PetscFunctionReturn(0);
8109 }
8110 
8111 /*@
8112    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8113    used during the assembly process to store values that belong to
8114    other processors.
8115 
8116    Not Collective
8117 
8118    Input Parameters:
8119 +  mat   - the matrix
8120 .  size  - the initial size of the stash.
8121 -  bsize - the initial size of the block-stash(if used).
8122 
8123    Options Database Keys:
8124 +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8125 -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>
8126 
8127    Level: intermediate
8128 
8129    Notes:
8130      The block-stash is used for values set with MatSetValuesBlocked() while
8131      the stash is used for values set with MatSetValues()
8132 
8133      Run with the option -info and look for output of the form
8134      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8135      to determine the appropriate value, MM, to use for size and
8136      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8137      to determine the value, BMM to use for bsize
8138 
8139    Concepts: stash^setting matrix size
8140    Concepts: matrices^stash
8141 
8142 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
8143 
8144 @*/
8145 PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8146 {
8147   PetscErrorCode ierr;
8148 
8149   PetscFunctionBegin;
8150   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8151   PetscValidType(mat,1);
8152   ierr = MatStashSetInitialSize_Private(&mat->stash,size);CHKERRQ(ierr);
8153   ierr = MatStashSetInitialSize_Private(&mat->bstash,bsize);CHKERRQ(ierr);
8154   PetscFunctionReturn(0);
8155 }
8156 
8157 /*@
8158    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8159      the matrix
8160 
8161    Neighbor-wise Collective on Mat
8162 
8163    Input Parameters:
8164 +  mat   - the matrix
8165 .  x,y - the vectors
8166 -  w - where the result is stored
8167 
8168    Level: intermediate
8169 
8170    Notes:
8171     w may be the same vector as y.
8172 
8173     This allows one to use either the restriction or interpolation (its transpose)
8174     matrix to do the interpolation
8175 
8176     Concepts: interpolation
8177 
8178 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8179 
8180 @*/
8181 PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8182 {
8183   PetscErrorCode ierr;
8184   PetscInt       M,N,Ny;
8185 
8186   PetscFunctionBegin;
8187   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8188   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8189   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8190   PetscValidHeaderSpecific(w,VEC_CLASSID,4);
8191   PetscValidType(A,1);
8192   MatCheckPreallocated(A,1);
8193   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8194   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8195   if (M == Ny) {
8196     ierr = MatMultAdd(A,x,y,w);CHKERRQ(ierr);
8197   } else {
8198     ierr = MatMultTransposeAdd(A,x,y,w);CHKERRQ(ierr);
8199   }
8200   PetscFunctionReturn(0);
8201 }
8202 
8203 /*@
8204    MatInterpolate - y = A*x or A'*x depending on the shape of
8205      the matrix
8206 
8207    Neighbor-wise Collective on Mat
8208 
8209    Input Parameters:
8210 +  mat   - the matrix
8211 -  x,y - the vectors
8212 
8213    Level: intermediate
8214 
8215    Notes:
8216     This allows one to use either the restriction or interpolation (its transpose)
8217     matrix to do the interpolation
8218 
8219    Concepts: matrices^interpolation
8220 
8221 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8222 
8223 @*/
8224 PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8225 {
8226   PetscErrorCode ierr;
8227   PetscInt       M,N,Ny;
8228 
8229   PetscFunctionBegin;
8230   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8231   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8232   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8233   PetscValidType(A,1);
8234   MatCheckPreallocated(A,1);
8235   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8236   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8237   if (M == Ny) {
8238     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8239   } else {
8240     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8241   }
8242   PetscFunctionReturn(0);
8243 }
8244 
8245 /*@
8246    MatRestrict - y = A*x or A'*x
8247 
8248    Neighbor-wise Collective on Mat
8249 
8250    Input Parameters:
8251 +  mat   - the matrix
8252 -  x,y - the vectors
8253 
8254    Level: intermediate
8255 
8256    Notes:
8257     This allows one to use either the restriction or interpolation (its transpose)
8258     matrix to do the restriction
8259 
8260    Concepts: matrices^restriction
8261 
8262 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8263 
8264 @*/
8265 PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8266 {
8267   PetscErrorCode ierr;
8268   PetscInt       M,N,Ny;
8269 
8270   PetscFunctionBegin;
8271   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8272   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8273   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8274   PetscValidType(A,1);
8275   MatCheckPreallocated(A,1);
8276 
8277   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8278   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8279   if (M == Ny) {
8280     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8281   } else {
8282     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8283   }
8284   PetscFunctionReturn(0);
8285 }
8286 
8287 /*@
8288    MatGetNullSpace - retrieves the null space of a matrix.
8289 
8290    Logically Collective on Mat and MatNullSpace
8291 
8292    Input Parameters:
8293 +  mat - the matrix
8294 -  nullsp - the null space object
8295 
8296    Level: developer
8297 
8298    Concepts: null space^attaching to matrix
8299 
8300 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8301 @*/
8302 PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8303 {
8304   PetscFunctionBegin;
8305   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8306   PetscValidPointer(nullsp,2);
8307   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8308   PetscFunctionReturn(0);
8309 }
8310 
8311 /*@
8312    MatSetNullSpace - attaches a null space to a matrix.
8313 
8314    Logically Collective on Mat and MatNullSpace
8315 
8316    Input Parameters:
8317 +  mat - the matrix
8318 -  nullsp - the null space object
8319 
8320    Level: advanced
8321 
8322    Notes:
8323       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8324 
8325       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8326       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8327 
8328       You can remove the null space by calling this routine with an nullsp of NULL
8329 
8330 
8331       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8332    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).
8333    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
8334    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
8335    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).
8336 
8337       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8338 
8339     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
8340     routine also automatically calls MatSetTransposeNullSpace().
8341 
8342    Concepts: null space^attaching to matrix
8343 
8344 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8345 @*/
8346 PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8347 {
8348   PetscErrorCode ierr;
8349 
8350   PetscFunctionBegin;
8351   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8352   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8353   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8354   ierr = MatNullSpaceDestroy(&mat->nullsp);CHKERRQ(ierr);
8355   mat->nullsp = nullsp;
8356   if (mat->symmetric_set && mat->symmetric) {
8357     ierr = MatSetTransposeNullSpace(mat,nullsp);CHKERRQ(ierr);
8358   }
8359   PetscFunctionReturn(0);
8360 }
8361 
8362 /*@
8363    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8364 
8365    Logically Collective on Mat and MatNullSpace
8366 
8367    Input Parameters:
8368 +  mat - the matrix
8369 -  nullsp - the null space object
8370 
8371    Level: developer
8372 
8373    Concepts: null space^attaching to matrix
8374 
8375 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8376 @*/
8377 PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8378 {
8379   PetscFunctionBegin;
8380   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8381   PetscValidType(mat,1);
8382   PetscValidPointer(nullsp,2);
8383   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8384   PetscFunctionReturn(0);
8385 }
8386 
8387 /*@
8388    MatSetTransposeNullSpace - attaches a null space to a matrix.
8389 
8390    Logically Collective on Mat and MatNullSpace
8391 
8392    Input Parameters:
8393 +  mat - the matrix
8394 -  nullsp - the null space object
8395 
8396    Level: advanced
8397 
8398    Notes:
8399       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.
8400       You must also call MatSetNullSpace()
8401 
8402 
8403       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8404    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).
8405    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
8406    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
8407    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).
8408 
8409       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8410 
8411    Concepts: null space^attaching to matrix
8412 
8413 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8414 @*/
8415 PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8416 {
8417   PetscErrorCode ierr;
8418 
8419   PetscFunctionBegin;
8420   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8421   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8422   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8423   ierr = MatNullSpaceDestroy(&mat->transnullsp);CHKERRQ(ierr);
8424   mat->transnullsp = nullsp;
8425   PetscFunctionReturn(0);
8426 }
8427 
8428 /*@
8429    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8430         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8431 
8432    Logically Collective on Mat and MatNullSpace
8433 
8434    Input Parameters:
8435 +  mat - the matrix
8436 -  nullsp - the null space object
8437 
8438    Level: advanced
8439 
8440    Notes:
8441       Overwrites any previous near null space that may have been attached
8442 
8443       You can remove the null space by calling this routine with an nullsp of NULL
8444 
8445    Concepts: null space^attaching to matrix
8446 
8447 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8448 @*/
8449 PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8450 {
8451   PetscErrorCode ierr;
8452 
8453   PetscFunctionBegin;
8454   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8455   PetscValidType(mat,1);
8456   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8457   MatCheckPreallocated(mat,1);
8458   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8459   ierr = MatNullSpaceDestroy(&mat->nearnullsp);CHKERRQ(ierr);
8460   mat->nearnullsp = nullsp;
8461   PetscFunctionReturn(0);
8462 }
8463 
8464 /*@
8465    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()
8466 
8467    Not Collective
8468 
8469    Input Parameters:
8470 .  mat - the matrix
8471 
8472    Output Parameters:
8473 .  nullsp - the null space object, NULL if not set
8474 
8475    Level: developer
8476 
8477    Concepts: null space^attaching to matrix
8478 
8479 .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8480 @*/
8481 PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8482 {
8483   PetscFunctionBegin;
8484   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8485   PetscValidType(mat,1);
8486   PetscValidPointer(nullsp,2);
8487   MatCheckPreallocated(mat,1);
8488   *nullsp = mat->nearnullsp;
8489   PetscFunctionReturn(0);
8490 }
8491 
8492 /*@C
8493    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8494 
8495    Collective on Mat
8496 
8497    Input Parameters:
8498 +  mat - the matrix
8499 .  row - row/column permutation
8500 .  fill - expected fill factor >= 1.0
8501 -  level - level of fill, for ICC(k)
8502 
8503    Notes:
8504    Probably really in-place only when level of fill is zero, otherwise allocates
8505    new space to store factored matrix and deletes previous memory.
8506 
8507    Most users should employ the simplified KSP interface for linear solvers
8508    instead of working directly with matrix algebra routines such as this.
8509    See, e.g., KSPCreate().
8510 
8511    Level: developer
8512 
8513    Concepts: matrices^incomplete Cholesky factorization
8514    Concepts: Cholesky factorization
8515 
8516 .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8517 
8518     Developer Note: fortran interface is not autogenerated as the f90
8519     interface defintion cannot be generated correctly [due to MatFactorInfo]
8520 
8521 @*/
8522 PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8523 {
8524   PetscErrorCode ierr;
8525 
8526   PetscFunctionBegin;
8527   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8528   PetscValidType(mat,1);
8529   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
8530   PetscValidPointer(info,3);
8531   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8532   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8533   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8534   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8535   MatCheckPreallocated(mat,1);
8536   ierr = (*mat->ops->iccfactor)(mat,row,info);CHKERRQ(ierr);
8537   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8538   PetscFunctionReturn(0);
8539 }
8540 
8541 /*@
8542    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8543          ghosted ones.
8544 
8545    Not Collective
8546 
8547    Input Parameters:
8548 +  mat - the matrix
8549 -  diag = the diagonal values, including ghost ones
8550 
8551    Level: developer
8552 
8553    Notes:
8554     Works only for MPIAIJ and MPIBAIJ matrices
8555 
8556 .seealso: MatDiagonalScale()
8557 @*/
8558 PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8559 {
8560   PetscErrorCode ierr;
8561   PetscMPIInt    size;
8562 
8563   PetscFunctionBegin;
8564   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8565   PetscValidHeaderSpecific(diag,VEC_CLASSID,2);
8566   PetscValidType(mat,1);
8567 
8568   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8569   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8570   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
8571   if (size == 1) {
8572     PetscInt n,m;
8573     ierr = VecGetSize(diag,&n);CHKERRQ(ierr);
8574     ierr = MatGetSize(mat,0,&m);CHKERRQ(ierr);
8575     if (m == n) {
8576       ierr = MatDiagonalScale(mat,0,diag);CHKERRQ(ierr);
8577     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8578   } else {
8579     ierr = PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));CHKERRQ(ierr);
8580   }
8581   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8582   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8583   PetscFunctionReturn(0);
8584 }
8585 
8586 /*@
8587    MatGetInertia - Gets the inertia from a factored matrix
8588 
8589    Collective on Mat
8590 
8591    Input Parameter:
8592 .  mat - the matrix
8593 
8594    Output Parameters:
8595 +   nneg - number of negative eigenvalues
8596 .   nzero - number of zero eigenvalues
8597 -   npos - number of positive eigenvalues
8598 
8599    Level: advanced
8600 
8601    Notes:
8602     Matrix must have been factored by MatCholeskyFactor()
8603 
8604 
8605 @*/
8606 PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8607 {
8608   PetscErrorCode ierr;
8609 
8610   PetscFunctionBegin;
8611   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8612   PetscValidType(mat,1);
8613   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8614   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8615   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8616   ierr = (*mat->ops->getinertia)(mat,nneg,nzero,npos);CHKERRQ(ierr);
8617   PetscFunctionReturn(0);
8618 }
8619 
8620 /* ----------------------------------------------------------------*/
8621 /*@C
8622    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8623 
8624    Neighbor-wise Collective on Mat and Vecs
8625 
8626    Input Parameters:
8627 +  mat - the factored matrix
8628 -  b - the right-hand-side vectors
8629 
8630    Output Parameter:
8631 .  x - the result vectors
8632 
8633    Notes:
8634    The vectors b and x cannot be the same.  I.e., one cannot
8635    call MatSolves(A,x,x).
8636 
8637    Notes:
8638    Most users should employ the simplified KSP interface for linear solvers
8639    instead of working directly with matrix algebra routines such as this.
8640    See, e.g., KSPCreate().
8641 
8642    Level: developer
8643 
8644    Concepts: matrices^triangular solves
8645 
8646 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8647 @*/
8648 PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8649 {
8650   PetscErrorCode ierr;
8651 
8652   PetscFunctionBegin;
8653   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8654   PetscValidType(mat,1);
8655   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8656   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8657   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
8658 
8659   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8660   MatCheckPreallocated(mat,1);
8661   ierr = PetscLogEventBegin(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8662   ierr = (*mat->ops->solves)(mat,b,x);CHKERRQ(ierr);
8663   ierr = PetscLogEventEnd(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8664   PetscFunctionReturn(0);
8665 }
8666 
8667 /*@
8668    MatIsSymmetric - Test whether a matrix is symmetric
8669 
8670    Collective on Mat
8671 
8672    Input Parameter:
8673 +  A - the matrix to test
8674 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8675 
8676    Output Parameters:
8677 .  flg - the result
8678 
8679    Notes:
8680     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8681 
8682    Level: intermediate
8683 
8684    Concepts: matrix^symmetry
8685 
8686 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8687 @*/
8688 PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8689 {
8690   PetscErrorCode ierr;
8691 
8692   PetscFunctionBegin;
8693   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8694   PetscValidPointer(flg,2);
8695 
8696   if (!A->symmetric_set) {
8697     if (!A->ops->issymmetric) {
8698       MatType mattype;
8699       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8700       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8701     }
8702     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8703     if (!tol) {
8704       A->symmetric_set = PETSC_TRUE;
8705       A->symmetric     = *flg;
8706       if (A->symmetric) {
8707         A->structurally_symmetric_set = PETSC_TRUE;
8708         A->structurally_symmetric     = PETSC_TRUE;
8709       }
8710     }
8711   } else if (A->symmetric) {
8712     *flg = PETSC_TRUE;
8713   } else if (!tol) {
8714     *flg = PETSC_FALSE;
8715   } else {
8716     if (!A->ops->issymmetric) {
8717       MatType mattype;
8718       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8719       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8720     }
8721     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8722   }
8723   PetscFunctionReturn(0);
8724 }
8725 
8726 /*@
8727    MatIsHermitian - Test whether a matrix is Hermitian
8728 
8729    Collective on Mat
8730 
8731    Input Parameter:
8732 +  A - the matrix to test
8733 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8734 
8735    Output Parameters:
8736 .  flg - the result
8737 
8738    Level: intermediate
8739 
8740    Concepts: matrix^symmetry
8741 
8742 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8743           MatIsSymmetricKnown(), MatIsSymmetric()
8744 @*/
8745 PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8746 {
8747   PetscErrorCode ierr;
8748 
8749   PetscFunctionBegin;
8750   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8751   PetscValidPointer(flg,2);
8752 
8753   if (!A->hermitian_set) {
8754     if (!A->ops->ishermitian) {
8755       MatType mattype;
8756       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8757       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8758     }
8759     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8760     if (!tol) {
8761       A->hermitian_set = PETSC_TRUE;
8762       A->hermitian     = *flg;
8763       if (A->hermitian) {
8764         A->structurally_symmetric_set = PETSC_TRUE;
8765         A->structurally_symmetric     = PETSC_TRUE;
8766       }
8767     }
8768   } else if (A->hermitian) {
8769     *flg = PETSC_TRUE;
8770   } else if (!tol) {
8771     *flg = PETSC_FALSE;
8772   } else {
8773     if (!A->ops->ishermitian) {
8774       MatType mattype;
8775       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8776       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8777     }
8778     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8779   }
8780   PetscFunctionReturn(0);
8781 }
8782 
8783 /*@
8784    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8785 
8786    Not Collective
8787 
8788    Input Parameter:
8789 .  A - the matrix to check
8790 
8791    Output Parameters:
8792 +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8793 -  flg - the result
8794 
8795    Level: advanced
8796 
8797    Concepts: matrix^symmetry
8798 
8799    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8800          if you want it explicitly checked
8801 
8802 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8803 @*/
8804 PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8805 {
8806   PetscFunctionBegin;
8807   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8808   PetscValidPointer(set,2);
8809   PetscValidPointer(flg,3);
8810   if (A->symmetric_set) {
8811     *set = PETSC_TRUE;
8812     *flg = A->symmetric;
8813   } else {
8814     *set = PETSC_FALSE;
8815   }
8816   PetscFunctionReturn(0);
8817 }
8818 
8819 /*@
8820    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8821 
8822    Not Collective
8823 
8824    Input Parameter:
8825 .  A - the matrix to check
8826 
8827    Output Parameters:
8828 +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8829 -  flg - the result
8830 
8831    Level: advanced
8832 
8833    Concepts: matrix^symmetry
8834 
8835    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8836          if you want it explicitly checked
8837 
8838 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8839 @*/
8840 PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8841 {
8842   PetscFunctionBegin;
8843   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8844   PetscValidPointer(set,2);
8845   PetscValidPointer(flg,3);
8846   if (A->hermitian_set) {
8847     *set = PETSC_TRUE;
8848     *flg = A->hermitian;
8849   } else {
8850     *set = PETSC_FALSE;
8851   }
8852   PetscFunctionReturn(0);
8853 }
8854 
8855 /*@
8856    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8857 
8858    Collective on Mat
8859 
8860    Input Parameter:
8861 .  A - the matrix to test
8862 
8863    Output Parameters:
8864 .  flg - the result
8865 
8866    Level: intermediate
8867 
8868    Concepts: matrix^symmetry
8869 
8870 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8871 @*/
8872 PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool  *flg)
8873 {
8874   PetscErrorCode ierr;
8875 
8876   PetscFunctionBegin;
8877   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8878   PetscValidPointer(flg,2);
8879   if (!A->structurally_symmetric_set) {
8880     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8881     ierr = (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);CHKERRQ(ierr);
8882 
8883     A->structurally_symmetric_set = PETSC_TRUE;
8884   }
8885   *flg = A->structurally_symmetric;
8886   PetscFunctionReturn(0);
8887 }
8888 
8889 /*@
8890    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8891        to be communicated to other processors during the MatAssemblyBegin/End() process
8892 
8893     Not collective
8894 
8895    Input Parameter:
8896 .   vec - the vector
8897 
8898    Output Parameters:
8899 +   nstash   - the size of the stash
8900 .   reallocs - the number of additional mallocs incurred.
8901 .   bnstash   - the size of the block stash
8902 -   breallocs - the number of additional mallocs incurred.in the block stash
8903 
8904    Level: advanced
8905 
8906 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8907 
8908 @*/
8909 PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8910 {
8911   PetscErrorCode ierr;
8912 
8913   PetscFunctionBegin;
8914   ierr = MatStashGetInfo_Private(&mat->stash,nstash,reallocs);CHKERRQ(ierr);
8915   ierr = MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);CHKERRQ(ierr);
8916   PetscFunctionReturn(0);
8917 }
8918 
8919 /*@C
8920    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8921      parallel layout
8922 
8923    Collective on Mat
8924 
8925    Input Parameter:
8926 .  mat - the matrix
8927 
8928    Output Parameter:
8929 +   right - (optional) vector that the matrix can be multiplied against
8930 -   left - (optional) vector that the matrix vector product can be stored in
8931 
8932    Notes:
8933     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().
8934 
8935   Notes:
8936     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8937 
8938   Level: advanced
8939 
8940 .seealso: MatCreate(), VecDestroy()
8941 @*/
8942 PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8943 {
8944   PetscErrorCode ierr;
8945 
8946   PetscFunctionBegin;
8947   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8948   PetscValidType(mat,1);
8949   if (mat->ops->getvecs) {
8950     ierr = (*mat->ops->getvecs)(mat,right,left);CHKERRQ(ierr);
8951   } else {
8952     PetscInt rbs,cbs;
8953     ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
8954     if (right) {
8955       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8956       ierr = VecCreate(PetscObjectComm((PetscObject)mat),right);CHKERRQ(ierr);
8957       ierr = VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8958       ierr = VecSetBlockSize(*right,cbs);CHKERRQ(ierr);
8959       ierr = VecSetType(*right,mat->defaultvectype);CHKERRQ(ierr);
8960       ierr = PetscLayoutReference(mat->cmap,&(*right)->map);CHKERRQ(ierr);
8961     }
8962     if (left) {
8963       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8964       ierr = VecCreate(PetscObjectComm((PetscObject)mat),left);CHKERRQ(ierr);
8965       ierr = VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8966       ierr = VecSetBlockSize(*left,rbs);CHKERRQ(ierr);
8967       ierr = VecSetType(*left,mat->defaultvectype);CHKERRQ(ierr);
8968       ierr = PetscLayoutReference(mat->rmap,&(*left)->map);CHKERRQ(ierr);
8969     }
8970   }
8971   PetscFunctionReturn(0);
8972 }
8973 
8974 /*@C
8975    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8976      with default values.
8977 
8978    Not Collective
8979 
8980    Input Parameters:
8981 .    info - the MatFactorInfo data structure
8982 
8983 
8984    Notes:
8985     The solvers are generally used through the KSP and PC objects, for example
8986           PCLU, PCILU, PCCHOLESKY, PCICC
8987 
8988    Level: developer
8989 
8990 .seealso: MatFactorInfo
8991 
8992     Developer Note: fortran interface is not autogenerated as the f90
8993     interface defintion cannot be generated correctly [due to MatFactorInfo]
8994 
8995 @*/
8996 
8997 PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8998 {
8999   PetscErrorCode ierr;
9000 
9001   PetscFunctionBegin;
9002   ierr = PetscMemzero(info,sizeof(MatFactorInfo));CHKERRQ(ierr);
9003   PetscFunctionReturn(0);
9004 }
9005 
9006 /*@
9007    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
9008 
9009    Collective on Mat
9010 
9011    Input Parameters:
9012 +  mat - the factored matrix
9013 -  is - the index set defining the Schur indices (0-based)
9014 
9015    Notes:
9016     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
9017 
9018    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
9019 
9020    Level: developer
9021 
9022    Concepts:
9023 
9024 .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
9025           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
9026 
9027 @*/
9028 PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
9029 {
9030   PetscErrorCode ierr,(*f)(Mat,IS);
9031 
9032   PetscFunctionBegin;
9033   PetscValidType(mat,1);
9034   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9035   PetscValidType(is,2);
9036   PetscValidHeaderSpecific(is,IS_CLASSID,2);
9037   PetscCheckSameComm(mat,1,is,2);
9038   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
9039   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);CHKERRQ(ierr);
9040   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");
9041   if (mat->schur) {
9042     ierr = MatDestroy(&mat->schur);CHKERRQ(ierr);
9043   }
9044   ierr = (*f)(mat,is);CHKERRQ(ierr);
9045   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
9046   ierr = MatFactorSetUpInPlaceSchur_Private(mat);CHKERRQ(ierr);
9047   PetscFunctionReturn(0);
9048 }
9049 
9050 /*@
9051   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
9052 
9053    Logically Collective on Mat
9054 
9055    Input Parameters:
9056 +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
9057 .  S - location where to return the Schur complement, can be NULL
9058 -  status - the status of the Schur complement matrix, can be NULL
9059 
9060    Notes:
9061    You must call MatFactorSetSchurIS() before calling this routine.
9062 
9063    The routine provides a copy of the Schur matrix stored within the solver data structures.
9064    The caller must destroy the object when it is no longer needed.
9065    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
9066 
9067    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)
9068 
9069    Developer Notes:
9070     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9071    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
9072 
9073    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
9074 
9075    Level: advanced
9076 
9077    References:
9078 
9079 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
9080 @*/
9081 PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9082 {
9083   PetscErrorCode ierr;
9084 
9085   PetscFunctionBegin;
9086   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9087   if (S) PetscValidPointer(S,2);
9088   if (status) PetscValidPointer(status,3);
9089   if (S) {
9090     PetscErrorCode (*f)(Mat,Mat*);
9091 
9092     ierr = PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);CHKERRQ(ierr);
9093     if (f) {
9094       ierr = (*f)(F,S);CHKERRQ(ierr);
9095     } else {
9096       ierr = MatDuplicate(F->schur,MAT_COPY_VALUES,S);CHKERRQ(ierr);
9097     }
9098   }
9099   if (status) *status = F->schur_status;
9100   PetscFunctionReturn(0);
9101 }
9102 
9103 /*@
9104   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
9105 
9106    Logically Collective on Mat
9107 
9108    Input Parameters:
9109 +  F - the factored matrix obtained by calling MatGetFactor()
9110 .  *S - location where to return the Schur complement, can be NULL
9111 -  status - the status of the Schur complement matrix, can be NULL
9112 
9113    Notes:
9114    You must call MatFactorSetSchurIS() before calling this routine.
9115 
9116    Schur complement mode is currently implemented for sequential matrices.
9117    The routine returns a the Schur Complement stored within the data strutures of the solver.
9118    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
9119    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
9120 
9121    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
9122 
9123    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
9124 
9125    Level: advanced
9126 
9127    References:
9128 
9129 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9130 @*/
9131 PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9132 {
9133   PetscFunctionBegin;
9134   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9135   if (S) PetscValidPointer(S,2);
9136   if (status) PetscValidPointer(status,3);
9137   if (S) *S = F->schur;
9138   if (status) *status = F->schur_status;
9139   PetscFunctionReturn(0);
9140 }
9141 
9142 /*@
9143   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
9144 
9145    Logically Collective on Mat
9146 
9147    Input Parameters:
9148 +  F - the factored matrix obtained by calling MatGetFactor()
9149 .  *S - location where the Schur complement is stored
9150 -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)
9151 
9152    Notes:
9153 
9154    Level: advanced
9155 
9156    References:
9157 
9158 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9159 @*/
9160 PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9161 {
9162   PetscErrorCode ierr;
9163 
9164   PetscFunctionBegin;
9165   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9166   if (S) {
9167     PetscValidHeaderSpecific(*S,MAT_CLASSID,2);
9168     *S = NULL;
9169   }
9170   F->schur_status = status;
9171   ierr = MatFactorUpdateSchurStatus_Private(F);CHKERRQ(ierr);
9172   PetscFunctionReturn(0);
9173 }
9174 
9175 /*@
9176   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
9177 
9178    Logically Collective on Mat
9179 
9180    Input Parameters:
9181 +  F - the factored matrix obtained by calling MatGetFactor()
9182 .  rhs - location where the right hand side of the Schur complement system is stored
9183 -  sol - location where the solution of the Schur complement system has to be returned
9184 
9185    Notes:
9186    The sizes of the vectors should match the size of the Schur complement
9187 
9188    Must be called after MatFactorSetSchurIS()
9189 
9190    Level: advanced
9191 
9192    References:
9193 
9194 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9195 @*/
9196 PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9197 {
9198   PetscErrorCode ierr;
9199 
9200   PetscFunctionBegin;
9201   PetscValidType(F,1);
9202   PetscValidType(rhs,2);
9203   PetscValidType(sol,3);
9204   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9205   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
9206   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
9207   PetscCheckSameComm(F,1,rhs,2);
9208   PetscCheckSameComm(F,1,sol,3);
9209   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9210   switch (F->schur_status) {
9211   case MAT_FACTOR_SCHUR_FACTORED:
9212     ierr = MatSolveTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
9213     break;
9214   case MAT_FACTOR_SCHUR_INVERTED:
9215     ierr = MatMultTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
9216     break;
9217   default:
9218     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9219     break;
9220   }
9221   PetscFunctionReturn(0);
9222 }
9223 
9224 /*@
9225   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
9226 
9227    Logically Collective on Mat
9228 
9229    Input Parameters:
9230 +  F - the factored matrix obtained by calling MatGetFactor()
9231 .  rhs - location where the right hand side of the Schur complement system is stored
9232 -  sol - location where the solution of the Schur complement system has to be returned
9233 
9234    Notes:
9235    The sizes of the vectors should match the size of the Schur complement
9236 
9237    Must be called after MatFactorSetSchurIS()
9238 
9239    Level: advanced
9240 
9241    References:
9242 
9243 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9244 @*/
9245 PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9246 {
9247   PetscErrorCode ierr;
9248 
9249   PetscFunctionBegin;
9250   PetscValidType(F,1);
9251   PetscValidType(rhs,2);
9252   PetscValidType(sol,3);
9253   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9254   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
9255   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
9256   PetscCheckSameComm(F,1,rhs,2);
9257   PetscCheckSameComm(F,1,sol,3);
9258   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9259   switch (F->schur_status) {
9260   case MAT_FACTOR_SCHUR_FACTORED:
9261     ierr = MatSolve(F->schur,rhs,sol);CHKERRQ(ierr);
9262     break;
9263   case MAT_FACTOR_SCHUR_INVERTED:
9264     ierr = MatMult(F->schur,rhs,sol);CHKERRQ(ierr);
9265     break;
9266   default:
9267     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9268     break;
9269   }
9270   PetscFunctionReturn(0);
9271 }
9272 
9273 /*@
9274   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9275 
9276    Logically Collective on Mat
9277 
9278    Input Parameters:
9279 +  F - the factored matrix obtained by calling MatGetFactor()
9280 
9281    Notes:
9282     Must be called after MatFactorSetSchurIS().
9283 
9284    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9285 
9286    Level: advanced
9287 
9288    References:
9289 
9290 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9291 @*/
9292 PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9293 {
9294   PetscErrorCode ierr;
9295 
9296   PetscFunctionBegin;
9297   PetscValidType(F,1);
9298   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9299   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(0);
9300   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9301   ierr = MatFactorInvertSchurComplement_Private(F);CHKERRQ(ierr);
9302   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9303   PetscFunctionReturn(0);
9304 }
9305 
9306 /*@
9307   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9308 
9309    Logically Collective on Mat
9310 
9311    Input Parameters:
9312 +  F - the factored matrix obtained by calling MatGetFactor()
9313 
9314    Notes:
9315     Must be called after MatFactorSetSchurIS().
9316 
9317    Level: advanced
9318 
9319    References:
9320 
9321 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9322 @*/
9323 PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9324 {
9325   PetscErrorCode ierr;
9326 
9327   PetscFunctionBegin;
9328   PetscValidType(F,1);
9329   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9330   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(0);
9331   ierr = MatFactorFactorizeSchurComplement_Private(F);CHKERRQ(ierr);
9332   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9333   PetscFunctionReturn(0);
9334 }
9335 
9336 /*@
9337    MatPtAP - Creates the matrix product C = P^T * A * P
9338 
9339    Neighbor-wise Collective on Mat
9340 
9341    Input Parameters:
9342 +  A - the matrix
9343 .  P - the projection matrix
9344 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9345 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9346           if the result is a dense matrix this is irrelevent
9347 
9348    Output Parameters:
9349 .  C - the product matrix
9350 
9351    Notes:
9352    C will be created and must be destroyed by the user with MatDestroy().
9353 
9354    This routine is currently only implemented for pairs of sequential dense matrices, AIJ matrices and classes
9355    which inherit from AIJ.
9356 
9357    Level: intermediate
9358 
9359 .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9360 @*/
9361 PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9362 {
9363   PetscErrorCode ierr;
9364   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9365   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9366   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9367   PetscBool      sametype;
9368 
9369   PetscFunctionBegin;
9370   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9371   PetscValidType(A,1);
9372   MatCheckPreallocated(A,1);
9373   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9374   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9375   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9376   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
9377   PetscValidType(P,2);
9378   MatCheckPreallocated(P,2);
9379   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9380   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9381 
9382   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);
9383   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);
9384   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9385   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9386 
9387   if (scall == MAT_REUSE_MATRIX) {
9388     PetscValidPointer(*C,5);
9389     PetscValidHeaderSpecific(*C,MAT_CLASSID,5);
9390 
9391     if (!(*C)->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You cannot use MAT_REUSE_MATRIX");
9392     ierr = PetscLogEventBegin(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9393     ierr = PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9394     ierr = (*(*C)->ops->ptapnumeric)(A,P,*C);CHKERRQ(ierr);
9395     ierr = PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9396     ierr = PetscLogEventEnd(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9397     PetscFunctionReturn(0);
9398   }
9399 
9400   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9401   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9402 
9403   fA = A->ops->ptap;
9404   fP = P->ops->ptap;
9405   ierr = PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);CHKERRQ(ierr);
9406   if (fP == fA && sametype) {
9407     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatPtAP not supported for A of type %s",((PetscObject)A)->type_name);
9408     ptap = fA;
9409   } else {
9410     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9411     char ptapname[256];
9412     ierr = PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));CHKERRQ(ierr);
9413     ierr = PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));CHKERRQ(ierr);
9414     ierr = PetscStrlcat(ptapname,"_",sizeof(ptapname));CHKERRQ(ierr);
9415     ierr = PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));CHKERRQ(ierr);
9416     ierr = PetscStrlcat(ptapname,"_C",sizeof(ptapname));CHKERRQ(ierr); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9417     ierr = PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);CHKERRQ(ierr);
9418     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);
9419   }
9420 
9421   ierr = PetscLogEventBegin(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9422   ierr = (*ptap)(A,P,scall,fill,C);CHKERRQ(ierr);
9423   ierr = PetscLogEventEnd(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9424   if (A->symmetric_set && A->symmetric) {
9425     ierr = MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
9426   }
9427   PetscFunctionReturn(0);
9428 }
9429 
9430 /*@
9431    MatPtAPNumeric - Computes the matrix product C = P^T * A * P
9432 
9433    Neighbor-wise Collective on Mat
9434 
9435    Input Parameters:
9436 +  A - the matrix
9437 -  P - the projection matrix
9438 
9439    Output Parameters:
9440 .  C - the product matrix
9441 
9442    Notes:
9443    C must have been created by calling MatPtAPSymbolic and must be destroyed by
9444    the user using MatDeatroy().
9445 
9446    This routine is currently only implemented for pairs of AIJ matrices and classes
9447    which inherit from AIJ.  C will be of type MATAIJ.
9448 
9449    Level: intermediate
9450 
9451 .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9452 @*/
9453 PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9454 {
9455   PetscErrorCode ierr;
9456 
9457   PetscFunctionBegin;
9458   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9459   PetscValidType(A,1);
9460   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9461   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9462   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
9463   PetscValidType(P,2);
9464   MatCheckPreallocated(P,2);
9465   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9466   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9467   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
9468   PetscValidType(C,3);
9469   MatCheckPreallocated(C,3);
9470   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9471   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);
9472   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);
9473   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);
9474   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);
9475   MatCheckPreallocated(A,1);
9476 
9477   if (!C->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You should call MatPtAPSymbolic first");
9478   ierr = PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9479   ierr = (*C->ops->ptapnumeric)(A,P,C);CHKERRQ(ierr);
9480   ierr = PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9481   PetscFunctionReturn(0);
9482 }
9483 
9484 /*@
9485    MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P
9486 
9487    Neighbor-wise Collective on Mat
9488 
9489    Input Parameters:
9490 +  A - the matrix
9491 -  P - the projection matrix
9492 
9493    Output Parameters:
9494 .  C - the (i,j) structure of the product matrix
9495 
9496    Notes:
9497    C will be created and must be destroyed by the user with MatDestroy().
9498 
9499    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9500    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
9501    this (i,j) structure by calling MatPtAPNumeric().
9502 
9503    Level: intermediate
9504 
9505 .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
9506 @*/
9507 PetscErrorCode MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
9508 {
9509   PetscErrorCode ierr;
9510 
9511   PetscFunctionBegin;
9512   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9513   PetscValidType(A,1);
9514   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9515   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9516   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9517   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
9518   PetscValidType(P,2);
9519   MatCheckPreallocated(P,2);
9520   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9521   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9522   PetscValidPointer(C,3);
9523 
9524   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);
9525   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);
9526   MatCheckPreallocated(A,1);
9527 
9528   if (!A->ops->ptapsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatType %s",((PetscObject)A)->type_name);
9529   ierr = PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);CHKERRQ(ierr);
9530   ierr = (*A->ops->ptapsymbolic)(A,P,fill,C);CHKERRQ(ierr);
9531   ierr = PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);CHKERRQ(ierr);
9532 
9533   /* ierr = MatSetBlockSize(*C,A->rmap->bs);CHKERRQ(ierr); NO! this is not always true -ma */
9534   PetscFunctionReturn(0);
9535 }
9536 
9537 /*@
9538    MatRARt - Creates the matrix product C = R * A * R^T
9539 
9540    Neighbor-wise Collective on Mat
9541 
9542    Input Parameters:
9543 +  A - the matrix
9544 .  R - the projection matrix
9545 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9546 -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9547           if the result is a dense matrix this is irrelevent
9548 
9549    Output Parameters:
9550 .  C - the product matrix
9551 
9552    Notes:
9553    C will be created and must be destroyed by the user with MatDestroy().
9554 
9555    This routine is currently only implemented for pairs of AIJ matrices and classes
9556    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9557    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9558    We recommend using MatPtAP().
9559 
9560    Level: intermediate
9561 
9562 .seealso: MatRARtSymbolic(), MatRARtNumeric(), MatMatMult(), MatPtAP()
9563 @*/
9564 PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9565 {
9566   PetscErrorCode ierr;
9567 
9568   PetscFunctionBegin;
9569   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9570   PetscValidType(A,1);
9571   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9572   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9573   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9574   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
9575   PetscValidType(R,2);
9576   MatCheckPreallocated(R,2);
9577   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9578   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9579   PetscValidPointer(C,3);
9580   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);
9581 
9582   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9583   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9584   MatCheckPreallocated(A,1);
9585 
9586   if (!A->ops->rart) {
9587     Mat Rt;
9588     ierr = MatTranspose(R,MAT_INITIAL_MATRIX,&Rt);CHKERRQ(ierr);
9589     ierr = MatMatMatMult(R,A,Rt,scall,fill,C);CHKERRQ(ierr);
9590     ierr = MatDestroy(&Rt);CHKERRQ(ierr);
9591     PetscFunctionReturn(0);
9592   }
9593   ierr = PetscLogEventBegin(MAT_RARt,A,R,0,0);CHKERRQ(ierr);
9594   ierr = (*A->ops->rart)(A,R,scall,fill,C);CHKERRQ(ierr);
9595   ierr = PetscLogEventEnd(MAT_RARt,A,R,0,0);CHKERRQ(ierr);
9596   PetscFunctionReturn(0);
9597 }
9598 
9599 /*@
9600    MatRARtNumeric - Computes the matrix product C = R * A * R^T
9601 
9602    Neighbor-wise Collective on Mat
9603 
9604    Input Parameters:
9605 +  A - the matrix
9606 -  R - the projection matrix
9607 
9608    Output Parameters:
9609 .  C - the product matrix
9610 
9611    Notes:
9612    C must have been created by calling MatRARtSymbolic and must be destroyed by
9613    the user using MatDestroy().
9614 
9615    This routine is currently only implemented for pairs of AIJ matrices and classes
9616    which inherit from AIJ.  C will be of type MATAIJ.
9617 
9618    Level: intermediate
9619 
9620 .seealso: MatRARt(), MatRARtSymbolic(), MatMatMultNumeric()
9621 @*/
9622 PetscErrorCode MatRARtNumeric(Mat A,Mat R,Mat C)
9623 {
9624   PetscErrorCode ierr;
9625 
9626   PetscFunctionBegin;
9627   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9628   PetscValidType(A,1);
9629   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9630   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9631   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
9632   PetscValidType(R,2);
9633   MatCheckPreallocated(R,2);
9634   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9635   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9636   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
9637   PetscValidType(C,3);
9638   MatCheckPreallocated(C,3);
9639   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9640   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);
9641   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);
9642   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);
9643   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);
9644   MatCheckPreallocated(A,1);
9645 
9646   ierr = PetscLogEventBegin(MAT_RARtNumeric,A,R,0,0);CHKERRQ(ierr);
9647   ierr = (*A->ops->rartnumeric)(A,R,C);CHKERRQ(ierr);
9648   ierr = PetscLogEventEnd(MAT_RARtNumeric,A,R,0,0);CHKERRQ(ierr);
9649   PetscFunctionReturn(0);
9650 }
9651 
9652 /*@
9653    MatRARtSymbolic - Creates the (i,j) structure of the matrix product C = R * A * R^T
9654 
9655    Neighbor-wise Collective on Mat
9656 
9657    Input Parameters:
9658 +  A - the matrix
9659 -  R - the projection matrix
9660 
9661    Output Parameters:
9662 .  C - the (i,j) structure of the product matrix
9663 
9664    Notes:
9665    C will be created and must be destroyed by the user with MatDestroy().
9666 
9667    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9668    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
9669    this (i,j) structure by calling MatRARtNumeric().
9670 
9671    Level: intermediate
9672 
9673 .seealso: MatRARt(), MatRARtNumeric(), MatMatMultSymbolic()
9674 @*/
9675 PetscErrorCode MatRARtSymbolic(Mat A,Mat R,PetscReal fill,Mat *C)
9676 {
9677   PetscErrorCode ierr;
9678 
9679   PetscFunctionBegin;
9680   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9681   PetscValidType(A,1);
9682   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9683   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9684   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9685   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
9686   PetscValidType(R,2);
9687   MatCheckPreallocated(R,2);
9688   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9689   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9690   PetscValidPointer(C,3);
9691 
9692   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);
9693   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);
9694   MatCheckPreallocated(A,1);
9695   ierr = PetscLogEventBegin(MAT_RARtSymbolic,A,R,0,0);CHKERRQ(ierr);
9696   ierr = (*A->ops->rartsymbolic)(A,R,fill,C);CHKERRQ(ierr);
9697   ierr = PetscLogEventEnd(MAT_RARtSymbolic,A,R,0,0);CHKERRQ(ierr);
9698 
9699   ierr = MatSetBlockSizes(*C,PetscAbs(R->rmap->bs),PetscAbs(R->rmap->bs));CHKERRQ(ierr);
9700   PetscFunctionReturn(0);
9701 }
9702 
9703 /*@
9704    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
9705 
9706    Neighbor-wise Collective on Mat
9707 
9708    Input Parameters:
9709 +  A - the left matrix
9710 .  B - the right matrix
9711 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9712 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9713           if the result is a dense matrix this is irrelevent
9714 
9715    Output Parameters:
9716 .  C - the product matrix
9717 
9718    Notes:
9719    Unless scall is MAT_REUSE_MATRIX C will be created.
9720 
9721    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
9722    call to this function with either MAT_INITIAL_MATRIX or MatMatMultSymbolic()
9723 
9724    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9725    actually needed.
9726 
9727    If you have many matrices with the same non-zero structure to multiply, you
9728    should either
9729 $   1) use MAT_REUSE_MATRIX in all calls but the first or
9730 $   2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed
9731    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
9732    with MAT_REUSE_MATRIX, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.
9733 
9734    Level: intermediate
9735 
9736 .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatTransposeMatMult(),  MatMatTransposeMult(), MatPtAP()
9737 @*/
9738 PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9739 {
9740   PetscErrorCode ierr;
9741   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9742   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9743   PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9744 
9745   PetscFunctionBegin;
9746   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9747   PetscValidType(A,1);
9748   MatCheckPreallocated(A,1);
9749   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9750   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9751   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9752   PetscValidType(B,2);
9753   MatCheckPreallocated(B,2);
9754   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9755   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9756   PetscValidPointer(C,3);
9757   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9758   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);
9759   if (scall == MAT_REUSE_MATRIX) {
9760     PetscValidPointer(*C,5);
9761     PetscValidHeaderSpecific(*C,MAT_CLASSID,5);
9762     ierr = PetscLogEventBegin(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9763     ierr = PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
9764     ierr = (*(*C)->ops->matmultnumeric)(A,B,*C);CHKERRQ(ierr);
9765     ierr = PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
9766     ierr = PetscLogEventEnd(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9767     PetscFunctionReturn(0);
9768   }
9769   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9770   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9771 
9772   fA = A->ops->matmult;
9773   fB = B->ops->matmult;
9774   if (fB == fA) {
9775     if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",((PetscObject)B)->type_name);
9776     mult = fB;
9777   } else {
9778     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9779     char multname[256];
9780     ierr = PetscStrncpy(multname,"MatMatMult_",sizeof(multname));CHKERRQ(ierr);
9781     ierr = PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));CHKERRQ(ierr);
9782     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
9783     ierr = PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));CHKERRQ(ierr);
9784     ierr = PetscStrlcat(multname,"_C",sizeof(multname));CHKERRQ(ierr); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9785     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&mult);CHKERRQ(ierr);
9786     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);
9787   }
9788   ierr = PetscLogEventBegin(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9789   ierr = (*mult)(A,B,scall,fill,C);CHKERRQ(ierr);
9790   ierr = PetscLogEventEnd(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9791   PetscFunctionReturn(0);
9792 }
9793 
9794 /*@
9795    MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
9796    of the matrix-matrix product C=A*B.  Call this routine before calling MatMatMultNumeric().
9797 
9798    Neighbor-wise Collective on Mat
9799 
9800    Input Parameters:
9801 +  A - the left matrix
9802 .  B - the right matrix
9803 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate,
9804       if C is a dense matrix this is irrelevent
9805 
9806    Output Parameters:
9807 .  C - the product matrix
9808 
9809    Notes:
9810    Unless scall is MAT_REUSE_MATRIX C will be created.
9811 
9812    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9813    actually needed.
9814 
9815    This routine is currently implemented for
9816     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type AIJ
9817     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9818     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9819 
9820    Level: intermediate
9821 
9822    Developers Note: There are ways to estimate the number of nonzeros in the resulting product, see for example, http://arxiv.org/abs/1006.4173
9823      We should incorporate them into PETSc.
9824 
9825 .seealso: MatMatMult(), MatMatMultNumeric()
9826 @*/
9827 PetscErrorCode MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
9828 {
9829   PetscErrorCode ierr;
9830   PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat*);
9831   PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat*);
9832   PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat*)=NULL;
9833 
9834   PetscFunctionBegin;
9835   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9836   PetscValidType(A,1);
9837   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9838   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9839 
9840   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9841   PetscValidType(B,2);
9842   MatCheckPreallocated(B,2);
9843   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9844   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9845   PetscValidPointer(C,3);
9846 
9847   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);
9848   if (fill == PETSC_DEFAULT) fill = 2.0;
9849   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9850   MatCheckPreallocated(A,1);
9851 
9852   Asymbolic = A->ops->matmultsymbolic;
9853   Bsymbolic = B->ops->matmultsymbolic;
9854   if (Asymbolic == Bsymbolic) {
9855     if (!Bsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
9856     symbolic = Bsymbolic;
9857   } else { /* dispatch based on the type of A and B */
9858     char symbolicname[256];
9859     ierr = PetscStrncpy(symbolicname,"MatMatMultSymbolic_",sizeof(symbolicname));CHKERRQ(ierr);
9860     ierr = PetscStrlcat(symbolicname,((PetscObject)A)->type_name,sizeof(symbolicname));CHKERRQ(ierr);
9861     ierr = PetscStrlcat(symbolicname,"_",sizeof(symbolicname));CHKERRQ(ierr);
9862     ierr = PetscStrlcat(symbolicname,((PetscObject)B)->type_name,sizeof(symbolicname));CHKERRQ(ierr);
9863     ierr = PetscStrlcat(symbolicname,"_C",sizeof(symbolicname));CHKERRQ(ierr);
9864     ierr = PetscObjectQueryFunction((PetscObject)B,symbolicname,&symbolic);CHKERRQ(ierr);
9865     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);
9866   }
9867   ierr = PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9868   ierr = (*symbolic)(A,B,fill,C);CHKERRQ(ierr);
9869   ierr = PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9870   PetscFunctionReturn(0);
9871 }
9872 
9873 /*@
9874    MatMatMultNumeric - Performs the numeric matrix-matrix product.
9875    Call this routine after first calling MatMatMultSymbolic().
9876 
9877    Neighbor-wise Collective on Mat
9878 
9879    Input Parameters:
9880 +  A - the left matrix
9881 -  B - the right matrix
9882 
9883    Output Parameters:
9884 .  C - the product matrix, which was created by from MatMatMultSymbolic() or a call to MatMatMult().
9885 
9886    Notes:
9887    C must have been created with MatMatMultSymbolic().
9888 
9889    This routine is currently implemented for
9890     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
9891     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9892     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9893 
9894    Level: intermediate
9895 
9896 .seealso: MatMatMult(), MatMatMultSymbolic()
9897 @*/
9898 PetscErrorCode MatMatMultNumeric(Mat A,Mat B,Mat C)
9899 {
9900   PetscErrorCode ierr;
9901 
9902   PetscFunctionBegin;
9903   ierr = MatMatMult(A,B,MAT_REUSE_MATRIX,0.0,&C);CHKERRQ(ierr);
9904   PetscFunctionReturn(0);
9905 }
9906 
9907 /*@
9908    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9909 
9910    Neighbor-wise Collective on Mat
9911 
9912    Input Parameters:
9913 +  A - the left matrix
9914 .  B - the right matrix
9915 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9916 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9917 
9918    Output Parameters:
9919 .  C - the product matrix
9920 
9921    Notes:
9922    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9923 
9924    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9925 
9926   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9927    actually needed.
9928 
9929    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9930    and for pairs of MPIDense matrices.
9931 
9932    Options Database Keys:
9933 +  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9934                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9935                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.
9936 
9937    Level: intermediate
9938 
9939 .seealso: MatMatTransposeMultSymbolic(), MatMatTransposeMultNumeric(), MatMatMult(), MatTransposeMatMult() MatPtAP()
9940 @*/
9941 PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9942 {
9943   PetscErrorCode ierr;
9944   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9945   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9946 
9947   PetscFunctionBegin;
9948   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9949   PetscValidType(A,1);
9950   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9951   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9952   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9953   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9954   PetscValidType(B,2);
9955   MatCheckPreallocated(B,2);
9956   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9957   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9958   PetscValidPointer(C,3);
9959   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);
9960   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9961   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9962   MatCheckPreallocated(A,1);
9963 
9964   fA = A->ops->mattransposemult;
9965   if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for A of type %s",((PetscObject)A)->type_name);
9966   fB = B->ops->mattransposemult;
9967   if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for B of type %s",((PetscObject)B)->type_name);
9968   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);
9969 
9970   ierr = PetscLogEventBegin(MAT_MatTransposeMult,A,B,0,0);CHKERRQ(ierr);
9971   if (scall == MAT_INITIAL_MATRIX) {
9972     ierr = PetscLogEventBegin(MAT_MatTransposeMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9973     ierr = (*A->ops->mattransposemultsymbolic)(A,B,fill,C);CHKERRQ(ierr);
9974     ierr = PetscLogEventEnd(MAT_MatTransposeMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9975   }
9976   ierr = PetscLogEventBegin(MAT_MatTransposeMultNumeric,A,B,0,0);CHKERRQ(ierr);
9977   ierr = (*A->ops->mattransposemultnumeric)(A,B,*C);CHKERRQ(ierr);
9978   ierr = PetscLogEventEnd(MAT_MatTransposeMultNumeric,A,B,0,0);CHKERRQ(ierr);
9979   ierr = PetscLogEventEnd(MAT_MatTransposeMult,A,B,0,0);CHKERRQ(ierr);
9980   PetscFunctionReturn(0);
9981 }
9982 
9983 /*@
9984    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
9985 
9986    Neighbor-wise Collective on Mat
9987 
9988    Input Parameters:
9989 +  A - the left matrix
9990 .  B - the right matrix
9991 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9992 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9993 
9994    Output Parameters:
9995 .  C - the product matrix
9996 
9997    Notes:
9998    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9999 
10000    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
10001 
10002   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10003    actually needed.
10004 
10005    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
10006    which inherit from SeqAIJ.  C will be of same type as the input matrices.
10007 
10008    Level: intermediate
10009 
10010 .seealso: MatTransposeMatMultSymbolic(), MatTransposeMatMultNumeric(), MatMatMult(), MatMatTransposeMult(), MatPtAP()
10011 @*/
10012 PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
10013 {
10014   PetscErrorCode ierr;
10015   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
10016   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
10017   PetscErrorCode (*transposematmult)(Mat,Mat,MatReuse,PetscReal,Mat*) = NULL;
10018 
10019   PetscFunctionBegin;
10020   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
10021   PetscValidType(A,1);
10022   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10023   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10024   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10025   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
10026   PetscValidType(B,2);
10027   MatCheckPreallocated(B,2);
10028   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10029   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10030   PetscValidPointer(C,3);
10031   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);
10032   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
10033   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
10034   MatCheckPreallocated(A,1);
10035 
10036   fA = A->ops->transposematmult;
10037   fB = B->ops->transposematmult;
10038   if (fB==fA) {
10039     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatTransposeMatMult not supported for A of type %s",((PetscObject)A)->type_name);
10040     transposematmult = fA;
10041   } else {
10042     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
10043     char multname[256];
10044     ierr = PetscStrncpy(multname,"MatTransposeMatMult_",sizeof(multname));CHKERRQ(ierr);
10045     ierr = PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));CHKERRQ(ierr);
10046     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
10047     ierr = PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));CHKERRQ(ierr);
10048     ierr = PetscStrlcat(multname,"_C",sizeof(multname));CHKERRQ(ierr); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
10049     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&transposematmult);CHKERRQ(ierr);
10050     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);
10051   }
10052   ierr = PetscLogEventBegin(MAT_TransposeMatMult,A,B,0,0);CHKERRQ(ierr);
10053   ierr = (*transposematmult)(A,B,scall,fill,C);CHKERRQ(ierr);
10054   ierr = PetscLogEventEnd(MAT_TransposeMatMult,A,B,0,0);CHKERRQ(ierr);
10055   PetscFunctionReturn(0);
10056 }
10057 
10058 /*@
10059    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
10060 
10061    Neighbor-wise Collective on Mat
10062 
10063    Input Parameters:
10064 +  A - the left matrix
10065 .  B - the middle matrix
10066 .  C - the right matrix
10067 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10068 -  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
10069           if the result is a dense matrix this is irrelevent
10070 
10071    Output Parameters:
10072 .  D - the product matrix
10073 
10074    Notes:
10075    Unless scall is MAT_REUSE_MATRIX D will be created.
10076 
10077    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
10078 
10079    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10080    actually needed.
10081 
10082    If you have many matrices with the same non-zero structure to multiply, you
10083    should use MAT_REUSE_MATRIX in all calls but the first or
10084 
10085    Level: intermediate
10086 
10087 .seealso: MatMatMult, MatPtAP()
10088 @*/
10089 PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
10090 {
10091   PetscErrorCode ierr;
10092   PetscErrorCode (*fA)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
10093   PetscErrorCode (*fB)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
10094   PetscErrorCode (*fC)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
10095   PetscErrorCode (*mult)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
10096 
10097   PetscFunctionBegin;
10098   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
10099   PetscValidType(A,1);
10100   MatCheckPreallocated(A,1);
10101   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10102   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10103   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10104   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
10105   PetscValidType(B,2);
10106   MatCheckPreallocated(B,2);
10107   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10108   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10109   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
10110   PetscValidPointer(C,3);
10111   MatCheckPreallocated(C,3);
10112   if (!C->assembled) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10113   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10114   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);
10115   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);
10116   if (scall == MAT_REUSE_MATRIX) {
10117     PetscValidPointer(*D,6);
10118     PetscValidHeaderSpecific(*D,MAT_CLASSID,6);
10119     ierr = PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
10120     ierr = (*(*D)->ops->matmatmult)(A,B,C,scall,fill,D);CHKERRQ(ierr);
10121     ierr = PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
10122     PetscFunctionReturn(0);
10123   }
10124   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
10125   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
10126 
10127   fA = A->ops->matmatmult;
10128   fB = B->ops->matmatmult;
10129   fC = C->ops->matmatmult;
10130   if (fA == fB && fA == fC) {
10131     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMatMult not supported for A of type %s",((PetscObject)A)->type_name);
10132     mult = fA;
10133   } else {
10134     /* dispatch based on the type of A, B and C from their PetscObject's PetscFunctionLists. */
10135     char multname[256];
10136     ierr = PetscStrncpy(multname,"MatMatMatMult_",sizeof(multname));CHKERRQ(ierr);
10137     ierr = PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));CHKERRQ(ierr);
10138     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
10139     ierr = PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));CHKERRQ(ierr);
10140     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
10141     ierr = PetscStrlcat(multname,((PetscObject)C)->type_name,sizeof(multname));CHKERRQ(ierr);
10142     ierr = PetscStrlcat(multname,"_C",sizeof(multname));CHKERRQ(ierr);
10143     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&mult);CHKERRQ(ierr);
10144     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);
10145   }
10146   ierr = PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
10147   ierr = (*mult)(A,B,C,scall,fill,D);CHKERRQ(ierr);
10148   ierr = PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
10149   PetscFunctionReturn(0);
10150 }
10151 
10152 /*@
10153    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
10154 
10155    Collective on Mat
10156 
10157    Input Parameters:
10158 +  mat - the matrix
10159 .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10160 .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
10161 -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10162 
10163    Output Parameter:
10164 .  matredundant - redundant matrix
10165 
10166    Notes:
10167    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
10168    original matrix has not changed from that last call to MatCreateRedundantMatrix().
10169 
10170    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
10171    calling it.
10172 
10173    Level: advanced
10174 
10175    Concepts: subcommunicator
10176    Concepts: duplicate matrix
10177 
10178 .seealso: MatDestroy()
10179 @*/
10180 PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
10181 {
10182   PetscErrorCode ierr;
10183   MPI_Comm       comm;
10184   PetscMPIInt    size;
10185   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
10186   Mat_Redundant  *redund=NULL;
10187   PetscSubcomm   psubcomm=NULL;
10188   MPI_Comm       subcomm_in=subcomm;
10189   Mat            *matseq;
10190   IS             isrow,iscol;
10191   PetscBool      newsubcomm=PETSC_FALSE;
10192 
10193   PetscFunctionBegin;
10194   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10195   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10196     PetscValidPointer(*matredundant,5);
10197     PetscValidHeaderSpecific(*matredundant,MAT_CLASSID,5);
10198   }
10199 
10200   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
10201   if (size == 1 || nsubcomm == 1) {
10202     if (reuse == MAT_INITIAL_MATRIX) {
10203       ierr = MatDuplicate(mat,MAT_COPY_VALUES,matredundant);CHKERRQ(ierr);
10204     } else {
10205       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");
10206       ierr = MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
10207     }
10208     PetscFunctionReturn(0);
10209   }
10210 
10211   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10212   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10213   MatCheckPreallocated(mat,1);
10214 
10215   ierr = PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
10216   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10217     /* create psubcomm, then get subcomm */
10218     ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
10219     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
10220     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
10221 
10222     ierr = PetscSubcommCreate(comm,&psubcomm);CHKERRQ(ierr);
10223     ierr = PetscSubcommSetNumber(psubcomm,nsubcomm);CHKERRQ(ierr);
10224     ierr = PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);CHKERRQ(ierr);
10225     ierr = PetscSubcommSetFromOptions(psubcomm);CHKERRQ(ierr);
10226     ierr = PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);CHKERRQ(ierr);
10227     newsubcomm = PETSC_TRUE;
10228     ierr = PetscSubcommDestroy(&psubcomm);CHKERRQ(ierr);
10229   }
10230 
10231   /* get isrow, iscol and a local sequential matrix matseq[0] */
10232   if (reuse == MAT_INITIAL_MATRIX) {
10233     mloc_sub = PETSC_DECIDE;
10234     nloc_sub = PETSC_DECIDE;
10235     if (bs < 1) {
10236       ierr = PetscSplitOwnership(subcomm,&mloc_sub,&M);CHKERRQ(ierr);
10237       ierr = PetscSplitOwnership(subcomm,&nloc_sub,&N);CHKERRQ(ierr);
10238     } else {
10239       ierr = PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);CHKERRQ(ierr);
10240       ierr = PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);CHKERRQ(ierr);
10241     }
10242     ierr = MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);CHKERRQ(ierr);
10243     rstart = rend - mloc_sub;
10244     ierr = ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);CHKERRQ(ierr);
10245     ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);CHKERRQ(ierr);
10246   } else { /* reuse == MAT_REUSE_MATRIX */
10247     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");
10248     /* retrieve subcomm */
10249     ierr = PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);CHKERRQ(ierr);
10250     redund = (*matredundant)->redundant;
10251     isrow  = redund->isrow;
10252     iscol  = redund->iscol;
10253     matseq = redund->matseq;
10254   }
10255   ierr = MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);CHKERRQ(ierr);
10256 
10257   /* get matredundant over subcomm */
10258   if (reuse == MAT_INITIAL_MATRIX) {
10259     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);CHKERRQ(ierr);
10260 
10261     /* create a supporting struct and attach it to C for reuse */
10262     ierr = PetscNewLog(*matredundant,&redund);CHKERRQ(ierr);
10263     (*matredundant)->redundant = redund;
10264     redund->isrow              = isrow;
10265     redund->iscol              = iscol;
10266     redund->matseq             = matseq;
10267     if (newsubcomm) {
10268       redund->subcomm          = subcomm;
10269     } else {
10270       redund->subcomm          = MPI_COMM_NULL;
10271     }
10272   } else {
10273     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);CHKERRQ(ierr);
10274   }
10275   ierr = PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
10276   PetscFunctionReturn(0);
10277 }
10278 
10279 /*@C
10280    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
10281    a given 'mat' object. Each submatrix can span multiple procs.
10282 
10283    Collective on Mat
10284 
10285    Input Parameters:
10286 +  mat - the matrix
10287 .  subcomm - the subcommunicator obtained by com_split(comm)
10288 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10289 
10290    Output Parameter:
10291 .  subMat - 'parallel submatrices each spans a given subcomm
10292 
10293   Notes:
10294   The submatrix partition across processors is dictated by 'subComm' a
10295   communicator obtained by com_split(comm). The comm_split
10296   is not restriced to be grouped with consecutive original ranks.
10297 
10298   Due the comm_split() usage, the parallel layout of the submatrices
10299   map directly to the layout of the original matrix [wrt the local
10300   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10301   into the 'DiagonalMat' of the subMat, hence it is used directly from
10302   the subMat. However the offDiagMat looses some columns - and this is
10303   reconstructed with MatSetValues()
10304 
10305   Level: advanced
10306 
10307   Concepts: subcommunicator
10308   Concepts: submatrices
10309 
10310 .seealso: MatCreateSubMatrices()
10311 @*/
10312 PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
10313 {
10314   PetscErrorCode ierr;
10315   PetscMPIInt    commsize,subCommSize;
10316 
10317   PetscFunctionBegin;
10318   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);CHKERRQ(ierr);
10319   ierr = MPI_Comm_size(subComm,&subCommSize);CHKERRQ(ierr);
10320   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
10321 
10322   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");
10323   ierr = PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
10324   ierr = (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);CHKERRQ(ierr);
10325   ierr = PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
10326   PetscFunctionReturn(0);
10327 }
10328 
10329 /*@
10330    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10331 
10332    Not Collective
10333 
10334    Input Arguments:
10335    mat - matrix to extract local submatrix from
10336    isrow - local row indices for submatrix
10337    iscol - local column indices for submatrix
10338 
10339    Output Arguments:
10340    submat - the submatrix
10341 
10342    Level: intermediate
10343 
10344    Notes:
10345    The submat should be returned with MatRestoreLocalSubMatrix().
10346 
10347    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
10348    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
10349 
10350    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
10351    MatSetValuesBlockedLocal() will also be implemented.
10352 
10353    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
10354    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.
10355 
10356 .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
10357 @*/
10358 PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10359 {
10360   PetscErrorCode ierr;
10361 
10362   PetscFunctionBegin;
10363   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10364   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
10365   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
10366   PetscCheckSameComm(isrow,2,iscol,3);
10367   PetscValidPointer(submat,4);
10368   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");
10369 
10370   if (mat->ops->getlocalsubmatrix) {
10371     ierr = (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
10372   } else {
10373     ierr = MatCreateLocalRef(mat,isrow,iscol,submat);CHKERRQ(ierr);
10374   }
10375   PetscFunctionReturn(0);
10376 }
10377 
10378 /*@
10379    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
10380 
10381    Not Collective
10382 
10383    Input Arguments:
10384    mat - matrix to extract local submatrix from
10385    isrow - local row indices for submatrix
10386    iscol - local column indices for submatrix
10387    submat - the submatrix
10388 
10389    Level: intermediate
10390 
10391 .seealso: MatGetLocalSubMatrix()
10392 @*/
10393 PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10394 {
10395   PetscErrorCode ierr;
10396 
10397   PetscFunctionBegin;
10398   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10399   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
10400   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
10401   PetscCheckSameComm(isrow,2,iscol,3);
10402   PetscValidPointer(submat,4);
10403   if (*submat) {
10404     PetscValidHeaderSpecific(*submat,MAT_CLASSID,4);
10405   }
10406 
10407   if (mat->ops->restorelocalsubmatrix) {
10408     ierr = (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
10409   } else {
10410     ierr = MatDestroy(submat);CHKERRQ(ierr);
10411   }
10412   *submat = NULL;
10413   PetscFunctionReturn(0);
10414 }
10415 
10416 /* --------------------------------------------------------*/
10417 /*@
10418    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
10419 
10420    Collective on Mat
10421 
10422    Input Parameter:
10423 .  mat - the matrix
10424 
10425    Output Parameter:
10426 .  is - if any rows have zero diagonals this contains the list of them
10427 
10428    Level: developer
10429 
10430    Concepts: matrix-vector product
10431 
10432 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10433 @*/
10434 PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
10435 {
10436   PetscErrorCode ierr;
10437 
10438   PetscFunctionBegin;
10439   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10440   PetscValidType(mat,1);
10441   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10442   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10443 
10444   if (!mat->ops->findzerodiagonals) {
10445     Vec                diag;
10446     const PetscScalar *a;
10447     PetscInt          *rows;
10448     PetscInt           rStart, rEnd, r, nrow = 0;
10449 
10450     ierr = MatCreateVecs(mat, &diag, NULL);CHKERRQ(ierr);
10451     ierr = MatGetDiagonal(mat, diag);CHKERRQ(ierr);
10452     ierr = MatGetOwnershipRange(mat, &rStart, &rEnd);CHKERRQ(ierr);
10453     ierr = VecGetArrayRead(diag, &a);CHKERRQ(ierr);
10454     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
10455     ierr = PetscMalloc1(nrow, &rows);CHKERRQ(ierr);
10456     nrow = 0;
10457     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
10458     ierr = VecRestoreArrayRead(diag, &a);CHKERRQ(ierr);
10459     ierr = VecDestroy(&diag);CHKERRQ(ierr);
10460     ierr = ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);CHKERRQ(ierr);
10461   } else {
10462     ierr = (*mat->ops->findzerodiagonals)(mat, is);CHKERRQ(ierr);
10463   }
10464   PetscFunctionReturn(0);
10465 }
10466 
10467 /*@
10468    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
10469 
10470    Collective on Mat
10471 
10472    Input Parameter:
10473 .  mat - the matrix
10474 
10475    Output Parameter:
10476 .  is - contains the list of rows with off block diagonal entries
10477 
10478    Level: developer
10479 
10480    Concepts: matrix-vector product
10481 
10482 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10483 @*/
10484 PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
10485 {
10486   PetscErrorCode ierr;
10487 
10488   PetscFunctionBegin;
10489   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10490   PetscValidType(mat,1);
10491   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10492   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10493 
10494   if (!mat->ops->findoffblockdiagonalentries) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find off block diagonal entries defined");
10495   ierr = (*mat->ops->findoffblockdiagonalentries)(mat,is);CHKERRQ(ierr);
10496   PetscFunctionReturn(0);
10497 }
10498 
10499 /*@C
10500   MatInvertBlockDiagonal - Inverts the block diagonal entries.
10501 
10502   Collective on Mat
10503 
10504   Input Parameters:
10505 . mat - the matrix
10506 
10507   Output Parameters:
10508 . values - the block inverses in column major order (FORTRAN-like)
10509 
10510    Note:
10511    This routine is not available from Fortran.
10512 
10513   Level: advanced
10514 
10515 .seealso: MatInvertBockDiagonalMat
10516 @*/
10517 PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
10518 {
10519   PetscErrorCode ierr;
10520 
10521   PetscFunctionBegin;
10522   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10523   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10524   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10525   if (!mat->ops->invertblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10526   ierr = (*mat->ops->invertblockdiagonal)(mat,values);CHKERRQ(ierr);
10527   PetscFunctionReturn(0);
10528 }
10529 
10530 /*@C
10531   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.
10532 
10533   Collective on Mat
10534 
10535   Input Parameters:
10536 + mat - the matrix
10537 . nblocks - the number of blocks
10538 - bsizes - the size of each block
10539 
10540   Output Parameters:
10541 . values - the block inverses in column major order (FORTRAN-like)
10542 
10543    Note:
10544    This routine is not available from Fortran.
10545 
10546   Level: advanced
10547 
10548 .seealso: MatInvertBockDiagonal()
10549 @*/
10550 PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
10551 {
10552   PetscErrorCode ierr;
10553 
10554   PetscFunctionBegin;
10555   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10556   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10557   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10558   if (!mat->ops->invertvariableblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10559   ierr = (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);CHKERRQ(ierr);
10560   PetscFunctionReturn(0);
10561 }
10562 
10563 /*@
10564   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A
10565 
10566   Collective on Mat
10567 
10568   Input Parameters:
10569 . A - the matrix
10570 
10571   Output Parameters:
10572 . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.
10573 
10574   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C
10575 
10576   Level: advanced
10577 
10578 .seealso: MatInvertBockDiagonal()
10579 @*/
10580 PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
10581 {
10582   PetscErrorCode     ierr;
10583   const PetscScalar *vals;
10584   PetscInt          *dnnz;
10585   PetscInt           M,N,m,n,rstart,rend,bs,i,j;
10586 
10587   PetscFunctionBegin;
10588   ierr = MatInvertBlockDiagonal(A,&vals);CHKERRQ(ierr);
10589   ierr = MatGetBlockSize(A,&bs);CHKERRQ(ierr);
10590   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
10591   ierr = MatGetLocalSize(A,&m,&n);CHKERRQ(ierr);
10592   ierr = MatSetSizes(C,m,n,M,N);CHKERRQ(ierr);
10593   ierr = MatSetBlockSize(C,bs);CHKERRQ(ierr);
10594   ierr = PetscMalloc1(m/bs,&dnnz);CHKERRQ(ierr);
10595   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
10596   ierr = MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);CHKERRQ(ierr);
10597   ierr = PetscFree(dnnz);CHKERRQ(ierr);
10598   ierr = MatGetOwnershipRange(C,&rstart,&rend);CHKERRQ(ierr);
10599   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);CHKERRQ(ierr);
10600   for (i = rstart/bs; i < rend/bs; i++) {
10601     ierr = MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);CHKERRQ(ierr);
10602   }
10603   ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10604   ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10605   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);CHKERRQ(ierr);
10606   PetscFunctionReturn(0);
10607 }
10608 
10609 /*@C
10610     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
10611     via MatTransposeColoringCreate().
10612 
10613     Collective on MatTransposeColoring
10614 
10615     Input Parameter:
10616 .   c - coloring context
10617 
10618     Level: intermediate
10619 
10620 .seealso: MatTransposeColoringCreate()
10621 @*/
10622 PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10623 {
10624   PetscErrorCode       ierr;
10625   MatTransposeColoring matcolor=*c;
10626 
10627   PetscFunctionBegin;
10628   if (!matcolor) PetscFunctionReturn(0);
10629   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; PetscFunctionReturn(0);}
10630 
10631   ierr = PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);CHKERRQ(ierr);
10632   ierr = PetscFree(matcolor->rows);CHKERRQ(ierr);
10633   ierr = PetscFree(matcolor->den2sp);CHKERRQ(ierr);
10634   ierr = PetscFree(matcolor->colorforcol);CHKERRQ(ierr);
10635   ierr = PetscFree(matcolor->columns);CHKERRQ(ierr);
10636   if (matcolor->brows>0) {
10637     ierr = PetscFree(matcolor->lstart);CHKERRQ(ierr);
10638   }
10639   ierr = PetscHeaderDestroy(c);CHKERRQ(ierr);
10640   PetscFunctionReturn(0);
10641 }
10642 
10643 /*@C
10644     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10645     a MatTransposeColoring context has been created, computes a dense B^T by Apply
10646     MatTransposeColoring to sparse B.
10647 
10648     Collective on MatTransposeColoring
10649 
10650     Input Parameters:
10651 +   B - sparse matrix B
10652 .   Btdense - symbolic dense matrix B^T
10653 -   coloring - coloring context created with MatTransposeColoringCreate()
10654 
10655     Output Parameter:
10656 .   Btdense - dense matrix B^T
10657 
10658     Level: advanced
10659 
10660      Notes:
10661     These are used internally for some implementations of MatRARt()
10662 
10663 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()
10664 
10665 .keywords: coloring
10666 @*/
10667 PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10668 {
10669   PetscErrorCode ierr;
10670 
10671   PetscFunctionBegin;
10672   PetscValidHeaderSpecific(B,MAT_CLASSID,1);
10673   PetscValidHeaderSpecific(Btdense,MAT_CLASSID,2);
10674   PetscValidHeaderSpecific(coloring,MAT_TRANSPOSECOLORING_CLASSID,3);
10675 
10676   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10677   ierr = (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);CHKERRQ(ierr);
10678   PetscFunctionReturn(0);
10679 }
10680 
10681 /*@C
10682     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10683     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10684     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10685     Csp from Cden.
10686 
10687     Collective on MatTransposeColoring
10688 
10689     Input Parameters:
10690 +   coloring - coloring context created with MatTransposeColoringCreate()
10691 -   Cden - matrix product of a sparse matrix and a dense matrix Btdense
10692 
10693     Output Parameter:
10694 .   Csp - sparse matrix
10695 
10696     Level: advanced
10697 
10698      Notes:
10699     These are used internally for some implementations of MatRARt()
10700 
10701 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
10702 
10703 .keywords: coloring
10704 @*/
10705 PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10706 {
10707   PetscErrorCode ierr;
10708 
10709   PetscFunctionBegin;
10710   PetscValidHeaderSpecific(matcoloring,MAT_TRANSPOSECOLORING_CLASSID,1);
10711   PetscValidHeaderSpecific(Cden,MAT_CLASSID,2);
10712   PetscValidHeaderSpecific(Csp,MAT_CLASSID,3);
10713 
10714   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10715   ierr = (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);CHKERRQ(ierr);
10716   PetscFunctionReturn(0);
10717 }
10718 
10719 /*@C
10720    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
10721 
10722    Collective on Mat
10723 
10724    Input Parameters:
10725 +  mat - the matrix product C
10726 -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
10727 
10728     Output Parameter:
10729 .   color - the new coloring context
10730 
10731     Level: intermediate
10732 
10733 .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
10734            MatTransColoringApplyDenToSp()
10735 @*/
10736 PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10737 {
10738   MatTransposeColoring c;
10739   MPI_Comm             comm;
10740   PetscErrorCode       ierr;
10741 
10742   PetscFunctionBegin;
10743   ierr = PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10744   ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
10745   ierr = PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);CHKERRQ(ierr);
10746 
10747   c->ctype = iscoloring->ctype;
10748   if (mat->ops->transposecoloringcreate) {
10749     ierr = (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);CHKERRQ(ierr);
10750   } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for this matrix type");
10751 
10752   *color = c;
10753   ierr   = PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10754   PetscFunctionReturn(0);
10755 }
10756 
10757 /*@
10758       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10759         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10760         same, otherwise it will be larger
10761 
10762      Not Collective
10763 
10764   Input Parameter:
10765 .    A  - the matrix
10766 
10767   Output Parameter:
10768 .    state - the current state
10769 
10770   Notes:
10771     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10772          different matrices
10773 
10774   Level: intermediate
10775 
10776 @*/
10777 PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10778 {
10779   PetscFunctionBegin;
10780   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10781   *state = mat->nonzerostate;
10782   PetscFunctionReturn(0);
10783 }
10784 
10785 /*@
10786       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10787                  matrices from each processor
10788 
10789     Collective on MPI_Comm
10790 
10791    Input Parameters:
10792 +    comm - the communicators the parallel matrix will live on
10793 .    seqmat - the input sequential matrices
10794 .    n - number of local columns (or PETSC_DECIDE)
10795 -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10796 
10797    Output Parameter:
10798 .    mpimat - the parallel matrix generated
10799 
10800     Level: advanced
10801 
10802    Notes:
10803     The number of columns of the matrix in EACH processor MUST be the same.
10804 
10805 @*/
10806 PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10807 {
10808   PetscErrorCode ierr;
10809 
10810   PetscFunctionBegin;
10811   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10812   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");
10813 
10814   ierr = PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10815   ierr = (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);CHKERRQ(ierr);
10816   ierr = PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10817   PetscFunctionReturn(0);
10818 }
10819 
10820 /*@
10821      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10822                  ranks' ownership ranges.
10823 
10824     Collective on A
10825 
10826    Input Parameters:
10827 +    A   - the matrix to create subdomains from
10828 -    N   - requested number of subdomains
10829 
10830 
10831    Output Parameters:
10832 +    n   - number of subdomains resulting on this rank
10833 -    iss - IS list with indices of subdomains on this rank
10834 
10835     Level: advanced
10836 
10837     Notes:
10838     number of subdomains must be smaller than the communicator size
10839 @*/
10840 PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10841 {
10842   MPI_Comm        comm,subcomm;
10843   PetscMPIInt     size,rank,color;
10844   PetscInt        rstart,rend,k;
10845   PetscErrorCode  ierr;
10846 
10847   PetscFunctionBegin;
10848   ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr);
10849   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
10850   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
10851   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);
10852   *n = 1;
10853   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10854   color = rank/k;
10855   ierr = MPI_Comm_split(comm,color,rank,&subcomm);CHKERRQ(ierr);
10856   ierr = PetscMalloc1(1,iss);CHKERRQ(ierr);
10857   ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
10858   ierr = ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);CHKERRQ(ierr);
10859   ierr = MPI_Comm_free(&subcomm);CHKERRQ(ierr);
10860   PetscFunctionReturn(0);
10861 }
10862 
10863 /*@
10864    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.
10865 
10866    If the interpolation and restriction operators are the same, uses MatPtAP.
10867    If they are not the same, use MatMatMatMult.
10868 
10869    Once the coarse grid problem is constructed, correct for interpolation operators
10870    that are not of full rank, which can legitimately happen in the case of non-nested
10871    geometric multigrid.
10872 
10873    Input Parameters:
10874 +  restrct - restriction operator
10875 .  dA - fine grid matrix
10876 .  interpolate - interpolation operator
10877 .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10878 -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate
10879 
10880    Output Parameters:
10881 .  A - the Galerkin coarse matrix
10882 
10883    Options Database Key:
10884 .  -pc_mg_galerkin <both,pmat,mat,none>
10885 
10886    Level: developer
10887 
10888 .keywords: MG, multigrid, Galerkin
10889 
10890 .seealso: MatPtAP(), MatMatMatMult()
10891 @*/
10892 PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10893 {
10894   PetscErrorCode ierr;
10895   IS             zerorows;
10896   Vec            diag;
10897 
10898   PetscFunctionBegin;
10899   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10900   /* Construct the coarse grid matrix */
10901   if (interpolate == restrct) {
10902     ierr = MatPtAP(dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10903   } else {
10904     ierr = MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10905   }
10906 
10907   /* If the interpolation matrix is not of full rank, A will have zero rows.
10908      This can legitimately happen in the case of non-nested geometric multigrid.
10909      In that event, we set the rows of the matrix to the rows of the identity,
10910      ignoring the equations (as the RHS will also be zero). */
10911 
10912   ierr = MatFindZeroRows(*A, &zerorows);CHKERRQ(ierr);
10913 
10914   if (zerorows != NULL) { /* if there are any zero rows */
10915     ierr = MatCreateVecs(*A, &diag, NULL);CHKERRQ(ierr);
10916     ierr = MatGetDiagonal(*A, diag);CHKERRQ(ierr);
10917     ierr = VecISSet(diag, zerorows, 1.0);CHKERRQ(ierr);
10918     ierr = MatDiagonalSet(*A, diag, INSERT_VALUES);CHKERRQ(ierr);
10919     ierr = VecDestroy(&diag);CHKERRQ(ierr);
10920     ierr = ISDestroy(&zerorows);CHKERRQ(ierr);
10921   }
10922   PetscFunctionReturn(0);
10923 }
10924 
10925 /*@C
10926     MatSetOperation - Allows user to set a matrix operation for any matrix type
10927 
10928    Logically Collective on Mat
10929 
10930     Input Parameters:
10931 +   mat - the matrix
10932 .   op - the name of the operation
10933 -   f - the function that provides the operation
10934 
10935    Level: developer
10936 
10937     Usage:
10938 $      extern PetscErrorCode usermult(Mat,Vec,Vec);
10939 $      ierr = MatCreateXXX(comm,...&A);
10940 $      ierr = MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
10941 
10942     Notes:
10943     See the file include/petscmat.h for a complete list of matrix
10944     operations, which all have the form MATOP_<OPERATION>, where
10945     <OPERATION> is the name (in all capital letters) of the
10946     user interface routine (e.g., MatMult() -> MATOP_MULT).
10947 
10948     All user-provided functions (except for MATOP_DESTROY) should have the same calling
10949     sequence as the usual matrix interface routines, since they
10950     are intended to be accessed via the usual matrix interface
10951     routines, e.g.,
10952 $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)
10953 
10954     In particular each function MUST return an error code of 0 on success and
10955     nonzero on failure.
10956 
10957     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.
10958 
10959 .keywords: matrix, set, operation
10960 
10961 .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10962 @*/
10963 PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10964 {
10965   PetscFunctionBegin;
10966   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10967   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10968     mat->ops->viewnative = mat->ops->view;
10969   }
10970   (((void(**)(void))mat->ops)[op]) = f;
10971   PetscFunctionReturn(0);
10972 }
10973 
10974 /*@C
10975     MatGetOperation - Gets a matrix operation for any matrix type.
10976 
10977     Not Collective
10978 
10979     Input Parameters:
10980 +   mat - the matrix
10981 -   op - the name of the operation
10982 
10983     Output Parameter:
10984 .   f - the function that provides the operation
10985 
10986     Level: developer
10987 
10988     Usage:
10989 $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
10990 $      ierr = MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);
10991 
10992     Notes:
10993     See the file include/petscmat.h for a complete list of matrix
10994     operations, which all have the form MATOP_<OPERATION>, where
10995     <OPERATION> is the name (in all capital letters) of the
10996     user interface routine (e.g., MatMult() -> MATOP_MULT).
10997 
10998     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.
10999 
11000 .keywords: matrix, get, operation
11001 
11002 .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
11003 @*/
11004 PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
11005 {
11006   PetscFunctionBegin;
11007   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
11008   *f = (((void (**)(void))mat->ops)[op]);
11009   PetscFunctionReturn(0);
11010 }
11011 
11012 /*@
11013     MatHasOperation - Determines whether the given matrix supports the particular
11014     operation.
11015 
11016    Not Collective
11017 
11018    Input Parameters:
11019 +  mat - the matrix
11020 -  op - the operation, for example, MATOP_GET_DIAGONAL
11021 
11022    Output Parameter:
11023 .  has - either PETSC_TRUE or PETSC_FALSE
11024 
11025    Level: advanced
11026 
11027    Notes:
11028    See the file include/petscmat.h for a complete list of matrix
11029    operations, which all have the form MATOP_<OPERATION>, where
11030    <OPERATION> is the name (in all capital letters) of the
11031    user-level routine.  E.g., MatNorm() -> MATOP_NORM.
11032 
11033 .keywords: matrix, has, operation
11034 
11035 .seealso: MatCreateShell()
11036 @*/
11037 PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
11038 {
11039   PetscErrorCode ierr;
11040 
11041   PetscFunctionBegin;
11042   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
11043   PetscValidType(mat,1);
11044   PetscValidPointer(has,3);
11045   if (mat->ops->hasoperation) {
11046     ierr = (*mat->ops->hasoperation)(mat,op,has);CHKERRQ(ierr);
11047   } else {
11048     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
11049     else {
11050       *has = PETSC_FALSE;
11051       if (op == MATOP_CREATE_SUBMATRIX) {
11052         PetscMPIInt size;
11053 
11054         ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
11055         if (size == 1) {
11056           ierr = MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);CHKERRQ(ierr);
11057         }
11058       }
11059     }
11060   }
11061   PetscFunctionReturn(0);
11062 }
11063 
11064 /*@
11065     MatHasCongruentLayouts - Determines whether the rows and columns layouts
11066     of the matrix are congruent
11067 
11068    Collective on mat
11069 
11070    Input Parameters:
11071 .  mat - the matrix
11072 
11073    Output Parameter:
11074 .  cong - either PETSC_TRUE or PETSC_FALSE
11075 
11076    Level: beginner
11077 
11078    Notes:
11079 
11080 .keywords: matrix, has
11081 
11082 .seealso: MatCreate(), MatSetSizes()
11083 @*/
11084 PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
11085 {
11086   PetscErrorCode ierr;
11087 
11088   PetscFunctionBegin;
11089   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
11090   PetscValidType(mat,1);
11091   PetscValidPointer(cong,2);
11092   if (!mat->rmap || !mat->cmap) {
11093     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11094     PetscFunctionReturn(0);
11095   }
11096   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11097     ierr = PetscLayoutCompare(mat->rmap,mat->cmap,cong);CHKERRQ(ierr);
11098     if (*cong) mat->congruentlayouts = 1;
11099     else       mat->congruentlayouts = 0;
11100   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11101   PetscFunctionReturn(0);
11102 }
11103 
11104 /*@
11105     MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
11106     e.g., matrx product of MatPtAP.
11107 
11108    Collective on mat
11109 
11110    Input Parameters:
11111 .  mat - the matrix
11112 
11113    Output Parameter:
11114 .  mat - the matrix with intermediate data structures released
11115 
11116    Level: advanced
11117 
11118    Notes:
11119 
11120 .keywords: matrix
11121 
11122 .seealso: MatPtAP(), MatMatMult()
11123 @*/
11124 PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
11125 {
11126   PetscErrorCode ierr;
11127 
11128   PetscFunctionBegin;
11129   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
11130   PetscValidType(mat,1);
11131   if (mat->ops->freeintermediatedatastructures) {
11132     ierr = (*mat->ops->freeintermediatedatastructures)(mat);CHKERRQ(ierr);
11133   }
11134   PetscFunctionReturn(0);
11135 }
11136