xref: /petsc/src/mat/interface/matrix.c (revision 29b3c8a1c1d29fc05018f23f4f087a3ebe1dff6f)
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_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_DenseCopyToGPU, MAT_DenseCopyFromGPU;
38 PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
39 PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;
40 
41 const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","MatFactorType","MAT_FACTOR_",0};
42 
43 /*@
44    MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated but not been assembled it randomly selects appropriate locations,
45                   for sparse matrices that already have locations it fills the locations with random numbers
46 
47    Logically Collective on Mat
48 
49    Input Parameters:
50 +  x  - the matrix
51 -  rctx - the random number context, formed by PetscRandomCreate(), or NULL and
52           it will create one internally.
53 
54    Output Parameter:
55 .  x  - the matrix
56 
57    Example of Usage:
58 .vb
59      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
60      MatSetRandom(x,rctx);
61      PetscRandomDestroy(rctx);
62 .ve
63 
64    Level: intermediate
65 
66 
67 .seealso: MatZeroEntries(), MatSetValues(), PetscRandomCreate(), PetscRandomDestroy()
68 @*/
69 PetscErrorCode MatSetRandom(Mat x,PetscRandom rctx)
70 {
71   PetscErrorCode ierr;
72   PetscRandom    randObj = NULL;
73 
74   PetscFunctionBegin;
75   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
76   if (rctx) PetscValidHeaderSpecific(rctx,PETSC_RANDOM_CLASSID,2);
77   PetscValidType(x,1);
78 
79   if (!x->ops->setrandom) SETERRQ1(PetscObjectComm((PetscObject)x),PETSC_ERR_SUP,"Mat type %s",((PetscObject)x)->type_name);
80 
81   if (!rctx) {
82     MPI_Comm comm;
83     ierr = PetscObjectGetComm((PetscObject)x,&comm);CHKERRQ(ierr);
84     ierr = PetscRandomCreate(comm,&randObj);CHKERRQ(ierr);
85     ierr = PetscRandomSetFromOptions(randObj);CHKERRQ(ierr);
86     rctx = randObj;
87   }
88 
89   ierr = PetscLogEventBegin(MAT_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
90   ierr = (*x->ops->setrandom)(x,rctx);CHKERRQ(ierr);
91   ierr = PetscLogEventEnd(MAT_SetRandom,x,rctx,0,0);CHKERRQ(ierr);
92 
93   ierr = MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
94   ierr = MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
95   ierr = PetscRandomDestroy(&randObj);CHKERRQ(ierr);
96   PetscFunctionReturn(0);
97 }
98 
99 /*@
100    MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
101 
102    Logically Collective on Mat
103 
104    Input Parameters:
105 .  mat - the factored matrix
106 
107    Output Parameter:
108 +  pivot - the pivot value computed
109 -  row - the row that the zero pivot occurred. Note that this row must be interpreted carefully due to row reorderings and which processes
110          the share the matrix
111 
112    Level: advanced
113 
114    Notes:
115     This routine does not work for factorizations done with external packages.
116    This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT
117 
118    This can be called on non-factored matrices that come from, for example, matrices used in SOR.
119 
120 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
121 @*/
122 PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat,PetscReal *pivot,PetscInt *row)
123 {
124   PetscFunctionBegin;
125   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
126   *pivot = mat->factorerror_zeropivot_value;
127   *row   = mat->factorerror_zeropivot_row;
128   PetscFunctionReturn(0);
129 }
130 
131 /*@
132    MatFactorGetError - gets the error code from a factorization
133 
134    Logically Collective on Mat
135 
136    Input Parameters:
137 .  mat - the factored matrix
138 
139    Output Parameter:
140 .  err  - the error code
141 
142    Level: advanced
143 
144    Notes:
145     This can be called on non-factored matrices that come from, for example, matrices used in SOR.
146 
147 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
148 @*/
149 PetscErrorCode MatFactorGetError(Mat mat,MatFactorError *err)
150 {
151   PetscFunctionBegin;
152   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
153   *err = mat->factorerrortype;
154   PetscFunctionReturn(0);
155 }
156 
157 /*@
158    MatFactorClearError - clears the error code in a factorization
159 
160    Logically Collective on Mat
161 
162    Input Parameter:
163 .  mat - the factored matrix
164 
165    Level: developer
166 
167    Notes:
168     This can be called on non-factored matrices that come from, for example, matrices used in SOR.
169 
170 .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorGetError(), MatFactorGetErrorZeroPivot()
171 @*/
172 PetscErrorCode MatFactorClearError(Mat mat)
173 {
174   PetscFunctionBegin;
175   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
176   mat->factorerrortype             = MAT_FACTOR_NOERROR;
177   mat->factorerror_zeropivot_value = 0.0;
178   mat->factorerror_zeropivot_row   = 0;
179   PetscFunctionReturn(0);
180 }
181 
182 PETSC_INTERN PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat,PetscBool cols,PetscReal tol,IS *nonzero)
183 {
184   PetscErrorCode    ierr;
185   Vec               r,l;
186   const PetscScalar *al;
187   PetscInt          i,nz,gnz,N,n;
188 
189   PetscFunctionBegin;
190   ierr = MatCreateVecs(mat,&r,&l);CHKERRQ(ierr);
191   if (!cols) { /* nonzero rows */
192     ierr = MatGetSize(mat,&N,NULL);CHKERRQ(ierr);
193     ierr = MatGetLocalSize(mat,&n,NULL);CHKERRQ(ierr);
194     ierr = VecSet(l,0.0);CHKERRQ(ierr);
195     ierr = VecSetRandom(r,NULL);CHKERRQ(ierr);
196     ierr = MatMult(mat,r,l);CHKERRQ(ierr);
197     ierr = VecGetArrayRead(l,&al);CHKERRQ(ierr);
198   } else { /* nonzero columns */
199     ierr = MatGetSize(mat,NULL,&N);CHKERRQ(ierr);
200     ierr = MatGetLocalSize(mat,NULL,&n);CHKERRQ(ierr);
201     ierr = VecSet(r,0.0);CHKERRQ(ierr);
202     ierr = VecSetRandom(l,NULL);CHKERRQ(ierr);
203     ierr = MatMultTranspose(mat,l,r);CHKERRQ(ierr);
204     ierr = VecGetArrayRead(r,&al);CHKERRQ(ierr);
205   }
206   if (tol <= 0.0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nz++; }
207   else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nz++; }
208   ierr = MPIU_Allreduce(&nz,&gnz,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
209   if (gnz != N) {
210     PetscInt *nzr;
211     ierr = PetscMalloc1(nz,&nzr);CHKERRQ(ierr);
212     if (nz) {
213       if (tol < 0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nzr[nz++] = i; }
214       else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i; }
215     }
216     ierr = ISCreateGeneral(PetscObjectComm((PetscObject)mat),nz,nzr,PETSC_OWN_POINTER,nonzero);CHKERRQ(ierr);
217   } else *nonzero = NULL;
218   if (!cols) { /* nonzero rows */
219     ierr = VecRestoreArrayRead(l,&al);CHKERRQ(ierr);
220   } else {
221     ierr = VecRestoreArrayRead(r,&al);CHKERRQ(ierr);
222   }
223   ierr = VecDestroy(&l);CHKERRQ(ierr);
224   ierr = VecDestroy(&r);CHKERRQ(ierr);
225   PetscFunctionReturn(0);
226 }
227 
228 /*@
229       MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
230 
231   Input Parameter:
232 .    A  - the matrix
233 
234   Output Parameter:
235 .    keptrows - the rows that are not completely zero
236 
237   Notes:
238     keptrows is set to NULL if all rows are nonzero.
239 
240   Level: intermediate
241 
242  @*/
243 PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
244 {
245   PetscErrorCode ierr;
246 
247   PetscFunctionBegin;
248   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
249   PetscValidType(mat,1);
250   PetscValidPointer(keptrows,2);
251   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
252   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
253   if (!mat->ops->findnonzerorows) {
254     ierr = MatFindNonzeroRowsOrCols_Basic(mat,PETSC_FALSE,0.0,keptrows);CHKERRQ(ierr);
255   } else {
256     ierr = (*mat->ops->findnonzerorows)(mat,keptrows);CHKERRQ(ierr);
257   }
258   PetscFunctionReturn(0);
259 }
260 
261 /*@
262       MatFindZeroRows - Locate all rows that are completely zero in the matrix
263 
264   Input Parameter:
265 .    A  - the matrix
266 
267   Output Parameter:
268 .    zerorows - the rows that are completely zero
269 
270   Notes:
271     zerorows is set to NULL if no rows are zero.
272 
273   Level: intermediate
274 
275  @*/
276 PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
277 {
278   PetscErrorCode ierr;
279   IS keptrows;
280   PetscInt m, n;
281 
282   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
283   PetscValidType(mat,1);
284 
285   ierr = MatFindNonzeroRows(mat, &keptrows);CHKERRQ(ierr);
286   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
287      In keeping with this convention, we set zerorows to NULL if there are no zero
288      rows. */
289   if (keptrows == NULL) {
290     *zerorows = NULL;
291   } else {
292     ierr = MatGetOwnershipRange(mat,&m,&n);CHKERRQ(ierr);
293     ierr = ISComplement(keptrows,m,n,zerorows);CHKERRQ(ierr);
294     ierr = ISDestroy(&keptrows);CHKERRQ(ierr);
295   }
296   PetscFunctionReturn(0);
297 }
298 
299 /*@
300    MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
301 
302    Not Collective
303 
304    Input Parameters:
305 .   A - the matrix
306 
307    Output Parameters:
308 .   a - the diagonal part (which is a SEQUENTIAL matrix)
309 
310    Notes:
311     see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.
312           Use caution, as the reference count on the returned matrix is not incremented and it is used as
313 	  part of the containing MPI Mat's normal operation.
314 
315    Level: advanced
316 
317 @*/
318 PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
319 {
320   PetscErrorCode ierr;
321 
322   PetscFunctionBegin;
323   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
324   PetscValidType(A,1);
325   PetscValidPointer(a,3);
326   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
327   if (!A->ops->getdiagonalblock) {
328     PetscMPIInt size;
329     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRQ(ierr);
330     if (size == 1) {
331       *a = A;
332       PetscFunctionReturn(0);
333     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Not coded for this matrix type");
334   }
335   ierr = (*A->ops->getdiagonalblock)(A,a);CHKERRQ(ierr);
336   PetscFunctionReturn(0);
337 }
338 
339 /*@
340    MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
341 
342    Collective on Mat
343 
344    Input Parameters:
345 .  mat - the matrix
346 
347    Output Parameter:
348 .   trace - the sum of the diagonal entries
349 
350    Level: advanced
351 
352 @*/
353 PetscErrorCode MatGetTrace(Mat mat,PetscScalar *trace)
354 {
355   PetscErrorCode ierr;
356   Vec            diag;
357 
358   PetscFunctionBegin;
359   ierr = MatCreateVecs(mat,&diag,NULL);CHKERRQ(ierr);
360   ierr = MatGetDiagonal(mat,diag);CHKERRQ(ierr);
361   ierr = VecSum(diag,trace);CHKERRQ(ierr);
362   ierr = VecDestroy(&diag);CHKERRQ(ierr);
363   PetscFunctionReturn(0);
364 }
365 
366 /*@
367    MatRealPart - Zeros out the imaginary part of the matrix
368 
369    Logically Collective on Mat
370 
371    Input Parameters:
372 .  mat - the matrix
373 
374    Level: advanced
375 
376 
377 .seealso: MatImaginaryPart()
378 @*/
379 PetscErrorCode MatRealPart(Mat mat)
380 {
381   PetscErrorCode ierr;
382 
383   PetscFunctionBegin;
384   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
385   PetscValidType(mat,1);
386   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
387   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
388   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
389   MatCheckPreallocated(mat,1);
390   ierr = (*mat->ops->realpart)(mat);CHKERRQ(ierr);
391   PetscFunctionReturn(0);
392 }
393 
394 /*@C
395    MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix
396 
397    Collective on Mat
398 
399    Input Parameter:
400 .  mat - the matrix
401 
402    Output Parameters:
403 +   nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
404 -   ghosts - the global indices of the ghost points
405 
406    Notes:
407     the nghosts and ghosts are suitable to pass into VecCreateGhost()
408 
409    Level: advanced
410 
411 @*/
412 PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
413 {
414   PetscErrorCode ierr;
415 
416   PetscFunctionBegin;
417   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
418   PetscValidType(mat,1);
419   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
420   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
421   if (!mat->ops->getghosts) {
422     if (nghosts) *nghosts = 0;
423     if (ghosts) *ghosts = 0;
424   } else {
425     ierr = (*mat->ops->getghosts)(mat,nghosts,ghosts);CHKERRQ(ierr);
426   }
427   PetscFunctionReturn(0);
428 }
429 
430 
431 /*@
432    MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
433 
434    Logically Collective on Mat
435 
436    Input Parameters:
437 .  mat - the matrix
438 
439    Level: advanced
440 
441 
442 .seealso: MatRealPart()
443 @*/
444 PetscErrorCode MatImaginaryPart(Mat mat)
445 {
446   PetscErrorCode ierr;
447 
448   PetscFunctionBegin;
449   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
450   PetscValidType(mat,1);
451   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
452   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
453   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
454   MatCheckPreallocated(mat,1);
455   ierr = (*mat->ops->imaginarypart)(mat);CHKERRQ(ierr);
456   PetscFunctionReturn(0);
457 }
458 
459 /*@
460    MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)
461 
462    Not Collective
463 
464    Input Parameter:
465 .  mat - the matrix
466 
467    Output Parameters:
468 +  missing - is any diagonal missing
469 -  dd - first diagonal entry that is missing (optional) on this process
470 
471    Level: advanced
472 
473 
474 .seealso: MatRealPart()
475 @*/
476 PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
477 {
478   PetscErrorCode ierr;
479 
480   PetscFunctionBegin;
481   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
482   PetscValidType(mat,1);
483   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
484   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
485   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
486   ierr = (*mat->ops->missingdiagonal)(mat,missing,dd);CHKERRQ(ierr);
487   PetscFunctionReturn(0);
488 }
489 
490 /*@C
491    MatGetRow - Gets a row of a matrix.  You MUST call MatRestoreRow()
492    for each row that you get to ensure that your application does
493    not bleed memory.
494 
495    Not Collective
496 
497    Input Parameters:
498 +  mat - the matrix
499 -  row - the row to get
500 
501    Output Parameters:
502 +  ncols -  if not NULL, the number of nonzeros in the row
503 .  cols - if not NULL, the column numbers
504 -  vals - if not NULL, the values
505 
506    Notes:
507    This routine is provided for people who need to have direct access
508    to the structure of a matrix.  We hope that we provide enough
509    high-level matrix routines that few users will need it.
510 
511    MatGetRow() always returns 0-based column indices, regardless of
512    whether the internal representation is 0-based (default) or 1-based.
513 
514    For better efficiency, set cols and/or vals to NULL if you do
515    not wish to extract these quantities.
516 
517    The user can only examine the values extracted with MatGetRow();
518    the values cannot be altered.  To change the matrix entries, one
519    must use MatSetValues().
520 
521    You can only have one call to MatGetRow() outstanding for a particular
522    matrix at a time, per processor. MatGetRow() can only obtain rows
523    associated with the given processor, it cannot get rows from the
524    other processors; for that we suggest using MatCreateSubMatrices(), then
525    MatGetRow() on the submatrix. The row index passed to MatGetRow()
526    is in the global number of rows.
527 
528    Fortran Notes:
529    The calling sequence from Fortran is
530 .vb
531    MatGetRow(matrix,row,ncols,cols,values,ierr)
532          Mat     matrix (input)
533          integer row    (input)
534          integer ncols  (output)
535          integer cols(maxcols) (output)
536          double precision (or double complex) values(maxcols) output
537 .ve
538    where maxcols >= maximum nonzeros in any row of the matrix.
539 
540 
541    Caution:
542    Do not try to change the contents of the output arrays (cols and vals).
543    In some cases, this may corrupt the matrix.
544 
545    Level: advanced
546 
547 .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
548 @*/
549 PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
550 {
551   PetscErrorCode ierr;
552   PetscInt       incols;
553 
554   PetscFunctionBegin;
555   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
556   PetscValidType(mat,1);
557   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
558   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
559   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
560   MatCheckPreallocated(mat,1);
561   ierr = PetscLogEventBegin(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
562   ierr = (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);CHKERRQ(ierr);
563   if (ncols) *ncols = incols;
564   ierr = PetscLogEventEnd(MAT_GetRow,mat,0,0,0);CHKERRQ(ierr);
565   PetscFunctionReturn(0);
566 }
567 
568 /*@
569    MatConjugate - replaces the matrix values with their complex conjugates
570 
571    Logically Collective on Mat
572 
573    Input Parameters:
574 .  mat - the matrix
575 
576    Level: advanced
577 
578 .seealso:  VecConjugate()
579 @*/
580 PetscErrorCode MatConjugate(Mat mat)
581 {
582 #if defined(PETSC_USE_COMPLEX)
583   PetscErrorCode ierr;
584 
585   PetscFunctionBegin;
586   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
587   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
588   if (!mat->ops->conjugate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not provided for this matrix format, send email to petsc-maint@mcs.anl.gov");
589   ierr = (*mat->ops->conjugate)(mat);CHKERRQ(ierr);
590 #else
591   PetscFunctionBegin;
592 #endif
593   PetscFunctionReturn(0);
594 }
595 
596 /*@C
597    MatRestoreRow - Frees any temporary space allocated by MatGetRow().
598 
599    Not Collective
600 
601    Input Parameters:
602 +  mat - the matrix
603 .  row - the row to get
604 .  ncols, cols - the number of nonzeros and their columns
605 -  vals - if nonzero the column values
606 
607    Notes:
608    This routine should be called after you have finished examining the entries.
609 
610    This routine zeros out ncols, cols, and vals. This is to prevent accidental
611    us of the array after it has been restored. If you pass NULL, it will
612    not zero the pointers.  Use of cols or vals after MatRestoreRow is invalid.
613 
614    Fortran Notes:
615    The calling sequence from Fortran is
616 .vb
617    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
618       Mat     matrix (input)
619       integer row    (input)
620       integer ncols  (output)
621       integer cols(maxcols) (output)
622       double precision (or double complex) values(maxcols) output
623 .ve
624    Where maxcols >= maximum nonzeros in any row of the matrix.
625 
626    In Fortran MatRestoreRow() MUST be called after MatGetRow()
627    before another call to MatGetRow() can be made.
628 
629    Level: advanced
630 
631 .seealso:  MatGetRow()
632 @*/
633 PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
634 {
635   PetscErrorCode ierr;
636 
637   PetscFunctionBegin;
638   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
639   if (ncols) PetscValidIntPointer(ncols,3);
640   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
641   if (!mat->ops->restorerow) PetscFunctionReturn(0);
642   ierr = (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);CHKERRQ(ierr);
643   if (ncols) *ncols = 0;
644   if (cols)  *cols = NULL;
645   if (vals)  *vals = NULL;
646   PetscFunctionReturn(0);
647 }
648 
649 /*@
650    MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
651    You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.
652 
653    Not Collective
654 
655    Input Parameters:
656 .  mat - the matrix
657 
658    Notes:
659    The flag is to ensure that users are aware of MatGetRow() only provides the upper triangular part of the row for the matrices in MATSBAIJ format.
660 
661    Level: advanced
662 
663 .seealso: MatRestoreRowUpperTriangular()
664 @*/
665 PetscErrorCode MatGetRowUpperTriangular(Mat mat)
666 {
667   PetscErrorCode ierr;
668 
669   PetscFunctionBegin;
670   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
671   PetscValidType(mat,1);
672   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
673   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
674   MatCheckPreallocated(mat,1);
675   if (!mat->ops->getrowuppertriangular) PetscFunctionReturn(0);
676   ierr = (*mat->ops->getrowuppertriangular)(mat);CHKERRQ(ierr);
677   PetscFunctionReturn(0);
678 }
679 
680 /*@
681    MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.
682 
683    Not Collective
684 
685    Input Parameters:
686 .  mat - the matrix
687 
688    Notes:
689    This routine should be called after you have finished MatGetRow/MatRestoreRow().
690 
691 
692    Level: advanced
693 
694 .seealso:  MatGetRowUpperTriangular()
695 @*/
696 PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
697 {
698   PetscErrorCode ierr;
699 
700   PetscFunctionBegin;
701   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
702   PetscValidType(mat,1);
703   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
704   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
705   MatCheckPreallocated(mat,1);
706   if (!mat->ops->restorerowuppertriangular) PetscFunctionReturn(0);
707   ierr = (*mat->ops->restorerowuppertriangular)(mat);CHKERRQ(ierr);
708   PetscFunctionReturn(0);
709 }
710 
711 /*@C
712    MatSetOptionsPrefix - Sets the prefix used for searching for all
713    Mat options in the database.
714 
715    Logically Collective on Mat
716 
717    Input Parameter:
718 +  A - the Mat context
719 -  prefix - the prefix to prepend to all option names
720 
721    Notes:
722    A hyphen (-) must NOT be given at the beginning of the prefix name.
723    The first character of all runtime options is AUTOMATICALLY the hyphen.
724 
725    Level: advanced
726 
727 .seealso: MatSetFromOptions()
728 @*/
729 PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
730 {
731   PetscErrorCode ierr;
732 
733   PetscFunctionBegin;
734   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
735   ierr = PetscObjectSetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
736   PetscFunctionReturn(0);
737 }
738 
739 /*@C
740    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
741    Mat options in the database.
742 
743    Logically Collective on Mat
744 
745    Input Parameters:
746 +  A - the Mat context
747 -  prefix - the prefix to prepend to all option names
748 
749    Notes:
750    A hyphen (-) must NOT be given at the beginning of the prefix name.
751    The first character of all runtime options is AUTOMATICALLY the hyphen.
752 
753    Level: advanced
754 
755 .seealso: MatGetOptionsPrefix()
756 @*/
757 PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
758 {
759   PetscErrorCode ierr;
760 
761   PetscFunctionBegin;
762   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
763   ierr = PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
764   PetscFunctionReturn(0);
765 }
766 
767 /*@C
768    MatGetOptionsPrefix - Sets the prefix used for searching for all
769    Mat options in the database.
770 
771    Not Collective
772 
773    Input Parameter:
774 .  A - the Mat context
775 
776    Output Parameter:
777 .  prefix - pointer to the prefix string used
778 
779    Notes:
780     On the fortran side, the user should pass in a string 'prefix' of
781    sufficient length to hold the prefix.
782 
783    Level: advanced
784 
785 .seealso: MatAppendOptionsPrefix()
786 @*/
787 PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
788 {
789   PetscErrorCode ierr;
790 
791   PetscFunctionBegin;
792   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
793   ierr = PetscObjectGetOptionsPrefix((PetscObject)A,prefix);CHKERRQ(ierr);
794   PetscFunctionReturn(0);
795 }
796 
797 /*@
798    MatResetPreallocation - Reset mat to use the original nonzero pattern provided by users.
799 
800    Collective on Mat
801 
802    Input Parameters:
803 .  A - the Mat context
804 
805    Notes:
806    The allocated memory will be shrunk after calling MatAssembly with MAT_FINAL_ASSEMBLY. Users can reset the preallocation to access the original memory.
807    Currently support MPIAIJ and SEQAIJ.
808 
809    Level: beginner
810 
811 .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
812 @*/
813 PetscErrorCode MatResetPreallocation(Mat A)
814 {
815   PetscErrorCode ierr;
816 
817   PetscFunctionBegin;
818   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
819   PetscValidType(A,1);
820   ierr = PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));CHKERRQ(ierr);
821   PetscFunctionReturn(0);
822 }
823 
824 
825 /*@
826    MatSetUp - Sets up the internal matrix data structures for the later use.
827 
828    Collective on Mat
829 
830    Input Parameters:
831 .  A - the Mat context
832 
833    Notes:
834    If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.
835 
836    If a suitable preallocation routine is used, this function does not need to be called.
837 
838    See the Performance chapter of the PETSc users manual for how to preallocate matrices
839 
840    Level: beginner
841 
842 .seealso: MatCreate(), MatDestroy()
843 @*/
844 PetscErrorCode MatSetUp(Mat A)
845 {
846   PetscMPIInt    size;
847   PetscErrorCode ierr;
848 
849   PetscFunctionBegin;
850   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
851   if (!((PetscObject)A)->type_name) {
852     ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);CHKERRQ(ierr);
853     if (size == 1) {
854       ierr = MatSetType(A, MATSEQAIJ);CHKERRQ(ierr);
855     } else {
856       ierr = MatSetType(A, MATMPIAIJ);CHKERRQ(ierr);
857     }
858   }
859   if (!A->preallocated && A->ops->setup) {
860     ierr = PetscInfo(A,"Warning not preallocating matrix storage\n");CHKERRQ(ierr);
861     ierr = (*A->ops->setup)(A);CHKERRQ(ierr);
862   }
863   ierr = PetscLayoutSetUp(A->rmap);CHKERRQ(ierr);
864   ierr = PetscLayoutSetUp(A->cmap);CHKERRQ(ierr);
865   A->preallocated = PETSC_TRUE;
866   PetscFunctionReturn(0);
867 }
868 
869 #if defined(PETSC_HAVE_SAWS)
870 #include <petscviewersaws.h>
871 #endif
872 /*@C
873    MatView - Visualizes a matrix object.
874 
875    Collective on Mat
876 
877    Input Parameters:
878 +  mat - the matrix
879 -  viewer - visualization context
880 
881   Notes:
882   The available visualization contexts include
883 +    PETSC_VIEWER_STDOUT_SELF - for sequential matrices
884 .    PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
885 .    PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
886 -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
887 
888    The user can open alternative visualization contexts with
889 +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
890 .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
891          specified file; corresponding input uses MatLoad()
892 .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
893          an X window display
894 -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
895          Currently only the sequential dense and AIJ
896          matrix types support the Socket viewer.
897 
898    The user can call PetscViewerPushFormat() to specify the output
899    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
900    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
901 +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
902 .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
903 .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
904 .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
905          format common among all matrix types
906 .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
907          format (which is in many cases the same as the default)
908 .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
909          size and structure (not the matrix entries)
910 -    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
911          the matrix structure
912 
913    Options Database Keys:
914 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
915 .  -mat_view ::ascii_info_detail - Prints more detailed info
916 .  -mat_view - Prints matrix in ASCII format
917 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
918 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
919 .  -display <name> - Sets display name (default is host)
920 .  -draw_pause <sec> - Sets number of seconds to pause after display
921 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: ch_matlab for details)
922 .  -viewer_socket_machine <machine> -
923 .  -viewer_socket_port <port> -
924 .  -mat_view binary - save matrix to file in binary format
925 -  -viewer_binary_filename <name> -
926    Level: beginner
927 
928    Notes:
929     The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
930     the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
931 
932     See the manual page for MatLoad() for the exact format of the binary file when the binary
933       viewer is used.
934 
935       See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
936       viewer is used.
937 
938       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
939       and then use the following mouse functions.
940 + left mouse: zoom in
941 . middle mouse: zoom out
942 - right mouse: continue with the simulation
943 
944 .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
945           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
946 @*/
947 PetscErrorCode MatView(Mat mat,PetscViewer viewer)
948 {
949   PetscErrorCode    ierr;
950   PetscInt          rows,cols,rbs,cbs;
951   PetscBool         iascii,ibinary,isstring;
952   PetscViewerFormat format;
953   PetscMPIInt       size;
954 #if defined(PETSC_HAVE_SAWS)
955   PetscBool         issaws;
956 #endif
957 
958   PetscFunctionBegin;
959   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
960   PetscValidType(mat,1);
961   if (!viewer) {
962     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);CHKERRQ(ierr);
963   }
964   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
965   PetscCheckSameComm(mat,1,viewer,2);
966   MatCheckPreallocated(mat,1);
967   ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
968   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
969   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(0);
970   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);CHKERRQ(ierr);
971   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
972   if (ibinary) {
973     PetscBool mpiio;
974     ierr = PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);CHKERRQ(ierr);
975     if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
976   }
977 
978   ierr = PetscLogEventBegin(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
979   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
980   if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
981     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
982   }
983 
984 #if defined(PETSC_HAVE_SAWS)
985   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);CHKERRQ(ierr);
986 #endif
987   if (iascii) {
988     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
989     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);CHKERRQ(ierr);
990     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
991       MatNullSpace nullsp,transnullsp;
992 
993       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
994       ierr = MatGetSize(mat,&rows,&cols);CHKERRQ(ierr);
995       ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
996       if (rbs != 1 || cbs != 1) {
997         if (rbs != cbs) {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs = %D\n",rows,cols,rbs,cbs);CHKERRQ(ierr);}
998         else            {ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);CHKERRQ(ierr);}
999       } else {
1000         ierr = PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);CHKERRQ(ierr);
1001       }
1002       if (mat->factortype) {
1003         MatSolverType solver;
1004         ierr = MatFactorGetSolverType(mat,&solver);CHKERRQ(ierr);
1005         ierr = PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);CHKERRQ(ierr);
1006       }
1007       if (mat->ops->getinfo) {
1008         MatInfo info;
1009         ierr = MatGetInfo(mat,MAT_GLOBAL_SUM,&info);CHKERRQ(ierr);
1010         ierr = PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);CHKERRQ(ierr);
1011         ierr = PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls =%D\n",(PetscInt)info.mallocs);CHKERRQ(ierr);
1012       }
1013       ierr = MatGetNullSpace(mat,&nullsp);CHKERRQ(ierr);
1014       ierr = MatGetTransposeNullSpace(mat,&transnullsp);CHKERRQ(ierr);
1015       if (nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached null space\n");CHKERRQ(ierr);}
1016       if (transnullsp && transnullsp != nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached transposed null space\n");CHKERRQ(ierr);}
1017       ierr = MatGetNearNullSpace(mat,&nullsp);CHKERRQ(ierr);
1018       if (nullsp) {ierr = PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");CHKERRQ(ierr);}
1019     }
1020 #if defined(PETSC_HAVE_SAWS)
1021   } else if (issaws) {
1022     PetscMPIInt rank;
1023 
1024     ierr = PetscObjectName((PetscObject)mat);CHKERRQ(ierr);
1025     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
1026     if (!((PetscObject)mat)->amsmem && !rank) {
1027       ierr = PetscObjectViewSAWs((PetscObject)mat,viewer);CHKERRQ(ierr);
1028     }
1029 #endif
1030   } else if (isstring) {
1031     const char *type;
1032     ierr = MatGetType(mat,&type);CHKERRQ(ierr);
1033     ierr = PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);CHKERRQ(ierr);
1034     if (mat->ops->view) {ierr = (*mat->ops->view)(mat,viewer);CHKERRQ(ierr);}
1035   }
1036   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1037     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1038     ierr = (*mat->ops->viewnative)(mat,viewer);CHKERRQ(ierr);
1039     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1040   } else if (mat->ops->view) {
1041     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1042     ierr = (*mat->ops->view)(mat,viewer);CHKERRQ(ierr);
1043     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1044   }
1045   if (iascii) {
1046     ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
1047     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1048       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1049     }
1050   }
1051   ierr = PetscLogEventEnd(MAT_View,mat,viewer,0,0);CHKERRQ(ierr);
1052   PetscFunctionReturn(0);
1053 }
1054 
1055 #if defined(PETSC_USE_DEBUG)
1056 #include <../src/sys/totalview/tv_data_display.h>
1057 PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1058 {
1059   TV_add_row("Local rows", "int", &mat->rmap->n);
1060   TV_add_row("Local columns", "int", &mat->cmap->n);
1061   TV_add_row("Global rows", "int", &mat->rmap->N);
1062   TV_add_row("Global columns", "int", &mat->cmap->N);
1063   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1064   return TV_format_OK;
1065 }
1066 #endif
1067 
1068 /*@C
1069    MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1070    with MatView().  The matrix format is determined from the options database.
1071    Generates a parallel MPI matrix if the communicator has more than one
1072    processor.  The default matrix type is AIJ.
1073 
1074    Collective on PetscViewer
1075 
1076    Input Parameters:
1077 +  newmat - the newly loaded matrix, this needs to have been created with MatCreate()
1078             or some related function before a call to MatLoad()
1079 -  viewer - binary/HDF5 file viewer
1080 
1081    Options Database Keys:
1082    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1083    block size
1084 .    -matload_block_size <bs>
1085 
1086    Level: beginner
1087 
1088    Notes:
1089    If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1090    Mat before calling this routine if you wish to set it from the options database.
1091 
1092    MatLoad() automatically loads into the options database any options
1093    given in the file filename.info where filename is the name of the file
1094    that was passed to the PetscViewerBinaryOpen(). The options in the info
1095    file will be ignored if you use the -viewer_binary_skip_info option.
1096 
1097    If the type or size of newmat is not set before a call to MatLoad, PETSc
1098    sets the default matrix type AIJ and sets the local and global sizes.
1099    If type and/or size is already set, then the same are used.
1100 
1101    In parallel, each processor can load a subset of rows (or the
1102    entire matrix).  This routine is especially useful when a large
1103    matrix is stored on disk and only part of it is desired on each
1104    processor.  For example, a parallel solver may access only some of
1105    the rows from each processor.  The algorithm used here reads
1106    relatively small blocks of data rather than reading the entire
1107    matrix and then subsetting it.
1108 
1109    Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1110    Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1111    or the sequence like
1112 $    PetscViewer v;
1113 $    PetscViewerCreate(PETSC_COMM_WORLD,&v);
1114 $    PetscViewerSetType(v,PETSCVIEWERBINARY);
1115 $    PetscViewerSetFromOptions(v);
1116 $    PetscViewerFileSetMode(v,FILE_MODE_READ);
1117 $    PetscViewerFileSetName(v,"datafile");
1118    The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1119 $ -viewer_type {binary,hdf5}
1120 
1121    See the example src/ksp/ksp/examples/tutorials/ex27.c with the first approach,
1122    and src/mat/examples/tutorials/ex10.c with the second approach.
1123 
1124    Notes about the PETSc binary format:
1125    In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1126    is read onto rank 0 and then shipped to its destination rank, one after another.
1127    Multiple objects, both matrices and vectors, can be stored within the same file.
1128    Their PetscObject name is ignored; they are loaded in the order of their storage.
1129 
1130    Most users should not need to know the details of the binary storage
1131    format, since MatLoad() and MatView() completely hide these details.
1132    But for anyone who's interested, the standard binary matrix storage
1133    format is
1134 
1135 $    int    MAT_FILE_CLASSID
1136 $    int    number of rows
1137 $    int    number of columns
1138 $    int    total number of nonzeros
1139 $    int    *number nonzeros in each row
1140 $    int    *column indices of all nonzeros (starting index is zero)
1141 $    PetscScalar *values of all nonzeros
1142 
1143    PETSc automatically does the byte swapping for
1144 machines that store the bytes reversed, e.g.  DEC alpha, freebsd,
1145 linux, Windows and the paragon; thus if you write your own binary
1146 read/write routines you have to swap the bytes; see PetscBinaryRead()
1147 and PetscBinaryWrite() to see how this may be done.
1148 
1149    Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1150    In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1151    Each processor's chunk is loaded independently by its owning rank.
1152    Multiple objects, both matrices and vectors, can be stored within the same file.
1153    They are looked up by their PetscObject name.
1154 
1155    As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1156    by default the same structure and naming of the AIJ arrays and column count
1157    within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1158 $    save example.mat A b -v7.3
1159    can be directly read by this routine (see Reference 1 for details).
1160    Note that depending on your MATLAB version, this format might be a default,
1161    otherwise you can set it as default in Preferences.
1162 
1163    Unless -nocompression flag is used to save the file in MATLAB,
1164    PETSc must be configured with ZLIB package.
1165 
1166    See also examples src/mat/examples/tutorials/ex10.c and src/ksp/ksp/examples/tutorials/ex27.c
1167 
1168    Current HDF5 (MAT-File) limitations:
1169    This reader currently supports only real MATSEQAIJ, MATMPIAIJ, MATSEQDENSE and MATMPIDENSE matrices.
1170 
1171    Corresponding MatView() is not yet implemented.
1172 
1173    The loaded matrix is actually a transpose of the original one in MATLAB,
1174    unless you push PETSC_VIEWER_HDF5_MAT format (see examples above).
1175    With this format, matrix is automatically transposed by PETSc,
1176    unless the matrix is marked as SPD or symmetric
1177    (see MatSetOption(), MAT_SPD, MAT_SYMMETRIC).
1178 
1179    References:
1180 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version
1181 
1182 .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), MatView(), VecLoad()
1183 
1184  @*/
1185 PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1186 {
1187   PetscErrorCode ierr;
1188   PetscBool      flg;
1189 
1190   PetscFunctionBegin;
1191   PetscValidHeaderSpecific(newmat,MAT_CLASSID,1);
1192   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1193 
1194   if (!((PetscObject)newmat)->type_name) {
1195     ierr = MatSetType(newmat,MATAIJ);CHKERRQ(ierr);
1196   }
1197 
1198   flg  = PETSC_FALSE;
1199   ierr = PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);CHKERRQ(ierr);
1200   if (flg) {
1201     ierr = MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
1202     ierr = MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);CHKERRQ(ierr);
1203   }
1204   flg  = PETSC_FALSE;
1205   ierr = PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);CHKERRQ(ierr);
1206   if (flg) {
1207     ierr = MatSetOption(newmat,MAT_SPD,PETSC_TRUE);CHKERRQ(ierr);
1208   }
1209 
1210   if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
1211   ierr = PetscLogEventBegin(MAT_Load,viewer,0,0,0);CHKERRQ(ierr);
1212   ierr = (*newmat->ops->load)(newmat,viewer);CHKERRQ(ierr);
1213   ierr = PetscLogEventEnd(MAT_Load,viewer,0,0,0);CHKERRQ(ierr);
1214   PetscFunctionReturn(0);
1215 }
1216 
1217 PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1218 {
1219   PetscErrorCode ierr;
1220   Mat_Redundant  *redund = *redundant;
1221   PetscInt       i;
1222 
1223   PetscFunctionBegin;
1224   if (redund){
1225     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1226       ierr = ISDestroy(&redund->isrow);CHKERRQ(ierr);
1227       ierr = ISDestroy(&redund->iscol);CHKERRQ(ierr);
1228       ierr = MatDestroySubMatrices(1,&redund->matseq);CHKERRQ(ierr);
1229     } else {
1230       ierr = PetscFree2(redund->send_rank,redund->recv_rank);CHKERRQ(ierr);
1231       ierr = PetscFree(redund->sbuf_j);CHKERRQ(ierr);
1232       ierr = PetscFree(redund->sbuf_a);CHKERRQ(ierr);
1233       for (i=0; i<redund->nrecvs; i++) {
1234         ierr = PetscFree(redund->rbuf_j[i]);CHKERRQ(ierr);
1235         ierr = PetscFree(redund->rbuf_a[i]);CHKERRQ(ierr);
1236       }
1237       ierr = PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);CHKERRQ(ierr);
1238     }
1239 
1240     if (redund->subcomm) {
1241       ierr = PetscCommDestroy(&redund->subcomm);CHKERRQ(ierr);
1242     }
1243     ierr = PetscFree(redund);CHKERRQ(ierr);
1244   }
1245   PetscFunctionReturn(0);
1246 }
1247 
1248 /*@
1249    MatDestroy - Frees space taken by a matrix.
1250 
1251    Collective on Mat
1252 
1253    Input Parameter:
1254 .  A - the matrix
1255 
1256    Level: beginner
1257 
1258 @*/
1259 PetscErrorCode MatDestroy(Mat *A)
1260 {
1261   PetscErrorCode ierr;
1262 
1263   PetscFunctionBegin;
1264   if (!*A) PetscFunctionReturn(0);
1265   PetscValidHeaderSpecific(*A,MAT_CLASSID,1);
1266   if (--((PetscObject)(*A))->refct > 0) {*A = NULL; PetscFunctionReturn(0);}
1267 
1268   /* if memory was published with SAWs then destroy it */
1269   ierr = PetscObjectSAWsViewOff((PetscObject)*A);CHKERRQ(ierr);
1270   if ((*A)->ops->destroy) {
1271     ierr = (*(*A)->ops->destroy)(*A);CHKERRQ(ierr);
1272   }
1273 
1274   ierr = PetscFree((*A)->defaultvectype);CHKERRQ(ierr);
1275   ierr = PetscFree((*A)->bsizes);CHKERRQ(ierr);
1276   ierr = PetscFree((*A)->solvertype);CHKERRQ(ierr);
1277   ierr = MatDestroy_Redundant(&(*A)->redundant);CHKERRQ(ierr);
1278   ierr = MatNullSpaceDestroy(&(*A)->nullsp);CHKERRQ(ierr);
1279   ierr = MatNullSpaceDestroy(&(*A)->transnullsp);CHKERRQ(ierr);
1280   ierr = MatNullSpaceDestroy(&(*A)->nearnullsp);CHKERRQ(ierr);
1281   ierr = MatDestroy(&(*A)->schur);CHKERRQ(ierr);
1282   ierr = PetscLayoutDestroy(&(*A)->rmap);CHKERRQ(ierr);
1283   ierr = PetscLayoutDestroy(&(*A)->cmap);CHKERRQ(ierr);
1284   ierr = PetscHeaderDestroy(A);CHKERRQ(ierr);
1285   PetscFunctionReturn(0);
1286 }
1287 
1288 /*@C
1289    MatSetValues - Inserts or adds a block of values into a matrix.
1290    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1291    MUST be called after all calls to MatSetValues() have been completed.
1292 
1293    Not Collective
1294 
1295    Input Parameters:
1296 +  mat - the matrix
1297 .  v - a logically two-dimensional array of values
1298 .  m, idxm - the number of rows and their global indices
1299 .  n, idxn - the number of columns and their global indices
1300 -  addv - either ADD_VALUES or INSERT_VALUES, where
1301    ADD_VALUES adds values to any existing entries, and
1302    INSERT_VALUES replaces existing entries with new values
1303 
1304    Notes:
1305    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1306       MatSetUp() before using this routine
1307 
1308    By default the values, v, are row-oriented. See MatSetOption() for other options.
1309 
1310    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1311    options cannot be mixed without intervening calls to the assembly
1312    routines.
1313 
1314    MatSetValues() uses 0-based row and column numbers in Fortran
1315    as well as in C.
1316 
1317    Negative indices may be passed in idxm and idxn, these rows and columns are
1318    simply ignored. This allows easily inserting element stiffness matrices
1319    with homogeneous Dirchlet boundary conditions that you don't want represented
1320    in the matrix.
1321 
1322    Efficiency Alert:
1323    The routine MatSetValuesBlocked() may offer much better efficiency
1324    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1325 
1326    Level: beginner
1327 
1328    Developer Notes:
1329     This is labeled with C so does not automatically generate Fortran stubs and interfaces
1330                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1331 
1332 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1333           InsertMode, INSERT_VALUES, ADD_VALUES
1334 @*/
1335 PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1336 {
1337   PetscErrorCode ierr;
1338 #if defined(PETSC_USE_DEBUG)
1339   PetscInt       i,j;
1340 #endif
1341 
1342   PetscFunctionBeginHot;
1343   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1344   PetscValidType(mat,1);
1345   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1346   PetscValidIntPointer(idxm,3);
1347   PetscValidIntPointer(idxn,5);
1348   MatCheckPreallocated(mat,1);
1349 
1350   if (mat->insertmode == NOT_SET_VALUES) {
1351     mat->insertmode = addv;
1352   }
1353 #if defined(PETSC_USE_DEBUG)
1354   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1355   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1356   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1357 
1358   for (i=0; i<m; i++) {
1359     for (j=0; j<n; j++) {
1360       if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1361 #if defined(PETSC_USE_COMPLEX)
1362         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]);
1363 #else
1364         SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1365 #endif
1366     }
1367   }
1368 #endif
1369 
1370   if (mat->assembled) {
1371     mat->was_assembled = PETSC_TRUE;
1372     mat->assembled     = PETSC_FALSE;
1373   }
1374   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1375   ierr = (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);CHKERRQ(ierr);
1376   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1377   PetscFunctionReturn(0);
1378 }
1379 
1380 
1381 /*@
1382    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1383         values into a matrix
1384 
1385    Not Collective
1386 
1387    Input Parameters:
1388 +  mat - the matrix
1389 .  row - the (block) row to set
1390 -  v - a logically two-dimensional array of values
1391 
1392    Notes:
1393    By the values, v, are column-oriented (for the block version) and sorted
1394 
1395    All the nonzeros in the row must be provided
1396 
1397    The matrix must have previously had its column indices set
1398 
1399    The row must belong to this process
1400 
1401    Level: intermediate
1402 
1403 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1404           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1405 @*/
1406 PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1407 {
1408   PetscErrorCode ierr;
1409   PetscInt       globalrow;
1410 
1411   PetscFunctionBegin;
1412   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1413   PetscValidType(mat,1);
1414   PetscValidScalarPointer(v,2);
1415   ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);CHKERRQ(ierr);
1416   ierr = MatSetValuesRow(mat,globalrow,v);CHKERRQ(ierr);
1417   PetscFunctionReturn(0);
1418 }
1419 
1420 /*@
1421    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1422         values into a matrix
1423 
1424    Not Collective
1425 
1426    Input Parameters:
1427 +  mat - the matrix
1428 .  row - the (block) row to set
1429 -  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
1430 
1431    Notes:
1432    The values, v, are column-oriented for the block version.
1433 
1434    All the nonzeros in the row must be provided
1435 
1436    THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1437 
1438    The row must belong to this process
1439 
1440    Level: advanced
1441 
1442 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1443           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1444 @*/
1445 PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1446 {
1447   PetscErrorCode ierr;
1448 
1449   PetscFunctionBeginHot;
1450   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1451   PetscValidType(mat,1);
1452   MatCheckPreallocated(mat,1);
1453   PetscValidScalarPointer(v,2);
1454 #if defined(PETSC_USE_DEBUG)
1455   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1456   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1457 #endif
1458   mat->insertmode = INSERT_VALUES;
1459 
1460   if (mat->assembled) {
1461     mat->was_assembled = PETSC_TRUE;
1462     mat->assembled     = PETSC_FALSE;
1463   }
1464   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1465   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1466   ierr = (*mat->ops->setvaluesrow)(mat,row,v);CHKERRQ(ierr);
1467   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1468   PetscFunctionReturn(0);
1469 }
1470 
1471 /*@
1472    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1473      Using structured grid indexing
1474 
1475    Not Collective
1476 
1477    Input Parameters:
1478 +  mat - the matrix
1479 .  m - number of rows being entered
1480 .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1481 .  n - number of columns being entered
1482 .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1483 .  v - a logically two-dimensional array of values
1484 -  addv - either ADD_VALUES or INSERT_VALUES, where
1485    ADD_VALUES adds values to any existing entries, and
1486    INSERT_VALUES replaces existing entries with new values
1487 
1488    Notes:
1489    By default the values, v, are row-oriented.  See MatSetOption() for other options.
1490 
1491    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1492    options cannot be mixed without intervening calls to the assembly
1493    routines.
1494 
1495    The grid coordinates are across the entire grid, not just the local portion
1496 
1497    MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1498    as well as in C.
1499 
1500    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1501 
1502    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1503    or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1504 
1505    The columns and rows in the stencil passed in MUST be contained within the
1506    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1507    if you create a DMDA with an overlap of one grid level and on a particular process its first
1508    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1509    first i index you can use in your column and row indices in MatSetStencil() is 5.
1510 
1511    In Fortran idxm and idxn should be declared as
1512 $     MatStencil idxm(4,m),idxn(4,n)
1513    and the values inserted using
1514 $    idxm(MatStencil_i,1) = i
1515 $    idxm(MatStencil_j,1) = j
1516 $    idxm(MatStencil_k,1) = k
1517 $    idxm(MatStencil_c,1) = c
1518    etc
1519 
1520    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1521    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1522    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1523    DM_BOUNDARY_PERIODIC boundary type.
1524 
1525    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
1526    a single value per point) you can skip filling those indices.
1527 
1528    Inspired by the structured grid interface to the HYPRE package
1529    (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1530 
1531    Efficiency Alert:
1532    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1533    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1534 
1535    Level: beginner
1536 
1537 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1538           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1539 @*/
1540 PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1541 {
1542   PetscErrorCode ierr;
1543   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1544   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1545   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1546 
1547   PetscFunctionBegin;
1548   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1549   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1550   PetscValidType(mat,1);
1551   PetscValidIntPointer(idxm,3);
1552   PetscValidIntPointer(idxn,5);
1553 
1554   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1555     jdxm = buf; jdxn = buf+m;
1556   } else {
1557     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1558     jdxm = bufm; jdxn = bufn;
1559   }
1560   for (i=0; i<m; i++) {
1561     for (j=0; j<3-sdim; j++) dxm++;
1562     tmp = *dxm++ - starts[0];
1563     for (j=0; j<dim-1; j++) {
1564       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1565       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1566     }
1567     if (mat->stencil.noc) dxm++;
1568     jdxm[i] = tmp;
1569   }
1570   for (i=0; i<n; i++) {
1571     for (j=0; j<3-sdim; j++) dxn++;
1572     tmp = *dxn++ - starts[0];
1573     for (j=0; j<dim-1; j++) {
1574       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1575       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1576     }
1577     if (mat->stencil.noc) dxn++;
1578     jdxn[i] = tmp;
1579   }
1580   ierr = MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1581   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1582   PetscFunctionReturn(0);
1583 }
1584 
1585 /*@
1586    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1587      Using structured grid indexing
1588 
1589    Not Collective
1590 
1591    Input Parameters:
1592 +  mat - the matrix
1593 .  m - number of rows being entered
1594 .  idxm - grid coordinates for matrix rows being entered
1595 .  n - number of columns being entered
1596 .  idxn - grid coordinates for matrix columns being entered
1597 .  v - a logically two-dimensional array of values
1598 -  addv - either ADD_VALUES or INSERT_VALUES, where
1599    ADD_VALUES adds values to any existing entries, and
1600    INSERT_VALUES replaces existing entries with new values
1601 
1602    Notes:
1603    By default the values, v, are row-oriented and unsorted.
1604    See MatSetOption() for other options.
1605 
1606    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1607    options cannot be mixed without intervening calls to the assembly
1608    routines.
1609 
1610    The grid coordinates are across the entire grid, not just the local portion
1611 
1612    MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1613    as well as in C.
1614 
1615    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1616 
1617    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1618    or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1619 
1620    The columns and rows in the stencil passed in MUST be contained within the
1621    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1622    if you create a DMDA with an overlap of one grid level and on a particular process its first
1623    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1624    first i index you can use in your column and row indices in MatSetStencil() is 5.
1625 
1626    In Fortran idxm and idxn should be declared as
1627 $     MatStencil idxm(4,m),idxn(4,n)
1628    and the values inserted using
1629 $    idxm(MatStencil_i,1) = i
1630 $    idxm(MatStencil_j,1) = j
1631 $    idxm(MatStencil_k,1) = k
1632    etc
1633 
1634    Negative indices may be passed in idxm and idxn, these rows and columns are
1635    simply ignored. This allows easily inserting element stiffness matrices
1636    with homogeneous Dirchlet boundary conditions that you don't want represented
1637    in the matrix.
1638 
1639    Inspired by the structured grid interface to the HYPRE package
1640    (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1641 
1642    Level: beginner
1643 
1644 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1645           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1646           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1647 @*/
1648 PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1649 {
1650   PetscErrorCode ierr;
1651   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1652   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1653   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1654 
1655   PetscFunctionBegin;
1656   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1657   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1658   PetscValidType(mat,1);
1659   PetscValidIntPointer(idxm,3);
1660   PetscValidIntPointer(idxn,5);
1661   PetscValidScalarPointer(v,6);
1662 
1663   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1664     jdxm = buf; jdxn = buf+m;
1665   } else {
1666     ierr = PetscMalloc2(m,&bufm,n,&bufn);CHKERRQ(ierr);
1667     jdxm = bufm; jdxn = bufn;
1668   }
1669   for (i=0; i<m; i++) {
1670     for (j=0; j<3-sdim; j++) dxm++;
1671     tmp = *dxm++ - starts[0];
1672     for (j=0; j<sdim-1; j++) {
1673       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1674       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1675     }
1676     dxm++;
1677     jdxm[i] = tmp;
1678   }
1679   for (i=0; i<n; i++) {
1680     for (j=0; j<3-sdim; j++) dxn++;
1681     tmp = *dxn++ - starts[0];
1682     for (j=0; j<sdim-1; j++) {
1683       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1684       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1685     }
1686     dxn++;
1687     jdxn[i] = tmp;
1688   }
1689   ierr = MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);CHKERRQ(ierr);
1690   ierr = PetscFree2(bufm,bufn);CHKERRQ(ierr);
1691   PetscFunctionReturn(0);
1692 }
1693 
1694 /*@
1695    MatSetStencil - Sets the grid information for setting values into a matrix via
1696         MatSetValuesStencil()
1697 
1698    Not Collective
1699 
1700    Input Parameters:
1701 +  mat - the matrix
1702 .  dim - dimension of the grid 1, 2, or 3
1703 .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1704 .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1705 -  dof - number of degrees of freedom per node
1706 
1707 
1708    Inspired by the structured grid interface to the HYPRE package
1709    (www.llnl.gov/CASC/hyper)
1710 
1711    For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1712    user.
1713 
1714    Level: beginner
1715 
1716 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1717           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1718 @*/
1719 PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1720 {
1721   PetscInt i;
1722 
1723   PetscFunctionBegin;
1724   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1725   PetscValidIntPointer(dims,3);
1726   PetscValidIntPointer(starts,4);
1727 
1728   mat->stencil.dim = dim + (dof > 1);
1729   for (i=0; i<dim; i++) {
1730     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1731     mat->stencil.starts[i] = starts[dim-i-1];
1732   }
1733   mat->stencil.dims[dim]   = dof;
1734   mat->stencil.starts[dim] = 0;
1735   mat->stencil.noc         = (PetscBool)(dof == 1);
1736   PetscFunctionReturn(0);
1737 }
1738 
1739 /*@C
1740    MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1741 
1742    Not Collective
1743 
1744    Input Parameters:
1745 +  mat - the matrix
1746 .  v - a logically two-dimensional array of values
1747 .  m, idxm - the number of block rows and their global block indices
1748 .  n, idxn - the number of block columns and their global block indices
1749 -  addv - either ADD_VALUES or INSERT_VALUES, where
1750    ADD_VALUES adds values to any existing entries, and
1751    INSERT_VALUES replaces existing entries with new values
1752 
1753    Notes:
1754    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1755    MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1756 
1757    The m and n count the NUMBER of blocks in the row direction and column direction,
1758    NOT the total number of rows/columns; for example, if the block size is 2 and
1759    you are passing in values for rows 2,3,4,5  then m would be 2 (not 4).
1760    The values in idxm would be 1 2; that is the first index for each block divided by
1761    the block size.
1762 
1763    Note that you must call MatSetBlockSize() when constructing this matrix (before
1764    preallocating it).
1765 
1766    By default the values, v, are row-oriented, so the layout of
1767    v is the same as for MatSetValues(). See MatSetOption() for other options.
1768 
1769    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1770    options cannot be mixed without intervening calls to the assembly
1771    routines.
1772 
1773    MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1774    as well as in C.
1775 
1776    Negative indices may be passed in idxm and idxn, these rows and columns are
1777    simply ignored. This allows easily inserting element stiffness matrices
1778    with homogeneous Dirchlet boundary conditions that you don't want represented
1779    in the matrix.
1780 
1781    Each time an entry is set within a sparse matrix via MatSetValues(),
1782    internal searching must be done to determine where to place the
1783    data in the matrix storage space.  By instead inserting blocks of
1784    entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1785    reduced.
1786 
1787    Example:
1788 $   Suppose m=n=2 and block size(bs) = 2 The array is
1789 $
1790 $   1  2  | 3  4
1791 $   5  6  | 7  8
1792 $   - - - | - - -
1793 $   9  10 | 11 12
1794 $   13 14 | 15 16
1795 $
1796 $   v[] should be passed in like
1797 $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1798 $
1799 $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1800 $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1801 
1802    Level: intermediate
1803 
1804 .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1805 @*/
1806 PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1807 {
1808   PetscErrorCode ierr;
1809 
1810   PetscFunctionBeginHot;
1811   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1812   PetscValidType(mat,1);
1813   if (!m || !n) PetscFunctionReturn(0); /* no values to insert */
1814   PetscValidIntPointer(idxm,3);
1815   PetscValidIntPointer(idxn,5);
1816   PetscValidScalarPointer(v,6);
1817   MatCheckPreallocated(mat,1);
1818   if (mat->insertmode == NOT_SET_VALUES) {
1819     mat->insertmode = addv;
1820   }
1821 #if defined(PETSC_USE_DEBUG)
1822   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1823   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1824   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1825 #endif
1826 
1827   if (mat->assembled) {
1828     mat->was_assembled = PETSC_TRUE;
1829     mat->assembled     = PETSC_FALSE;
1830   }
1831   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1832   if (mat->ops->setvaluesblocked) {
1833     ierr = (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);CHKERRQ(ierr);
1834   } else {
1835     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1836     PetscInt i,j,bs,cbs;
1837     ierr = MatGetBlockSizes(mat,&bs,&cbs);CHKERRQ(ierr);
1838     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1839       iidxm = buf; iidxn = buf + m*bs;
1840     } else {
1841       ierr  = PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);CHKERRQ(ierr);
1842       iidxm = bufr; iidxn = bufc;
1843     }
1844     for (i=0; i<m; i++) {
1845       for (j=0; j<bs; j++) {
1846         iidxm[i*bs+j] = bs*idxm[i] + j;
1847       }
1848     }
1849     for (i=0; i<n; i++) {
1850       for (j=0; j<cbs; j++) {
1851         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1852       }
1853     }
1854     ierr = MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);CHKERRQ(ierr);
1855     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
1856   }
1857   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
1858   PetscFunctionReturn(0);
1859 }
1860 
1861 /*@
1862    MatGetValues - Gets a block of values from a matrix.
1863 
1864    Not Collective; currently only returns a local block
1865 
1866    Input Parameters:
1867 +  mat - the matrix
1868 .  v - a logically two-dimensional array for storing the values
1869 .  m, idxm - the number of rows and their global indices
1870 -  n, idxn - the number of columns and their global indices
1871 
1872    Notes:
1873    The user must allocate space (m*n PetscScalars) for the values, v.
1874    The values, v, are then returned in a row-oriented format,
1875    analogous to that used by default in MatSetValues().
1876 
1877    MatGetValues() uses 0-based row and column numbers in
1878    Fortran as well as in C.
1879 
1880    MatGetValues() requires that the matrix has been assembled
1881    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1882    MatSetValues() and MatGetValues() CANNOT be made in succession
1883    without intermediate matrix assembly.
1884 
1885    Negative row or column indices will be ignored and those locations in v[] will be
1886    left unchanged.
1887 
1888    Level: advanced
1889 
1890 .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1891 @*/
1892 PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1893 {
1894   PetscErrorCode ierr;
1895 
1896   PetscFunctionBegin;
1897   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1898   PetscValidType(mat,1);
1899   if (!m || !n) PetscFunctionReturn(0);
1900   PetscValidIntPointer(idxm,3);
1901   PetscValidIntPointer(idxn,5);
1902   PetscValidScalarPointer(v,6);
1903   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1904   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1905   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1906   MatCheckPreallocated(mat,1);
1907 
1908   ierr = PetscLogEventBegin(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1909   ierr = (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);CHKERRQ(ierr);
1910   ierr = PetscLogEventEnd(MAT_GetValues,mat,0,0,0);CHKERRQ(ierr);
1911   PetscFunctionReturn(0);
1912 }
1913 
1914 /*@
1915   MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1916   the same size. Currently, this can only be called once and creates the given matrix.
1917 
1918   Not Collective
1919 
1920   Input Parameters:
1921 + mat - the matrix
1922 . nb - the number of blocks
1923 . bs - the number of rows (and columns) in each block
1924 . rows - a concatenation of the rows for each block
1925 - v - a concatenation of logically two-dimensional arrays of values
1926 
1927   Notes:
1928   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
1929 
1930   Level: advanced
1931 
1932 .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1933           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1934 @*/
1935 PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1936 {
1937   PetscErrorCode ierr;
1938 
1939   PetscFunctionBegin;
1940   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
1941   PetscValidType(mat,1);
1942   PetscValidScalarPointer(rows,4);
1943   PetscValidScalarPointer(v,5);
1944 #if defined(PETSC_USE_DEBUG)
1945   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1946 #endif
1947 
1948   ierr = PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
1949   if (mat->ops->setvaluesbatch) {
1950     ierr = (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);CHKERRQ(ierr);
1951   } else {
1952     PetscInt b;
1953     for (b = 0; b < nb; ++b) {
1954       ierr = MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);CHKERRQ(ierr);
1955     }
1956   }
1957   ierr = PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);CHKERRQ(ierr);
1958   PetscFunctionReturn(0);
1959 }
1960 
1961 /*@
1962    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1963    the routine MatSetValuesLocal() to allow users to insert matrix entries
1964    using a local (per-processor) numbering.
1965 
1966    Not Collective
1967 
1968    Input Parameters:
1969 +  x - the matrix
1970 .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
1971 - cmapping - column mapping
1972 
1973    Level: intermediate
1974 
1975 
1976 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
1977 @*/
1978 PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
1979 {
1980   PetscErrorCode ierr;
1981 
1982   PetscFunctionBegin;
1983   PetscValidHeaderSpecific(x,MAT_CLASSID,1);
1984   PetscValidType(x,1);
1985   PetscValidHeaderSpecific(rmapping,IS_LTOGM_CLASSID,2);
1986   PetscValidHeaderSpecific(cmapping,IS_LTOGM_CLASSID,3);
1987 
1988   if (x->ops->setlocaltoglobalmapping) {
1989     ierr = (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);CHKERRQ(ierr);
1990   } else {
1991     ierr = PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);CHKERRQ(ierr);
1992     ierr = PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);CHKERRQ(ierr);
1993   }
1994   PetscFunctionReturn(0);
1995 }
1996 
1997 
1998 /*@
1999    MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
2000 
2001    Not Collective
2002 
2003    Input Parameters:
2004 .  A - the matrix
2005 
2006    Output Parameters:
2007 + rmapping - row mapping
2008 - cmapping - column mapping
2009 
2010    Level: advanced
2011 
2012 
2013 .seealso:  MatSetValuesLocal()
2014 @*/
2015 PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2016 {
2017   PetscFunctionBegin;
2018   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
2019   PetscValidType(A,1);
2020   if (rmapping) PetscValidPointer(rmapping,2);
2021   if (cmapping) PetscValidPointer(cmapping,3);
2022   if (rmapping) *rmapping = A->rmap->mapping;
2023   if (cmapping) *cmapping = A->cmap->mapping;
2024   PetscFunctionReturn(0);
2025 }
2026 
2027 /*@
2028    MatGetLayouts - Gets the PetscLayout objects for rows and columns
2029 
2030    Not Collective
2031 
2032    Input Parameters:
2033 .  A - the matrix
2034 
2035    Output Parameters:
2036 + rmap - row layout
2037 - cmap - column layout
2038 
2039    Level: advanced
2040 
2041 .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2042 @*/
2043 PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2044 {
2045   PetscFunctionBegin;
2046   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
2047   PetscValidType(A,1);
2048   if (rmap) PetscValidPointer(rmap,2);
2049   if (cmap) PetscValidPointer(cmap,3);
2050   if (rmap) *rmap = A->rmap;
2051   if (cmap) *cmap = A->cmap;
2052   PetscFunctionReturn(0);
2053 }
2054 
2055 /*@C
2056    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2057    using a local ordering of the nodes.
2058 
2059    Not Collective
2060 
2061    Input Parameters:
2062 +  mat - the matrix
2063 .  nrow, irow - number of rows and their local indices
2064 .  ncol, icol - number of columns and their local indices
2065 .  y -  a logically two-dimensional array of values
2066 -  addv - either INSERT_VALUES or ADD_VALUES, where
2067    ADD_VALUES adds values to any existing entries, and
2068    INSERT_VALUES replaces existing entries with new values
2069 
2070    Notes:
2071    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2072       MatSetUp() before using this routine
2073 
2074    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
2075 
2076    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2077    options cannot be mixed without intervening calls to the assembly
2078    routines.
2079 
2080    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2081    MUST be called after all calls to MatSetValuesLocal() have been completed.
2082 
2083    Level: intermediate
2084 
2085    Developer Notes:
2086     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2087                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2088 
2089 .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2090            MatSetValueLocal()
2091 @*/
2092 PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2093 {
2094   PetscErrorCode ierr;
2095 
2096   PetscFunctionBeginHot;
2097   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2098   PetscValidType(mat,1);
2099   MatCheckPreallocated(mat,1);
2100   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
2101   PetscValidIntPointer(irow,3);
2102   PetscValidIntPointer(icol,5);
2103   if (mat->insertmode == NOT_SET_VALUES) {
2104     mat->insertmode = addv;
2105   }
2106 #if defined(PETSC_USE_DEBUG)
2107   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2108   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2109   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2110 #endif
2111 
2112   if (mat->assembled) {
2113     mat->was_assembled = PETSC_TRUE;
2114     mat->assembled     = PETSC_FALSE;
2115   }
2116   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2117   if (mat->ops->setvalueslocal) {
2118     ierr = (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2119   } else {
2120     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2121     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2122       irowm = buf; icolm = buf+nrow;
2123     } else {
2124       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2125       irowm = bufr; icolm = bufc;
2126     }
2127     ierr = ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2128     ierr = ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2129     ierr = MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2130     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2131   }
2132   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2133   PetscFunctionReturn(0);
2134 }
2135 
2136 /*@C
2137    MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2138    using a local ordering of the nodes a block at a time.
2139 
2140    Not Collective
2141 
2142    Input Parameters:
2143 +  x - the matrix
2144 .  nrow, irow - number of rows and their local indices
2145 .  ncol, icol - number of columns and their local indices
2146 .  y -  a logically two-dimensional array of values
2147 -  addv - either INSERT_VALUES or ADD_VALUES, where
2148    ADD_VALUES adds values to any existing entries, and
2149    INSERT_VALUES replaces existing entries with new values
2150 
2151    Notes:
2152    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2153       MatSetUp() before using this routine
2154 
2155    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2156       before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2157 
2158    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2159    options cannot be mixed without intervening calls to the assembly
2160    routines.
2161 
2162    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2163    MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2164 
2165    Level: intermediate
2166 
2167    Developer Notes:
2168     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2169                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2170 
2171 .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2172            MatSetValuesLocal(),  MatSetValuesBlocked()
2173 @*/
2174 PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2175 {
2176   PetscErrorCode ierr;
2177 
2178   PetscFunctionBeginHot;
2179   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2180   PetscValidType(mat,1);
2181   MatCheckPreallocated(mat,1);
2182   if (!nrow || !ncol) PetscFunctionReturn(0); /* no values to insert */
2183   PetscValidIntPointer(irow,3);
2184   PetscValidIntPointer(icol,5);
2185   PetscValidScalarPointer(y,6);
2186   if (mat->insertmode == NOT_SET_VALUES) {
2187     mat->insertmode = addv;
2188   }
2189 #if defined(PETSC_USE_DEBUG)
2190   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2191   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2192   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);
2193 #endif
2194 
2195   if (mat->assembled) {
2196     mat->was_assembled = PETSC_TRUE;
2197     mat->assembled     = PETSC_FALSE;
2198   }
2199 #if defined(PETSC_USE_DEBUG)
2200   /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2201   if (mat->rmap->mapping) {
2202     PetscInt irbs, rbs;
2203     ierr = MatGetBlockSizes(mat, &rbs, NULL);CHKERRQ(ierr);
2204     ierr = ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);CHKERRQ(ierr);
2205     if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2206   }
2207   if (mat->cmap->mapping) {
2208     PetscInt icbs, cbs;
2209     ierr = MatGetBlockSizes(mat,NULL,&cbs);CHKERRQ(ierr);
2210     ierr = ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);CHKERRQ(ierr);
2211     if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2212   }
2213 #endif
2214   ierr = PetscLogEventBegin(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2215   if (mat->ops->setvaluesblockedlocal) {
2216     ierr = (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);CHKERRQ(ierr);
2217   } else {
2218     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2219     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2220       irowm = buf; icolm = buf + nrow;
2221     } else {
2222       ierr  = PetscMalloc2(nrow,&bufr,ncol,&bufc);CHKERRQ(ierr);
2223       irowm = bufr; icolm = bufc;
2224     }
2225     ierr = ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);CHKERRQ(ierr);
2226     ierr = ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);CHKERRQ(ierr);
2227     ierr = MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);CHKERRQ(ierr);
2228     ierr = PetscFree2(bufr,bufc);CHKERRQ(ierr);
2229   }
2230   ierr = PetscLogEventEnd(MAT_SetValues,mat,0,0,0);CHKERRQ(ierr);
2231   PetscFunctionReturn(0);
2232 }
2233 
2234 /*@
2235    MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2236 
2237    Collective on Mat
2238 
2239    Input Parameters:
2240 +  mat - the matrix
2241 -  x   - the vector to be multiplied
2242 
2243    Output Parameters:
2244 .  y - the result
2245 
2246    Notes:
2247    The vectors x and y cannot be the same.  I.e., one cannot
2248    call MatMult(A,y,y).
2249 
2250    Level: developer
2251 
2252 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2253 @*/
2254 PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2255 {
2256   PetscErrorCode ierr;
2257 
2258   PetscFunctionBegin;
2259   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2260   PetscValidType(mat,1);
2261   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2262   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2263 
2264   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2265   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2266   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2267   MatCheckPreallocated(mat,1);
2268 
2269   if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2270   ierr = (*mat->ops->multdiagonalblock)(mat,x,y);CHKERRQ(ierr);
2271   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2272   PetscFunctionReturn(0);
2273 }
2274 
2275 /* --------------------------------------------------------*/
2276 /*@
2277    MatMult - Computes the matrix-vector product, y = Ax.
2278 
2279    Neighbor-wise Collective on Mat
2280 
2281    Input Parameters:
2282 +  mat - the matrix
2283 -  x   - the vector to be multiplied
2284 
2285    Output Parameters:
2286 .  y - the result
2287 
2288    Notes:
2289    The vectors x and y cannot be the same.  I.e., one cannot
2290    call MatMult(A,y,y).
2291 
2292    Level: beginner
2293 
2294 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2295 @*/
2296 PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2297 {
2298   PetscErrorCode ierr;
2299 
2300   PetscFunctionBegin;
2301   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2302   PetscValidType(mat,1);
2303   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2304   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2305   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2306   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2307   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2308 #if !defined(PETSC_HAVE_CONSTRAINTS)
2309   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);
2310   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);
2311   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);
2312 #endif
2313   ierr = VecSetErrorIfLocked(y,3);CHKERRQ(ierr);
2314   if (mat->erroriffailure) {ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);}
2315   MatCheckPreallocated(mat,1);
2316 
2317   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2318   if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2319   ierr = PetscLogEventBegin(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2320   ierr = (*mat->ops->mult)(mat,x,y);CHKERRQ(ierr);
2321   ierr = PetscLogEventEnd(MAT_Mult,mat,x,y,0);CHKERRQ(ierr);
2322   if (mat->erroriffailure) {ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);}
2323   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2324   PetscFunctionReturn(0);
2325 }
2326 
2327 /*@
2328    MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.
2329 
2330    Neighbor-wise Collective on Mat
2331 
2332    Input Parameters:
2333 +  mat - the matrix
2334 -  x   - the vector to be multiplied
2335 
2336    Output Parameters:
2337 .  y - the result
2338 
2339    Notes:
2340    The vectors x and y cannot be the same.  I.e., one cannot
2341    call MatMultTranspose(A,y,y).
2342 
2343    For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2344    use MatMultHermitianTranspose()
2345 
2346    Level: beginner
2347 
2348 .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2349 @*/
2350 PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2351 {
2352   PetscErrorCode ierr;
2353 
2354   PetscFunctionBegin;
2355   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2356   PetscValidType(mat,1);
2357   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2358   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2359 
2360   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2361   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2362   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2363 #if !defined(PETSC_HAVE_CONSTRAINTS)
2364   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);
2365   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);
2366 #endif
2367   if (mat->erroriffailure) {ierr = VecValidValues(x,2,PETSC_TRUE);CHKERRQ(ierr);}
2368   MatCheckPreallocated(mat,1);
2369 
2370   if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2371   ierr = PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2372   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2373   ierr = (*mat->ops->multtranspose)(mat,x,y);CHKERRQ(ierr);
2374   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2375   ierr = PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);CHKERRQ(ierr);
2376   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2377   if (mat->erroriffailure) {ierr = VecValidValues(y,3,PETSC_FALSE);CHKERRQ(ierr);}
2378   PetscFunctionReturn(0);
2379 }
2380 
2381 /*@
2382    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2383 
2384    Neighbor-wise Collective on Mat
2385 
2386    Input Parameters:
2387 +  mat - the matrix
2388 -  x   - the vector to be multilplied
2389 
2390    Output Parameters:
2391 .  y - the result
2392 
2393    Notes:
2394    The vectors x and y cannot be the same.  I.e., one cannot
2395    call MatMultHermitianTranspose(A,y,y).
2396 
2397    Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2398 
2399    For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2400 
2401    Level: beginner
2402 
2403 .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2404 @*/
2405 PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2406 {
2407   PetscErrorCode ierr;
2408   Vec            w;
2409 
2410   PetscFunctionBegin;
2411   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2412   PetscValidType(mat,1);
2413   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2414   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2415 
2416   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2417   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2418   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2419 #if !defined(PETSC_HAVE_CONSTRAINTS)
2420   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);
2421   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);
2422 #endif
2423   MatCheckPreallocated(mat,1);
2424 
2425   ierr = PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2426   if (mat->ops->multhermitiantranspose) {
2427     ierr = VecLockReadPush(x);CHKERRQ(ierr);
2428     ierr = (*mat->ops->multhermitiantranspose)(mat,x,y);CHKERRQ(ierr);
2429     ierr = VecLockReadPop(x);CHKERRQ(ierr);
2430   } else {
2431     ierr = VecDuplicate(x,&w);CHKERRQ(ierr);
2432     ierr = VecCopy(x,w);CHKERRQ(ierr);
2433     ierr = VecConjugate(w);CHKERRQ(ierr);
2434     ierr = MatMultTranspose(mat,w,y);CHKERRQ(ierr);
2435     ierr = VecDestroy(&w);CHKERRQ(ierr);
2436     ierr = VecConjugate(y);CHKERRQ(ierr);
2437   }
2438   ierr = PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);CHKERRQ(ierr);
2439   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2440   PetscFunctionReturn(0);
2441 }
2442 
2443 /*@
2444     MatMultAdd -  Computes v3 = v2 + A * v1.
2445 
2446     Neighbor-wise Collective on Mat
2447 
2448     Input Parameters:
2449 +   mat - the matrix
2450 -   v1, v2 - the vectors
2451 
2452     Output Parameters:
2453 .   v3 - the result
2454 
2455     Notes:
2456     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2457     call MatMultAdd(A,v1,v2,v1).
2458 
2459     Level: beginner
2460 
2461 .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2462 @*/
2463 PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2464 {
2465   PetscErrorCode ierr;
2466 
2467   PetscFunctionBegin;
2468   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2469   PetscValidType(mat,1);
2470   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2471   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2472   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2473 
2474   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2475   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2476   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);
2477   /* 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);
2478      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); */
2479   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);
2480   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);
2481   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2482   MatCheckPreallocated(mat,1);
2483 
2484   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2485   ierr = PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2486   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2487   ierr = (*mat->ops->multadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2488   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2489   ierr = PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2490   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2491   PetscFunctionReturn(0);
2492 }
2493 
2494 /*@
2495    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2496 
2497    Neighbor-wise Collective on Mat
2498 
2499    Input Parameters:
2500 +  mat - the matrix
2501 -  v1, v2 - the vectors
2502 
2503    Output Parameters:
2504 .  v3 - the result
2505 
2506    Notes:
2507    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2508    call MatMultTransposeAdd(A,v1,v2,v1).
2509 
2510    Level: beginner
2511 
2512 .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2513 @*/
2514 PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2515 {
2516   PetscErrorCode ierr;
2517 
2518   PetscFunctionBegin;
2519   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2520   PetscValidType(mat,1);
2521   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2522   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2523   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2524 
2525   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2526   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2527   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2528   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2529   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);
2530   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);
2531   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);
2532   MatCheckPreallocated(mat,1);
2533 
2534   ierr = PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2535   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2536   ierr = (*mat->ops->multtransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2537   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2538   ierr = PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2539   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2540   PetscFunctionReturn(0);
2541 }
2542 
2543 /*@
2544    MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2545 
2546    Neighbor-wise Collective on Mat
2547 
2548    Input Parameters:
2549 +  mat - the matrix
2550 -  v1, v2 - the vectors
2551 
2552    Output Parameters:
2553 .  v3 - the result
2554 
2555    Notes:
2556    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2557    call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2558 
2559    Level: beginner
2560 
2561 .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2562 @*/
2563 PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2564 {
2565   PetscErrorCode ierr;
2566 
2567   PetscFunctionBegin;
2568   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2569   PetscValidType(mat,1);
2570   PetscValidHeaderSpecific(v1,VEC_CLASSID,2);
2571   PetscValidHeaderSpecific(v2,VEC_CLASSID,3);
2572   PetscValidHeaderSpecific(v3,VEC_CLASSID,4);
2573 
2574   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2575   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2576   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2577   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);
2578   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);
2579   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);
2580   MatCheckPreallocated(mat,1);
2581 
2582   ierr = PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2583   ierr = VecLockReadPush(v1);CHKERRQ(ierr);
2584   if (mat->ops->multhermitiantransposeadd) {
2585     ierr = (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);CHKERRQ(ierr);
2586   } else {
2587     Vec w,z;
2588     ierr = VecDuplicate(v1,&w);CHKERRQ(ierr);
2589     ierr = VecCopy(v1,w);CHKERRQ(ierr);
2590     ierr = VecConjugate(w);CHKERRQ(ierr);
2591     ierr = VecDuplicate(v3,&z);CHKERRQ(ierr);
2592     ierr = MatMultTranspose(mat,w,z);CHKERRQ(ierr);
2593     ierr = VecDestroy(&w);CHKERRQ(ierr);
2594     ierr = VecConjugate(z);CHKERRQ(ierr);
2595     if (v2 != v3) {
2596       ierr = VecWAXPY(v3,1.0,v2,z);CHKERRQ(ierr);
2597     } else {
2598       ierr = VecAXPY(v3,1.0,z);CHKERRQ(ierr);
2599     }
2600     ierr = VecDestroy(&z);CHKERRQ(ierr);
2601   }
2602   ierr = VecLockReadPop(v1);CHKERRQ(ierr);
2603   ierr = PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);CHKERRQ(ierr);
2604   ierr = PetscObjectStateIncrease((PetscObject)v3);CHKERRQ(ierr);
2605   PetscFunctionReturn(0);
2606 }
2607 
2608 /*@
2609    MatMultConstrained - The inner multiplication routine for a
2610    constrained matrix P^T A P.
2611 
2612    Neighbor-wise Collective on Mat
2613 
2614    Input Parameters:
2615 +  mat - the matrix
2616 -  x   - the vector to be multilplied
2617 
2618    Output Parameters:
2619 .  y - the result
2620 
2621    Notes:
2622    The vectors x and y cannot be the same.  I.e., one cannot
2623    call MatMult(A,y,y).
2624 
2625    Level: beginner
2626 
2627 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2628 @*/
2629 PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2630 {
2631   PetscErrorCode ierr;
2632 
2633   PetscFunctionBegin;
2634   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2635   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2636   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2637   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2638   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2639   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2640   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);
2641   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);
2642   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);
2643 
2644   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2645   ierr = VecLockReadPush(x);CHKERRQ(ierr);
2646   ierr = (*mat->ops->multconstrained)(mat,x,y);CHKERRQ(ierr);
2647   ierr = VecLockReadPop(x);CHKERRQ(ierr);
2648   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2649   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2650   PetscFunctionReturn(0);
2651 }
2652 
2653 /*@
2654    MatMultTransposeConstrained - The inner multiplication routine for a
2655    constrained matrix P^T A^T P.
2656 
2657    Neighbor-wise Collective on Mat
2658 
2659    Input Parameters:
2660 +  mat - the matrix
2661 -  x   - the vector to be multilplied
2662 
2663    Output Parameters:
2664 .  y - the result
2665 
2666    Notes:
2667    The vectors x and y cannot be the same.  I.e., one cannot
2668    call MatMult(A,y,y).
2669 
2670    Level: beginner
2671 
2672 .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2673 @*/
2674 PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2675 {
2676   PetscErrorCode ierr;
2677 
2678   PetscFunctionBegin;
2679   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2680   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2681   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2682   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2683   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2684   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2685   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);
2686   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);
2687 
2688   ierr = PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2689   ierr = (*mat->ops->multtransposeconstrained)(mat,x,y);CHKERRQ(ierr);
2690   ierr = PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);CHKERRQ(ierr);
2691   ierr = PetscObjectStateIncrease((PetscObject)y);CHKERRQ(ierr);
2692   PetscFunctionReturn(0);
2693 }
2694 
2695 /*@C
2696    MatGetFactorType - gets the type of factorization it is
2697 
2698    Not Collective
2699 
2700    Input Parameters:
2701 .  mat - the matrix
2702 
2703    Output Parameters:
2704 .  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2705 
2706    Level: intermediate
2707 
2708 .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2709 @*/
2710 PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2711 {
2712   PetscFunctionBegin;
2713   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2714   PetscValidType(mat,1);
2715   PetscValidPointer(t,2);
2716   *t = mat->factortype;
2717   PetscFunctionReturn(0);
2718 }
2719 
2720 /*@C
2721    MatSetFactorType - sets the type of factorization it is
2722 
2723    Logically Collective on Mat
2724 
2725    Input Parameters:
2726 +  mat - the matrix
2727 -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2728 
2729    Level: intermediate
2730 
2731 .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2732 @*/
2733 PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2734 {
2735   PetscFunctionBegin;
2736   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2737   PetscValidType(mat,1);
2738   mat->factortype = t;
2739   PetscFunctionReturn(0);
2740 }
2741 
2742 /* ------------------------------------------------------------*/
2743 /*@C
2744    MatGetInfo - Returns information about matrix storage (number of
2745    nonzeros, memory, etc.).
2746 
2747    Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2748 
2749    Input Parameters:
2750 .  mat - the matrix
2751 
2752    Output Parameters:
2753 +  flag - flag indicating the type of parameters to be returned
2754    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2755    MAT_GLOBAL_SUM - sum over all processors)
2756 -  info - matrix information context
2757 
2758    Notes:
2759    The MatInfo context contains a variety of matrix data, including
2760    number of nonzeros allocated and used, number of mallocs during
2761    matrix assembly, etc.  Additional information for factored matrices
2762    is provided (such as the fill ratio, number of mallocs during
2763    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2764    when using the runtime options
2765 $       -info -mat_view ::ascii_info
2766 
2767    Example for C/C++ Users:
2768    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2769    data within the MatInfo context.  For example,
2770 .vb
2771       MatInfo info;
2772       Mat     A;
2773       double  mal, nz_a, nz_u;
2774 
2775       MatGetInfo(A,MAT_LOCAL,&info);
2776       mal  = info.mallocs;
2777       nz_a = info.nz_allocated;
2778 .ve
2779 
2780    Example for Fortran Users:
2781    Fortran users should declare info as a double precision
2782    array of dimension MAT_INFO_SIZE, and then extract the parameters
2783    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2784    a complete list of parameter names.
2785 .vb
2786       double  precision info(MAT_INFO_SIZE)
2787       double  precision mal, nz_a
2788       Mat     A
2789       integer ierr
2790 
2791       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2792       mal = info(MAT_INFO_MALLOCS)
2793       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2794 .ve
2795 
2796     Level: intermediate
2797 
2798     Developer Note: fortran interface is not autogenerated as the f90
2799     interface defintion cannot be generated correctly [due to MatInfo]
2800 
2801 .seealso: MatStashGetInfo()
2802 
2803 @*/
2804 PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2805 {
2806   PetscErrorCode ierr;
2807 
2808   PetscFunctionBegin;
2809   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2810   PetscValidType(mat,1);
2811   PetscValidPointer(info,3);
2812   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2813   MatCheckPreallocated(mat,1);
2814   ierr = (*mat->ops->getinfo)(mat,flag,info);CHKERRQ(ierr);
2815   PetscFunctionReturn(0);
2816 }
2817 
2818 /*
2819    This is used by external packages where it is not easy to get the info from the actual
2820    matrix factorization.
2821 */
2822 PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2823 {
2824   PetscErrorCode ierr;
2825 
2826   PetscFunctionBegin;
2827   ierr = PetscMemzero(info,sizeof(MatInfo));CHKERRQ(ierr);
2828   PetscFunctionReturn(0);
2829 }
2830 
2831 /* ----------------------------------------------------------*/
2832 
2833 /*@C
2834    MatLUFactor - Performs in-place LU factorization of matrix.
2835 
2836    Collective on Mat
2837 
2838    Input Parameters:
2839 +  mat - the matrix
2840 .  row - row permutation
2841 .  col - column permutation
2842 -  info - options for factorization, includes
2843 $          fill - expected fill as ratio of original fill.
2844 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2845 $                   Run with the option -info to determine an optimal value to use
2846 
2847    Notes:
2848    Most users should employ the simplified KSP interface for linear solvers
2849    instead of working directly with matrix algebra routines such as this.
2850    See, e.g., KSPCreate().
2851 
2852    This changes the state of the matrix to a factored matrix; it cannot be used
2853    for example with MatSetValues() unless one first calls MatSetUnfactored().
2854 
2855    Level: developer
2856 
2857 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2858           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2859 
2860     Developer Note: fortran interface is not autogenerated as the f90
2861     interface defintion cannot be generated correctly [due to MatFactorInfo]
2862 
2863 @*/
2864 PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2865 {
2866   PetscErrorCode ierr;
2867   MatFactorInfo  tinfo;
2868 
2869   PetscFunctionBegin;
2870   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2871   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2872   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2873   if (info) PetscValidPointer(info,4);
2874   PetscValidType(mat,1);
2875   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2876   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2877   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2878   MatCheckPreallocated(mat,1);
2879   if (!info) {
2880     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
2881     info = &tinfo;
2882   }
2883 
2884   ierr = PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2885   ierr = (*mat->ops->lufactor)(mat,row,col,info);CHKERRQ(ierr);
2886   ierr = PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);CHKERRQ(ierr);
2887   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
2888   PetscFunctionReturn(0);
2889 }
2890 
2891 /*@C
2892    MatILUFactor - Performs in-place ILU factorization of matrix.
2893 
2894    Collective on Mat
2895 
2896    Input Parameters:
2897 +  mat - the matrix
2898 .  row - row permutation
2899 .  col - column permutation
2900 -  info - structure containing
2901 $      levels - number of levels of fill.
2902 $      expected fill - as ratio of original fill.
2903 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2904                 missing diagonal entries)
2905 
2906    Notes:
2907    Probably really in-place only when level of fill is zero, otherwise allocates
2908    new space to store factored matrix and deletes previous memory.
2909 
2910    Most users should employ the simplified KSP interface for linear solvers
2911    instead of working directly with matrix algebra routines such as this.
2912    See, e.g., KSPCreate().
2913 
2914    Level: developer
2915 
2916 .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2917 
2918     Developer Note: fortran interface is not autogenerated as the f90
2919     interface defintion cannot be generated correctly [due to MatFactorInfo]
2920 
2921 @*/
2922 PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2923 {
2924   PetscErrorCode ierr;
2925 
2926   PetscFunctionBegin;
2927   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2928   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2929   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2930   PetscValidPointer(info,4);
2931   PetscValidType(mat,1);
2932   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
2933   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2934   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2935   if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2936   MatCheckPreallocated(mat,1);
2937 
2938   ierr = PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
2939   ierr = (*mat->ops->ilufactor)(mat,row,col,info);CHKERRQ(ierr);
2940   ierr = PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);CHKERRQ(ierr);
2941   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
2942   PetscFunctionReturn(0);
2943 }
2944 
2945 /*@C
2946    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2947    Call this routine before calling MatLUFactorNumeric().
2948 
2949    Collective on Mat
2950 
2951    Input Parameters:
2952 +  fact - the factor matrix obtained with MatGetFactor()
2953 .  mat - the matrix
2954 .  row, col - row and column permutations
2955 -  info - options for factorization, includes
2956 $          fill - expected fill as ratio of original fill.
2957 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2958 $                   Run with the option -info to determine an optimal value to use
2959 
2960 
2961    Notes:
2962     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
2963 
2964    Most users should employ the simplified KSP interface for linear solvers
2965    instead of working directly with matrix algebra routines such as this.
2966    See, e.g., KSPCreate().
2967 
2968    Level: developer
2969 
2970 .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
2971 
2972     Developer Note: fortran interface is not autogenerated as the f90
2973     interface defintion cannot be generated correctly [due to MatFactorInfo]
2974 
2975 @*/
2976 PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
2977 {
2978   PetscErrorCode ierr;
2979   MatFactorInfo  tinfo;
2980 
2981   PetscFunctionBegin;
2982   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
2983   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
2984   if (col) PetscValidHeaderSpecific(col,IS_CLASSID,3);
2985   if (info) PetscValidPointer(info,4);
2986   PetscValidType(mat,1);
2987   PetscValidPointer(fact,5);
2988   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2989   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2990   if (!(fact)->ops->lufactorsymbolic) {
2991     MatSolverType spackage;
2992     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
2993     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
2994   }
2995   MatCheckPreallocated(mat,2);
2996   if (!info) {
2997     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
2998     info = &tinfo;
2999   }
3000 
3001   ierr = PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
3002   ierr = (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
3003   ierr = PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
3004   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3005   PetscFunctionReturn(0);
3006 }
3007 
3008 /*@C
3009    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3010    Call this routine after first calling MatLUFactorSymbolic().
3011 
3012    Collective on Mat
3013 
3014    Input Parameters:
3015 +  fact - the factor matrix obtained with MatGetFactor()
3016 .  mat - the matrix
3017 -  info - options for factorization
3018 
3019    Notes:
3020    See MatLUFactor() for in-place factorization.  See
3021    MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3022 
3023    Most users should employ the simplified KSP interface for linear solvers
3024    instead of working directly with matrix algebra routines such as this.
3025    See, e.g., KSPCreate().
3026 
3027    Level: developer
3028 
3029 .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3030 
3031     Developer Note: fortran interface is not autogenerated as the f90
3032     interface defintion cannot be generated correctly [due to MatFactorInfo]
3033 
3034 @*/
3035 PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3036 {
3037   MatFactorInfo  tinfo;
3038   PetscErrorCode ierr;
3039 
3040   PetscFunctionBegin;
3041   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3042   PetscValidType(mat,1);
3043   PetscValidPointer(fact,2);
3044   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
3045   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3046   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dimensions are different %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3047 
3048   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3049   MatCheckPreallocated(mat,2);
3050   if (!info) {
3051     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3052     info = &tinfo;
3053   }
3054 
3055   ierr = PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3056   ierr = (fact->ops->lufactornumeric)(fact,mat,info);CHKERRQ(ierr);
3057   ierr = PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3058   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3059   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3060   PetscFunctionReturn(0);
3061 }
3062 
3063 /*@C
3064    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3065    symmetric matrix.
3066 
3067    Collective on Mat
3068 
3069    Input Parameters:
3070 +  mat - the matrix
3071 .  perm - row and column permutations
3072 -  f - expected fill as ratio of original fill
3073 
3074    Notes:
3075    See MatLUFactor() for the nonsymmetric case.  See also
3076    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3077 
3078    Most users should employ the simplified KSP interface for linear solvers
3079    instead of working directly with matrix algebra routines such as this.
3080    See, e.g., KSPCreate().
3081 
3082    Level: developer
3083 
3084 .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3085           MatGetOrdering()
3086 
3087     Developer Note: fortran interface is not autogenerated as the f90
3088     interface defintion cannot be generated correctly [due to MatFactorInfo]
3089 
3090 @*/
3091 PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3092 {
3093   PetscErrorCode ierr;
3094   MatFactorInfo  tinfo;
3095 
3096   PetscFunctionBegin;
3097   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3098   PetscValidType(mat,1);
3099   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3100   if (info) PetscValidPointer(info,3);
3101   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3102   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3103   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3104   if (!mat->ops->choleskyfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"In-place factorization for Mat type %s is not supported, try out-of-place factorization. See MatCholeskyFactorSymbolic/Numeric",((PetscObject)mat)->type_name);
3105   MatCheckPreallocated(mat,1);
3106   if (!info) {
3107     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3108     info = &tinfo;
3109   }
3110 
3111   ierr = PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3112   ierr = (*mat->ops->choleskyfactor)(mat,perm,info);CHKERRQ(ierr);
3113   ierr = PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);CHKERRQ(ierr);
3114   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
3115   PetscFunctionReturn(0);
3116 }
3117 
3118 /*@C
3119    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3120    of a symmetric matrix.
3121 
3122    Collective on Mat
3123 
3124    Input Parameters:
3125 +  fact - the factor matrix obtained with MatGetFactor()
3126 .  mat - the matrix
3127 .  perm - row and column permutations
3128 -  info - options for factorization, includes
3129 $          fill - expected fill as ratio of original fill.
3130 $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3131 $                   Run with the option -info to determine an optimal value to use
3132 
3133    Notes:
3134    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3135    MatCholeskyFactor() and MatCholeskyFactorNumeric().
3136 
3137    Most users should employ the simplified KSP interface for linear solvers
3138    instead of working directly with matrix algebra routines such as this.
3139    See, e.g., KSPCreate().
3140 
3141    Level: developer
3142 
3143 .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3144           MatGetOrdering()
3145 
3146     Developer Note: fortran interface is not autogenerated as the f90
3147     interface defintion cannot be generated correctly [due to MatFactorInfo]
3148 
3149 @*/
3150 PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3151 {
3152   PetscErrorCode ierr;
3153   MatFactorInfo  tinfo;
3154 
3155   PetscFunctionBegin;
3156   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3157   PetscValidType(mat,1);
3158   if (perm) PetscValidHeaderSpecific(perm,IS_CLASSID,2);
3159   if (info) PetscValidPointer(info,3);
3160   PetscValidPointer(fact,4);
3161   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3162   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3163   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3164   if (!(fact)->ops->choleskyfactorsymbolic) {
3165     MatSolverType spackage;
3166     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
3167     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3168   }
3169   MatCheckPreallocated(mat,2);
3170   if (!info) {
3171     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3172     info = &tinfo;
3173   }
3174 
3175   ierr = PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3176   ierr = (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
3177   ierr = PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
3178   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3179   PetscFunctionReturn(0);
3180 }
3181 
3182 /*@C
3183    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3184    of a symmetric matrix. Call this routine after first calling
3185    MatCholeskyFactorSymbolic().
3186 
3187    Collective on Mat
3188 
3189    Input Parameters:
3190 +  fact - the factor matrix obtained with MatGetFactor()
3191 .  mat - the initial matrix
3192 .  info - options for factorization
3193 -  fact - the symbolic factor of mat
3194 
3195 
3196    Notes:
3197    Most users should employ the simplified KSP interface for linear solvers
3198    instead of working directly with matrix algebra routines such as this.
3199    See, e.g., KSPCreate().
3200 
3201    Level: developer
3202 
3203 .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3204 
3205     Developer Note: fortran interface is not autogenerated as the f90
3206     interface defintion cannot be generated correctly [due to MatFactorInfo]
3207 
3208 @*/
3209 PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3210 {
3211   MatFactorInfo  tinfo;
3212   PetscErrorCode ierr;
3213 
3214   PetscFunctionBegin;
3215   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3216   PetscValidType(mat,1);
3217   PetscValidPointer(fact,2);
3218   PetscValidHeaderSpecific(fact,MAT_CLASSID,2);
3219   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3220   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3221   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dim %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3222   MatCheckPreallocated(mat,2);
3223   if (!info) {
3224     ierr = MatFactorInfoInitialize(&tinfo);CHKERRQ(ierr);
3225     info = &tinfo;
3226   }
3227 
3228   ierr = PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3229   ierr = (fact->ops->choleskyfactornumeric)(fact,mat,info);CHKERRQ(ierr);
3230   ierr = PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);CHKERRQ(ierr);
3231   ierr = MatViewFromOptions(fact,NULL,"-mat_factor_view");CHKERRQ(ierr);
3232   ierr = PetscObjectStateIncrease((PetscObject)fact);CHKERRQ(ierr);
3233   PetscFunctionReturn(0);
3234 }
3235 
3236 /* ----------------------------------------------------------------*/
3237 /*@
3238    MatSolve - Solves A x = b, given a factored matrix.
3239 
3240    Neighbor-wise Collective on Mat
3241 
3242    Input Parameters:
3243 +  mat - the factored matrix
3244 -  b - the right-hand-side vector
3245 
3246    Output Parameter:
3247 .  x - the result vector
3248 
3249    Notes:
3250    The vectors b and x cannot be the same.  I.e., one cannot
3251    call MatSolve(A,x,x).
3252 
3253    Notes:
3254    Most users should employ the simplified KSP interface for linear solvers
3255    instead of working directly with matrix algebra routines such as this.
3256    See, e.g., KSPCreate().
3257 
3258    Level: developer
3259 
3260 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3261 @*/
3262 PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3263 {
3264   PetscErrorCode ierr;
3265 
3266   PetscFunctionBegin;
3267   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3268   PetscValidType(mat,1);
3269   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3270   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3271   PetscCheckSameComm(mat,1,b,2);
3272   PetscCheckSameComm(mat,1,x,3);
3273   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3274   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);
3275   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);
3276   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);
3277   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3278   if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3279   MatCheckPreallocated(mat,1);
3280 
3281   ierr = PetscLogEventBegin(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3282   if (mat->factorerrortype) {
3283     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3284     ierr = VecSetInf(x);CHKERRQ(ierr);
3285   } else {
3286     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3287     ierr = (*mat->ops->solve)(mat,b,x);CHKERRQ(ierr);
3288   }
3289   ierr = PetscLogEventEnd(MAT_Solve,mat,b,x,0);CHKERRQ(ierr);
3290   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3291   PetscFunctionReturn(0);
3292 }
3293 
3294 static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X, PetscBool trans)
3295 {
3296   PetscErrorCode ierr;
3297   Vec            b,x;
3298   PetscInt       m,N,i;
3299   PetscScalar    *bb,*xx;
3300 
3301   PetscFunctionBegin;
3302   ierr = MatDenseGetArray(B,&bb);CHKERRQ(ierr);
3303   ierr = MatDenseGetArray(X,&xx);CHKERRQ(ierr);
3304   ierr = MatGetLocalSize(B,&m,NULL);CHKERRQ(ierr);  /* number local rows */
3305   ierr = MatGetSize(B,NULL,&N);CHKERRQ(ierr);       /* total columns in dense matrix */
3306   ierr = MatCreateVecs(A,&x,&b);CHKERRQ(ierr);
3307   for (i=0; i<N; i++) {
3308     ierr = VecPlaceArray(b,bb + i*m);CHKERRQ(ierr);
3309     ierr = VecPlaceArray(x,xx + i*m);CHKERRQ(ierr);
3310     if (trans) {
3311       ierr = MatSolveTranspose(A,b,x);CHKERRQ(ierr);
3312     } else {
3313       ierr = MatSolve(A,b,x);CHKERRQ(ierr);
3314     }
3315     ierr = VecResetArray(x);CHKERRQ(ierr);
3316     ierr = VecResetArray(b);CHKERRQ(ierr);
3317   }
3318   ierr = VecDestroy(&b);CHKERRQ(ierr);
3319   ierr = VecDestroy(&x);CHKERRQ(ierr);
3320   ierr = MatDenseRestoreArray(B,&bb);CHKERRQ(ierr);
3321   ierr = MatDenseRestoreArray(X,&xx);CHKERRQ(ierr);
3322   PetscFunctionReturn(0);
3323 }
3324 
3325 /*@
3326    MatMatSolve - Solves A X = B, given a factored matrix.
3327 
3328    Neighbor-wise Collective on Mat
3329 
3330    Input Parameters:
3331 +  A - the factored matrix
3332 -  B - the right-hand-side matrix  (dense matrix)
3333 
3334    Output Parameter:
3335 .  X - the result matrix (dense matrix)
3336 
3337    Notes:
3338    The matrices b and x cannot be the same.  I.e., one cannot
3339    call MatMatSolve(A,x,x).
3340 
3341    Notes:
3342    Most users should usually employ the simplified KSP interface for linear solvers
3343    instead of working directly with matrix algebra routines such as this.
3344    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3345    at a time.
3346 
3347    When using SuperLU_Dist as a parallel solver PETSc will use the SuperLU_Dist functionality to solve multiple right hand sides simultaneously. For MUMPS
3348    it calls a separate solve for each right hand side since MUMPS does not yet support distributed right hand sides.
3349 
3350    Since the resulting matrix X must always be dense we do not support sparse representation of the matrix B.
3351 
3352    Level: developer
3353 
3354 .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3355 @*/
3356 PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3357 {
3358   PetscErrorCode ierr;
3359 
3360   PetscFunctionBegin;
3361   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3362   PetscValidType(A,1);
3363   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3364   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3365   PetscCheckSameComm(A,1,B,2);
3366   PetscCheckSameComm(A,1,X,3);
3367   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3368   if (A->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);
3369   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);
3370   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");
3371   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3372   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3373   MatCheckPreallocated(A,1);
3374 
3375   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3376   if (!A->ops->matsolve) {
3377     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3378     ierr = MatMatSolve_Basic(A,B,X,PETSC_FALSE);CHKERRQ(ierr);
3379   } else {
3380     ierr = (*A->ops->matsolve)(A,B,X);CHKERRQ(ierr);
3381   }
3382   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3383   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3384   PetscFunctionReturn(0);
3385 }
3386 
3387 /*@
3388    MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3389 
3390    Neighbor-wise Collective on Mat
3391 
3392    Input Parameters:
3393 +  A - the factored matrix
3394 -  B - the right-hand-side matrix  (dense matrix)
3395 
3396    Output Parameter:
3397 .  X - the result matrix (dense matrix)
3398 
3399    Notes:
3400    The matrices B and X cannot be the same.  I.e., one cannot
3401    call MatMatSolveTranspose(A,X,X).
3402 
3403    Notes:
3404    Most users should usually employ the simplified KSP interface for linear solvers
3405    instead of working directly with matrix algebra routines such as this.
3406    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3407    at a time.
3408 
3409    When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3410 
3411    Level: developer
3412 
3413 .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3414 @*/
3415 PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3416 {
3417   PetscErrorCode ierr;
3418 
3419   PetscFunctionBegin;
3420   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3421   PetscValidType(A,1);
3422   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3423   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3424   PetscCheckSameComm(A,1,B,2);
3425   PetscCheckSameComm(A,1,X,3);
3426   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3427   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);
3428   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);
3429   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);
3430   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");
3431   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3432   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3433   MatCheckPreallocated(A,1);
3434 
3435   ierr = PetscLogEventBegin(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3436   if (!A->ops->matsolvetranspose) {
3437     ierr = PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);CHKERRQ(ierr);
3438     ierr = MatMatSolve_Basic(A,B,X,PETSC_TRUE);CHKERRQ(ierr);
3439   } else {
3440     ierr = (*A->ops->matsolvetranspose)(A,B,X);CHKERRQ(ierr);
3441   }
3442   ierr = PetscLogEventEnd(MAT_MatSolve,A,B,X,0);CHKERRQ(ierr);
3443   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3444   PetscFunctionReturn(0);
3445 }
3446 
3447 /*@
3448    MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3449 
3450    Neighbor-wise Collective on Mat
3451 
3452    Input Parameters:
3453 +  A - the factored matrix
3454 -  Bt - the transpose of right-hand-side matrix
3455 
3456    Output Parameter:
3457 .  X - the result matrix (dense matrix)
3458 
3459    Notes:
3460    Most users should usually employ the simplified KSP interface for linear solvers
3461    instead of working directly with matrix algebra routines such as this.
3462    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3463    at a time.
3464 
3465    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().
3466 
3467    Level: developer
3468 
3469 .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3470 @*/
3471 PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3472 {
3473   PetscErrorCode ierr;
3474 
3475   PetscFunctionBegin;
3476   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3477   PetscValidType(A,1);
3478   PetscValidHeaderSpecific(Bt,MAT_CLASSID,2);
3479   PetscValidHeaderSpecific(X,MAT_CLASSID,3);
3480   PetscCheckSameComm(A,1,Bt,2);
3481   PetscCheckSameComm(A,1,X,3);
3482 
3483   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3484   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);
3485   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);
3486   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");
3487   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(0);
3488   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3489   MatCheckPreallocated(A,1);
3490 
3491   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3492   ierr = PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3493   ierr = (*A->ops->mattransposesolve)(A,Bt,X);CHKERRQ(ierr);
3494   ierr = PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);CHKERRQ(ierr);
3495   ierr = PetscObjectStateIncrease((PetscObject)X);CHKERRQ(ierr);
3496   PetscFunctionReturn(0);
3497 }
3498 
3499 /*@
3500    MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3501                             U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3502 
3503    Neighbor-wise Collective on Mat
3504 
3505    Input Parameters:
3506 +  mat - the factored matrix
3507 -  b - the right-hand-side vector
3508 
3509    Output Parameter:
3510 .  x - the result vector
3511 
3512    Notes:
3513    MatSolve() should be used for most applications, as it performs
3514    a forward solve followed by a backward solve.
3515 
3516    The vectors b and x cannot be the same,  i.e., one cannot
3517    call MatForwardSolve(A,x,x).
3518 
3519    For matrix in seqsbaij format with block size larger than 1,
3520    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3521    MatForwardSolve() solves U^T*D y = b, and
3522    MatBackwardSolve() solves U x = y.
3523    Thus they do not provide a symmetric preconditioner.
3524 
3525    Most users should employ the simplified KSP interface for linear solvers
3526    instead of working directly with matrix algebra routines such as this.
3527    See, e.g., KSPCreate().
3528 
3529    Level: developer
3530 
3531 .seealso: MatSolve(), MatBackwardSolve()
3532 @*/
3533 PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3534 {
3535   PetscErrorCode ierr;
3536 
3537   PetscFunctionBegin;
3538   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3539   PetscValidType(mat,1);
3540   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3541   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3542   PetscCheckSameComm(mat,1,b,2);
3543   PetscCheckSameComm(mat,1,x,3);
3544   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3545   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);
3546   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);
3547   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);
3548   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3549   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3550   MatCheckPreallocated(mat,1);
3551 
3552   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3553   ierr = PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3554   ierr = (*mat->ops->forwardsolve)(mat,b,x);CHKERRQ(ierr);
3555   ierr = PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);CHKERRQ(ierr);
3556   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3557   PetscFunctionReturn(0);
3558 }
3559 
3560 /*@
3561    MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3562                              D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3563 
3564    Neighbor-wise Collective on Mat
3565 
3566    Input Parameters:
3567 +  mat - the factored matrix
3568 -  b - the right-hand-side vector
3569 
3570    Output Parameter:
3571 .  x - the result vector
3572 
3573    Notes:
3574    MatSolve() should be used for most applications, as it performs
3575    a forward solve followed by a backward solve.
3576 
3577    The vectors b and x cannot be the same.  I.e., one cannot
3578    call MatBackwardSolve(A,x,x).
3579 
3580    For matrix in seqsbaij format with block size larger than 1,
3581    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3582    MatForwardSolve() solves U^T*D y = b, and
3583    MatBackwardSolve() solves U x = y.
3584    Thus they do not provide a symmetric preconditioner.
3585 
3586    Most users should employ the simplified KSP interface for linear solvers
3587    instead of working directly with matrix algebra routines such as this.
3588    See, e.g., KSPCreate().
3589 
3590    Level: developer
3591 
3592 .seealso: MatSolve(), MatForwardSolve()
3593 @*/
3594 PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3595 {
3596   PetscErrorCode ierr;
3597 
3598   PetscFunctionBegin;
3599   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3600   PetscValidType(mat,1);
3601   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3602   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3603   PetscCheckSameComm(mat,1,b,2);
3604   PetscCheckSameComm(mat,1,x,3);
3605   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3606   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);
3607   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);
3608   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);
3609   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3610   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3611   MatCheckPreallocated(mat,1);
3612 
3613   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3614   ierr = PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3615   ierr = (*mat->ops->backwardsolve)(mat,b,x);CHKERRQ(ierr);
3616   ierr = PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);CHKERRQ(ierr);
3617   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3618   PetscFunctionReturn(0);
3619 }
3620 
3621 /*@
3622    MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3623 
3624    Neighbor-wise Collective on Mat
3625 
3626    Input Parameters:
3627 +  mat - the factored matrix
3628 .  b - the right-hand-side vector
3629 -  y - the vector to be added to
3630 
3631    Output Parameter:
3632 .  x - the result vector
3633 
3634    Notes:
3635    The vectors b and x cannot be the same.  I.e., one cannot
3636    call MatSolveAdd(A,x,y,x).
3637 
3638    Most users should employ the simplified KSP interface for linear solvers
3639    instead of working directly with matrix algebra routines such as this.
3640    See, e.g., KSPCreate().
3641 
3642    Level: developer
3643 
3644 .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3645 @*/
3646 PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3647 {
3648   PetscScalar    one = 1.0;
3649   Vec            tmp;
3650   PetscErrorCode ierr;
3651 
3652   PetscFunctionBegin;
3653   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3654   PetscValidType(mat,1);
3655   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3656   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3657   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3658   PetscCheckSameComm(mat,1,b,2);
3659   PetscCheckSameComm(mat,1,y,2);
3660   PetscCheckSameComm(mat,1,x,3);
3661   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3662   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);
3663   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);
3664   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);
3665   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);
3666   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);
3667   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3668   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3669   MatCheckPreallocated(mat,1);
3670 
3671   ierr = PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3672   if (mat->ops->solveadd) {
3673     ierr = (*mat->ops->solveadd)(mat,b,y,x);CHKERRQ(ierr);
3674   } else {
3675     /* do the solve then the add manually */
3676     if (x != y) {
3677       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3678       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3679     } else {
3680       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3681       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3682       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3683       ierr = MatSolve(mat,b,x);CHKERRQ(ierr);
3684       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3685       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3686     }
3687   }
3688   ierr = PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);CHKERRQ(ierr);
3689   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3690   PetscFunctionReturn(0);
3691 }
3692 
3693 /*@
3694    MatSolveTranspose - Solves A' x = b, given a factored matrix.
3695 
3696    Neighbor-wise Collective on Mat
3697 
3698    Input Parameters:
3699 +  mat - the factored matrix
3700 -  b - the right-hand-side vector
3701 
3702    Output Parameter:
3703 .  x - the result vector
3704 
3705    Notes:
3706    The vectors b and x cannot be the same.  I.e., one cannot
3707    call MatSolveTranspose(A,x,x).
3708 
3709    Most users should employ the simplified KSP interface for linear solvers
3710    instead of working directly with matrix algebra routines such as this.
3711    See, e.g., KSPCreate().
3712 
3713    Level: developer
3714 
3715 .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3716 @*/
3717 PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3718 {
3719   PetscErrorCode ierr;
3720 
3721   PetscFunctionBegin;
3722   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3723   PetscValidType(mat,1);
3724   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3725   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
3726   PetscCheckSameComm(mat,1,b,2);
3727   PetscCheckSameComm(mat,1,x,3);
3728   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3729   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);
3730   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);
3731   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3732   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3733   MatCheckPreallocated(mat,1);
3734   ierr = PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3735   if (mat->factorerrortype) {
3736     ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3737     ierr = VecSetInf(x);CHKERRQ(ierr);
3738   } else {
3739     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3740     ierr = (*mat->ops->solvetranspose)(mat,b,x);CHKERRQ(ierr);
3741   }
3742   ierr = PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);CHKERRQ(ierr);
3743   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3744   PetscFunctionReturn(0);
3745 }
3746 
3747 /*@
3748    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3749                       factored matrix.
3750 
3751    Neighbor-wise Collective on Mat
3752 
3753    Input Parameters:
3754 +  mat - the factored matrix
3755 .  b - the right-hand-side vector
3756 -  y - the vector to be added to
3757 
3758    Output Parameter:
3759 .  x - the result vector
3760 
3761    Notes:
3762    The vectors b and x cannot be the same.  I.e., one cannot
3763    call MatSolveTransposeAdd(A,x,y,x).
3764 
3765    Most users should employ the simplified KSP interface for linear solvers
3766    instead of working directly with matrix algebra routines such as this.
3767    See, e.g., KSPCreate().
3768 
3769    Level: developer
3770 
3771 .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3772 @*/
3773 PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3774 {
3775   PetscScalar    one = 1.0;
3776   PetscErrorCode ierr;
3777   Vec            tmp;
3778 
3779   PetscFunctionBegin;
3780   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3781   PetscValidType(mat,1);
3782   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
3783   PetscValidHeaderSpecific(b,VEC_CLASSID,3);
3784   PetscValidHeaderSpecific(x,VEC_CLASSID,4);
3785   PetscCheckSameComm(mat,1,b,2);
3786   PetscCheckSameComm(mat,1,y,3);
3787   PetscCheckSameComm(mat,1,x,4);
3788   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3789   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);
3790   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);
3791   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);
3792   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);
3793   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
3794   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3795   MatCheckPreallocated(mat,1);
3796 
3797   ierr = PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3798   if (mat->ops->solvetransposeadd) {
3799     if (mat->factorerrortype) {
3800       ierr = PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);CHKERRQ(ierr);
3801       ierr = VecSetInf(x);CHKERRQ(ierr);
3802     } else {
3803       ierr = (*mat->ops->solvetransposeadd)(mat,b,y,x);CHKERRQ(ierr);
3804     }
3805   } else {
3806     /* do the solve then the add manually */
3807     if (x != y) {
3808       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3809       ierr = VecAXPY(x,one,y);CHKERRQ(ierr);
3810     } else {
3811       ierr = VecDuplicate(x,&tmp);CHKERRQ(ierr);
3812       ierr = PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);CHKERRQ(ierr);
3813       ierr = VecCopy(x,tmp);CHKERRQ(ierr);
3814       ierr = MatSolveTranspose(mat,b,x);CHKERRQ(ierr);
3815       ierr = VecAXPY(x,one,tmp);CHKERRQ(ierr);
3816       ierr = VecDestroy(&tmp);CHKERRQ(ierr);
3817     }
3818   }
3819   ierr = PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);CHKERRQ(ierr);
3820   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3821   PetscFunctionReturn(0);
3822 }
3823 /* ----------------------------------------------------------------*/
3824 
3825 /*@
3826    MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3827 
3828    Neighbor-wise Collective on Mat
3829 
3830    Input Parameters:
3831 +  mat - the matrix
3832 .  b - the right hand side
3833 .  omega - the relaxation factor
3834 .  flag - flag indicating the type of SOR (see below)
3835 .  shift -  diagonal shift
3836 .  its - the number of iterations
3837 -  lits - the number of local iterations
3838 
3839    Output Parameters:
3840 .  x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3841 
3842    SOR Flags:
3843 +     SOR_FORWARD_SWEEP - forward SOR
3844 .     SOR_BACKWARD_SWEEP - backward SOR
3845 .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3846 .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3847 .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3848 .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3849 .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3850          upper/lower triangular part of matrix to
3851          vector (with omega)
3852 -     SOR_ZERO_INITIAL_GUESS - zero initial guess
3853 
3854    Notes:
3855    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3856    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3857    on each processor.
3858 
3859    Application programmers will not generally use MatSOR() directly,
3860    but instead will employ the KSP/PC interface.
3861 
3862    Notes:
3863     for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3864 
3865    Notes for Advanced Users:
3866    The flags are implemented as bitwise inclusive or operations.
3867    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3868    to specify a zero initial guess for SSOR.
3869 
3870    Most users should employ the simplified KSP interface for linear solvers
3871    instead of working directly with matrix algebra routines such as this.
3872    See, e.g., KSPCreate().
3873 
3874    Vectors x and b CANNOT be the same
3875 
3876    Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3877 
3878    Level: developer
3879 
3880 @*/
3881 PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3882 {
3883   PetscErrorCode ierr;
3884 
3885   PetscFunctionBegin;
3886   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
3887   PetscValidType(mat,1);
3888   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
3889   PetscValidHeaderSpecific(x,VEC_CLASSID,8);
3890   PetscCheckSameComm(mat,1,b,2);
3891   PetscCheckSameComm(mat,1,x,8);
3892   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3893   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3894   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3895   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);
3896   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);
3897   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);
3898   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3899   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3900   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
3901 
3902   MatCheckPreallocated(mat,1);
3903   ierr = PetscLogEventBegin(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
3904   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);CHKERRQ(ierr);
3905   ierr = PetscLogEventEnd(MAT_SOR,mat,b,x,0);CHKERRQ(ierr);
3906   ierr = PetscObjectStateIncrease((PetscObject)x);CHKERRQ(ierr);
3907   PetscFunctionReturn(0);
3908 }
3909 
3910 /*
3911       Default matrix copy routine.
3912 */
3913 PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3914 {
3915   PetscErrorCode    ierr;
3916   PetscInt          i,rstart = 0,rend = 0,nz;
3917   const PetscInt    *cwork;
3918   const PetscScalar *vwork;
3919 
3920   PetscFunctionBegin;
3921   if (B->assembled) {
3922     ierr = MatZeroEntries(B);CHKERRQ(ierr);
3923   }
3924   if (str == SAME_NONZERO_PATTERN) {
3925     ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
3926     for (i=rstart; i<rend; i++) {
3927       ierr = MatGetRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
3928       ierr = MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);CHKERRQ(ierr);
3929       ierr = MatRestoreRow(A,i,&nz,&cwork,&vwork);CHKERRQ(ierr);
3930     }
3931   } else {
3932     ierr = MatAYPX(B,0.0,A,str);CHKERRQ(ierr);
3933   }
3934   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
3935   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
3936   PetscFunctionReturn(0);
3937 }
3938 
3939 /*@
3940    MatCopy - Copies a matrix to another matrix.
3941 
3942    Collective on Mat
3943 
3944    Input Parameters:
3945 +  A - the matrix
3946 -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
3947 
3948    Output Parameter:
3949 .  B - where the copy is put
3950 
3951    Notes:
3952    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3953    same nonzero pattern or the routine will crash.
3954 
3955    MatCopy() copies the matrix entries of a matrix to another existing
3956    matrix (after first zeroing the second matrix).  A related routine is
3957    MatConvert(), which first creates a new matrix and then copies the data.
3958 
3959    Level: intermediate
3960 
3961 .seealso: MatConvert(), MatDuplicate()
3962 
3963 @*/
3964 PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
3965 {
3966   PetscErrorCode ierr;
3967   PetscInt       i;
3968 
3969   PetscFunctionBegin;
3970   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
3971   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
3972   PetscValidType(A,1);
3973   PetscValidType(B,2);
3974   PetscCheckSameComm(A,1,B,2);
3975   MatCheckPreallocated(B,2);
3976   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3977   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3978   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);
3979   MatCheckPreallocated(A,1);
3980   if (A == B) PetscFunctionReturn(0);
3981 
3982   ierr = PetscLogEventBegin(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
3983   if (A->ops->copy) {
3984     ierr = (*A->ops->copy)(A,B,str);CHKERRQ(ierr);
3985   } else { /* generic conversion */
3986     ierr = MatCopy_Basic(A,B,str);CHKERRQ(ierr);
3987   }
3988 
3989   B->stencil.dim = A->stencil.dim;
3990   B->stencil.noc = A->stencil.noc;
3991   for (i=0; i<=A->stencil.dim; i++) {
3992     B->stencil.dims[i]   = A->stencil.dims[i];
3993     B->stencil.starts[i] = A->stencil.starts[i];
3994   }
3995 
3996   ierr = PetscLogEventEnd(MAT_Copy,A,B,0,0);CHKERRQ(ierr);
3997   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
3998   PetscFunctionReturn(0);
3999 }
4000 
4001 /*@C
4002    MatConvert - Converts a matrix to another matrix, either of the same
4003    or different type.
4004 
4005    Collective on Mat
4006 
4007    Input Parameters:
4008 +  mat - the matrix
4009 .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4010    same type as the original matrix.
4011 -  reuse - denotes if the destination matrix is to be created or reused.
4012    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
4013    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).
4014 
4015    Output Parameter:
4016 .  M - pointer to place new matrix
4017 
4018    Notes:
4019    MatConvert() first creates a new matrix and then copies the data from
4020    the first matrix.  A related routine is MatCopy(), which copies the matrix
4021    entries of one matrix to another already existing matrix context.
4022 
4023    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4024    the MPI communicator of the generated matrix is always the same as the communicator
4025    of the input matrix.
4026 
4027    Level: intermediate
4028 
4029 .seealso: MatCopy(), MatDuplicate()
4030 @*/
4031 PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4032 {
4033   PetscErrorCode ierr;
4034   PetscBool      sametype,issame,flg;
4035   char           convname[256],mtype[256];
4036   Mat            B;
4037 
4038   PetscFunctionBegin;
4039   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4040   PetscValidType(mat,1);
4041   PetscValidPointer(M,3);
4042   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4043   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4044   MatCheckPreallocated(mat,1);
4045 
4046   ierr = PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);CHKERRQ(ierr);
4047   if (flg) {
4048     newtype = mtype;
4049   }
4050   ierr = PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);CHKERRQ(ierr);
4051   ierr = PetscStrcmp(newtype,"same",&issame);CHKERRQ(ierr);
4052   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4053   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");
4054 
4055   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) PetscFunctionReturn(0);
4056 
4057   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4058     ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4059   } else {
4060     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4061     const char     *prefix[3] = {"seq","mpi",""};
4062     PetscInt       i;
4063     /*
4064        Order of precedence:
4065        0) See if newtype is a superclass of the current matrix.
4066        1) See if a specialized converter is known to the current matrix.
4067        2) See if a specialized converter is known to the desired matrix class.
4068        3) See if a good general converter is registered for the desired class
4069           (as of 6/27/03 only MATMPIADJ falls into this category).
4070        4) See if a good general converter is known for the current matrix.
4071        5) Use a really basic converter.
4072     */
4073 
4074     /* 0) See if newtype is a superclass of the current matrix.
4075           i.e mat is mpiaij and newtype is aij */
4076     for (i=0; i<2; i++) {
4077       ierr = PetscStrncpy(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4078       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4079       ierr = PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);CHKERRQ(ierr);
4080       ierr = PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);CHKERRQ(ierr);
4081       if (flg) {
4082         if (reuse == MAT_INPLACE_MATRIX) {
4083           PetscFunctionReturn(0);
4084         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4085           ierr = (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);CHKERRQ(ierr);
4086           PetscFunctionReturn(0);
4087         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4088           ierr = MatCopy(mat,*M,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
4089           PetscFunctionReturn(0);
4090         }
4091       }
4092     }
4093     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4094     for (i=0; i<3; i++) {
4095       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4096       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4097       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4098       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4099       ierr = PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));CHKERRQ(ierr);
4100       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4101       ierr = PetscObjectQueryFunction((PetscObject)mat,convname,&conv);CHKERRQ(ierr);
4102       ierr = PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);CHKERRQ(ierr);
4103       if (conv) goto foundconv;
4104     }
4105 
4106     /* 2)  See if a specialized converter is known to the desired matrix class. */
4107     ierr = MatCreate(PetscObjectComm((PetscObject)mat),&B);CHKERRQ(ierr);
4108     ierr = MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);CHKERRQ(ierr);
4109     ierr = MatSetType(B,newtype);CHKERRQ(ierr);
4110     for (i=0; i<3; i++) {
4111       ierr = PetscStrncpy(convname,"MatConvert_",sizeof(convname));CHKERRQ(ierr);
4112       ierr = PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));CHKERRQ(ierr);
4113       ierr = PetscStrlcat(convname,"_",sizeof(convname));CHKERRQ(ierr);
4114       ierr = PetscStrlcat(convname,prefix[i],sizeof(convname));CHKERRQ(ierr);
4115       ierr = PetscStrlcat(convname,newtype,sizeof(convname));CHKERRQ(ierr);
4116       ierr = PetscStrlcat(convname,"_C",sizeof(convname));CHKERRQ(ierr);
4117       ierr = PetscObjectQueryFunction((PetscObject)B,convname,&conv);CHKERRQ(ierr);
4118       ierr = PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);CHKERRQ(ierr);
4119       if (conv) {
4120         ierr = MatDestroy(&B);CHKERRQ(ierr);
4121         goto foundconv;
4122       }
4123     }
4124 
4125     /* 3) See if a good general converter is registered for the desired class */
4126     conv = B->ops->convertfrom;
4127     ierr = PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);CHKERRQ(ierr);
4128     ierr = MatDestroy(&B);CHKERRQ(ierr);
4129     if (conv) goto foundconv;
4130 
4131     /* 4) See if a good general converter is known for the current matrix */
4132     if (mat->ops->convert) {
4133       conv = mat->ops->convert;
4134     }
4135     ierr = PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);CHKERRQ(ierr);
4136     if (conv) goto foundconv;
4137 
4138     /* 5) Use a really basic converter. */
4139     ierr = PetscInfo(mat,"Using MatConvert_Basic\n");CHKERRQ(ierr);
4140     conv = MatConvert_Basic;
4141 
4142 foundconv:
4143     ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4144     ierr = (*conv)(mat,newtype,reuse,M);CHKERRQ(ierr);
4145     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4146       /* the block sizes must be same if the mappings are copied over */
4147       (*M)->rmap->bs = mat->rmap->bs;
4148       (*M)->cmap->bs = mat->cmap->bs;
4149       ierr = PetscObjectReference((PetscObject)mat->rmap->mapping);CHKERRQ(ierr);
4150       ierr = PetscObjectReference((PetscObject)mat->cmap->mapping);CHKERRQ(ierr);
4151       (*M)->rmap->mapping = mat->rmap->mapping;
4152       (*M)->cmap->mapping = mat->cmap->mapping;
4153     }
4154     (*M)->stencil.dim = mat->stencil.dim;
4155     (*M)->stencil.noc = mat->stencil.noc;
4156     for (i=0; i<=mat->stencil.dim; i++) {
4157       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4158       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4159     }
4160     ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4161   }
4162   ierr = PetscObjectStateIncrease((PetscObject)*M);CHKERRQ(ierr);
4163 
4164   /* Copy Mat options */
4165   if (mat->symmetric) {ierr = MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);}
4166   if (mat->hermitian) {ierr = MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);}
4167   PetscFunctionReturn(0);
4168 }
4169 
4170 /*@C
4171    MatFactorGetSolverType - Returns name of the package providing the factorization routines
4172 
4173    Not Collective
4174 
4175    Input Parameter:
4176 .  mat - the matrix, must be a factored matrix
4177 
4178    Output Parameter:
4179 .   type - the string name of the package (do not free this string)
4180 
4181    Notes:
4182       In Fortran you pass in a empty string and the package name will be copied into it.
4183     (Make sure the string is long enough)
4184 
4185    Level: intermediate
4186 
4187 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4188 @*/
4189 PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4190 {
4191   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4192 
4193   PetscFunctionBegin;
4194   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4195   PetscValidType(mat,1);
4196   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4197   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);CHKERRQ(ierr);
4198   if (!conv) {
4199     *type = MATSOLVERPETSC;
4200   } else {
4201     ierr = (*conv)(mat,type);CHKERRQ(ierr);
4202   }
4203   PetscFunctionReturn(0);
4204 }
4205 
4206 typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4207 struct _MatSolverTypeForSpecifcType {
4208   MatType                        mtype;
4209   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4210   MatSolverTypeForSpecifcType next;
4211 };
4212 
4213 typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4214 struct _MatSolverTypeHolder {
4215   char                           *name;
4216   MatSolverTypeForSpecifcType handlers;
4217   MatSolverTypeHolder         next;
4218 };
4219 
4220 static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4221 
4222 /*@C
4223    MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type
4224 
4225    Input Parameters:
4226 +    package - name of the package, for example petsc or superlu
4227 .    mtype - the matrix type that works with this package
4228 .    ftype - the type of factorization supported by the package
4229 -    getfactor - routine that will create the factored matrix ready to be used
4230 
4231     Level: intermediate
4232 
4233 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4234 @*/
4235 PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4236 {
4237   PetscErrorCode              ierr;
4238   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4239   PetscBool                   flg;
4240   MatSolverTypeForSpecifcType inext,iprev = NULL;
4241 
4242   PetscFunctionBegin;
4243   ierr = MatInitializePackage();CHKERRQ(ierr);
4244   if (!next) {
4245     ierr = PetscNew(&MatSolverTypeHolders);CHKERRQ(ierr);
4246     ierr = PetscStrallocpy(package,&MatSolverTypeHolders->name);CHKERRQ(ierr);
4247     ierr = PetscNew(&MatSolverTypeHolders->handlers);CHKERRQ(ierr);
4248     ierr = PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);CHKERRQ(ierr);
4249     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4250     PetscFunctionReturn(0);
4251   }
4252   while (next) {
4253     ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4254     if (flg) {
4255       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4256       inext = next->handlers;
4257       while (inext) {
4258         ierr = PetscStrcasecmp(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4259         if (flg) {
4260           inext->getfactor[(int)ftype-1] = getfactor;
4261           PetscFunctionReturn(0);
4262         }
4263         iprev = inext;
4264         inext = inext->next;
4265       }
4266       ierr = PetscNew(&iprev->next);CHKERRQ(ierr);
4267       ierr = PetscStrallocpy(mtype,(char **)&iprev->next->mtype);CHKERRQ(ierr);
4268       iprev->next->getfactor[(int)ftype-1] = getfactor;
4269       PetscFunctionReturn(0);
4270     }
4271     prev = next;
4272     next = next->next;
4273   }
4274   ierr = PetscNew(&prev->next);CHKERRQ(ierr);
4275   ierr = PetscStrallocpy(package,&prev->next->name);CHKERRQ(ierr);
4276   ierr = PetscNew(&prev->next->handlers);CHKERRQ(ierr);
4277   ierr = PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);CHKERRQ(ierr);
4278   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4279   PetscFunctionReturn(0);
4280 }
4281 
4282 /*@C
4283    MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4284 
4285    Input Parameters:
4286 +    package - name of the package, for example petsc or superlu
4287 .    ftype - the type of factorization supported by the package
4288 -    mtype - the matrix type that works with this package
4289 
4290    Output Parameters:
4291 +   foundpackage - PETSC_TRUE if the package was registered
4292 .   foundmtype - PETSC_TRUE if the package supports the requested mtype
4293 -   getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4294 
4295     Level: intermediate
4296 
4297 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4298 @*/
4299 PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4300 {
4301   PetscErrorCode                 ierr;
4302   MatSolverTypeHolder         next = MatSolverTypeHolders;
4303   PetscBool                      flg;
4304   MatSolverTypeForSpecifcType inext;
4305 
4306   PetscFunctionBegin;
4307   if (foundpackage) *foundpackage = PETSC_FALSE;
4308   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4309   if (getfactor)    *getfactor    = NULL;
4310 
4311   if (package) {
4312     while (next) {
4313       ierr = PetscStrcasecmp(package,next->name,&flg);CHKERRQ(ierr);
4314       if (flg) {
4315         if (foundpackage) *foundpackage = PETSC_TRUE;
4316         inext = next->handlers;
4317         while (inext) {
4318           ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4319           if (flg) {
4320             if (foundmtype) *foundmtype = PETSC_TRUE;
4321             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4322             PetscFunctionReturn(0);
4323           }
4324           inext = inext->next;
4325         }
4326       }
4327       next = next->next;
4328     }
4329   } else {
4330     while (next) {
4331       inext = next->handlers;
4332       while (inext) {
4333         ierr = PetscStrbeginswith(mtype,inext->mtype,&flg);CHKERRQ(ierr);
4334         if (flg && inext->getfactor[(int)ftype-1]) {
4335           if (foundpackage) *foundpackage = PETSC_TRUE;
4336           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4337           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
4338           PetscFunctionReturn(0);
4339         }
4340         inext = inext->next;
4341       }
4342       next = next->next;
4343     }
4344   }
4345   PetscFunctionReturn(0);
4346 }
4347 
4348 PetscErrorCode MatSolverTypeDestroy(void)
4349 {
4350   PetscErrorCode              ierr;
4351   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4352   MatSolverTypeForSpecifcType inext,iprev;
4353 
4354   PetscFunctionBegin;
4355   while (next) {
4356     ierr = PetscFree(next->name);CHKERRQ(ierr);
4357     inext = next->handlers;
4358     while (inext) {
4359       ierr = PetscFree(inext->mtype);CHKERRQ(ierr);
4360       iprev = inext;
4361       inext = inext->next;
4362       ierr = PetscFree(iprev);CHKERRQ(ierr);
4363     }
4364     prev = next;
4365     next = next->next;
4366     ierr = PetscFree(prev);CHKERRQ(ierr);
4367   }
4368   MatSolverTypeHolders = NULL;
4369   PetscFunctionReturn(0);
4370 }
4371 
4372 /*@C
4373    MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4374 
4375    Collective on Mat
4376 
4377    Input Parameters:
4378 +  mat - the matrix
4379 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4380 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4381 
4382    Output Parameters:
4383 .  f - the factor matrix used with MatXXFactorSymbolic() calls
4384 
4385    Notes:
4386       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4387      such as pastix, superlu, mumps etc.
4388 
4389       PETSc must have been ./configure to use the external solver, using the option --download-package
4390 
4391    Level: intermediate
4392 
4393 .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4394 @*/
4395 PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4396 {
4397   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4398   PetscBool      foundpackage,foundmtype;
4399 
4400   PetscFunctionBegin;
4401   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4402   PetscValidType(mat,1);
4403 
4404   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4405   MatCheckPreallocated(mat,1);
4406 
4407   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);CHKERRQ(ierr);
4408   if (!foundpackage) {
4409     if (type) {
4410       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4411     } else {
4412       SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4413     }
4414   }
4415 
4416   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4417   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);
4418 
4419 #if defined(PETSC_USE_COMPLEX)
4420   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");
4421 #endif
4422 
4423   ierr = (*conv)(mat,ftype,f);CHKERRQ(ierr);
4424   PetscFunctionReturn(0);
4425 }
4426 
4427 /*@C
4428    MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4429 
4430    Not Collective
4431 
4432    Input Parameters:
4433 +  mat - the matrix
4434 .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4435 -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4436 
4437    Output Parameter:
4438 .    flg - PETSC_TRUE if the factorization is available
4439 
4440    Notes:
4441       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4442      such as pastix, superlu, mumps etc.
4443 
4444       PETSc must have been ./configure to use the external solver, using the option --download-package
4445 
4446    Level: intermediate
4447 
4448 .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4449 @*/
4450 PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4451 {
4452   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4453 
4454   PetscFunctionBegin;
4455   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4456   PetscValidType(mat,1);
4457 
4458   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4459   MatCheckPreallocated(mat,1);
4460 
4461   *flg = PETSC_FALSE;
4462   ierr = MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);CHKERRQ(ierr);
4463   if (gconv) {
4464     *flg = PETSC_TRUE;
4465   }
4466   PetscFunctionReturn(0);
4467 }
4468 
4469 #include <petscdmtypes.h>
4470 
4471 /*@
4472    MatDuplicate - Duplicates a matrix including the non-zero structure.
4473 
4474    Collective on Mat
4475 
4476    Input Parameters:
4477 +  mat - the matrix
4478 -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4479         See the manual page for MatDuplicateOption for an explanation of these options.
4480 
4481    Output Parameter:
4482 .  M - pointer to place new matrix
4483 
4484    Level: intermediate
4485 
4486    Notes:
4487     You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4488     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.
4489 
4490 .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4491 @*/
4492 PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4493 {
4494   PetscErrorCode ierr;
4495   Mat            B;
4496   PetscInt       i;
4497   DM             dm;
4498   void           (*viewf)(void);
4499 
4500   PetscFunctionBegin;
4501   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4502   PetscValidType(mat,1);
4503   PetscValidPointer(M,3);
4504   if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4505   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4506   MatCheckPreallocated(mat,1);
4507 
4508   *M = 0;
4509   if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4510   ierr = PetscLogEventBegin(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4511   ierr = (*mat->ops->duplicate)(mat,op,M);CHKERRQ(ierr);
4512   B    = *M;
4513 
4514   ierr = MatGetOperation(mat,MATOP_VIEW,&viewf);CHKERRQ(ierr);
4515   if (viewf) {
4516     ierr = MatSetOperation(B,MATOP_VIEW,viewf);CHKERRQ(ierr);
4517   }
4518 
4519   B->stencil.dim = mat->stencil.dim;
4520   B->stencil.noc = mat->stencil.noc;
4521   for (i=0; i<=mat->stencil.dim; i++) {
4522     B->stencil.dims[i]   = mat->stencil.dims[i];
4523     B->stencil.starts[i] = mat->stencil.starts[i];
4524   }
4525 
4526   B->nooffproczerorows = mat->nooffproczerorows;
4527   B->nooffprocentries  = mat->nooffprocentries;
4528 
4529   ierr = PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);CHKERRQ(ierr);
4530   if (dm) {
4531     ierr = PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);CHKERRQ(ierr);
4532   }
4533   ierr = PetscLogEventEnd(MAT_Convert,mat,0,0,0);CHKERRQ(ierr);
4534   ierr = PetscObjectStateIncrease((PetscObject)B);CHKERRQ(ierr);
4535   PetscFunctionReturn(0);
4536 }
4537 
4538 /*@
4539    MatGetDiagonal - Gets the diagonal of a matrix.
4540 
4541    Logically Collective on Mat
4542 
4543    Input Parameters:
4544 +  mat - the matrix
4545 -  v - the vector for storing the diagonal
4546 
4547    Output Parameter:
4548 .  v - the diagonal of the matrix
4549 
4550    Level: intermediate
4551 
4552    Note:
4553    Currently only correct in parallel for square matrices.
4554 
4555 .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4556 @*/
4557 PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4558 {
4559   PetscErrorCode ierr;
4560 
4561   PetscFunctionBegin;
4562   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4563   PetscValidType(mat,1);
4564   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4565   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4566   if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4567   MatCheckPreallocated(mat,1);
4568 
4569   ierr = (*mat->ops->getdiagonal)(mat,v);CHKERRQ(ierr);
4570   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4571   PetscFunctionReturn(0);
4572 }
4573 
4574 /*@C
4575    MatGetRowMin - Gets the minimum value (of the real part) of each
4576         row of the matrix
4577 
4578    Logically Collective on Mat
4579 
4580    Input Parameters:
4581 .  mat - the matrix
4582 
4583    Output Parameter:
4584 +  v - the vector for storing the maximums
4585 -  idx - the indices of the column found for each row (optional)
4586 
4587    Level: intermediate
4588 
4589    Notes:
4590     The result of this call are the same as if one converted the matrix to dense format
4591       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4592 
4593     This code is only implemented for a couple of matrix formats.
4594 
4595 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4596           MatGetRowMax()
4597 @*/
4598 PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4599 {
4600   PetscErrorCode ierr;
4601 
4602   PetscFunctionBegin;
4603   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4604   PetscValidType(mat,1);
4605   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4606   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4607   if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4608   MatCheckPreallocated(mat,1);
4609 
4610   ierr = (*mat->ops->getrowmin)(mat,v,idx);CHKERRQ(ierr);
4611   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4612   PetscFunctionReturn(0);
4613 }
4614 
4615 /*@C
4616    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4617         row of the matrix
4618 
4619    Logically Collective on Mat
4620 
4621    Input Parameters:
4622 .  mat - the matrix
4623 
4624    Output Parameter:
4625 +  v - the vector for storing the minimums
4626 -  idx - the indices of the column found for each row (or NULL if not needed)
4627 
4628    Level: intermediate
4629 
4630    Notes:
4631     if a row is completely empty or has only 0.0 values then the idx[] value for that
4632     row is 0 (the first column).
4633 
4634     This code is only implemented for a couple of matrix formats.
4635 
4636 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4637 @*/
4638 PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4639 {
4640   PetscErrorCode ierr;
4641 
4642   PetscFunctionBegin;
4643   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4644   PetscValidType(mat,1);
4645   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4646   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4647   if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4648   MatCheckPreallocated(mat,1);
4649   if (idx) {ierr = PetscArrayzero(idx,mat->rmap->n);CHKERRQ(ierr);}
4650 
4651   ierr = (*mat->ops->getrowminabs)(mat,v,idx);CHKERRQ(ierr);
4652   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4653   PetscFunctionReturn(0);
4654 }
4655 
4656 /*@C
4657    MatGetRowMax - Gets the maximum value (of the real part) of each
4658         row of the matrix
4659 
4660    Logically Collective on Mat
4661 
4662    Input Parameters:
4663 .  mat - the matrix
4664 
4665    Output Parameter:
4666 +  v - the vector for storing the maximums
4667 -  idx - the indices of the column found for each row (optional)
4668 
4669    Level: intermediate
4670 
4671    Notes:
4672     The result of this call are the same as if one converted the matrix to dense format
4673       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4674 
4675     This code is only implemented for a couple of matrix formats.
4676 
4677 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4678 @*/
4679 PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4680 {
4681   PetscErrorCode ierr;
4682 
4683   PetscFunctionBegin;
4684   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4685   PetscValidType(mat,1);
4686   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4687   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4688   if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4689   MatCheckPreallocated(mat,1);
4690 
4691   ierr = (*mat->ops->getrowmax)(mat,v,idx);CHKERRQ(ierr);
4692   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4693   PetscFunctionReturn(0);
4694 }
4695 
4696 /*@C
4697    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4698         row of the matrix
4699 
4700    Logically Collective on Mat
4701 
4702    Input Parameters:
4703 .  mat - the matrix
4704 
4705    Output Parameter:
4706 +  v - the vector for storing the maximums
4707 -  idx - the indices of the column found for each row (or NULL if not needed)
4708 
4709    Level: intermediate
4710 
4711    Notes:
4712     if a row is completely empty or has only 0.0 values then the idx[] value for that
4713     row is 0 (the first column).
4714 
4715     This code is only implemented for a couple of matrix formats.
4716 
4717 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4718 @*/
4719 PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4720 {
4721   PetscErrorCode ierr;
4722 
4723   PetscFunctionBegin;
4724   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4725   PetscValidType(mat,1);
4726   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4727   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4728   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4729   MatCheckPreallocated(mat,1);
4730   if (idx) {ierr = PetscArrayzero(idx,mat->rmap->n);CHKERRQ(ierr);}
4731 
4732   ierr = (*mat->ops->getrowmaxabs)(mat,v,idx);CHKERRQ(ierr);
4733   ierr = PetscObjectStateIncrease((PetscObject)v);CHKERRQ(ierr);
4734   PetscFunctionReturn(0);
4735 }
4736 
4737 /*@
4738    MatGetRowSum - Gets the sum of each row of the matrix
4739 
4740    Logically or Neighborhood Collective on Mat
4741 
4742    Input Parameters:
4743 .  mat - the matrix
4744 
4745    Output Parameter:
4746 .  v - the vector for storing the sum of rows
4747 
4748    Level: intermediate
4749 
4750    Notes:
4751     This code is slow since it is not currently specialized for different formats
4752 
4753 .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4754 @*/
4755 PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4756 {
4757   Vec            ones;
4758   PetscErrorCode ierr;
4759 
4760   PetscFunctionBegin;
4761   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4762   PetscValidType(mat,1);
4763   PetscValidHeaderSpecific(v,VEC_CLASSID,2);
4764   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4765   MatCheckPreallocated(mat,1);
4766   ierr = MatCreateVecs(mat,&ones,NULL);CHKERRQ(ierr);
4767   ierr = VecSet(ones,1.);CHKERRQ(ierr);
4768   ierr = MatMult(mat,ones,v);CHKERRQ(ierr);
4769   ierr = VecDestroy(&ones);CHKERRQ(ierr);
4770   PetscFunctionReturn(0);
4771 }
4772 
4773 /*@
4774    MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4775 
4776    Collective on Mat
4777 
4778    Input Parameter:
4779 +  mat - the matrix to transpose
4780 -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
4781 
4782    Output Parameters:
4783 .  B - the transpose
4784 
4785    Notes:
4786      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
4787 
4788      MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
4789 
4790      Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4791 
4792    Level: intermediate
4793 
4794 .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4795 @*/
4796 PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4797 {
4798   PetscErrorCode ierr;
4799 
4800   PetscFunctionBegin;
4801   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4802   PetscValidType(mat,1);
4803   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4804   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4805   if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4806   if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4807   if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4808   MatCheckPreallocated(mat,1);
4809 
4810   ierr = PetscLogEventBegin(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4811   ierr = (*mat->ops->transpose)(mat,reuse,B);CHKERRQ(ierr);
4812   ierr = PetscLogEventEnd(MAT_Transpose,mat,0,0,0);CHKERRQ(ierr);
4813   if (B) {ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);}
4814   PetscFunctionReturn(0);
4815 }
4816 
4817 /*@
4818    MatIsTranspose - Test whether a matrix is another one's transpose,
4819         or its own, in which case it tests symmetry.
4820 
4821    Collective on Mat
4822 
4823    Input Parameter:
4824 +  A - the matrix to test
4825 -  B - the matrix to test against, this can equal the first parameter
4826 
4827    Output Parameters:
4828 .  flg - the result
4829 
4830    Notes:
4831    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4832    has a running time of the order of the number of nonzeros; the parallel
4833    test involves parallel copies of the block-offdiagonal parts of the matrix.
4834 
4835    Level: intermediate
4836 
4837 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4838 @*/
4839 PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4840 {
4841   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4842 
4843   PetscFunctionBegin;
4844   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4845   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4846   PetscValidBoolPointer(flg,3);
4847   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);CHKERRQ(ierr);
4848   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);CHKERRQ(ierr);
4849   *flg = PETSC_FALSE;
4850   if (f && g) {
4851     if (f == g) {
4852       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
4853     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4854   } else {
4855     MatType mattype;
4856     if (!f) {
4857       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
4858     } else {
4859       ierr = MatGetType(B,&mattype);CHKERRQ(ierr);
4860     }
4861     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4862   }
4863   PetscFunctionReturn(0);
4864 }
4865 
4866 /*@
4867    MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
4868 
4869    Collective on Mat
4870 
4871    Input Parameter:
4872 +  mat - the matrix to transpose and complex conjugate
4873 -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose
4874 
4875    Output Parameters:
4876 .  B - the Hermitian
4877 
4878    Level: intermediate
4879 
4880 .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4881 @*/
4882 PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4883 {
4884   PetscErrorCode ierr;
4885 
4886   PetscFunctionBegin;
4887   ierr = MatTranspose(mat,reuse,B);CHKERRQ(ierr);
4888 #if defined(PETSC_USE_COMPLEX)
4889   ierr = MatConjugate(*B);CHKERRQ(ierr);
4890 #endif
4891   PetscFunctionReturn(0);
4892 }
4893 
4894 /*@
4895    MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
4896 
4897    Collective on Mat
4898 
4899    Input Parameter:
4900 +  A - the matrix to test
4901 -  B - the matrix to test against, this can equal the first parameter
4902 
4903    Output Parameters:
4904 .  flg - the result
4905 
4906    Notes:
4907    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4908    has a running time of the order of the number of nonzeros; the parallel
4909    test involves parallel copies of the block-offdiagonal parts of the matrix.
4910 
4911    Level: intermediate
4912 
4913 .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4914 @*/
4915 PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4916 {
4917   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4918 
4919   PetscFunctionBegin;
4920   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4921   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4922   PetscValidBoolPointer(flg,3);
4923   ierr = PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);CHKERRQ(ierr);
4924   ierr = PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);CHKERRQ(ierr);
4925   if (f && g) {
4926     if (f==g) {
4927       ierr = (*f)(A,B,tol,flg);CHKERRQ(ierr);
4928     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4929   }
4930   PetscFunctionReturn(0);
4931 }
4932 
4933 /*@
4934    MatPermute - Creates a new matrix with rows and columns permuted from the
4935    original.
4936 
4937    Collective on Mat
4938 
4939    Input Parameters:
4940 +  mat - the matrix to permute
4941 .  row - row permutation, each processor supplies only the permutation for its rows
4942 -  col - column permutation, each processor supplies only the permutation for its columns
4943 
4944    Output Parameters:
4945 .  B - the permuted matrix
4946 
4947    Level: advanced
4948 
4949    Note:
4950    The index sets map from row/col of permuted matrix to row/col of original matrix.
4951    The index sets should be on the same communicator as Mat and have the same local sizes.
4952 
4953 .seealso: MatGetOrdering(), ISAllGather()
4954 
4955 @*/
4956 PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
4957 {
4958   PetscErrorCode ierr;
4959 
4960   PetscFunctionBegin;
4961   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
4962   PetscValidType(mat,1);
4963   PetscValidHeaderSpecific(row,IS_CLASSID,2);
4964   PetscValidHeaderSpecific(col,IS_CLASSID,3);
4965   PetscValidPointer(B,4);
4966   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4967   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4968   if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
4969   MatCheckPreallocated(mat,1);
4970 
4971   ierr = (*mat->ops->permute)(mat,row,col,B);CHKERRQ(ierr);
4972   ierr = PetscObjectStateIncrease((PetscObject)*B);CHKERRQ(ierr);
4973   PetscFunctionReturn(0);
4974 }
4975 
4976 /*@
4977    MatEqual - Compares two matrices.
4978 
4979    Collective on Mat
4980 
4981    Input Parameters:
4982 +  A - the first matrix
4983 -  B - the second matrix
4984 
4985    Output Parameter:
4986 .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
4987 
4988    Level: intermediate
4989 
4990 @*/
4991 PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
4992 {
4993   PetscErrorCode ierr;
4994 
4995   PetscFunctionBegin;
4996   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
4997   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
4998   PetscValidType(A,1);
4999   PetscValidType(B,2);
5000   PetscValidBoolPointer(flg,3);
5001   PetscCheckSameComm(A,1,B,2);
5002   MatCheckPreallocated(B,2);
5003   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5004   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5005   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);
5006   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5007   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5008   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);
5009   MatCheckPreallocated(A,1);
5010 
5011   ierr = (*A->ops->equal)(A,B,flg);CHKERRQ(ierr);
5012   PetscFunctionReturn(0);
5013 }
5014 
5015 /*@
5016    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5017    matrices that are stored as vectors.  Either of the two scaling
5018    matrices can be NULL.
5019 
5020    Collective on Mat
5021 
5022    Input Parameters:
5023 +  mat - the matrix to be scaled
5024 .  l - the left scaling vector (or NULL)
5025 -  r - the right scaling vector (or NULL)
5026 
5027    Notes:
5028    MatDiagonalScale() computes A = LAR, where
5029    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5030    The L scales the rows of the matrix, the R scales the columns of the matrix.
5031 
5032    Level: intermediate
5033 
5034 
5035 .seealso: MatScale(), MatShift(), MatDiagonalSet()
5036 @*/
5037 PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5038 {
5039   PetscErrorCode ierr;
5040 
5041   PetscFunctionBegin;
5042   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5043   PetscValidType(mat,1);
5044   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5045   if (l) {PetscValidHeaderSpecific(l,VEC_CLASSID,2);PetscCheckSameComm(mat,1,l,2);}
5046   if (r) {PetscValidHeaderSpecific(r,VEC_CLASSID,3);PetscCheckSameComm(mat,1,r,3);}
5047   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5048   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5049   MatCheckPreallocated(mat,1);
5050 
5051   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5052   ierr = (*mat->ops->diagonalscale)(mat,l,r);CHKERRQ(ierr);
5053   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5054   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5055   PetscFunctionReturn(0);
5056 }
5057 
5058 /*@
5059     MatScale - Scales all elements of a matrix by a given number.
5060 
5061     Logically Collective on Mat
5062 
5063     Input Parameters:
5064 +   mat - the matrix to be scaled
5065 -   a  - the scaling value
5066 
5067     Output Parameter:
5068 .   mat - the scaled matrix
5069 
5070     Level: intermediate
5071 
5072 .seealso: MatDiagonalScale()
5073 @*/
5074 PetscErrorCode MatScale(Mat mat,PetscScalar a)
5075 {
5076   PetscErrorCode ierr;
5077 
5078   PetscFunctionBegin;
5079   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5080   PetscValidType(mat,1);
5081   if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
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   PetscValidLogicalCollectiveScalar(mat,a,2);
5085   MatCheckPreallocated(mat,1);
5086 
5087   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5088   if (a != (PetscScalar)1.0) {
5089     ierr = (*mat->ops->scale)(mat,a);CHKERRQ(ierr);
5090     ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5091   }
5092   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
5093   PetscFunctionReturn(0);
5094 }
5095 
5096 /*@
5097    MatNorm - Calculates various norms of a matrix.
5098 
5099    Collective on Mat
5100 
5101    Input Parameters:
5102 +  mat - the matrix
5103 -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5104 
5105    Output Parameters:
5106 .  nrm - the resulting norm
5107 
5108    Level: intermediate
5109 
5110 @*/
5111 PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5112 {
5113   PetscErrorCode ierr;
5114 
5115   PetscFunctionBegin;
5116   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5117   PetscValidType(mat,1);
5118   PetscValidScalarPointer(nrm,3);
5119 
5120   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5121   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5122   if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5123   MatCheckPreallocated(mat,1);
5124 
5125   ierr = (*mat->ops->norm)(mat,type,nrm);CHKERRQ(ierr);
5126   PetscFunctionReturn(0);
5127 }
5128 
5129 /*
5130      This variable is used to prevent counting of MatAssemblyBegin() that
5131    are called from within a MatAssemblyEnd().
5132 */
5133 static PetscInt MatAssemblyEnd_InUse = 0;
5134 /*@
5135    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5136    be called after completing all calls to MatSetValues().
5137 
5138    Collective on Mat
5139 
5140    Input Parameters:
5141 +  mat - the matrix
5142 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5143 
5144    Notes:
5145    MatSetValues() generally caches the values.  The matrix is ready to
5146    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5147    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5148    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5149    using the matrix.
5150 
5151    ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5152    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
5153    a global collective operation requring all processes that share the matrix.
5154 
5155    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5156    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5157    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5158 
5159    Level: beginner
5160 
5161 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5162 @*/
5163 PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5164 {
5165   PetscErrorCode ierr;
5166 
5167   PetscFunctionBegin;
5168   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5169   PetscValidType(mat,1);
5170   MatCheckPreallocated(mat,1);
5171   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5172   if (mat->assembled) {
5173     mat->was_assembled = PETSC_TRUE;
5174     mat->assembled     = PETSC_FALSE;
5175   }
5176 
5177   if (!MatAssemblyEnd_InUse) {
5178     ierr = PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5179     if (mat->ops->assemblybegin) {ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);}
5180     ierr = PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);CHKERRQ(ierr);
5181   } else if (mat->ops->assemblybegin) {
5182     ierr = (*mat->ops->assemblybegin)(mat,type);CHKERRQ(ierr);
5183   }
5184   PetscFunctionReturn(0);
5185 }
5186 
5187 /*@
5188    MatAssembled - Indicates if a matrix has been assembled and is ready for
5189      use; for example, in matrix-vector product.
5190 
5191    Not Collective
5192 
5193    Input Parameter:
5194 .  mat - the matrix
5195 
5196    Output Parameter:
5197 .  assembled - PETSC_TRUE or PETSC_FALSE
5198 
5199    Level: advanced
5200 
5201 .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5202 @*/
5203 PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5204 {
5205   PetscFunctionBegin;
5206   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5207   PetscValidPointer(assembled,2);
5208   *assembled = mat->assembled;
5209   PetscFunctionReturn(0);
5210 }
5211 
5212 /*@
5213    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5214    be called after MatAssemblyBegin().
5215 
5216    Collective on Mat
5217 
5218    Input Parameters:
5219 +  mat - the matrix
5220 -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5221 
5222    Options Database Keys:
5223 +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5224 .  -mat_view ::ascii_info_detail - Prints more detailed info
5225 .  -mat_view - Prints matrix in ASCII format
5226 .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5227 .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5228 .  -display <name> - Sets display name (default is host)
5229 .  -draw_pause <sec> - Sets number of seconds to pause after display
5230 .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: ch_matlab )
5231 .  -viewer_socket_machine <machine> - Machine to use for socket
5232 .  -viewer_socket_port <port> - Port number to use for socket
5233 -  -mat_view binary:filename[:append] - Save matrix to file in binary format
5234 
5235    Notes:
5236    MatSetValues() generally caches the values.  The matrix is ready to
5237    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5238    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5239    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5240    using the matrix.
5241 
5242    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5243    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5244    before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5245 
5246    Level: beginner
5247 
5248 .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5249 @*/
5250 PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5251 {
5252   PetscErrorCode  ierr;
5253   static PetscInt inassm = 0;
5254   PetscBool       flg    = PETSC_FALSE;
5255 
5256   PetscFunctionBegin;
5257   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5258   PetscValidType(mat,1);
5259 
5260   inassm++;
5261   MatAssemblyEnd_InUse++;
5262   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5263     ierr = PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5264     if (mat->ops->assemblyend) {
5265       ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5266     }
5267     ierr = PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);CHKERRQ(ierr);
5268   } else if (mat->ops->assemblyend) {
5269     ierr = (*mat->ops->assemblyend)(mat,type);CHKERRQ(ierr);
5270   }
5271 
5272   /* Flush assembly is not a true assembly */
5273   if (type != MAT_FLUSH_ASSEMBLY) {
5274     mat->num_ass++;
5275     mat->assembled        = PETSC_TRUE;
5276     mat->ass_nonzerostate = mat->nonzerostate;
5277   }
5278 
5279   mat->insertmode = NOT_SET_VALUES;
5280   MatAssemblyEnd_InUse--;
5281   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5282   if (!mat->symmetric_eternal) {
5283     mat->symmetric_set              = PETSC_FALSE;
5284     mat->hermitian_set              = PETSC_FALSE;
5285     mat->structurally_symmetric_set = PETSC_FALSE;
5286   }
5287   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5288     ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5289 
5290     if (mat->checksymmetryonassembly) {
5291       ierr = MatIsSymmetric(mat,mat->checksymmetrytol,&flg);CHKERRQ(ierr);
5292       if (flg) {
5293         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5294       } else {
5295         ierr = PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);CHKERRQ(ierr);
5296       }
5297     }
5298     if (mat->nullsp && mat->checknullspaceonassembly) {
5299       ierr = MatNullSpaceTest(mat->nullsp,mat,NULL);CHKERRQ(ierr);
5300     }
5301   }
5302   inassm--;
5303   PetscFunctionReturn(0);
5304 }
5305 
5306 /*@
5307    MatSetOption - Sets a parameter option for a matrix. Some options
5308    may be specific to certain storage formats.  Some options
5309    determine how values will be inserted (or added). Sorted,
5310    row-oriented input will generally assemble the fastest. The default
5311    is row-oriented.
5312 
5313    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5314 
5315    Input Parameters:
5316 +  mat - the matrix
5317 .  option - the option, one of those listed below (and possibly others),
5318 -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5319 
5320   Options Describing Matrix Structure:
5321 +    MAT_SPD - symmetric positive definite
5322 .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5323 .    MAT_HERMITIAN - transpose is the complex conjugation
5324 .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5325 -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5326                             you set to be kept with all future use of the matrix
5327                             including after MatAssemblyBegin/End() which could
5328                             potentially change the symmetry structure, i.e. you
5329                             KNOW the matrix will ALWAYS have the property you set.
5330 
5331 
5332    Options For Use with MatSetValues():
5333    Insert a logically dense subblock, which can be
5334 .    MAT_ROW_ORIENTED - row-oriented (default)
5335 
5336    Note these options reflect the data you pass in with MatSetValues(); it has
5337    nothing to do with how the data is stored internally in the matrix
5338    data structure.
5339 
5340    When (re)assembling a matrix, we can restrict the input for
5341    efficiency/debugging purposes.  These options include:
5342 +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5343 .    MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5344 .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5345 .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5346 .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5347 .    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5348         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5349         performance for very large process counts.
5350 -    MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5351         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5352         functions, instead sending only neighbor messages.
5353 
5354    Notes:
5355    Except for MAT_UNUSED_NONZERO_LOCATION_ERR and  MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5356 
5357    Some options are relevant only for particular matrix types and
5358    are thus ignored by others.  Other options are not supported by
5359    certain matrix types and will generate an error message if set.
5360 
5361    If using a Fortran 77 module to compute a matrix, one may need to
5362    use the column-oriented option (or convert to the row-oriented
5363    format).
5364 
5365    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5366    that would generate a new entry in the nonzero structure is instead
5367    ignored.  Thus, if memory has not alredy been allocated for this particular
5368    data, then the insertion is ignored. For dense matrices, in which
5369    the entire array is allocated, no entries are ever ignored.
5370    Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5371 
5372    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5373    that would generate a new entry in the nonzero structure instead produces
5374    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
5375 
5376    MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5377    that would generate a new entry that has not been preallocated will
5378    instead produce an error. (Currently supported for AIJ and BAIJ formats
5379    only.) This is a useful flag when debugging matrix memory preallocation.
5380    If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5381 
5382    MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5383    other processors should be dropped, rather than stashed.
5384    This is useful if you know that the "owning" processor is also
5385    always generating the correct matrix entries, so that PETSc need
5386    not transfer duplicate entries generated on another processor.
5387 
5388    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5389    searches during matrix assembly. When this flag is set, the hash table
5390    is created during the first Matrix Assembly. This hash table is
5391    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5392    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5393    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5394    supported by MATMPIBAIJ format only.
5395 
5396    MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5397    are kept in the nonzero structure
5398 
5399    MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5400    a zero location in the matrix
5401 
5402    MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5403 
5404    MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5405         zero row routines and thus improves performance for very large process counts.
5406 
5407    MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5408         part of the matrix (since they should match the upper triangular part).
5409 
5410    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5411                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5412                      with finite difference schemes with non-periodic boundary conditions.
5413    Notes:
5414     Can only be called after MatSetSizes() and MatSetType() have been set.
5415 
5416    Level: intermediate
5417 
5418 .seealso:  MatOption, Mat
5419 
5420 @*/
5421 PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5422 {
5423   PetscErrorCode ierr;
5424 
5425   PetscFunctionBegin;
5426   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5427   PetscValidType(mat,1);
5428   if (op > 0) {
5429     PetscValidLogicalCollectiveEnum(mat,op,2);
5430     PetscValidLogicalCollectiveBool(mat,flg,3);
5431   }
5432 
5433   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);
5434   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()");
5435 
5436   switch (op) {
5437   case MAT_NO_OFF_PROC_ENTRIES:
5438     mat->nooffprocentries = flg;
5439     PetscFunctionReturn(0);
5440     break;
5441   case MAT_SUBSET_OFF_PROC_ENTRIES:
5442     mat->assembly_subset = flg;
5443     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5444 #if !defined(PETSC_HAVE_MPIUNI)
5445       ierr = MatStashScatterDestroy_BTS(&mat->stash);CHKERRQ(ierr);
5446 #endif
5447       mat->stash.first_assembly_done = PETSC_FALSE;
5448     }
5449     PetscFunctionReturn(0);
5450   case MAT_NO_OFF_PROC_ZERO_ROWS:
5451     mat->nooffproczerorows = flg;
5452     PetscFunctionReturn(0);
5453     break;
5454   case MAT_SPD:
5455     mat->spd_set = PETSC_TRUE;
5456     mat->spd     = flg;
5457     if (flg) {
5458       mat->symmetric                  = PETSC_TRUE;
5459       mat->structurally_symmetric     = PETSC_TRUE;
5460       mat->symmetric_set              = PETSC_TRUE;
5461       mat->structurally_symmetric_set = PETSC_TRUE;
5462     }
5463     break;
5464   case MAT_SYMMETRIC:
5465     mat->symmetric = flg;
5466     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5467     mat->symmetric_set              = PETSC_TRUE;
5468     mat->structurally_symmetric_set = flg;
5469 #if !defined(PETSC_USE_COMPLEX)
5470     mat->hermitian     = flg;
5471     mat->hermitian_set = PETSC_TRUE;
5472 #endif
5473     break;
5474   case MAT_HERMITIAN:
5475     mat->hermitian = flg;
5476     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5477     mat->hermitian_set              = PETSC_TRUE;
5478     mat->structurally_symmetric_set = flg;
5479 #if !defined(PETSC_USE_COMPLEX)
5480     mat->symmetric     = flg;
5481     mat->symmetric_set = PETSC_TRUE;
5482 #endif
5483     break;
5484   case MAT_STRUCTURALLY_SYMMETRIC:
5485     mat->structurally_symmetric     = flg;
5486     mat->structurally_symmetric_set = PETSC_TRUE;
5487     break;
5488   case MAT_SYMMETRY_ETERNAL:
5489     mat->symmetric_eternal = flg;
5490     break;
5491   case MAT_STRUCTURE_ONLY:
5492     mat->structure_only = flg;
5493     break;
5494   case MAT_SORTED_FULL:
5495     mat->sortedfull = flg;
5496     break;
5497   default:
5498     break;
5499   }
5500   if (mat->ops->setoption) {
5501     ierr = (*mat->ops->setoption)(mat,op,flg);CHKERRQ(ierr);
5502   }
5503   PetscFunctionReturn(0);
5504 }
5505 
5506 /*@
5507    MatGetOption - Gets a parameter option that has been set for a matrix.
5508 
5509    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5510 
5511    Input Parameters:
5512 +  mat - the matrix
5513 -  option - the option, this only responds to certain options, check the code for which ones
5514 
5515    Output Parameter:
5516 .  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5517 
5518     Notes:
5519     Can only be called after MatSetSizes() and MatSetType() have been set.
5520 
5521    Level: intermediate
5522 
5523 .seealso:  MatOption, MatSetOption()
5524 
5525 @*/
5526 PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5527 {
5528   PetscFunctionBegin;
5529   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5530   PetscValidType(mat,1);
5531 
5532   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);
5533   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()");
5534 
5535   switch (op) {
5536   case MAT_NO_OFF_PROC_ENTRIES:
5537     *flg = mat->nooffprocentries;
5538     break;
5539   case MAT_NO_OFF_PROC_ZERO_ROWS:
5540     *flg = mat->nooffproczerorows;
5541     break;
5542   case MAT_SYMMETRIC:
5543     *flg = mat->symmetric;
5544     break;
5545   case MAT_HERMITIAN:
5546     *flg = mat->hermitian;
5547     break;
5548   case MAT_STRUCTURALLY_SYMMETRIC:
5549     *flg = mat->structurally_symmetric;
5550     break;
5551   case MAT_SYMMETRY_ETERNAL:
5552     *flg = mat->symmetric_eternal;
5553     break;
5554   case MAT_SPD:
5555     *flg = mat->spd;
5556     break;
5557   default:
5558     break;
5559   }
5560   PetscFunctionReturn(0);
5561 }
5562 
5563 /*@
5564    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5565    this routine retains the old nonzero structure.
5566 
5567    Logically Collective on Mat
5568 
5569    Input Parameters:
5570 .  mat - the matrix
5571 
5572    Level: intermediate
5573 
5574    Notes:
5575     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.
5576    See the Performance chapter of the users manual for information on preallocating matrices.
5577 
5578 .seealso: MatZeroRows()
5579 @*/
5580 PetscErrorCode MatZeroEntries(Mat mat)
5581 {
5582   PetscErrorCode ierr;
5583 
5584   PetscFunctionBegin;
5585   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5586   PetscValidType(mat,1);
5587   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5588   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");
5589   if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5590   MatCheckPreallocated(mat,1);
5591 
5592   ierr = PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5593   ierr = (*mat->ops->zeroentries)(mat);CHKERRQ(ierr);
5594   ierr = PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);CHKERRQ(ierr);
5595   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5596   PetscFunctionReturn(0);
5597 }
5598 
5599 /*@
5600    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5601    of a set of rows and columns of a matrix.
5602 
5603    Collective on Mat
5604 
5605    Input Parameters:
5606 +  mat - the matrix
5607 .  numRows - the number of rows to remove
5608 .  rows - the global row indices
5609 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5610 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5611 -  b - optional vector of right hand side, that will be adjusted by provided solution
5612 
5613    Notes:
5614    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5615 
5616    The user can set a value in the diagonal entry (or for the AIJ and
5617    row formats can optionally remove the main diagonal entry from the
5618    nonzero structure as well, by passing 0.0 as the final argument).
5619 
5620    For the parallel case, all processes that share the matrix (i.e.,
5621    those in the communicator used for matrix creation) MUST call this
5622    routine, regardless of whether any rows being zeroed are owned by
5623    them.
5624 
5625    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5626    list only rows local to itself).
5627 
5628    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5629 
5630    Level: intermediate
5631 
5632 .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5633           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5634 @*/
5635 PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5636 {
5637   PetscErrorCode ierr;
5638 
5639   PetscFunctionBegin;
5640   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5641   PetscValidType(mat,1);
5642   if (numRows) PetscValidIntPointer(rows,3);
5643   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5644   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5645   if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5646   MatCheckPreallocated(mat,1);
5647 
5648   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5649   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5650   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5651   PetscFunctionReturn(0);
5652 }
5653 
5654 /*@
5655    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5656    of a set of rows and columns of a matrix.
5657 
5658    Collective on Mat
5659 
5660    Input Parameters:
5661 +  mat - the matrix
5662 .  is - the rows to zero
5663 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5664 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5665 -  b - optional vector of right hand side, that will be adjusted by provided solution
5666 
5667    Notes:
5668    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5669 
5670    The user can set a value in the diagonal entry (or for the AIJ and
5671    row formats can optionally remove the main diagonal entry from the
5672    nonzero structure as well, by passing 0.0 as the final argument).
5673 
5674    For the parallel case, all processes that share the matrix (i.e.,
5675    those in the communicator used for matrix creation) MUST call this
5676    routine, regardless of whether any rows being zeroed are owned by
5677    them.
5678 
5679    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5680    list only rows local to itself).
5681 
5682    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5683 
5684    Level: intermediate
5685 
5686 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5687           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5688 @*/
5689 PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5690 {
5691   PetscErrorCode ierr;
5692   PetscInt       numRows;
5693   const PetscInt *rows;
5694 
5695   PetscFunctionBegin;
5696   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5697   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5698   PetscValidType(mat,1);
5699   PetscValidType(is,2);
5700   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5701   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5702   ierr = MatZeroRowsColumns(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5703   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5704   PetscFunctionReturn(0);
5705 }
5706 
5707 /*@
5708    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5709    of a set of rows of a matrix.
5710 
5711    Collective on Mat
5712 
5713    Input Parameters:
5714 +  mat - the matrix
5715 .  numRows - the number of rows to remove
5716 .  rows - the global row indices
5717 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5718 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5719 -  b - optional vector of right hand side, that will be adjusted by provided solution
5720 
5721    Notes:
5722    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5723    but does not release memory.  For the dense and block diagonal
5724    formats this does not alter the nonzero structure.
5725 
5726    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5727    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5728    merely zeroed.
5729 
5730    The user can set a value in the diagonal entry (or for the AIJ and
5731    row formats can optionally remove the main diagonal entry from the
5732    nonzero structure as well, by passing 0.0 as the final argument).
5733 
5734    For the parallel case, all processes that share the matrix (i.e.,
5735    those in the communicator used for matrix creation) MUST call this
5736    routine, regardless of whether any rows being zeroed are owned by
5737    them.
5738 
5739    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5740    list only rows local to itself).
5741 
5742    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5743    owns that are to be zeroed. This saves a global synchronization in the implementation.
5744 
5745    Level: intermediate
5746 
5747 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5748           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5749 @*/
5750 PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5751 {
5752   PetscErrorCode ierr;
5753 
5754   PetscFunctionBegin;
5755   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5756   PetscValidType(mat,1);
5757   if (numRows) PetscValidIntPointer(rows,3);
5758   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5759   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5760   if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5761   MatCheckPreallocated(mat,1);
5762 
5763   ierr = (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5764   ierr = MatViewFromOptions(mat,NULL,"-mat_view");CHKERRQ(ierr);
5765   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
5766   PetscFunctionReturn(0);
5767 }
5768 
5769 /*@
5770    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5771    of a set of rows of a matrix.
5772 
5773    Collective on Mat
5774 
5775    Input Parameters:
5776 +  mat - the matrix
5777 .  is - index set of rows to remove
5778 .  diag - value put in all diagonals of eliminated rows
5779 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5780 -  b - optional vector of right hand side, that will be adjusted by provided solution
5781 
5782    Notes:
5783    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5784    but does not release memory.  For the dense and block diagonal
5785    formats this does not alter the nonzero structure.
5786 
5787    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5788    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5789    merely zeroed.
5790 
5791    The user can set a value in the diagonal entry (or for the AIJ and
5792    row formats can optionally remove the main diagonal entry from the
5793    nonzero structure as well, by passing 0.0 as the final argument).
5794 
5795    For the parallel case, all processes that share the matrix (i.e.,
5796    those in the communicator used for matrix creation) MUST call this
5797    routine, regardless of whether any rows being zeroed are owned by
5798    them.
5799 
5800    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5801    list only rows local to itself).
5802 
5803    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5804    owns that are to be zeroed. This saves a global synchronization in the implementation.
5805 
5806    Level: intermediate
5807 
5808 .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5809           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5810 @*/
5811 PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5812 {
5813   PetscInt       numRows;
5814   const PetscInt *rows;
5815   PetscErrorCode ierr;
5816 
5817   PetscFunctionBegin;
5818   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5819   PetscValidType(mat,1);
5820   PetscValidHeaderSpecific(is,IS_CLASSID,2);
5821   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
5822   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
5823   ierr = MatZeroRows(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
5824   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
5825   PetscFunctionReturn(0);
5826 }
5827 
5828 /*@
5829    MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5830    of a set of rows of a matrix. These rows must be local to the process.
5831 
5832    Collective on Mat
5833 
5834    Input Parameters:
5835 +  mat - the matrix
5836 .  numRows - the number of rows to remove
5837 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5838 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5839 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5840 -  b - optional vector of right hand side, that will be adjusted by provided solution
5841 
5842    Notes:
5843    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5844    but does not release memory.  For the dense and block diagonal
5845    formats this does not alter the nonzero structure.
5846 
5847    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5848    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5849    merely zeroed.
5850 
5851    The user can set a value in the diagonal entry (or for the AIJ and
5852    row formats can optionally remove the main diagonal entry from the
5853    nonzero structure as well, by passing 0.0 as the final argument).
5854 
5855    For the parallel case, all processes that share the matrix (i.e.,
5856    those in the communicator used for matrix creation) MUST call this
5857    routine, regardless of whether any rows being zeroed are owned by
5858    them.
5859 
5860    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5861    list only rows local to itself).
5862 
5863    The grid coordinates are across the entire grid, not just the local portion
5864 
5865    In Fortran idxm and idxn should be declared as
5866 $     MatStencil idxm(4,m)
5867    and the values inserted using
5868 $    idxm(MatStencil_i,1) = i
5869 $    idxm(MatStencil_j,1) = j
5870 $    idxm(MatStencil_k,1) = k
5871 $    idxm(MatStencil_c,1) = c
5872    etc
5873 
5874    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5875    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5876    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5877    DM_BOUNDARY_PERIODIC boundary type.
5878 
5879    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
5880    a single value per point) you can skip filling those indices.
5881 
5882    Level: intermediate
5883 
5884 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5885           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5886 @*/
5887 PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5888 {
5889   PetscInt       dim     = mat->stencil.dim;
5890   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5891   PetscInt       *dims   = mat->stencil.dims+1;
5892   PetscInt       *starts = mat->stencil.starts;
5893   PetscInt       *dxm    = (PetscInt*) rows;
5894   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
5895   PetscErrorCode ierr;
5896 
5897   PetscFunctionBegin;
5898   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5899   PetscValidType(mat,1);
5900   if (numRows) PetscValidIntPointer(rows,3);
5901 
5902   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
5903   for (i = 0; i < numRows; ++i) {
5904     /* Skip unused dimensions (they are ordered k, j, i, c) */
5905     for (j = 0; j < 3-sdim; ++j) dxm++;
5906     /* Local index in X dir */
5907     tmp = *dxm++ - starts[0];
5908     /* Loop over remaining dimensions */
5909     for (j = 0; j < dim-1; ++j) {
5910       /* If nonlocal, set index to be negative */
5911       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5912       /* Update local index */
5913       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5914     }
5915     /* Skip component slot if necessary */
5916     if (mat->stencil.noc) dxm++;
5917     /* Local row number */
5918     if (tmp >= 0) {
5919       jdxm[numNewRows++] = tmp;
5920     }
5921   }
5922   ierr = MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
5923   ierr = PetscFree(jdxm);CHKERRQ(ierr);
5924   PetscFunctionReturn(0);
5925 }
5926 
5927 /*@
5928    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
5929    of a set of rows and columns of a matrix.
5930 
5931    Collective on Mat
5932 
5933    Input Parameters:
5934 +  mat - the matrix
5935 .  numRows - the number of rows/columns to remove
5936 .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5937 .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5938 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5939 -  b - optional vector of right hand side, that will be adjusted by provided solution
5940 
5941    Notes:
5942    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5943    but does not release memory.  For the dense and block diagonal
5944    formats this does not alter the nonzero structure.
5945 
5946    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5947    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5948    merely zeroed.
5949 
5950    The user can set a value in the diagonal entry (or for the AIJ and
5951    row formats can optionally remove the main diagonal entry from the
5952    nonzero structure as well, by passing 0.0 as the final argument).
5953 
5954    For the parallel case, all processes that share the matrix (i.e.,
5955    those in the communicator used for matrix creation) MUST call this
5956    routine, regardless of whether any rows being zeroed are owned by
5957    them.
5958 
5959    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5960    list only rows local to itself, but the row/column numbers are given in local numbering).
5961 
5962    The grid coordinates are across the entire grid, not just the local portion
5963 
5964    In Fortran idxm and idxn should be declared as
5965 $     MatStencil idxm(4,m)
5966    and the values inserted using
5967 $    idxm(MatStencil_i,1) = i
5968 $    idxm(MatStencil_j,1) = j
5969 $    idxm(MatStencil_k,1) = k
5970 $    idxm(MatStencil_c,1) = c
5971    etc
5972 
5973    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5974    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5975    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5976    DM_BOUNDARY_PERIODIC boundary type.
5977 
5978    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
5979    a single value per point) you can skip filling those indices.
5980 
5981    Level: intermediate
5982 
5983 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5984           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
5985 @*/
5986 PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5987 {
5988   PetscInt       dim     = mat->stencil.dim;
5989   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5990   PetscInt       *dims   = mat->stencil.dims+1;
5991   PetscInt       *starts = mat->stencil.starts;
5992   PetscInt       *dxm    = (PetscInt*) rows;
5993   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;
5994   PetscErrorCode ierr;
5995 
5996   PetscFunctionBegin;
5997   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
5998   PetscValidType(mat,1);
5999   if (numRows) PetscValidIntPointer(rows,3);
6000 
6001   ierr = PetscMalloc1(numRows, &jdxm);CHKERRQ(ierr);
6002   for (i = 0; i < numRows; ++i) {
6003     /* Skip unused dimensions (they are ordered k, j, i, c) */
6004     for (j = 0; j < 3-sdim; ++j) dxm++;
6005     /* Local index in X dir */
6006     tmp = *dxm++ - starts[0];
6007     /* Loop over remaining dimensions */
6008     for (j = 0; j < dim-1; ++j) {
6009       /* If nonlocal, set index to be negative */
6010       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6011       /* Update local index */
6012       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6013     }
6014     /* Skip component slot if necessary */
6015     if (mat->stencil.noc) dxm++;
6016     /* Local row number */
6017     if (tmp >= 0) {
6018       jdxm[numNewRows++] = tmp;
6019     }
6020   }
6021   ierr = MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);CHKERRQ(ierr);
6022   ierr = PetscFree(jdxm);CHKERRQ(ierr);
6023   PetscFunctionReturn(0);
6024 }
6025 
6026 /*@C
6027    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6028    of a set of rows of a matrix; using local numbering of rows.
6029 
6030    Collective on Mat
6031 
6032    Input Parameters:
6033 +  mat - the matrix
6034 .  numRows - the number of rows to remove
6035 .  rows - the global row indices
6036 .  diag - value put in all diagonals of eliminated rows
6037 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6038 -  b - optional vector of right hand side, that will be adjusted by provided solution
6039 
6040    Notes:
6041    Before calling MatZeroRowsLocal(), the user must first set the
6042    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6043 
6044    For the AIJ matrix formats this removes the old nonzero structure,
6045    but does not release memory.  For the dense and block diagonal
6046    formats this does not alter the nonzero structure.
6047 
6048    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6049    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6050    merely zeroed.
6051 
6052    The user can set a value in the diagonal entry (or for the AIJ and
6053    row formats can optionally remove the main diagonal entry from the
6054    nonzero structure as well, by passing 0.0 as the final argument).
6055 
6056    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6057    owns that are to be zeroed. This saves a global synchronization in the implementation.
6058 
6059    Level: intermediate
6060 
6061 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6062           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6063 @*/
6064 PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6065 {
6066   PetscErrorCode ierr;
6067 
6068   PetscFunctionBegin;
6069   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6070   PetscValidType(mat,1);
6071   if (numRows) PetscValidIntPointer(rows,3);
6072   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6073   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6074   MatCheckPreallocated(mat,1);
6075 
6076   if (mat->ops->zerorowslocal) {
6077     ierr = (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6078   } else {
6079     IS             is, newis;
6080     const PetscInt *newRows;
6081 
6082     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6083     ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6084     ierr = ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);CHKERRQ(ierr);
6085     ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6086     ierr = (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6087     ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6088     ierr = ISDestroy(&newis);CHKERRQ(ierr);
6089     ierr = ISDestroy(&is);CHKERRQ(ierr);
6090   }
6091   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6092   PetscFunctionReturn(0);
6093 }
6094 
6095 /*@
6096    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6097    of a set of rows of a matrix; using local numbering of rows.
6098 
6099    Collective on Mat
6100 
6101    Input Parameters:
6102 +  mat - the matrix
6103 .  is - index set of rows to remove
6104 .  diag - value put in all diagonals of eliminated rows
6105 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6106 -  b - optional vector of right hand side, that will be adjusted by provided solution
6107 
6108    Notes:
6109    Before calling MatZeroRowsLocalIS(), the user must first set the
6110    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6111 
6112    For the AIJ matrix formats this removes the old nonzero structure,
6113    but does not release memory.  For the dense and block diagonal
6114    formats this does not alter the nonzero structure.
6115 
6116    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6117    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6118    merely zeroed.
6119 
6120    The user can set a value in the diagonal entry (or for the AIJ and
6121    row formats can optionally remove the main diagonal entry from the
6122    nonzero structure as well, by passing 0.0 as the final argument).
6123 
6124    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6125    owns that are to be zeroed. This saves a global synchronization in the implementation.
6126 
6127    Level: intermediate
6128 
6129 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6130           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6131 @*/
6132 PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6133 {
6134   PetscErrorCode ierr;
6135   PetscInt       numRows;
6136   const PetscInt *rows;
6137 
6138   PetscFunctionBegin;
6139   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6140   PetscValidType(mat,1);
6141   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6142   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6143   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6144   MatCheckPreallocated(mat,1);
6145 
6146   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6147   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6148   ierr = MatZeroRowsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6149   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6150   PetscFunctionReturn(0);
6151 }
6152 
6153 /*@
6154    MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6155    of a set of rows and columns of a matrix; using local numbering of rows.
6156 
6157    Collective on Mat
6158 
6159    Input Parameters:
6160 +  mat - the matrix
6161 .  numRows - the number of rows to remove
6162 .  rows - the global row indices
6163 .  diag - value put in all diagonals of eliminated rows
6164 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6165 -  b - optional vector of right hand side, that will be adjusted by provided solution
6166 
6167    Notes:
6168    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6169    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6170 
6171    The user can set a value in the diagonal entry (or for the AIJ and
6172    row formats can optionally remove the main diagonal entry from the
6173    nonzero structure as well, by passing 0.0 as the final argument).
6174 
6175    Level: intermediate
6176 
6177 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6178           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6179 @*/
6180 PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6181 {
6182   PetscErrorCode ierr;
6183   IS             is, newis;
6184   const PetscInt *newRows;
6185 
6186   PetscFunctionBegin;
6187   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6188   PetscValidType(mat,1);
6189   if (numRows) PetscValidIntPointer(rows,3);
6190   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6191   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6192   MatCheckPreallocated(mat,1);
6193 
6194   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6195   ierr = ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);CHKERRQ(ierr);
6196   ierr = ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);CHKERRQ(ierr);
6197   ierr = ISGetIndices(newis,&newRows);CHKERRQ(ierr);
6198   ierr = (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);CHKERRQ(ierr);
6199   ierr = ISRestoreIndices(newis,&newRows);CHKERRQ(ierr);
6200   ierr = ISDestroy(&newis);CHKERRQ(ierr);
6201   ierr = ISDestroy(&is);CHKERRQ(ierr);
6202   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
6203   PetscFunctionReturn(0);
6204 }
6205 
6206 /*@
6207    MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6208    of a set of rows and columns of a matrix; using local numbering of rows.
6209 
6210    Collective on Mat
6211 
6212    Input Parameters:
6213 +  mat - the matrix
6214 .  is - index set of rows to remove
6215 .  diag - value put in all diagonals of eliminated rows
6216 .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6217 -  b - optional vector of right hand side, that will be adjusted by provided solution
6218 
6219    Notes:
6220    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6221    local-to-global mapping by calling MatSetLocalToGlobalMapping().
6222 
6223    The user can set a value in the diagonal entry (or for the AIJ and
6224    row formats can optionally remove the main diagonal entry from the
6225    nonzero structure as well, by passing 0.0 as the final argument).
6226 
6227    Level: intermediate
6228 
6229 .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6230           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6231 @*/
6232 PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6233 {
6234   PetscErrorCode ierr;
6235   PetscInt       numRows;
6236   const PetscInt *rows;
6237 
6238   PetscFunctionBegin;
6239   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6240   PetscValidType(mat,1);
6241   PetscValidHeaderSpecific(is,IS_CLASSID,2);
6242   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6243   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6244   MatCheckPreallocated(mat,1);
6245 
6246   ierr = ISGetLocalSize(is,&numRows);CHKERRQ(ierr);
6247   ierr = ISGetIndices(is,&rows);CHKERRQ(ierr);
6248   ierr = MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);CHKERRQ(ierr);
6249   ierr = ISRestoreIndices(is,&rows);CHKERRQ(ierr);
6250   PetscFunctionReturn(0);
6251 }
6252 
6253 /*@C
6254    MatGetSize - Returns the numbers of rows and columns in a matrix.
6255 
6256    Not Collective
6257 
6258    Input Parameter:
6259 .  mat - the matrix
6260 
6261    Output Parameters:
6262 +  m - the number of global rows
6263 -  n - the number of global columns
6264 
6265    Note: both output parameters can be NULL on input.
6266 
6267    Level: beginner
6268 
6269 .seealso: MatGetLocalSize()
6270 @*/
6271 PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6272 {
6273   PetscFunctionBegin;
6274   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6275   if (m) *m = mat->rmap->N;
6276   if (n) *n = mat->cmap->N;
6277   PetscFunctionReturn(0);
6278 }
6279 
6280 /*@C
6281    MatGetLocalSize - Returns the number of rows and columns in a matrix
6282    stored locally.  This information may be implementation dependent, so
6283    use with care.
6284 
6285    Not Collective
6286 
6287    Input Parameters:
6288 .  mat - the matrix
6289 
6290    Output Parameters:
6291 +  m - the number of local rows
6292 -  n - the number of local columns
6293 
6294    Note: both output parameters can be NULL on input.
6295 
6296    Level: beginner
6297 
6298 .seealso: MatGetSize()
6299 @*/
6300 PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6301 {
6302   PetscFunctionBegin;
6303   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6304   if (m) PetscValidIntPointer(m,2);
6305   if (n) PetscValidIntPointer(n,3);
6306   if (m) *m = mat->rmap->n;
6307   if (n) *n = mat->cmap->n;
6308   PetscFunctionReturn(0);
6309 }
6310 
6311 /*@C
6312    MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6313    this processor. (The columns of the "diagonal block")
6314 
6315    Not Collective, unless matrix has not been allocated, then collective on Mat
6316 
6317    Input Parameters:
6318 .  mat - the matrix
6319 
6320    Output Parameters:
6321 +  m - the global index of the first local column
6322 -  n - one more than the global index of the last local column
6323 
6324    Notes:
6325     both output parameters can be NULL on input.
6326 
6327    Level: developer
6328 
6329 .seealso:  MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6330 
6331 @*/
6332 PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6333 {
6334   PetscFunctionBegin;
6335   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6336   PetscValidType(mat,1);
6337   if (m) PetscValidIntPointer(m,2);
6338   if (n) PetscValidIntPointer(n,3);
6339   MatCheckPreallocated(mat,1);
6340   if (m) *m = mat->cmap->rstart;
6341   if (n) *n = mat->cmap->rend;
6342   PetscFunctionReturn(0);
6343 }
6344 
6345 /*@C
6346    MatGetOwnershipRange - Returns the range of matrix rows owned by
6347    this processor, assuming that the matrix is laid out with the first
6348    n1 rows on the first processor, the next n2 rows on the second, etc.
6349    For certain parallel layouts this range may not be well defined.
6350 
6351    Not Collective
6352 
6353    Input Parameters:
6354 .  mat - the matrix
6355 
6356    Output Parameters:
6357 +  m - the global index of the first local row
6358 -  n - one more than the global index of the last local row
6359 
6360    Note: Both output parameters can be NULL on input.
6361 $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6362 $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6363 $  and then MPI_Scan() to calculate prefix sums of the local sizes.
6364 
6365    Level: beginner
6366 
6367 .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6368 
6369 @*/
6370 PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6371 {
6372   PetscFunctionBegin;
6373   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6374   PetscValidType(mat,1);
6375   if (m) PetscValidIntPointer(m,2);
6376   if (n) PetscValidIntPointer(n,3);
6377   MatCheckPreallocated(mat,1);
6378   if (m) *m = mat->rmap->rstart;
6379   if (n) *n = mat->rmap->rend;
6380   PetscFunctionReturn(0);
6381 }
6382 
6383 /*@C
6384    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6385    each process
6386 
6387    Not Collective, unless matrix has not been allocated, then collective on Mat
6388 
6389    Input Parameters:
6390 .  mat - the matrix
6391 
6392    Output Parameters:
6393 .  ranges - start of each processors portion plus one more than the total length at the end
6394 
6395    Level: beginner
6396 
6397 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6398 
6399 @*/
6400 PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6401 {
6402   PetscErrorCode ierr;
6403 
6404   PetscFunctionBegin;
6405   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6406   PetscValidType(mat,1);
6407   MatCheckPreallocated(mat,1);
6408   ierr = PetscLayoutGetRanges(mat->rmap,ranges);CHKERRQ(ierr);
6409   PetscFunctionReturn(0);
6410 }
6411 
6412 /*@C
6413    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6414    this processor. (The columns of the "diagonal blocks" for each process)
6415 
6416    Not Collective, unless matrix has not been allocated, then collective on Mat
6417 
6418    Input Parameters:
6419 .  mat - the matrix
6420 
6421    Output Parameters:
6422 .  ranges - start of each processors portion plus one more then the total length at the end
6423 
6424    Level: beginner
6425 
6426 .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6427 
6428 @*/
6429 PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6430 {
6431   PetscErrorCode ierr;
6432 
6433   PetscFunctionBegin;
6434   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6435   PetscValidType(mat,1);
6436   MatCheckPreallocated(mat,1);
6437   ierr = PetscLayoutGetRanges(mat->cmap,ranges);CHKERRQ(ierr);
6438   PetscFunctionReturn(0);
6439 }
6440 
6441 /*@C
6442    MatGetOwnershipIS - Get row and column ownership as index sets
6443 
6444    Not Collective
6445 
6446    Input Arguments:
6447 .  A - matrix of type Elemental
6448 
6449    Output Arguments:
6450 +  rows - rows in which this process owns elements
6451 -  cols - columns in which this process owns elements
6452 
6453    Level: intermediate
6454 
6455 .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6456 @*/
6457 PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6458 {
6459   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6460 
6461   PetscFunctionBegin;
6462   MatCheckPreallocated(A,1);
6463   ierr = PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);CHKERRQ(ierr);
6464   if (f) {
6465     ierr = (*f)(A,rows,cols);CHKERRQ(ierr);
6466   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6467     if (rows) {ierr = ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);CHKERRQ(ierr);}
6468     if (cols) {ierr = ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);CHKERRQ(ierr);}
6469   }
6470   PetscFunctionReturn(0);
6471 }
6472 
6473 /*@C
6474    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6475    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6476    to complete the factorization.
6477 
6478    Collective on Mat
6479 
6480    Input Parameters:
6481 +  mat - the matrix
6482 .  row - row permutation
6483 .  column - column permutation
6484 -  info - structure containing
6485 $      levels - number of levels of fill.
6486 $      expected fill - as ratio of original fill.
6487 $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6488                 missing diagonal entries)
6489 
6490    Output Parameters:
6491 .  fact - new matrix that has been symbolically factored
6492 
6493    Notes:
6494     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6495 
6496    Most users should employ the simplified KSP interface for linear solvers
6497    instead of working directly with matrix algebra routines such as this.
6498    See, e.g., KSPCreate().
6499 
6500    Level: developer
6501 
6502 .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6503           MatGetOrdering(), MatFactorInfo
6504 
6505     Note: this uses the definition of level of fill as in Y. Saad, 2003
6506 
6507     Developer Note: fortran interface is not autogenerated as the f90
6508     interface defintion cannot be generated correctly [due to MatFactorInfo]
6509 
6510    References:
6511      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6512 @*/
6513 PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6514 {
6515   PetscErrorCode ierr;
6516 
6517   PetscFunctionBegin;
6518   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6519   PetscValidType(mat,1);
6520   PetscValidHeaderSpecific(row,IS_CLASSID,2);
6521   PetscValidHeaderSpecific(col,IS_CLASSID,3);
6522   PetscValidPointer(info,4);
6523   PetscValidPointer(fact,5);
6524   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6525   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6526   if (!(fact)->ops->ilufactorsymbolic) {
6527     MatSolverType spackage;
6528     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
6529     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6530   }
6531   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6532   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6533   MatCheckPreallocated(mat,2);
6534 
6535   ierr = PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6536   ierr = (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);CHKERRQ(ierr);
6537   ierr = PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);CHKERRQ(ierr);
6538   PetscFunctionReturn(0);
6539 }
6540 
6541 /*@C
6542    MatICCFactorSymbolic - Performs symbolic incomplete
6543    Cholesky factorization for a symmetric matrix.  Use
6544    MatCholeskyFactorNumeric() to complete the factorization.
6545 
6546    Collective on Mat
6547 
6548    Input Parameters:
6549 +  mat - the matrix
6550 .  perm - row and column permutation
6551 -  info - structure containing
6552 $      levels - number of levels of fill.
6553 $      expected fill - as ratio of original fill.
6554 
6555    Output Parameter:
6556 .  fact - the factored matrix
6557 
6558    Notes:
6559    Most users should employ the KSP interface for linear solvers
6560    instead of working directly with matrix algebra routines such as this.
6561    See, e.g., KSPCreate().
6562 
6563    Level: developer
6564 
6565 .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6566 
6567     Note: this uses the definition of level of fill as in Y. Saad, 2003
6568 
6569     Developer Note: fortran interface is not autogenerated as the f90
6570     interface defintion cannot be generated correctly [due to MatFactorInfo]
6571 
6572    References:
6573      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6574 @*/
6575 PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6576 {
6577   PetscErrorCode ierr;
6578 
6579   PetscFunctionBegin;
6580   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6581   PetscValidType(mat,1);
6582   PetscValidHeaderSpecific(perm,IS_CLASSID,2);
6583   PetscValidPointer(info,3);
6584   PetscValidPointer(fact,4);
6585   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6586   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6587   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6588   if (!(fact)->ops->iccfactorsymbolic) {
6589     MatSolverType spackage;
6590     ierr = MatFactorGetSolverType(fact,&spackage);CHKERRQ(ierr);
6591     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6592   }
6593   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6594   MatCheckPreallocated(mat,2);
6595 
6596   ierr = PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6597   ierr = (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);CHKERRQ(ierr);
6598   ierr = PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);CHKERRQ(ierr);
6599   PetscFunctionReturn(0);
6600 }
6601 
6602 /*@C
6603    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6604    points to an array of valid matrices, they may be reused to store the new
6605    submatrices.
6606 
6607    Collective on Mat
6608 
6609    Input Parameters:
6610 +  mat - the matrix
6611 .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6612 .  irow, icol - index sets of rows and columns to extract
6613 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6614 
6615    Output Parameter:
6616 .  submat - the array of submatrices
6617 
6618    Notes:
6619    MatCreateSubMatrices() can extract ONLY sequential submatrices
6620    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6621    to extract a parallel submatrix.
6622 
6623    Some matrix types place restrictions on the row and column
6624    indices, such as that they be sorted or that they be equal to each other.
6625 
6626    The index sets may not have duplicate entries.
6627 
6628    When extracting submatrices from a parallel matrix, each processor can
6629    form a different submatrix by setting the rows and columns of its
6630    individual index sets according to the local submatrix desired.
6631 
6632    When finished using the submatrices, the user should destroy
6633    them with MatDestroySubMatrices().
6634 
6635    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6636    original matrix has not changed from that last call to MatCreateSubMatrices().
6637 
6638    This routine creates the matrices in submat; you should NOT create them before
6639    calling it. It also allocates the array of matrix pointers submat.
6640 
6641    For BAIJ matrices the index sets must respect the block structure, that is if they
6642    request one row/column in a block, they must request all rows/columns that are in
6643    that block. For example, if the block size is 2 you cannot request just row 0 and
6644    column 0.
6645 
6646    Fortran Note:
6647    The Fortran interface is slightly different from that given below; it
6648    requires one to pass in  as submat a Mat (integer) array of size at least n+1.
6649 
6650    Level: advanced
6651 
6652 
6653 .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6654 @*/
6655 PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6656 {
6657   PetscErrorCode ierr;
6658   PetscInt       i;
6659   PetscBool      eq;
6660 
6661   PetscFunctionBegin;
6662   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6663   PetscValidType(mat,1);
6664   if (n) {
6665     PetscValidPointer(irow,3);
6666     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6667     PetscValidPointer(icol,4);
6668     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6669   }
6670   PetscValidPointer(submat,6);
6671   if (n && scall == MAT_REUSE_MATRIX) {
6672     PetscValidPointer(*submat,6);
6673     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6674   }
6675   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6676   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6677   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6678   MatCheckPreallocated(mat,1);
6679 
6680   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6681   ierr = (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6682   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6683   for (i=0; i<n; i++) {
6684     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6685     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6686       ierr = ISEqual(irow[i],icol[i],&eq);CHKERRQ(ierr);
6687       if (eq) {
6688         if (mat->symmetric) {
6689           ierr = MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6690         } else if (mat->hermitian) {
6691           ierr = MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
6692         } else if (mat->structurally_symmetric) {
6693           ierr = MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6694         }
6695       }
6696     }
6697   }
6698   PetscFunctionReturn(0);
6699 }
6700 
6701 /*@C
6702    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
6703 
6704    Collective on Mat
6705 
6706    Input Parameters:
6707 +  mat - the matrix
6708 .  n   - the number of submatrixes to be extracted
6709 .  irow, icol - index sets of rows and columns to extract
6710 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6711 
6712    Output Parameter:
6713 .  submat - the array of submatrices
6714 
6715    Level: advanced
6716 
6717 
6718 .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6719 @*/
6720 PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6721 {
6722   PetscErrorCode ierr;
6723   PetscInt       i;
6724   PetscBool      eq;
6725 
6726   PetscFunctionBegin;
6727   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6728   PetscValidType(mat,1);
6729   if (n) {
6730     PetscValidPointer(irow,3);
6731     PetscValidHeaderSpecific(*irow,IS_CLASSID,3);
6732     PetscValidPointer(icol,4);
6733     PetscValidHeaderSpecific(*icol,IS_CLASSID,4);
6734   }
6735   PetscValidPointer(submat,6);
6736   if (n && scall == MAT_REUSE_MATRIX) {
6737     PetscValidPointer(*submat,6);
6738     PetscValidHeaderSpecific(**submat,MAT_CLASSID,6);
6739   }
6740   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6741   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6742   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6743   MatCheckPreallocated(mat,1);
6744 
6745   ierr = PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6746   ierr = (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);CHKERRQ(ierr);
6747   ierr = PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);CHKERRQ(ierr);
6748   for (i=0; i<n; i++) {
6749     if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6750       ierr = ISEqual(irow[i],icol[i],&eq);CHKERRQ(ierr);
6751       if (eq) {
6752         if (mat->symmetric) {
6753           ierr = MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6754         } else if (mat->hermitian) {
6755           ierr = MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
6756         } else if (mat->structurally_symmetric) {
6757           ierr = MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
6758         }
6759       }
6760     }
6761   }
6762   PetscFunctionReturn(0);
6763 }
6764 
6765 /*@C
6766    MatDestroyMatrices - Destroys an array of matrices.
6767 
6768    Collective on Mat
6769 
6770    Input Parameters:
6771 +  n - the number of local matrices
6772 -  mat - the matrices (note that this is a pointer to the array of matrices)
6773 
6774    Level: advanced
6775 
6776     Notes:
6777     Frees not only the matrices, but also the array that contains the matrices
6778            In Fortran will not free the array.
6779 
6780 .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6781 @*/
6782 PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6783 {
6784   PetscErrorCode ierr;
6785   PetscInt       i;
6786 
6787   PetscFunctionBegin;
6788   if (!*mat) PetscFunctionReturn(0);
6789   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6790   PetscValidPointer(mat,2);
6791 
6792   for (i=0; i<n; i++) {
6793     ierr = MatDestroy(&(*mat)[i]);CHKERRQ(ierr);
6794   }
6795 
6796   /* memory is allocated even if n = 0 */
6797   ierr = PetscFree(*mat);CHKERRQ(ierr);
6798   PetscFunctionReturn(0);
6799 }
6800 
6801 /*@C
6802    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
6803 
6804    Collective on Mat
6805 
6806    Input Parameters:
6807 +  n - the number of local matrices
6808 -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6809                        sequence of MatCreateSubMatrices())
6810 
6811    Level: advanced
6812 
6813     Notes:
6814     Frees not only the matrices, but also the array that contains the matrices
6815            In Fortran will not free the array.
6816 
6817 .seealso: MatCreateSubMatrices()
6818 @*/
6819 PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6820 {
6821   PetscErrorCode ierr;
6822   Mat            mat0;
6823 
6824   PetscFunctionBegin;
6825   if (!*mat) PetscFunctionReturn(0);
6826   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6827   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6828   PetscValidPointer(mat,2);
6829 
6830   mat0 = (*mat)[0];
6831   if (mat0 && mat0->ops->destroysubmatrices) {
6832     ierr = (mat0->ops->destroysubmatrices)(n,mat);CHKERRQ(ierr);
6833   } else {
6834     ierr = MatDestroyMatrices(n,mat);CHKERRQ(ierr);
6835   }
6836   PetscFunctionReturn(0);
6837 }
6838 
6839 /*@C
6840    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
6841 
6842    Collective on Mat
6843 
6844    Input Parameters:
6845 .  mat - the matrix
6846 
6847    Output Parameter:
6848 .  matstruct - the sequential matrix with the nonzero structure of mat
6849 
6850   Level: intermediate
6851 
6852 .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6853 @*/
6854 PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6855 {
6856   PetscErrorCode ierr;
6857 
6858   PetscFunctionBegin;
6859   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6860   PetscValidPointer(matstruct,2);
6861 
6862   PetscValidType(mat,1);
6863   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6864   MatCheckPreallocated(mat,1);
6865 
6866   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6867   ierr = PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
6868   ierr = (*mat->ops->getseqnonzerostructure)(mat,matstruct);CHKERRQ(ierr);
6869   ierr = PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);CHKERRQ(ierr);
6870   PetscFunctionReturn(0);
6871 }
6872 
6873 /*@C
6874    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
6875 
6876    Collective on Mat
6877 
6878    Input Parameters:
6879 .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6880                        sequence of MatGetSequentialNonzeroStructure())
6881 
6882    Level: advanced
6883 
6884     Notes:
6885     Frees not only the matrices, but also the array that contains the matrices
6886 
6887 .seealso: MatGetSeqNonzeroStructure()
6888 @*/
6889 PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6890 {
6891   PetscErrorCode ierr;
6892 
6893   PetscFunctionBegin;
6894   PetscValidPointer(mat,1);
6895   ierr = MatDestroy(mat);CHKERRQ(ierr);
6896   PetscFunctionReturn(0);
6897 }
6898 
6899 /*@
6900    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6901    replaces the index sets by larger ones that represent submatrices with
6902    additional overlap.
6903 
6904    Collective on Mat
6905 
6906    Input Parameters:
6907 +  mat - the matrix
6908 .  n   - the number of index sets
6909 .  is  - the array of index sets (these index sets will changed during the call)
6910 -  ov  - the additional overlap requested
6911 
6912    Options Database:
6913 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6914 
6915    Level: developer
6916 
6917 
6918 .seealso: MatCreateSubMatrices()
6919 @*/
6920 PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6921 {
6922   PetscErrorCode ierr;
6923 
6924   PetscFunctionBegin;
6925   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6926   PetscValidType(mat,1);
6927   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6928   if (n) {
6929     PetscValidPointer(is,3);
6930     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
6931   }
6932   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6933   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6934   MatCheckPreallocated(mat,1);
6935 
6936   if (!ov) PetscFunctionReturn(0);
6937   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6938   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
6939   ierr = (*mat->ops->increaseoverlap)(mat,n,is,ov);CHKERRQ(ierr);
6940   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
6941   PetscFunctionReturn(0);
6942 }
6943 
6944 
6945 PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
6946 
6947 /*@
6948    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
6949    a sub communicator, replaces the index sets by larger ones that represent submatrices with
6950    additional overlap.
6951 
6952    Collective on Mat
6953 
6954    Input Parameters:
6955 +  mat - the matrix
6956 .  n   - the number of index sets
6957 .  is  - the array of index sets (these index sets will changed during the call)
6958 -  ov  - the additional overlap requested
6959 
6960    Options Database:
6961 .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6962 
6963    Level: developer
6964 
6965 
6966 .seealso: MatCreateSubMatrices()
6967 @*/
6968 PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
6969 {
6970   PetscInt       i;
6971   PetscErrorCode ierr;
6972 
6973   PetscFunctionBegin;
6974   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
6975   PetscValidType(mat,1);
6976   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6977   if (n) {
6978     PetscValidPointer(is,3);
6979     PetscValidHeaderSpecific(*is,IS_CLASSID,3);
6980   }
6981   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6982   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6983   MatCheckPreallocated(mat,1);
6984   if (!ov) PetscFunctionReturn(0);
6985   ierr = PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
6986   for(i=0; i<n; i++){
6987 	ierr =  MatIncreaseOverlapSplit_Single(mat,&is[i],ov);CHKERRQ(ierr);
6988   }
6989   ierr = PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);CHKERRQ(ierr);
6990   PetscFunctionReturn(0);
6991 }
6992 
6993 
6994 
6995 
6996 /*@
6997    MatGetBlockSize - Returns the matrix block size.
6998 
6999    Not Collective
7000 
7001    Input Parameter:
7002 .  mat - the matrix
7003 
7004    Output Parameter:
7005 .  bs - block size
7006 
7007    Notes:
7008     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7009 
7010    If the block size has not been set yet this routine returns 1.
7011 
7012    Level: intermediate
7013 
7014 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7015 @*/
7016 PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7017 {
7018   PetscFunctionBegin;
7019   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7020   PetscValidIntPointer(bs,2);
7021   *bs = PetscAbs(mat->rmap->bs);
7022   PetscFunctionReturn(0);
7023 }
7024 
7025 /*@
7026    MatGetBlockSizes - Returns the matrix block row and column sizes.
7027 
7028    Not Collective
7029 
7030    Input Parameter:
7031 .  mat - the matrix
7032 
7033    Output Parameter:
7034 +  rbs - row block size
7035 -  cbs - column block size
7036 
7037    Notes:
7038     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7039     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7040 
7041    If a block size has not been set yet this routine returns 1.
7042 
7043    Level: intermediate
7044 
7045 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7046 @*/
7047 PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7048 {
7049   PetscFunctionBegin;
7050   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7051   if (rbs) PetscValidIntPointer(rbs,2);
7052   if (cbs) PetscValidIntPointer(cbs,3);
7053   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7054   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7055   PetscFunctionReturn(0);
7056 }
7057 
7058 /*@
7059    MatSetBlockSize - Sets the matrix block size.
7060 
7061    Logically Collective on Mat
7062 
7063    Input Parameters:
7064 +  mat - the matrix
7065 -  bs - block size
7066 
7067    Notes:
7068     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7069     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7070 
7071     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7072     is compatible with the matrix local sizes.
7073 
7074    Level: intermediate
7075 
7076 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7077 @*/
7078 PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7079 {
7080   PetscErrorCode ierr;
7081 
7082   PetscFunctionBegin;
7083   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7084   PetscValidLogicalCollectiveInt(mat,bs,2);
7085   ierr = MatSetBlockSizes(mat,bs,bs);CHKERRQ(ierr);
7086   PetscFunctionReturn(0);
7087 }
7088 
7089 /*@
7090    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7091 
7092    Logically Collective on Mat
7093 
7094    Input Parameters:
7095 +  mat - the matrix
7096 .  nblocks - the number of blocks on this process
7097 -  bsizes - the block sizes
7098 
7099    Notes:
7100     Currently used by PCVPBJACOBI for SeqAIJ matrices
7101 
7102    Level: intermediate
7103 
7104 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7105 @*/
7106 PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7107 {
7108   PetscErrorCode ierr;
7109   PetscInt       i,ncnt = 0, nlocal;
7110 
7111   PetscFunctionBegin;
7112   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7113   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7114   ierr = MatGetLocalSize(mat,&nlocal,NULL);CHKERRQ(ierr);
7115   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7116   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);
7117   ierr = PetscFree(mat->bsizes);CHKERRQ(ierr);
7118   mat->nblocks = nblocks;
7119   ierr = PetscMalloc1(nblocks,&mat->bsizes);CHKERRQ(ierr);
7120   ierr = PetscArraycpy(mat->bsizes,bsizes,nblocks);CHKERRQ(ierr);
7121   PetscFunctionReturn(0);
7122 }
7123 
7124 /*@C
7125    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7126 
7127    Logically Collective on Mat
7128 
7129    Input Parameters:
7130 .  mat - the matrix
7131 
7132    Output Parameters:
7133 +  nblocks - the number of blocks on this process
7134 -  bsizes - the block sizes
7135 
7136    Notes: Currently not supported from Fortran
7137 
7138    Level: intermediate
7139 
7140 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7141 @*/
7142 PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7143 {
7144   PetscFunctionBegin;
7145   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7146   *nblocks = mat->nblocks;
7147   *bsizes  = mat->bsizes;
7148   PetscFunctionReturn(0);
7149 }
7150 
7151 /*@
7152    MatSetBlockSizes - Sets the matrix block row and column sizes.
7153 
7154    Logically Collective on Mat
7155 
7156    Input Parameters:
7157 +  mat - the matrix
7158 -  rbs - row block size
7159 -  cbs - column block size
7160 
7161    Notes:
7162     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7163     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7164     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later
7165 
7166     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7167     are compatible with the matrix local sizes.
7168 
7169     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7170 
7171    Level: intermediate
7172 
7173 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7174 @*/
7175 PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7176 {
7177   PetscErrorCode ierr;
7178 
7179   PetscFunctionBegin;
7180   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7181   PetscValidLogicalCollectiveInt(mat,rbs,2);
7182   PetscValidLogicalCollectiveInt(mat,cbs,3);
7183   if (mat->ops->setblocksizes) {
7184     ierr = (*mat->ops->setblocksizes)(mat,rbs,cbs);CHKERRQ(ierr);
7185   }
7186   if (mat->rmap->refcnt) {
7187     ISLocalToGlobalMapping l2g = NULL;
7188     PetscLayout            nmap = NULL;
7189 
7190     ierr = PetscLayoutDuplicate(mat->rmap,&nmap);CHKERRQ(ierr);
7191     if (mat->rmap->mapping) {
7192       ierr = ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);CHKERRQ(ierr);
7193     }
7194     ierr = PetscLayoutDestroy(&mat->rmap);CHKERRQ(ierr);
7195     mat->rmap = nmap;
7196     mat->rmap->mapping = l2g;
7197   }
7198   if (mat->cmap->refcnt) {
7199     ISLocalToGlobalMapping l2g = NULL;
7200     PetscLayout            nmap = NULL;
7201 
7202     ierr = PetscLayoutDuplicate(mat->cmap,&nmap);CHKERRQ(ierr);
7203     if (mat->cmap->mapping) {
7204       ierr = ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);CHKERRQ(ierr);
7205     }
7206     ierr = PetscLayoutDestroy(&mat->cmap);CHKERRQ(ierr);
7207     mat->cmap = nmap;
7208     mat->cmap->mapping = l2g;
7209   }
7210   ierr = PetscLayoutSetBlockSize(mat->rmap,rbs);CHKERRQ(ierr);
7211   ierr = PetscLayoutSetBlockSize(mat->cmap,cbs);CHKERRQ(ierr);
7212   PetscFunctionReturn(0);
7213 }
7214 
7215 /*@
7216    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7217 
7218    Logically Collective on Mat
7219 
7220    Input Parameters:
7221 +  mat - the matrix
7222 .  fromRow - matrix from which to copy row block size
7223 -  fromCol - matrix from which to copy column block size (can be same as fromRow)
7224 
7225    Level: developer
7226 
7227 .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7228 @*/
7229 PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7230 {
7231   PetscErrorCode ierr;
7232 
7233   PetscFunctionBegin;
7234   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7235   PetscValidHeaderSpecific(fromRow,MAT_CLASSID,2);
7236   PetscValidHeaderSpecific(fromCol,MAT_CLASSID,3);
7237   if (fromRow->rmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);CHKERRQ(ierr);}
7238   if (fromCol->cmap->bs > 0) {ierr = PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);CHKERRQ(ierr);}
7239   PetscFunctionReturn(0);
7240 }
7241 
7242 /*@
7243    MatResidual - Default routine to calculate the residual.
7244 
7245    Collective on Mat
7246 
7247    Input Parameters:
7248 +  mat - the matrix
7249 .  b   - the right-hand-side
7250 -  x   - the approximate solution
7251 
7252    Output Parameter:
7253 .  r - location to store the residual
7254 
7255    Level: developer
7256 
7257 .seealso: PCMGSetResidual()
7258 @*/
7259 PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7260 {
7261   PetscErrorCode ierr;
7262 
7263   PetscFunctionBegin;
7264   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7265   PetscValidHeaderSpecific(b,VEC_CLASSID,2);
7266   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
7267   PetscValidHeaderSpecific(r,VEC_CLASSID,4);
7268   PetscValidType(mat,1);
7269   MatCheckPreallocated(mat,1);
7270   ierr  = PetscLogEventBegin(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7271   if (!mat->ops->residual) {
7272     ierr = MatMult(mat,x,r);CHKERRQ(ierr);
7273     ierr = VecAYPX(r,-1.0,b);CHKERRQ(ierr);
7274   } else {
7275     ierr  = (*mat->ops->residual)(mat,b,x,r);CHKERRQ(ierr);
7276   }
7277   ierr  = PetscLogEventEnd(MAT_Residual,mat,0,0,0);CHKERRQ(ierr);
7278   PetscFunctionReturn(0);
7279 }
7280 
7281 /*@C
7282     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7283 
7284    Collective on Mat
7285 
7286     Input Parameters:
7287 +   mat - the matrix
7288 .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7289 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7290 -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7291                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7292                  always used.
7293 
7294     Output Parameters:
7295 +   n - number of rows in the (possibly compressed) matrix
7296 .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7297 .   ja - the column indices
7298 -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7299            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7300 
7301     Level: developer
7302 
7303     Notes:
7304     You CANNOT change any of the ia[] or ja[] values.
7305 
7306     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7307 
7308     Fortran Notes:
7309     In Fortran use
7310 $
7311 $      PetscInt ia(1), ja(1)
7312 $      PetscOffset iia, jja
7313 $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7314 $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7315 
7316      or
7317 $
7318 $    PetscInt, pointer :: ia(:),ja(:)
7319 $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7320 $    ! Access the ith and jth entries via ia(i) and ja(j)
7321 
7322 .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7323 @*/
7324 PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7325 {
7326   PetscErrorCode ierr;
7327 
7328   PetscFunctionBegin;
7329   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7330   PetscValidType(mat,1);
7331   PetscValidIntPointer(n,5);
7332   if (ia) PetscValidIntPointer(ia,6);
7333   if (ja) PetscValidIntPointer(ja,7);
7334   PetscValidIntPointer(done,8);
7335   MatCheckPreallocated(mat,1);
7336   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7337   else {
7338     *done = PETSC_TRUE;
7339     ierr  = PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7340     ierr  = (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7341     ierr  = PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);CHKERRQ(ierr);
7342   }
7343   PetscFunctionReturn(0);
7344 }
7345 
7346 /*@C
7347     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7348 
7349     Collective on Mat
7350 
7351     Input Parameters:
7352 +   mat - the matrix
7353 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7354 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7355                 symmetrized
7356 .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7357                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7358                  always used.
7359 .   n - number of columns in the (possibly compressed) matrix
7360 .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7361 -   ja - the row indices
7362 
7363     Output Parameters:
7364 .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7365 
7366     Level: developer
7367 
7368 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7369 @*/
7370 PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7371 {
7372   PetscErrorCode ierr;
7373 
7374   PetscFunctionBegin;
7375   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7376   PetscValidType(mat,1);
7377   PetscValidIntPointer(n,4);
7378   if (ia) PetscValidIntPointer(ia,5);
7379   if (ja) PetscValidIntPointer(ja,6);
7380   PetscValidIntPointer(done,7);
7381   MatCheckPreallocated(mat,1);
7382   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7383   else {
7384     *done = PETSC_TRUE;
7385     ierr  = (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7386   }
7387   PetscFunctionReturn(0);
7388 }
7389 
7390 /*@C
7391     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7392     MatGetRowIJ().
7393 
7394     Collective on Mat
7395 
7396     Input Parameters:
7397 +   mat - the matrix
7398 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7399 .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7400                 symmetrized
7401 .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7402                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7403                  always used.
7404 .   n - size of (possibly compressed) matrix
7405 .   ia - the row pointers
7406 -   ja - the column indices
7407 
7408     Output Parameters:
7409 .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7410 
7411     Note:
7412     This routine zeros out n, ia, and ja. This is to prevent accidental
7413     us of the array after it has been restored. If you pass NULL, it will
7414     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.
7415 
7416     Level: developer
7417 
7418 .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7419 @*/
7420 PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7421 {
7422   PetscErrorCode ierr;
7423 
7424   PetscFunctionBegin;
7425   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7426   PetscValidType(mat,1);
7427   if (ia) PetscValidIntPointer(ia,6);
7428   if (ja) PetscValidIntPointer(ja,7);
7429   PetscValidIntPointer(done,8);
7430   MatCheckPreallocated(mat,1);
7431 
7432   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7433   else {
7434     *done = PETSC_TRUE;
7435     ierr  = (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7436     if (n)  *n = 0;
7437     if (ia) *ia = NULL;
7438     if (ja) *ja = NULL;
7439   }
7440   PetscFunctionReturn(0);
7441 }
7442 
7443 /*@C
7444     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7445     MatGetColumnIJ().
7446 
7447     Collective on Mat
7448 
7449     Input Parameters:
7450 +   mat - the matrix
7451 .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7452 -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7453                 symmetrized
7454 -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7455                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7456                  always used.
7457 
7458     Output Parameters:
7459 +   n - size of (possibly compressed) matrix
7460 .   ia - the column pointers
7461 .   ja - the row indices
7462 -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7463 
7464     Level: developer
7465 
7466 .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7467 @*/
7468 PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7469 {
7470   PetscErrorCode ierr;
7471 
7472   PetscFunctionBegin;
7473   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7474   PetscValidType(mat,1);
7475   if (ia) PetscValidIntPointer(ia,5);
7476   if (ja) PetscValidIntPointer(ja,6);
7477   PetscValidIntPointer(done,7);
7478   MatCheckPreallocated(mat,1);
7479 
7480   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7481   else {
7482     *done = PETSC_TRUE;
7483     ierr  = (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);CHKERRQ(ierr);
7484     if (n)  *n = 0;
7485     if (ia) *ia = NULL;
7486     if (ja) *ja = NULL;
7487   }
7488   PetscFunctionReturn(0);
7489 }
7490 
7491 /*@C
7492     MatColoringPatch -Used inside matrix coloring routines that
7493     use MatGetRowIJ() and/or MatGetColumnIJ().
7494 
7495     Collective on Mat
7496 
7497     Input Parameters:
7498 +   mat - the matrix
7499 .   ncolors - max color value
7500 .   n   - number of entries in colorarray
7501 -   colorarray - array indicating color for each column
7502 
7503     Output Parameters:
7504 .   iscoloring - coloring generated using colorarray information
7505 
7506     Level: developer
7507 
7508 .seealso: MatGetRowIJ(), MatGetColumnIJ()
7509 
7510 @*/
7511 PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7512 {
7513   PetscErrorCode ierr;
7514 
7515   PetscFunctionBegin;
7516   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7517   PetscValidType(mat,1);
7518   PetscValidIntPointer(colorarray,4);
7519   PetscValidPointer(iscoloring,5);
7520   MatCheckPreallocated(mat,1);
7521 
7522   if (!mat->ops->coloringpatch) {
7523     ierr = ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);CHKERRQ(ierr);
7524   } else {
7525     ierr = (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);CHKERRQ(ierr);
7526   }
7527   PetscFunctionReturn(0);
7528 }
7529 
7530 
7531 /*@
7532    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7533 
7534    Logically Collective on Mat
7535 
7536    Input Parameter:
7537 .  mat - the factored matrix to be reset
7538 
7539    Notes:
7540    This routine should be used only with factored matrices formed by in-place
7541    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7542    format).  This option can save memory, for example, when solving nonlinear
7543    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7544    ILU(0) preconditioner.
7545 
7546    Note that one can specify in-place ILU(0) factorization by calling
7547 .vb
7548      PCType(pc,PCILU);
7549      PCFactorSeUseInPlace(pc);
7550 .ve
7551    or by using the options -pc_type ilu -pc_factor_in_place
7552 
7553    In-place factorization ILU(0) can also be used as a local
7554    solver for the blocks within the block Jacobi or additive Schwarz
7555    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7556    for details on setting local solver options.
7557 
7558    Most users should employ the simplified KSP interface for linear solvers
7559    instead of working directly with matrix algebra routines such as this.
7560    See, e.g., KSPCreate().
7561 
7562    Level: developer
7563 
7564 .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7565 
7566 @*/
7567 PetscErrorCode MatSetUnfactored(Mat mat)
7568 {
7569   PetscErrorCode ierr;
7570 
7571   PetscFunctionBegin;
7572   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7573   PetscValidType(mat,1);
7574   MatCheckPreallocated(mat,1);
7575   mat->factortype = MAT_FACTOR_NONE;
7576   if (!mat->ops->setunfactored) PetscFunctionReturn(0);
7577   ierr = (*mat->ops->setunfactored)(mat);CHKERRQ(ierr);
7578   PetscFunctionReturn(0);
7579 }
7580 
7581 /*MC
7582     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7583 
7584     Synopsis:
7585     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7586 
7587     Not collective
7588 
7589     Input Parameter:
7590 .   x - matrix
7591 
7592     Output Parameters:
7593 +   xx_v - the Fortran90 pointer to the array
7594 -   ierr - error code
7595 
7596     Example of Usage:
7597 .vb
7598       PetscScalar, pointer xx_v(:,:)
7599       ....
7600       call MatDenseGetArrayF90(x,xx_v,ierr)
7601       a = xx_v(3)
7602       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7603 .ve
7604 
7605     Level: advanced
7606 
7607 .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7608 
7609 M*/
7610 
7611 /*MC
7612     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7613     accessed with MatDenseGetArrayF90().
7614 
7615     Synopsis:
7616     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7617 
7618     Not collective
7619 
7620     Input Parameters:
7621 +   x - matrix
7622 -   xx_v - the Fortran90 pointer to the array
7623 
7624     Output Parameter:
7625 .   ierr - error code
7626 
7627     Example of Usage:
7628 .vb
7629        PetscScalar, pointer xx_v(:,:)
7630        ....
7631        call MatDenseGetArrayF90(x,xx_v,ierr)
7632        a = xx_v(3)
7633        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7634 .ve
7635 
7636     Level: advanced
7637 
7638 .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7639 
7640 M*/
7641 
7642 
7643 /*MC
7644     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7645 
7646     Synopsis:
7647     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7648 
7649     Not collective
7650 
7651     Input Parameter:
7652 .   x - matrix
7653 
7654     Output Parameters:
7655 +   xx_v - the Fortran90 pointer to the array
7656 -   ierr - error code
7657 
7658     Example of Usage:
7659 .vb
7660       PetscScalar, pointer xx_v(:)
7661       ....
7662       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7663       a = xx_v(3)
7664       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7665 .ve
7666 
7667     Level: advanced
7668 
7669 .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7670 
7671 M*/
7672 
7673 /*MC
7674     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7675     accessed with MatSeqAIJGetArrayF90().
7676 
7677     Synopsis:
7678     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7679 
7680     Not collective
7681 
7682     Input Parameters:
7683 +   x - matrix
7684 -   xx_v - the Fortran90 pointer to the array
7685 
7686     Output Parameter:
7687 .   ierr - error code
7688 
7689     Example of Usage:
7690 .vb
7691        PetscScalar, pointer xx_v(:)
7692        ....
7693        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7694        a = xx_v(3)
7695        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7696 .ve
7697 
7698     Level: advanced
7699 
7700 .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7701 
7702 M*/
7703 
7704 
7705 /*@
7706     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7707                       as the original matrix.
7708 
7709     Collective on Mat
7710 
7711     Input Parameters:
7712 +   mat - the original matrix
7713 .   isrow - parallel IS containing the rows this processor should obtain
7714 .   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.
7715 -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7716 
7717     Output Parameter:
7718 .   newmat - the new submatrix, of the same type as the old
7719 
7720     Level: advanced
7721 
7722     Notes:
7723     The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7724 
7725     Some matrix types place restrictions on the row and column indices, such
7726     as that they be sorted or that they be equal to each other.
7727 
7728     The index sets may not have duplicate entries.
7729 
7730       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7731    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7732    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7733    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7734    you are finished using it.
7735 
7736     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7737     the input matrix.
7738 
7739     If iscol is NULL then all columns are obtained (not supported in Fortran).
7740 
7741    Example usage:
7742    Consider the following 8x8 matrix with 34 non-zero values, that is
7743    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7744    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7745    as follows:
7746 
7747 .vb
7748             1  2  0  |  0  3  0  |  0  4
7749     Proc0   0  5  6  |  7  0  0  |  8  0
7750             9  0 10  | 11  0  0  | 12  0
7751     -------------------------------------
7752            13  0 14  | 15 16 17  |  0  0
7753     Proc1   0 18  0  | 19 20 21  |  0  0
7754             0  0  0  | 22 23  0  | 24  0
7755     -------------------------------------
7756     Proc2  25 26 27  |  0  0 28  | 29  0
7757            30  0  0  | 31 32 33  |  0 34
7758 .ve
7759 
7760     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is
7761 
7762 .vb
7763             2  0  |  0  3  0  |  0
7764     Proc0   5  6  |  7  0  0  |  8
7765     -------------------------------
7766     Proc1  18  0  | 19 20 21  |  0
7767     -------------------------------
7768     Proc2  26 27  |  0  0 28  | 29
7769             0  0  | 31 32 33  |  0
7770 .ve
7771 
7772 
7773 .seealso: MatCreateSubMatrices()
7774 @*/
7775 PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7776 {
7777   PetscErrorCode ierr;
7778   PetscMPIInt    size;
7779   Mat            *local;
7780   IS             iscoltmp;
7781 
7782   PetscFunctionBegin;
7783   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7784   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
7785   if (iscol) PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
7786   PetscValidPointer(newmat,5);
7787   if (cll == MAT_REUSE_MATRIX) PetscValidHeaderSpecific(*newmat,MAT_CLASSID,5);
7788   PetscValidType(mat,1);
7789   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7790   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
7791 
7792   MatCheckPreallocated(mat,1);
7793   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
7794 
7795   if (!iscol || isrow == iscol) {
7796     PetscBool   stride;
7797     PetscMPIInt grabentirematrix = 0,grab;
7798     ierr = PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);CHKERRQ(ierr);
7799     if (stride) {
7800       PetscInt first,step,n,rstart,rend;
7801       ierr = ISStrideGetInfo(isrow,&first,&step);CHKERRQ(ierr);
7802       if (step == 1) {
7803         ierr = MatGetOwnershipRange(mat,&rstart,&rend);CHKERRQ(ierr);
7804         if (rstart == first) {
7805           ierr = ISGetLocalSize(isrow,&n);CHKERRQ(ierr);
7806           if (n == rend-rstart) {
7807             grabentirematrix = 1;
7808           }
7809         }
7810       }
7811     }
7812     ierr = MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
7813     if (grab) {
7814       ierr = PetscInfo(mat,"Getting entire matrix as submatrix\n");CHKERRQ(ierr);
7815       if (cll == MAT_INITIAL_MATRIX) {
7816         *newmat = mat;
7817         ierr    = PetscObjectReference((PetscObject)mat);CHKERRQ(ierr);
7818       }
7819       PetscFunctionReturn(0);
7820     }
7821   }
7822 
7823   if (!iscol) {
7824     ierr = ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);CHKERRQ(ierr);
7825   } else {
7826     iscoltmp = iscol;
7827   }
7828 
7829   /* if original matrix is on just one processor then use submatrix generated */
7830   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7831     ierr = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);CHKERRQ(ierr);
7832     goto setproperties;
7833   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7834     ierr    = MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);CHKERRQ(ierr);
7835     *newmat = *local;
7836     ierr    = PetscFree(local);CHKERRQ(ierr);
7837     goto setproperties;
7838   } else if (!mat->ops->createsubmatrix) {
7839     /* Create a new matrix type that implements the operation using the full matrix */
7840     ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7841     switch (cll) {
7842     case MAT_INITIAL_MATRIX:
7843       ierr = MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);CHKERRQ(ierr);
7844       break;
7845     case MAT_REUSE_MATRIX:
7846       ierr = MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);CHKERRQ(ierr);
7847       break;
7848     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7849     }
7850     ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7851     goto setproperties;
7852   }
7853 
7854   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7855   ierr = PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7856   ierr = (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);CHKERRQ(ierr);
7857   ierr = PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);CHKERRQ(ierr);
7858 
7859   /* Propagate symmetry information for diagonal blocks */
7860 setproperties:
7861   if (isrow == iscoltmp) {
7862     if (mat->symmetric_set && mat->symmetric) {
7863       ierr = MatSetOption(*newmat,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
7864     }
7865     if (mat->structurally_symmetric_set && mat->structurally_symmetric) {
7866       ierr = MatSetOption(*newmat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
7867     }
7868     if (mat->hermitian_set && mat->hermitian) {
7869       ierr = MatSetOption(*newmat,MAT_HERMITIAN,PETSC_TRUE);CHKERRQ(ierr);
7870     }
7871     if (mat->spd_set && mat->spd) {
7872       ierr = MatSetOption(*newmat,MAT_SPD,PETSC_TRUE);CHKERRQ(ierr);
7873     }
7874   }
7875 
7876   if (!iscol) {ierr = ISDestroy(&iscoltmp);CHKERRQ(ierr);}
7877   if (*newmat && cll == MAT_INITIAL_MATRIX) {ierr = PetscObjectStateIncrease((PetscObject)*newmat);CHKERRQ(ierr);}
7878   PetscFunctionReturn(0);
7879 }
7880 
7881 /*@
7882    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7883    used during the assembly process to store values that belong to
7884    other processors.
7885 
7886    Not Collective
7887 
7888    Input Parameters:
7889 +  mat   - the matrix
7890 .  size  - the initial size of the stash.
7891 -  bsize - the initial size of the block-stash(if used).
7892 
7893    Options Database Keys:
7894 +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7895 -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>
7896 
7897    Level: intermediate
7898 
7899    Notes:
7900      The block-stash is used for values set with MatSetValuesBlocked() while
7901      the stash is used for values set with MatSetValues()
7902 
7903      Run with the option -info and look for output of the form
7904      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7905      to determine the appropriate value, MM, to use for size and
7906      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7907      to determine the value, BMM to use for bsize
7908 
7909 
7910 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
7911 
7912 @*/
7913 PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7914 {
7915   PetscErrorCode ierr;
7916 
7917   PetscFunctionBegin;
7918   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
7919   PetscValidType(mat,1);
7920   ierr = MatStashSetInitialSize_Private(&mat->stash,size);CHKERRQ(ierr);
7921   ierr = MatStashSetInitialSize_Private(&mat->bstash,bsize);CHKERRQ(ierr);
7922   PetscFunctionReturn(0);
7923 }
7924 
7925 /*@
7926    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7927      the matrix
7928 
7929    Neighbor-wise Collective on Mat
7930 
7931    Input Parameters:
7932 +  mat   - the matrix
7933 .  x,y - the vectors
7934 -  w - where the result is stored
7935 
7936    Level: intermediate
7937 
7938    Notes:
7939     w may be the same vector as y.
7940 
7941     This allows one to use either the restriction or interpolation (its transpose)
7942     matrix to do the interpolation
7943 
7944 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
7945 
7946 @*/
7947 PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
7948 {
7949   PetscErrorCode ierr;
7950   PetscInt       M,N,Ny;
7951 
7952   PetscFunctionBegin;
7953   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
7954   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
7955   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
7956   PetscValidHeaderSpecific(w,VEC_CLASSID,4);
7957   PetscValidType(A,1);
7958   MatCheckPreallocated(A,1);
7959   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
7960   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
7961   if (M == Ny) {
7962     ierr = MatMultAdd(A,x,y,w);CHKERRQ(ierr);
7963   } else {
7964     ierr = MatMultTransposeAdd(A,x,y,w);CHKERRQ(ierr);
7965   }
7966   PetscFunctionReturn(0);
7967 }
7968 
7969 /*@
7970    MatInterpolate - y = A*x or A'*x depending on the shape of
7971      the matrix
7972 
7973    Neighbor-wise Collective on Mat
7974 
7975    Input Parameters:
7976 +  mat   - the matrix
7977 -  x,y - the vectors
7978 
7979    Level: intermediate
7980 
7981    Notes:
7982     This allows one to use either the restriction or interpolation (its transpose)
7983     matrix to do the interpolation
7984 
7985 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
7986 
7987 @*/
7988 PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
7989 {
7990   PetscErrorCode ierr;
7991   PetscInt       M,N,Ny;
7992 
7993   PetscFunctionBegin;
7994   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
7995   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
7996   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
7997   PetscValidType(A,1);
7998   MatCheckPreallocated(A,1);
7999   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8000   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8001   if (M == Ny) {
8002     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8003   } else {
8004     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8005   }
8006   PetscFunctionReturn(0);
8007 }
8008 
8009 /*@
8010    MatRestrict - y = A*x or A'*x
8011 
8012    Neighbor-wise Collective on Mat
8013 
8014    Input Parameters:
8015 +  mat   - the matrix
8016 -  x,y - the vectors
8017 
8018    Level: intermediate
8019 
8020    Notes:
8021     This allows one to use either the restriction or interpolation (its transpose)
8022     matrix to do the restriction
8023 
8024 .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8025 
8026 @*/
8027 PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8028 {
8029   PetscErrorCode ierr;
8030   PetscInt       M,N,Ny;
8031 
8032   PetscFunctionBegin;
8033   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8034   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
8035   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
8036   PetscValidType(A,1);
8037   MatCheckPreallocated(A,1);
8038 
8039   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
8040   ierr = VecGetSize(y,&Ny);CHKERRQ(ierr);
8041   if (M == Ny) {
8042     ierr = MatMult(A,x,y);CHKERRQ(ierr);
8043   } else {
8044     ierr = MatMultTranspose(A,x,y);CHKERRQ(ierr);
8045   }
8046   PetscFunctionReturn(0);
8047 }
8048 
8049 /*@
8050    MatGetNullSpace - retrieves the null space of a matrix.
8051 
8052    Logically Collective on Mat
8053 
8054    Input Parameters:
8055 +  mat - the matrix
8056 -  nullsp - the null space object
8057 
8058    Level: developer
8059 
8060 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8061 @*/
8062 PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8063 {
8064   PetscFunctionBegin;
8065   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8066   PetscValidPointer(nullsp,2);
8067   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8068   PetscFunctionReturn(0);
8069 }
8070 
8071 /*@
8072    MatSetNullSpace - attaches a null space to a matrix.
8073 
8074    Logically Collective on Mat
8075 
8076    Input Parameters:
8077 +  mat - the matrix
8078 -  nullsp - the null space object
8079 
8080    Level: advanced
8081 
8082    Notes:
8083       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8084 
8085       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8086       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8087 
8088       You can remove the null space by calling this routine with an nullsp of NULL
8089 
8090 
8091       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8092    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).
8093    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
8094    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
8095    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).
8096 
8097       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8098 
8099     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
8100     routine also automatically calls MatSetTransposeNullSpace().
8101 
8102 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8103 @*/
8104 PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8105 {
8106   PetscErrorCode ierr;
8107 
8108   PetscFunctionBegin;
8109   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8110   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8111   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8112   ierr = MatNullSpaceDestroy(&mat->nullsp);CHKERRQ(ierr);
8113   mat->nullsp = nullsp;
8114   if (mat->symmetric_set && mat->symmetric) {
8115     ierr = MatSetTransposeNullSpace(mat,nullsp);CHKERRQ(ierr);
8116   }
8117   PetscFunctionReturn(0);
8118 }
8119 
8120 /*@
8121    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8122 
8123    Logically Collective on Mat
8124 
8125    Input Parameters:
8126 +  mat - the matrix
8127 -  nullsp - the null space object
8128 
8129    Level: developer
8130 
8131 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8132 @*/
8133 PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8134 {
8135   PetscFunctionBegin;
8136   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8137   PetscValidType(mat,1);
8138   PetscValidPointer(nullsp,2);
8139   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8140   PetscFunctionReturn(0);
8141 }
8142 
8143 /*@
8144    MatSetTransposeNullSpace - attaches a null space to a matrix.
8145 
8146    Logically Collective on Mat
8147 
8148    Input Parameters:
8149 +  mat - the matrix
8150 -  nullsp - the null space object
8151 
8152    Level: advanced
8153 
8154    Notes:
8155       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.
8156       You must also call MatSetNullSpace()
8157 
8158 
8159       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8160    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).
8161    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
8162    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
8163    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).
8164 
8165       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8166 
8167 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8168 @*/
8169 PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8170 {
8171   PetscErrorCode ierr;
8172 
8173   PetscFunctionBegin;
8174   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8175   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8176   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8177   ierr = MatNullSpaceDestroy(&mat->transnullsp);CHKERRQ(ierr);
8178   mat->transnullsp = nullsp;
8179   PetscFunctionReturn(0);
8180 }
8181 
8182 /*@
8183    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8184         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8185 
8186    Logically Collective on Mat
8187 
8188    Input Parameters:
8189 +  mat - the matrix
8190 -  nullsp - the null space object
8191 
8192    Level: advanced
8193 
8194    Notes:
8195       Overwrites any previous near null space that may have been attached
8196 
8197       You can remove the null space by calling this routine with an nullsp of NULL
8198 
8199 .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8200 @*/
8201 PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8202 {
8203   PetscErrorCode ierr;
8204 
8205   PetscFunctionBegin;
8206   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8207   PetscValidType(mat,1);
8208   if (nullsp) PetscValidHeaderSpecific(nullsp,MAT_NULLSPACE_CLASSID,2);
8209   MatCheckPreallocated(mat,1);
8210   if (nullsp) {ierr = PetscObjectReference((PetscObject)nullsp);CHKERRQ(ierr);}
8211   ierr = MatNullSpaceDestroy(&mat->nearnullsp);CHKERRQ(ierr);
8212   mat->nearnullsp = nullsp;
8213   PetscFunctionReturn(0);
8214 }
8215 
8216 /*@
8217    MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()
8218 
8219    Not Collective
8220 
8221    Input Parameters:
8222 .  mat - the matrix
8223 
8224    Output Parameters:
8225 .  nullsp - the null space object, NULL if not set
8226 
8227    Level: developer
8228 
8229 .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8230 @*/
8231 PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8232 {
8233   PetscFunctionBegin;
8234   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8235   PetscValidType(mat,1);
8236   PetscValidPointer(nullsp,2);
8237   MatCheckPreallocated(mat,1);
8238   *nullsp = mat->nearnullsp;
8239   PetscFunctionReturn(0);
8240 }
8241 
8242 /*@C
8243    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8244 
8245    Collective on Mat
8246 
8247    Input Parameters:
8248 +  mat - the matrix
8249 .  row - row/column permutation
8250 .  fill - expected fill factor >= 1.0
8251 -  level - level of fill, for ICC(k)
8252 
8253    Notes:
8254    Probably really in-place only when level of fill is zero, otherwise allocates
8255    new space to store factored matrix and deletes previous memory.
8256 
8257    Most users should employ the simplified KSP interface for linear solvers
8258    instead of working directly with matrix algebra routines such as this.
8259    See, e.g., KSPCreate().
8260 
8261    Level: developer
8262 
8263 
8264 .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8265 
8266     Developer Note: fortran interface is not autogenerated as the f90
8267     interface defintion cannot be generated correctly [due to MatFactorInfo]
8268 
8269 @*/
8270 PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8271 {
8272   PetscErrorCode ierr;
8273 
8274   PetscFunctionBegin;
8275   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8276   PetscValidType(mat,1);
8277   if (row) PetscValidHeaderSpecific(row,IS_CLASSID,2);
8278   PetscValidPointer(info,3);
8279   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8280   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8281   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8282   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8283   MatCheckPreallocated(mat,1);
8284   ierr = (*mat->ops->iccfactor)(mat,row,info);CHKERRQ(ierr);
8285   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8286   PetscFunctionReturn(0);
8287 }
8288 
8289 /*@
8290    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8291          ghosted ones.
8292 
8293    Not Collective
8294 
8295    Input Parameters:
8296 +  mat - the matrix
8297 -  diag = the diagonal values, including ghost ones
8298 
8299    Level: developer
8300 
8301    Notes:
8302     Works only for MPIAIJ and MPIBAIJ matrices
8303 
8304 .seealso: MatDiagonalScale()
8305 @*/
8306 PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8307 {
8308   PetscErrorCode ierr;
8309   PetscMPIInt    size;
8310 
8311   PetscFunctionBegin;
8312   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8313   PetscValidHeaderSpecific(diag,VEC_CLASSID,2);
8314   PetscValidType(mat,1);
8315 
8316   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8317   ierr = PetscLogEventBegin(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8318   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
8319   if (size == 1) {
8320     PetscInt n,m;
8321     ierr = VecGetSize(diag,&n);CHKERRQ(ierr);
8322     ierr = MatGetSize(mat,0,&m);CHKERRQ(ierr);
8323     if (m == n) {
8324       ierr = MatDiagonalScale(mat,0,diag);CHKERRQ(ierr);
8325     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8326   } else {
8327     ierr = PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));CHKERRQ(ierr);
8328   }
8329   ierr = PetscLogEventEnd(MAT_Scale,mat,0,0,0);CHKERRQ(ierr);
8330   ierr = PetscObjectStateIncrease((PetscObject)mat);CHKERRQ(ierr);
8331   PetscFunctionReturn(0);
8332 }
8333 
8334 /*@
8335    MatGetInertia - Gets the inertia from a factored matrix
8336 
8337    Collective on Mat
8338 
8339    Input Parameter:
8340 .  mat - the matrix
8341 
8342    Output Parameters:
8343 +   nneg - number of negative eigenvalues
8344 .   nzero - number of zero eigenvalues
8345 -   npos - number of positive eigenvalues
8346 
8347    Level: advanced
8348 
8349    Notes:
8350     Matrix must have been factored by MatCholeskyFactor()
8351 
8352 
8353 @*/
8354 PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8355 {
8356   PetscErrorCode ierr;
8357 
8358   PetscFunctionBegin;
8359   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8360   PetscValidType(mat,1);
8361   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8362   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8363   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8364   ierr = (*mat->ops->getinertia)(mat,nneg,nzero,npos);CHKERRQ(ierr);
8365   PetscFunctionReturn(0);
8366 }
8367 
8368 /* ----------------------------------------------------------------*/
8369 /*@C
8370    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8371 
8372    Neighbor-wise Collective on Mats
8373 
8374    Input Parameters:
8375 +  mat - the factored matrix
8376 -  b - the right-hand-side vectors
8377 
8378    Output Parameter:
8379 .  x - the result vectors
8380 
8381    Notes:
8382    The vectors b and x cannot be the same.  I.e., one cannot
8383    call MatSolves(A,x,x).
8384 
8385    Notes:
8386    Most users should employ the simplified KSP interface for linear solvers
8387    instead of working directly with matrix algebra routines such as this.
8388    See, e.g., KSPCreate().
8389 
8390    Level: developer
8391 
8392 .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8393 @*/
8394 PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8395 {
8396   PetscErrorCode ierr;
8397 
8398   PetscFunctionBegin;
8399   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8400   PetscValidType(mat,1);
8401   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8402   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8403   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(0);
8404 
8405   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8406   MatCheckPreallocated(mat,1);
8407   ierr = PetscLogEventBegin(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8408   ierr = (*mat->ops->solves)(mat,b,x);CHKERRQ(ierr);
8409   ierr = PetscLogEventEnd(MAT_Solves,mat,0,0,0);CHKERRQ(ierr);
8410   PetscFunctionReturn(0);
8411 }
8412 
8413 /*@
8414    MatIsSymmetric - Test whether a matrix is symmetric
8415 
8416    Collective on Mat
8417 
8418    Input Parameter:
8419 +  A - the matrix to test
8420 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8421 
8422    Output Parameters:
8423 .  flg - the result
8424 
8425    Notes:
8426     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8427 
8428    Level: intermediate
8429 
8430 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8431 @*/
8432 PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8433 {
8434   PetscErrorCode ierr;
8435 
8436   PetscFunctionBegin;
8437   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8438   PetscValidBoolPointer(flg,2);
8439 
8440   if (!A->symmetric_set) {
8441     if (!A->ops->issymmetric) {
8442       MatType mattype;
8443       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8444       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8445     }
8446     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8447     if (!tol) {
8448       A->symmetric_set = PETSC_TRUE;
8449       A->symmetric     = *flg;
8450       if (A->symmetric) {
8451         A->structurally_symmetric_set = PETSC_TRUE;
8452         A->structurally_symmetric     = PETSC_TRUE;
8453       }
8454     }
8455   } else if (A->symmetric) {
8456     *flg = PETSC_TRUE;
8457   } else if (!tol) {
8458     *flg = PETSC_FALSE;
8459   } else {
8460     if (!A->ops->issymmetric) {
8461       MatType mattype;
8462       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8463       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8464     }
8465     ierr = (*A->ops->issymmetric)(A,tol,flg);CHKERRQ(ierr);
8466   }
8467   PetscFunctionReturn(0);
8468 }
8469 
8470 /*@
8471    MatIsHermitian - Test whether a matrix is Hermitian
8472 
8473    Collective on Mat
8474 
8475    Input Parameter:
8476 +  A - the matrix to test
8477 -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8478 
8479    Output Parameters:
8480 .  flg - the result
8481 
8482    Level: intermediate
8483 
8484 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8485           MatIsSymmetricKnown(), MatIsSymmetric()
8486 @*/
8487 PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8488 {
8489   PetscErrorCode ierr;
8490 
8491   PetscFunctionBegin;
8492   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8493   PetscValidBoolPointer(flg,2);
8494 
8495   if (!A->hermitian_set) {
8496     if (!A->ops->ishermitian) {
8497       MatType mattype;
8498       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8499       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8500     }
8501     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8502     if (!tol) {
8503       A->hermitian_set = PETSC_TRUE;
8504       A->hermitian     = *flg;
8505       if (A->hermitian) {
8506         A->structurally_symmetric_set = PETSC_TRUE;
8507         A->structurally_symmetric     = PETSC_TRUE;
8508       }
8509     }
8510   } else if (A->hermitian) {
8511     *flg = PETSC_TRUE;
8512   } else if (!tol) {
8513     *flg = PETSC_FALSE;
8514   } else {
8515     if (!A->ops->ishermitian) {
8516       MatType mattype;
8517       ierr = MatGetType(A,&mattype);CHKERRQ(ierr);
8518       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8519     }
8520     ierr = (*A->ops->ishermitian)(A,tol,flg);CHKERRQ(ierr);
8521   }
8522   PetscFunctionReturn(0);
8523 }
8524 
8525 /*@
8526    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8527 
8528    Not Collective
8529 
8530    Input Parameter:
8531 .  A - the matrix to check
8532 
8533    Output Parameters:
8534 +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8535 -  flg - the result
8536 
8537    Level: advanced
8538 
8539    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8540          if you want it explicitly checked
8541 
8542 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8543 @*/
8544 PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8545 {
8546   PetscFunctionBegin;
8547   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8548   PetscValidPointer(set,2);
8549   PetscValidBoolPointer(flg,3);
8550   if (A->symmetric_set) {
8551     *set = PETSC_TRUE;
8552     *flg = A->symmetric;
8553   } else {
8554     *set = PETSC_FALSE;
8555   }
8556   PetscFunctionReturn(0);
8557 }
8558 
8559 /*@
8560    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8561 
8562    Not Collective
8563 
8564    Input Parameter:
8565 .  A - the matrix to check
8566 
8567    Output Parameters:
8568 +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8569 -  flg - the result
8570 
8571    Level: advanced
8572 
8573    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8574          if you want it explicitly checked
8575 
8576 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8577 @*/
8578 PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8579 {
8580   PetscFunctionBegin;
8581   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8582   PetscValidPointer(set,2);
8583   PetscValidBoolPointer(flg,3);
8584   if (A->hermitian_set) {
8585     *set = PETSC_TRUE;
8586     *flg = A->hermitian;
8587   } else {
8588     *set = PETSC_FALSE;
8589   }
8590   PetscFunctionReturn(0);
8591 }
8592 
8593 /*@
8594    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8595 
8596    Collective on Mat
8597 
8598    Input Parameter:
8599 .  A - the matrix to test
8600 
8601    Output Parameters:
8602 .  flg - the result
8603 
8604    Level: intermediate
8605 
8606 .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8607 @*/
8608 PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8609 {
8610   PetscErrorCode ierr;
8611 
8612   PetscFunctionBegin;
8613   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
8614   PetscValidBoolPointer(flg,2);
8615   if (!A->structurally_symmetric_set) {
8616     if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8617     ierr = (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);CHKERRQ(ierr);
8618 
8619     A->structurally_symmetric_set = PETSC_TRUE;
8620   }
8621   *flg = A->structurally_symmetric;
8622   PetscFunctionReturn(0);
8623 }
8624 
8625 /*@
8626    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8627        to be communicated to other processors during the MatAssemblyBegin/End() process
8628 
8629     Not collective
8630 
8631    Input Parameter:
8632 .   vec - the vector
8633 
8634    Output Parameters:
8635 +   nstash   - the size of the stash
8636 .   reallocs - the number of additional mallocs incurred.
8637 .   bnstash   - the size of the block stash
8638 -   breallocs - the number of additional mallocs incurred.in the block stash
8639 
8640    Level: advanced
8641 
8642 .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8643 
8644 @*/
8645 PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8646 {
8647   PetscErrorCode ierr;
8648 
8649   PetscFunctionBegin;
8650   ierr = MatStashGetInfo_Private(&mat->stash,nstash,reallocs);CHKERRQ(ierr);
8651   ierr = MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);CHKERRQ(ierr);
8652   PetscFunctionReturn(0);
8653 }
8654 
8655 /*@C
8656    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8657      parallel layout
8658 
8659    Collective on Mat
8660 
8661    Input Parameter:
8662 .  mat - the matrix
8663 
8664    Output Parameter:
8665 +   right - (optional) vector that the matrix can be multiplied against
8666 -   left - (optional) vector that the matrix vector product can be stored in
8667 
8668    Notes:
8669     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().
8670 
8671   Notes:
8672     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8673 
8674   Level: advanced
8675 
8676 .seealso: MatCreate(), VecDestroy()
8677 @*/
8678 PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8679 {
8680   PetscErrorCode ierr;
8681 
8682   PetscFunctionBegin;
8683   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8684   PetscValidType(mat,1);
8685   if (mat->ops->getvecs) {
8686     ierr = (*mat->ops->getvecs)(mat,right,left);CHKERRQ(ierr);
8687   } else {
8688     PetscInt rbs,cbs;
8689     ierr = MatGetBlockSizes(mat,&rbs,&cbs);CHKERRQ(ierr);
8690     if (right) {
8691       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8692       ierr = VecCreate(PetscObjectComm((PetscObject)mat),right);CHKERRQ(ierr);
8693       ierr = VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8694       ierr = VecSetBlockSize(*right,cbs);CHKERRQ(ierr);
8695       ierr = VecSetType(*right,mat->defaultvectype);CHKERRQ(ierr);
8696       ierr = PetscLayoutReference(mat->cmap,&(*right)->map);CHKERRQ(ierr);
8697     }
8698     if (left) {
8699       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8700       ierr = VecCreate(PetscObjectComm((PetscObject)mat),left);CHKERRQ(ierr);
8701       ierr = VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);CHKERRQ(ierr);
8702       ierr = VecSetBlockSize(*left,rbs);CHKERRQ(ierr);
8703       ierr = VecSetType(*left,mat->defaultvectype);CHKERRQ(ierr);
8704       ierr = PetscLayoutReference(mat->rmap,&(*left)->map);CHKERRQ(ierr);
8705     }
8706   }
8707   PetscFunctionReturn(0);
8708 }
8709 
8710 /*@C
8711    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8712      with default values.
8713 
8714    Not Collective
8715 
8716    Input Parameters:
8717 .    info - the MatFactorInfo data structure
8718 
8719 
8720    Notes:
8721     The solvers are generally used through the KSP and PC objects, for example
8722           PCLU, PCILU, PCCHOLESKY, PCICC
8723 
8724    Level: developer
8725 
8726 .seealso: MatFactorInfo
8727 
8728     Developer Note: fortran interface is not autogenerated as the f90
8729     interface defintion cannot be generated correctly [due to MatFactorInfo]
8730 
8731 @*/
8732 
8733 PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8734 {
8735   PetscErrorCode ierr;
8736 
8737   PetscFunctionBegin;
8738   ierr = PetscMemzero(info,sizeof(MatFactorInfo));CHKERRQ(ierr);
8739   PetscFunctionReturn(0);
8740 }
8741 
8742 /*@
8743    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
8744 
8745    Collective on Mat
8746 
8747    Input Parameters:
8748 +  mat - the factored matrix
8749 -  is - the index set defining the Schur indices (0-based)
8750 
8751    Notes:
8752     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
8753 
8754    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
8755 
8756    Level: developer
8757 
8758 .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8759           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
8760 
8761 @*/
8762 PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8763 {
8764   PetscErrorCode ierr,(*f)(Mat,IS);
8765 
8766   PetscFunctionBegin;
8767   PetscValidType(mat,1);
8768   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
8769   PetscValidType(is,2);
8770   PetscValidHeaderSpecific(is,IS_CLASSID,2);
8771   PetscCheckSameComm(mat,1,is,2);
8772   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8773   ierr = PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);CHKERRQ(ierr);
8774   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");
8775   if (mat->schur) {
8776     ierr = MatDestroy(&mat->schur);CHKERRQ(ierr);
8777   }
8778   ierr = (*f)(mat,is);CHKERRQ(ierr);
8779   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8780   ierr = MatFactorSetUpInPlaceSchur_Private(mat);CHKERRQ(ierr);
8781   PetscFunctionReturn(0);
8782 }
8783 
8784 /*@
8785   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
8786 
8787    Logically Collective on Mat
8788 
8789    Input Parameters:
8790 +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8791 .  S - location where to return the Schur complement, can be NULL
8792 -  status - the status of the Schur complement matrix, can be NULL
8793 
8794    Notes:
8795    You must call MatFactorSetSchurIS() before calling this routine.
8796 
8797    The routine provides a copy of the Schur matrix stored within the solver data structures.
8798    The caller must destroy the object when it is no longer needed.
8799    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
8800 
8801    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)
8802 
8803    Developer Notes:
8804     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8805    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
8806 
8807    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8808 
8809    Level: advanced
8810 
8811    References:
8812 
8813 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8814 @*/
8815 PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8816 {
8817   PetscErrorCode ierr;
8818 
8819   PetscFunctionBegin;
8820   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8821   if (S) PetscValidPointer(S,2);
8822   if (status) PetscValidPointer(status,3);
8823   if (S) {
8824     PetscErrorCode (*f)(Mat,Mat*);
8825 
8826     ierr = PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);CHKERRQ(ierr);
8827     if (f) {
8828       ierr = (*f)(F,S);CHKERRQ(ierr);
8829     } else {
8830       ierr = MatDuplicate(F->schur,MAT_COPY_VALUES,S);CHKERRQ(ierr);
8831     }
8832   }
8833   if (status) *status = F->schur_status;
8834   PetscFunctionReturn(0);
8835 }
8836 
8837 /*@
8838   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
8839 
8840    Logically Collective on Mat
8841 
8842    Input Parameters:
8843 +  F - the factored matrix obtained by calling MatGetFactor()
8844 .  *S - location where to return the Schur complement, can be NULL
8845 -  status - the status of the Schur complement matrix, can be NULL
8846 
8847    Notes:
8848    You must call MatFactorSetSchurIS() before calling this routine.
8849 
8850    Schur complement mode is currently implemented for sequential matrices.
8851    The routine returns a the Schur Complement stored within the data strutures of the solver.
8852    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8853    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
8854 
8855    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
8856 
8857    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8858 
8859    Level: advanced
8860 
8861    References:
8862 
8863 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8864 @*/
8865 PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8866 {
8867   PetscFunctionBegin;
8868   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8869   if (S) PetscValidPointer(S,2);
8870   if (status) PetscValidPointer(status,3);
8871   if (S) *S = F->schur;
8872   if (status) *status = F->schur_status;
8873   PetscFunctionReturn(0);
8874 }
8875 
8876 /*@
8877   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
8878 
8879    Logically Collective on Mat
8880 
8881    Input Parameters:
8882 +  F - the factored matrix obtained by calling MatGetFactor()
8883 .  *S - location where the Schur complement is stored
8884 -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)
8885 
8886    Notes:
8887 
8888    Level: advanced
8889 
8890    References:
8891 
8892 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8893 @*/
8894 PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8895 {
8896   PetscErrorCode ierr;
8897 
8898   PetscFunctionBegin;
8899   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8900   if (S) {
8901     PetscValidHeaderSpecific(*S,MAT_CLASSID,2);
8902     *S = NULL;
8903   }
8904   F->schur_status = status;
8905   ierr = MatFactorUpdateSchurStatus_Private(F);CHKERRQ(ierr);
8906   PetscFunctionReturn(0);
8907 }
8908 
8909 /*@
8910   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
8911 
8912    Logically Collective on Mat
8913 
8914    Input Parameters:
8915 +  F - the factored matrix obtained by calling MatGetFactor()
8916 .  rhs - location where the right hand side of the Schur complement system is stored
8917 -  sol - location where the solution of the Schur complement system has to be returned
8918 
8919    Notes:
8920    The sizes of the vectors should match the size of the Schur complement
8921 
8922    Must be called after MatFactorSetSchurIS()
8923 
8924    Level: advanced
8925 
8926    References:
8927 
8928 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
8929 @*/
8930 PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
8931 {
8932   PetscErrorCode ierr;
8933 
8934   PetscFunctionBegin;
8935   PetscValidType(F,1);
8936   PetscValidType(rhs,2);
8937   PetscValidType(sol,3);
8938   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8939   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
8940   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
8941   PetscCheckSameComm(F,1,rhs,2);
8942   PetscCheckSameComm(F,1,sol,3);
8943   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
8944   switch (F->schur_status) {
8945   case MAT_FACTOR_SCHUR_FACTORED:
8946     ierr = MatSolveTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
8947     break;
8948   case MAT_FACTOR_SCHUR_INVERTED:
8949     ierr = MatMultTranspose(F->schur,rhs,sol);CHKERRQ(ierr);
8950     break;
8951   default:
8952     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
8953     break;
8954   }
8955   PetscFunctionReturn(0);
8956 }
8957 
8958 /*@
8959   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
8960 
8961    Logically Collective on Mat
8962 
8963    Input Parameters:
8964 +  F - the factored matrix obtained by calling MatGetFactor()
8965 .  rhs - location where the right hand side of the Schur complement system is stored
8966 -  sol - location where the solution of the Schur complement system has to be returned
8967 
8968    Notes:
8969    The sizes of the vectors should match the size of the Schur complement
8970 
8971    Must be called after MatFactorSetSchurIS()
8972 
8973    Level: advanced
8974 
8975    References:
8976 
8977 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
8978 @*/
8979 PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
8980 {
8981   PetscErrorCode ierr;
8982 
8983   PetscFunctionBegin;
8984   PetscValidType(F,1);
8985   PetscValidType(rhs,2);
8986   PetscValidType(sol,3);
8987   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
8988   PetscValidHeaderSpecific(rhs,VEC_CLASSID,2);
8989   PetscValidHeaderSpecific(sol,VEC_CLASSID,3);
8990   PetscCheckSameComm(F,1,rhs,2);
8991   PetscCheckSameComm(F,1,sol,3);
8992   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
8993   switch (F->schur_status) {
8994   case MAT_FACTOR_SCHUR_FACTORED:
8995     ierr = MatSolve(F->schur,rhs,sol);CHKERRQ(ierr);
8996     break;
8997   case MAT_FACTOR_SCHUR_INVERTED:
8998     ierr = MatMult(F->schur,rhs,sol);CHKERRQ(ierr);
8999     break;
9000   default:
9001     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9002     break;
9003   }
9004   PetscFunctionReturn(0);
9005 }
9006 
9007 /*@
9008   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9009 
9010    Logically Collective on Mat
9011 
9012    Input Parameters:
9013 .  F - the factored matrix obtained by calling MatGetFactor()
9014 
9015    Notes:
9016     Must be called after MatFactorSetSchurIS().
9017 
9018    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9019 
9020    Level: advanced
9021 
9022    References:
9023 
9024 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9025 @*/
9026 PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9027 {
9028   PetscErrorCode ierr;
9029 
9030   PetscFunctionBegin;
9031   PetscValidType(F,1);
9032   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9033   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(0);
9034   ierr = MatFactorFactorizeSchurComplement(F);CHKERRQ(ierr);
9035   ierr = MatFactorInvertSchurComplement_Private(F);CHKERRQ(ierr);
9036   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9037   PetscFunctionReturn(0);
9038 }
9039 
9040 /*@
9041   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9042 
9043    Logically Collective on Mat
9044 
9045    Input Parameters:
9046 .  F - the factored matrix obtained by calling MatGetFactor()
9047 
9048    Notes:
9049     Must be called after MatFactorSetSchurIS().
9050 
9051    Level: advanced
9052 
9053    References:
9054 
9055 .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9056 @*/
9057 PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9058 {
9059   PetscErrorCode ierr;
9060 
9061   PetscFunctionBegin;
9062   PetscValidType(F,1);
9063   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
9064   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(0);
9065   ierr = MatFactorFactorizeSchurComplement_Private(F);CHKERRQ(ierr);
9066   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9067   PetscFunctionReturn(0);
9068 }
9069 
9070 PetscErrorCode MatPtAP_Basic(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9071 {
9072   Mat            AP;
9073   PetscErrorCode ierr;
9074 
9075   PetscFunctionBegin;
9076   ierr = PetscInfo2(A,"Mat types %s and %s using basic PtAP\n",((PetscObject)A)->type_name,((PetscObject)P)->type_name);CHKERRQ(ierr);
9077   ierr = MatMatMult(A,P,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&AP);CHKERRQ(ierr);
9078   ierr = MatTransposeMatMult(P,AP,scall,fill,C);CHKERRQ(ierr);
9079   ierr = MatDestroy(&AP);CHKERRQ(ierr);
9080   PetscFunctionReturn(0);
9081 }
9082 
9083 /*@
9084    MatPtAP - Creates the matrix product C = P^T * A * P
9085 
9086    Neighbor-wise Collective on Mat
9087 
9088    Input Parameters:
9089 +  A - the matrix
9090 .  P - the projection matrix
9091 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9092 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9093           if the result is a dense matrix this is irrelevent
9094 
9095    Output Parameters:
9096 .  C - the product matrix
9097 
9098    Notes:
9099    C will be created and must be destroyed by the user with MatDestroy().
9100 
9101    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().
9102 
9103    Level: intermediate
9104 
9105 .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9106 @*/
9107 PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9108 {
9109   PetscErrorCode ierr;
9110   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9111   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9112   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9113   PetscBool      sametype;
9114 
9115   PetscFunctionBegin;
9116   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9117   PetscValidType(A,1);
9118   MatCheckPreallocated(A,1);
9119   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9120   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9121   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9122   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
9123   PetscValidType(P,2);
9124   MatCheckPreallocated(P,2);
9125   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9126   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9127 
9128   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);
9129   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);
9130   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9131   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9132 
9133   if (scall == MAT_REUSE_MATRIX) {
9134     PetscValidPointer(*C,5);
9135     PetscValidHeaderSpecific(*C,MAT_CLASSID,5);
9136 
9137     ierr = PetscLogEventBegin(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9138     ierr = PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9139     if ((*C)->ops->ptapnumeric) {
9140       ierr = (*(*C)->ops->ptapnumeric)(A,P,*C);CHKERRQ(ierr);
9141     } else {
9142       ierr = MatPtAP_Basic(A,P,scall,fill,C);
9143     }
9144     ierr = PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9145     ierr = PetscLogEventEnd(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9146     PetscFunctionReturn(0);
9147   }
9148 
9149   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9150   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9151 
9152   fA = A->ops->ptap;
9153   fP = P->ops->ptap;
9154   ierr = PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);CHKERRQ(ierr);
9155   if (fP == fA && sametype) {
9156     ptap = fA;
9157   } else {
9158     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9159     char ptapname[256];
9160     ierr = PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));CHKERRQ(ierr);
9161     ierr = PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));CHKERRQ(ierr);
9162     ierr = PetscStrlcat(ptapname,"_",sizeof(ptapname));CHKERRQ(ierr);
9163     ierr = PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));CHKERRQ(ierr);
9164     ierr = PetscStrlcat(ptapname,"_C",sizeof(ptapname));CHKERRQ(ierr); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9165     ierr = PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);CHKERRQ(ierr);
9166   }
9167 
9168   if (!ptap) ptap = MatPtAP_Basic;
9169   ierr = PetscLogEventBegin(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9170   ierr = (*ptap)(A,P,scall,fill,C);CHKERRQ(ierr);
9171   ierr = PetscLogEventEnd(MAT_PtAP,A,P,0,0);CHKERRQ(ierr);
9172   if (A->symmetric_set && A->symmetric) {
9173     ierr = MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
9174   }
9175   PetscFunctionReturn(0);
9176 }
9177 
9178 /*@
9179    MatPtAPNumeric - Computes the matrix product C = P^T * A * P
9180 
9181    Neighbor-wise Collective on Mat
9182 
9183    Input Parameters:
9184 +  A - the matrix
9185 -  P - the projection matrix
9186 
9187    Output Parameters:
9188 .  C - the product matrix
9189 
9190    Notes:
9191    C must have been created by calling MatPtAPSymbolic and must be destroyed by
9192    the user using MatDeatroy().
9193 
9194    This routine is currently only implemented for pairs of AIJ matrices and classes
9195    which inherit from AIJ.  C will be of type MATAIJ.
9196 
9197    Level: intermediate
9198 
9199 .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9200 @*/
9201 PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9202 {
9203   PetscErrorCode ierr;
9204 
9205   PetscFunctionBegin;
9206   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9207   PetscValidType(A,1);
9208   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9209   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9210   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
9211   PetscValidType(P,2);
9212   MatCheckPreallocated(P,2);
9213   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9214   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9215   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
9216   PetscValidType(C,3);
9217   MatCheckPreallocated(C,3);
9218   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9219   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);
9220   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);
9221   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);
9222   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);
9223   MatCheckPreallocated(A,1);
9224 
9225   if (!C->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You should call MatPtAPSymbolic first");
9226   ierr = PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9227   ierr = (*C->ops->ptapnumeric)(A,P,C);CHKERRQ(ierr);
9228   ierr = PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);CHKERRQ(ierr);
9229   PetscFunctionReturn(0);
9230 }
9231 
9232 /*@
9233    MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P
9234 
9235    Neighbor-wise Collective on Mat
9236 
9237    Input Parameters:
9238 +  A - the matrix
9239 -  P - the projection matrix
9240 
9241    Output Parameters:
9242 .  C - the (i,j) structure of the product matrix
9243 
9244    Notes:
9245    C will be created and must be destroyed by the user with MatDestroy().
9246 
9247    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9248    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
9249    this (i,j) structure by calling MatPtAPNumeric().
9250 
9251    Level: intermediate
9252 
9253 .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
9254 @*/
9255 PetscErrorCode MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
9256 {
9257   PetscErrorCode ierr;
9258 
9259   PetscFunctionBegin;
9260   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9261   PetscValidType(A,1);
9262   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9263   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9264   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9265   PetscValidHeaderSpecific(P,MAT_CLASSID,2);
9266   PetscValidType(P,2);
9267   MatCheckPreallocated(P,2);
9268   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9269   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9270   PetscValidPointer(C,3);
9271 
9272   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);
9273   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);
9274   MatCheckPreallocated(A,1);
9275 
9276   if (!A->ops->ptapsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatType %s",((PetscObject)A)->type_name);
9277   ierr = PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);CHKERRQ(ierr);
9278   ierr = (*A->ops->ptapsymbolic)(A,P,fill,C);CHKERRQ(ierr);
9279   ierr = PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);CHKERRQ(ierr);
9280 
9281   /* ierr = MatSetBlockSize(*C,A->rmap->bs);CHKERRQ(ierr); NO! this is not always true -ma */
9282   PetscFunctionReturn(0);
9283 }
9284 
9285 /*@
9286    MatRARt - Creates the matrix product C = R * A * R^T
9287 
9288    Neighbor-wise Collective on Mat
9289 
9290    Input Parameters:
9291 +  A - the matrix
9292 .  R - the projection matrix
9293 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9294 -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9295           if the result is a dense matrix this is irrelevent
9296 
9297    Output Parameters:
9298 .  C - the product matrix
9299 
9300    Notes:
9301    C will be created and must be destroyed by the user with MatDestroy().
9302 
9303    This routine is currently only implemented for pairs of AIJ matrices and classes
9304    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9305    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9306    We recommend using MatPtAP().
9307 
9308    Level: intermediate
9309 
9310 .seealso: MatRARtSymbolic(), MatRARtNumeric(), MatMatMult(), MatPtAP()
9311 @*/
9312 PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9313 {
9314   PetscErrorCode ierr;
9315 
9316   PetscFunctionBegin;
9317   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9318   PetscValidType(A,1);
9319   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9320   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9321   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9322   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
9323   PetscValidType(R,2);
9324   MatCheckPreallocated(R,2);
9325   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9326   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9327   PetscValidPointer(C,3);
9328   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);
9329 
9330   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9331   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9332   MatCheckPreallocated(A,1);
9333 
9334   if (!A->ops->rart) {
9335     Mat Rt;
9336     ierr = MatTranspose(R,MAT_INITIAL_MATRIX,&Rt);CHKERRQ(ierr);
9337     ierr = MatMatMatMult(R,A,Rt,scall,fill,C);CHKERRQ(ierr);
9338     ierr = MatDestroy(&Rt);CHKERRQ(ierr);
9339     PetscFunctionReturn(0);
9340   }
9341   ierr = PetscLogEventBegin(MAT_RARt,A,R,0,0);CHKERRQ(ierr);
9342   ierr = (*A->ops->rart)(A,R,scall,fill,C);CHKERRQ(ierr);
9343   ierr = PetscLogEventEnd(MAT_RARt,A,R,0,0);CHKERRQ(ierr);
9344   PetscFunctionReturn(0);
9345 }
9346 
9347 /*@
9348    MatRARtNumeric - Computes the matrix product C = R * A * R^T
9349 
9350    Neighbor-wise Collective on Mat
9351 
9352    Input Parameters:
9353 +  A - the matrix
9354 -  R - the projection matrix
9355 
9356    Output Parameters:
9357 .  C - the product matrix
9358 
9359    Notes:
9360    C must have been created by calling MatRARtSymbolic and must be destroyed by
9361    the user using MatDestroy().
9362 
9363    This routine is currently only implemented for pairs of AIJ matrices and classes
9364    which inherit from AIJ.  C will be of type MATAIJ.
9365 
9366    Level: intermediate
9367 
9368 .seealso: MatRARt(), MatRARtSymbolic(), MatMatMultNumeric()
9369 @*/
9370 PetscErrorCode MatRARtNumeric(Mat A,Mat R,Mat C)
9371 {
9372   PetscErrorCode ierr;
9373 
9374   PetscFunctionBegin;
9375   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9376   PetscValidType(A,1);
9377   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9378   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9379   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
9380   PetscValidType(R,2);
9381   MatCheckPreallocated(R,2);
9382   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9383   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9384   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
9385   PetscValidType(C,3);
9386   MatCheckPreallocated(C,3);
9387   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9388   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);
9389   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);
9390   if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
9391   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);
9392   MatCheckPreallocated(A,1);
9393 
9394   ierr = PetscLogEventBegin(MAT_RARtNumeric,A,R,0,0);CHKERRQ(ierr);
9395   ierr = (*A->ops->rartnumeric)(A,R,C);CHKERRQ(ierr);
9396   ierr = PetscLogEventEnd(MAT_RARtNumeric,A,R,0,0);CHKERRQ(ierr);
9397   PetscFunctionReturn(0);
9398 }
9399 
9400 /*@
9401    MatRARtSymbolic - Creates the (i,j) structure of the matrix product C = R * A * R^T
9402 
9403    Neighbor-wise Collective on Mat
9404 
9405    Input Parameters:
9406 +  A - the matrix
9407 -  R - the projection matrix
9408 
9409    Output Parameters:
9410 .  C - the (i,j) structure of the product matrix
9411 
9412    Notes:
9413    C will be created and must be destroyed by the user with MatDestroy().
9414 
9415    This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9416    which inherit from SeqAIJ.  C will be of type MATSEQAIJ.  The product is computed using
9417    this (i,j) structure by calling MatRARtNumeric().
9418 
9419    Level: intermediate
9420 
9421 .seealso: MatRARt(), MatRARtNumeric(), MatMatMultSymbolic()
9422 @*/
9423 PetscErrorCode MatRARtSymbolic(Mat A,Mat R,PetscReal fill,Mat *C)
9424 {
9425   PetscErrorCode ierr;
9426 
9427   PetscFunctionBegin;
9428   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9429   PetscValidType(A,1);
9430   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9431   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9432   if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9433   PetscValidHeaderSpecific(R,MAT_CLASSID,2);
9434   PetscValidType(R,2);
9435   MatCheckPreallocated(R,2);
9436   if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9437   if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9438   PetscValidPointer(C,3);
9439 
9440   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);
9441   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);
9442   MatCheckPreallocated(A,1);
9443   ierr = PetscLogEventBegin(MAT_RARtSymbolic,A,R,0,0);CHKERRQ(ierr);
9444   ierr = (*A->ops->rartsymbolic)(A,R,fill,C);CHKERRQ(ierr);
9445   ierr = PetscLogEventEnd(MAT_RARtSymbolic,A,R,0,0);CHKERRQ(ierr);
9446 
9447   ierr = MatSetBlockSizes(*C,PetscAbs(R->rmap->bs),PetscAbs(R->rmap->bs));CHKERRQ(ierr);
9448   PetscFunctionReturn(0);
9449 }
9450 
9451 /*@
9452    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
9453 
9454    Neighbor-wise Collective on Mat
9455 
9456    Input Parameters:
9457 +  A - the left matrix
9458 .  B - the right matrix
9459 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9460 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9461           if the result is a dense matrix this is irrelevent
9462 
9463    Output Parameters:
9464 .  C - the product matrix
9465 
9466    Notes:
9467    Unless scall is MAT_REUSE_MATRIX C will be created.
9468 
9469    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
9470    call to this function with either MAT_INITIAL_MATRIX or MatMatMultSymbolic()
9471 
9472    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9473    actually needed.
9474 
9475    If you have many matrices with the same non-zero structure to multiply, you
9476    should either
9477 $   1) use MAT_REUSE_MATRIX in all calls but the first or
9478 $   2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed
9479    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
9480    with MAT_REUSE_MATRIX, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.
9481 
9482    Level: intermediate
9483 
9484 .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatTransposeMatMult(),  MatMatTransposeMult(), MatPtAP()
9485 @*/
9486 PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9487 {
9488   PetscErrorCode ierr;
9489   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9490   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9491   PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9492   Mat            T;
9493   PetscBool      istrans;
9494 
9495   PetscFunctionBegin;
9496   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9497   PetscValidType(A,1);
9498   MatCheckPreallocated(A,1);
9499   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9500   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9501   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9502   PetscValidType(B,2);
9503   MatCheckPreallocated(B,2);
9504   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9505   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9506   PetscValidPointer(C,3);
9507   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9508   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);
9509   ierr = PetscObjectTypeCompare((PetscObject)A,MATTRANSPOSEMAT,&istrans);CHKERRQ(ierr);
9510   if (istrans) {
9511     ierr = MatTransposeGetMat(A,&T);CHKERRQ(ierr);
9512     ierr = MatTransposeMatMult(T,B,scall,fill,C);CHKERRQ(ierr);
9513     PetscFunctionReturn(0);
9514   } else {
9515     ierr = PetscObjectTypeCompare((PetscObject)B,MATTRANSPOSEMAT,&istrans);CHKERRQ(ierr);
9516     if (istrans) {
9517       ierr = MatTransposeGetMat(B,&T);CHKERRQ(ierr);
9518       ierr = MatMatTransposeMult(A,T,scall,fill,C);CHKERRQ(ierr);
9519       PetscFunctionReturn(0);
9520     }
9521   }
9522   if (scall == MAT_REUSE_MATRIX) {
9523     PetscValidPointer(*C,5);
9524     PetscValidHeaderSpecific(*C,MAT_CLASSID,5);
9525     ierr = PetscLogEventBegin(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9526     ierr = PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
9527     ierr = (*(*C)->ops->matmultnumeric)(A,B,*C);CHKERRQ(ierr);
9528     ierr = PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
9529     ierr = PetscLogEventEnd(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9530     PetscFunctionReturn(0);
9531   }
9532   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9533   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9534 
9535   fA = A->ops->matmult;
9536   fB = B->ops->matmult;
9537   if (fB == fA) {
9538     if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",((PetscObject)B)->type_name);
9539     mult = fB;
9540   } else {
9541     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9542     char multname[256];
9543     ierr = PetscStrncpy(multname,"MatMatMult_",sizeof(multname));CHKERRQ(ierr);
9544     ierr = PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));CHKERRQ(ierr);
9545     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
9546     ierr = PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));CHKERRQ(ierr);
9547     ierr = PetscStrlcat(multname,"_C",sizeof(multname));CHKERRQ(ierr); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9548     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&mult);CHKERRQ(ierr);
9549     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);
9550   }
9551   ierr = PetscLogEventBegin(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9552   ierr = (*mult)(A,B,scall,fill,C);CHKERRQ(ierr);
9553   ierr = PetscLogEventEnd(MAT_MatMult,A,B,0,0);CHKERRQ(ierr);
9554   PetscFunctionReturn(0);
9555 }
9556 
9557 /*@
9558    MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
9559    of the matrix-matrix product C=A*B.  Call this routine before calling MatMatMultNumeric().
9560 
9561    Neighbor-wise Collective on Mat
9562 
9563    Input Parameters:
9564 +  A - the left matrix
9565 .  B - the right matrix
9566 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate,
9567       if C is a dense matrix this is irrelevent
9568 
9569    Output Parameters:
9570 .  C - the product matrix
9571 
9572    Notes:
9573    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9574    actually needed.
9575 
9576    This routine is currently implemented for
9577     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type AIJ
9578     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9579     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9580 
9581    Level: intermediate
9582 
9583    Developers Note: There are ways to estimate the number of nonzeros in the resulting product, see for example, https://arxiv.org/abs/1006.4173
9584      We should incorporate them into PETSc.
9585 
9586 .seealso: MatMatMult(), MatMatMultNumeric()
9587 @*/
9588 PetscErrorCode MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
9589 {
9590   PetscErrorCode ierr;
9591   PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat*);
9592   PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat*);
9593   PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat*)=NULL;
9594 
9595   PetscFunctionBegin;
9596   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9597   PetscValidType(A,1);
9598   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9599   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9600 
9601   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9602   PetscValidType(B,2);
9603   MatCheckPreallocated(B,2);
9604   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9605   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9606   PetscValidPointer(C,3);
9607 
9608   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);
9609   if (fill == PETSC_DEFAULT) fill = 2.0;
9610   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9611   MatCheckPreallocated(A,1);
9612 
9613   Asymbolic = A->ops->matmultsymbolic;
9614   Bsymbolic = B->ops->matmultsymbolic;
9615   if (Asymbolic == Bsymbolic) {
9616     if (!Bsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
9617     symbolic = Bsymbolic;
9618   } else { /* dispatch based on the type of A and B */
9619     char symbolicname[256];
9620     ierr = PetscStrncpy(symbolicname,"MatMatMultSymbolic_",sizeof(symbolicname));CHKERRQ(ierr);
9621     ierr = PetscStrlcat(symbolicname,((PetscObject)A)->type_name,sizeof(symbolicname));CHKERRQ(ierr);
9622     ierr = PetscStrlcat(symbolicname,"_",sizeof(symbolicname));CHKERRQ(ierr);
9623     ierr = PetscStrlcat(symbolicname,((PetscObject)B)->type_name,sizeof(symbolicname));CHKERRQ(ierr);
9624     ierr = PetscStrlcat(symbolicname,"_C",sizeof(symbolicname));CHKERRQ(ierr);
9625     ierr = PetscObjectQueryFunction((PetscObject)B,symbolicname,&symbolic);CHKERRQ(ierr);
9626     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);
9627   }
9628   ierr = PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9629   ierr = (*symbolic)(A,B,fill,C);CHKERRQ(ierr);
9630   ierr = PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9631   PetscFunctionReturn(0);
9632 }
9633 
9634 /*@
9635    MatMatMultNumeric - Performs the numeric matrix-matrix product.
9636    Call this routine after first calling MatMatMultSymbolic().
9637 
9638    Neighbor-wise Collective on Mat
9639 
9640    Input Parameters:
9641 +  A - the left matrix
9642 -  B - the right matrix
9643 
9644    Output Parameters:
9645 .  C - the product matrix, which was created by from MatMatMultSymbolic() or a call to MatMatMult().
9646 
9647    Notes:
9648    C must have been created with MatMatMultSymbolic().
9649 
9650    This routine is currently implemented for
9651     - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
9652     - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9653     - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9654 
9655    Level: intermediate
9656 
9657 .seealso: MatMatMult(), MatMatMultSymbolic()
9658 @*/
9659 PetscErrorCode MatMatMultNumeric(Mat A,Mat B,Mat C)
9660 {
9661   PetscErrorCode ierr;
9662 
9663   PetscFunctionBegin;
9664   ierr = MatMatMult(A,B,MAT_REUSE_MATRIX,0.0,&C);CHKERRQ(ierr);
9665   PetscFunctionReturn(0);
9666 }
9667 
9668 /*@
9669    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9670 
9671    Neighbor-wise Collective on Mat
9672 
9673    Input Parameters:
9674 +  A - the left matrix
9675 .  B - the right matrix
9676 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9677 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9678 
9679    Output Parameters:
9680 .  C - the product matrix
9681 
9682    Notes:
9683    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9684 
9685    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9686 
9687   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9688    actually needed.
9689 
9690    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9691    and for pairs of MPIDense matrices.
9692 
9693    Options Database Keys:
9694 .  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9695                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9696                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.
9697 
9698    Level: intermediate
9699 
9700 .seealso: MatMatTransposeMultSymbolic(), MatMatTransposeMultNumeric(), MatMatMult(), MatTransposeMatMult() MatPtAP()
9701 @*/
9702 PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9703 {
9704   PetscErrorCode ierr;
9705   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9706   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9707   Mat            T;
9708   PetscBool      istrans;
9709 
9710   PetscFunctionBegin;
9711   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9712   PetscValidType(A,1);
9713   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9714   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9715   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9716   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9717   PetscValidType(B,2);
9718   MatCheckPreallocated(B,2);
9719   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9720   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9721   PetscValidPointer(C,3);
9722   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);
9723   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9724   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9725   MatCheckPreallocated(A,1);
9726 
9727   ierr = PetscObjectTypeCompare((PetscObject)B,MATTRANSPOSEMAT,&istrans);CHKERRQ(ierr);
9728   if (istrans) {
9729     ierr = MatTransposeGetMat(B,&T);CHKERRQ(ierr);
9730     ierr = MatMatMult(A,T,scall,fill,C);CHKERRQ(ierr);
9731     PetscFunctionReturn(0);
9732   }
9733   fA = A->ops->mattransposemult;
9734   if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for A of type %s",((PetscObject)A)->type_name);
9735   fB = B->ops->mattransposemult;
9736   if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for B of type %s",((PetscObject)B)->type_name);
9737   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);
9738 
9739   ierr = PetscLogEventBegin(MAT_MatTransposeMult,A,B,0,0);CHKERRQ(ierr);
9740   if (scall == MAT_INITIAL_MATRIX) {
9741     ierr = PetscLogEventBegin(MAT_MatTransposeMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9742     ierr = (*A->ops->mattransposemultsymbolic)(A,B,fill,C);CHKERRQ(ierr);
9743     ierr = PetscLogEventEnd(MAT_MatTransposeMultSymbolic,A,B,0,0);CHKERRQ(ierr);
9744   }
9745   ierr = PetscLogEventBegin(MAT_MatTransposeMultNumeric,A,B,0,0);CHKERRQ(ierr);
9746   ierr = (*A->ops->mattransposemultnumeric)(A,B,*C);CHKERRQ(ierr);
9747   ierr = PetscLogEventEnd(MAT_MatTransposeMultNumeric,A,B,0,0);CHKERRQ(ierr);
9748   ierr = PetscLogEventEnd(MAT_MatTransposeMult,A,B,0,0);CHKERRQ(ierr);
9749   PetscFunctionReturn(0);
9750 }
9751 
9752 /*@
9753    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
9754 
9755    Neighbor-wise Collective on Mat
9756 
9757    Input Parameters:
9758 +  A - the left matrix
9759 .  B - the right matrix
9760 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9761 -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9762 
9763    Output Parameters:
9764 .  C - the product matrix
9765 
9766    Notes:
9767    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9768 
9769    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9770 
9771   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9772    actually needed.
9773 
9774    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9775    which inherit from SeqAIJ.  C will be of same type as the input matrices.
9776 
9777    Level: intermediate
9778 
9779 .seealso: MatTransposeMatMultSymbolic(), MatTransposeMatMultNumeric(), MatMatMult(), MatMatTransposeMult(), MatPtAP()
9780 @*/
9781 PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9782 {
9783   PetscErrorCode ierr;
9784   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9785   PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9786   PetscErrorCode (*transposematmult)(Mat,Mat,MatReuse,PetscReal,Mat*) = NULL;
9787   Mat            T;
9788   PetscBool      istrans;
9789 
9790   PetscFunctionBegin;
9791   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9792   PetscValidType(A,1);
9793   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9794   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9795   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9796   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9797   PetscValidType(B,2);
9798   MatCheckPreallocated(B,2);
9799   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9800   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9801   PetscValidPointer(C,3);
9802   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);
9803   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9804   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9805   MatCheckPreallocated(A,1);
9806 
9807   ierr = PetscObjectTypeCompare((PetscObject)A,MATTRANSPOSEMAT,&istrans);CHKERRQ(ierr);
9808   if (istrans) {
9809     ierr = MatTransposeGetMat(A,&T);CHKERRQ(ierr);
9810     ierr = MatMatMult(T,B,scall,fill,C);CHKERRQ(ierr);
9811     PetscFunctionReturn(0);
9812   }
9813   fA = A->ops->transposematmult;
9814   fB = B->ops->transposematmult;
9815   if (fB==fA) {
9816     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatTransposeMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9817     transposematmult = fA;
9818   } else {
9819     /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9820     char multname[256];
9821     ierr = PetscStrncpy(multname,"MatTransposeMatMult_",sizeof(multname));CHKERRQ(ierr);
9822     ierr = PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));CHKERRQ(ierr);
9823     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
9824     ierr = PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));CHKERRQ(ierr);
9825     ierr = PetscStrlcat(multname,"_C",sizeof(multname));CHKERRQ(ierr); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9826     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&transposematmult);CHKERRQ(ierr);
9827     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);
9828   }
9829   ierr = PetscLogEventBegin(MAT_TransposeMatMult,A,B,0,0);CHKERRQ(ierr);
9830   ierr = (*transposematmult)(A,B,scall,fill,C);CHKERRQ(ierr);
9831   ierr = PetscLogEventEnd(MAT_TransposeMatMult,A,B,0,0);CHKERRQ(ierr);
9832   PetscFunctionReturn(0);
9833 }
9834 
9835 /*@
9836    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
9837 
9838    Neighbor-wise Collective on Mat
9839 
9840    Input Parameters:
9841 +  A - the left matrix
9842 .  B - the middle matrix
9843 .  C - the right matrix
9844 .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9845 -  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
9846           if the result is a dense matrix this is irrelevent
9847 
9848    Output Parameters:
9849 .  D - the product matrix
9850 
9851    Notes:
9852    Unless scall is MAT_REUSE_MATRIX D will be created.
9853 
9854    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
9855 
9856    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9857    actually needed.
9858 
9859    If you have many matrices with the same non-zero structure to multiply, you
9860    should use MAT_REUSE_MATRIX in all calls but the first or
9861 
9862    Level: intermediate
9863 
9864 .seealso: MatMatMult, MatPtAP()
9865 @*/
9866 PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9867 {
9868   PetscErrorCode ierr;
9869   PetscErrorCode (*fA)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9870   PetscErrorCode (*fB)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9871   PetscErrorCode (*fC)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9872   PetscErrorCode (*mult)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9873 
9874   PetscFunctionBegin;
9875   PetscValidHeaderSpecific(A,MAT_CLASSID,1);
9876   PetscValidType(A,1);
9877   MatCheckPreallocated(A,1);
9878   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9879   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9880   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9881   PetscValidHeaderSpecific(B,MAT_CLASSID,2);
9882   PetscValidType(B,2);
9883   MatCheckPreallocated(B,2);
9884   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9885   if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9886   PetscValidHeaderSpecific(C,MAT_CLASSID,3);
9887   PetscValidPointer(C,3);
9888   MatCheckPreallocated(C,3);
9889   if (!C->assembled) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9890   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9891   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);
9892   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);
9893   if (scall == MAT_REUSE_MATRIX) {
9894     PetscValidPointer(*D,6);
9895     PetscValidHeaderSpecific(*D,MAT_CLASSID,6);
9896     ierr = PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9897     ierr = (*(*D)->ops->matmatmult)(A,B,C,scall,fill,D);CHKERRQ(ierr);
9898     ierr = PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9899     PetscFunctionReturn(0);
9900   }
9901   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9902   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9903 
9904   fA = A->ops->matmatmult;
9905   fB = B->ops->matmatmult;
9906   fC = C->ops->matmatmult;
9907   if (fA == fB && fA == fC) {
9908     if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9909     mult = fA;
9910   } else {
9911     /* dispatch based on the type of A, B and C from their PetscObject's PetscFunctionLists. */
9912     char multname[256];
9913     ierr = PetscStrncpy(multname,"MatMatMatMult_",sizeof(multname));CHKERRQ(ierr);
9914     ierr = PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));CHKERRQ(ierr);
9915     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
9916     ierr = PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));CHKERRQ(ierr);
9917     ierr = PetscStrlcat(multname,"_",sizeof(multname));CHKERRQ(ierr);
9918     ierr = PetscStrlcat(multname,((PetscObject)C)->type_name,sizeof(multname));CHKERRQ(ierr);
9919     ierr = PetscStrlcat(multname,"_C",sizeof(multname));CHKERRQ(ierr);
9920     ierr = PetscObjectQueryFunction((PetscObject)B,multname,&mult);CHKERRQ(ierr);
9921     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);
9922   }
9923   ierr = PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9924   ierr = (*mult)(A,B,C,scall,fill,D);CHKERRQ(ierr);
9925   ierr = PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);CHKERRQ(ierr);
9926   PetscFunctionReturn(0);
9927 }
9928 
9929 /*@
9930    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
9931 
9932    Collective on Mat
9933 
9934    Input Parameters:
9935 +  mat - the matrix
9936 .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9937 .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9938 -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9939 
9940    Output Parameter:
9941 .  matredundant - redundant matrix
9942 
9943    Notes:
9944    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9945    original matrix has not changed from that last call to MatCreateRedundantMatrix().
9946 
9947    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9948    calling it.
9949 
9950    Level: advanced
9951 
9952 
9953 .seealso: MatDestroy()
9954 @*/
9955 PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9956 {
9957   PetscErrorCode ierr;
9958   MPI_Comm       comm;
9959   PetscMPIInt    size;
9960   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9961   Mat_Redundant  *redund=NULL;
9962   PetscSubcomm   psubcomm=NULL;
9963   MPI_Comm       subcomm_in=subcomm;
9964   Mat            *matseq;
9965   IS             isrow,iscol;
9966   PetscBool      newsubcomm=PETSC_FALSE;
9967 
9968   PetscFunctionBegin;
9969   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
9970   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9971     PetscValidPointer(*matredundant,5);
9972     PetscValidHeaderSpecific(*matredundant,MAT_CLASSID,5);
9973   }
9974 
9975   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
9976   if (size == 1 || nsubcomm == 1) {
9977     if (reuse == MAT_INITIAL_MATRIX) {
9978       ierr = MatDuplicate(mat,MAT_COPY_VALUES,matredundant);CHKERRQ(ierr);
9979     } else {
9980       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");
9981       ierr = MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
9982     }
9983     PetscFunctionReturn(0);
9984   }
9985 
9986   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9987   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9988   MatCheckPreallocated(mat,1);
9989 
9990   ierr = PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
9991   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9992     /* create psubcomm, then get subcomm */
9993     ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
9994     ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
9995     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
9996 
9997     ierr = PetscSubcommCreate(comm,&psubcomm);CHKERRQ(ierr);
9998     ierr = PetscSubcommSetNumber(psubcomm,nsubcomm);CHKERRQ(ierr);
9999     ierr = PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);CHKERRQ(ierr);
10000     ierr = PetscSubcommSetFromOptions(psubcomm);CHKERRQ(ierr);
10001     ierr = PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);CHKERRQ(ierr);
10002     newsubcomm = PETSC_TRUE;
10003     ierr = PetscSubcommDestroy(&psubcomm);CHKERRQ(ierr);
10004   }
10005 
10006   /* get isrow, iscol and a local sequential matrix matseq[0] */
10007   if (reuse == MAT_INITIAL_MATRIX) {
10008     mloc_sub = PETSC_DECIDE;
10009     nloc_sub = PETSC_DECIDE;
10010     if (bs < 1) {
10011       ierr = PetscSplitOwnership(subcomm,&mloc_sub,&M);CHKERRQ(ierr);
10012       ierr = PetscSplitOwnership(subcomm,&nloc_sub,&N);CHKERRQ(ierr);
10013     } else {
10014       ierr = PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);CHKERRQ(ierr);
10015       ierr = PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);CHKERRQ(ierr);
10016     }
10017     ierr = MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);CHKERRQ(ierr);
10018     rstart = rend - mloc_sub;
10019     ierr = ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);CHKERRQ(ierr);
10020     ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);CHKERRQ(ierr);
10021   } else { /* reuse == MAT_REUSE_MATRIX */
10022     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");
10023     /* retrieve subcomm */
10024     ierr = PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);CHKERRQ(ierr);
10025     redund = (*matredundant)->redundant;
10026     isrow  = redund->isrow;
10027     iscol  = redund->iscol;
10028     matseq = redund->matseq;
10029   }
10030   ierr = MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);CHKERRQ(ierr);
10031 
10032   /* get matredundant over subcomm */
10033   if (reuse == MAT_INITIAL_MATRIX) {
10034     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);CHKERRQ(ierr);
10035 
10036     /* create a supporting struct and attach it to C for reuse */
10037     ierr = PetscNewLog(*matredundant,&redund);CHKERRQ(ierr);
10038     (*matredundant)->redundant = redund;
10039     redund->isrow              = isrow;
10040     redund->iscol              = iscol;
10041     redund->matseq             = matseq;
10042     if (newsubcomm) {
10043       redund->subcomm          = subcomm;
10044     } else {
10045       redund->subcomm          = MPI_COMM_NULL;
10046     }
10047   } else {
10048     ierr = MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);CHKERRQ(ierr);
10049   }
10050   ierr = PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);CHKERRQ(ierr);
10051   PetscFunctionReturn(0);
10052 }
10053 
10054 /*@C
10055    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
10056    a given 'mat' object. Each submatrix can span multiple procs.
10057 
10058    Collective on Mat
10059 
10060    Input Parameters:
10061 +  mat - the matrix
10062 .  subcomm - the subcommunicator obtained by com_split(comm)
10063 -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10064 
10065    Output Parameter:
10066 .  subMat - 'parallel submatrices each spans a given subcomm
10067 
10068   Notes:
10069   The submatrix partition across processors is dictated by 'subComm' a
10070   communicator obtained by com_split(comm). The comm_split
10071   is not restriced to be grouped with consecutive original ranks.
10072 
10073   Due the comm_split() usage, the parallel layout of the submatrices
10074   map directly to the layout of the original matrix [wrt the local
10075   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10076   into the 'DiagonalMat' of the subMat, hence it is used directly from
10077   the subMat. However the offDiagMat looses some columns - and this is
10078   reconstructed with MatSetValues()
10079 
10080   Level: advanced
10081 
10082 
10083 .seealso: MatCreateSubMatrices()
10084 @*/
10085 PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
10086 {
10087   PetscErrorCode ierr;
10088   PetscMPIInt    commsize,subCommSize;
10089 
10090   PetscFunctionBegin;
10091   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);CHKERRQ(ierr);
10092   ierr = MPI_Comm_size(subComm,&subCommSize);CHKERRQ(ierr);
10093   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
10094 
10095   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");
10096   ierr = PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
10097   ierr = (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);CHKERRQ(ierr);
10098   ierr = PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);CHKERRQ(ierr);
10099   PetscFunctionReturn(0);
10100 }
10101 
10102 /*@
10103    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10104 
10105    Not Collective
10106 
10107    Input Arguments:
10108 +  mat - matrix to extract local submatrix from
10109 .  isrow - local row indices for submatrix
10110 -  iscol - local column indices for submatrix
10111 
10112    Output Arguments:
10113 .  submat - the submatrix
10114 
10115    Level: intermediate
10116 
10117    Notes:
10118    The submat should be returned with MatRestoreLocalSubMatrix().
10119 
10120    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
10121    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
10122 
10123    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
10124    MatSetValuesBlockedLocal() will also be implemented.
10125 
10126    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
10127    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.
10128 
10129 .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
10130 @*/
10131 PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10132 {
10133   PetscErrorCode ierr;
10134 
10135   PetscFunctionBegin;
10136   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10137   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
10138   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
10139   PetscCheckSameComm(isrow,2,iscol,3);
10140   PetscValidPointer(submat,4);
10141   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");
10142 
10143   if (mat->ops->getlocalsubmatrix) {
10144     ierr = (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
10145   } else {
10146     ierr = MatCreateLocalRef(mat,isrow,iscol,submat);CHKERRQ(ierr);
10147   }
10148   PetscFunctionReturn(0);
10149 }
10150 
10151 /*@
10152    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
10153 
10154    Not Collective
10155 
10156    Input Arguments:
10157    mat - matrix to extract local submatrix from
10158    isrow - local row indices for submatrix
10159    iscol - local column indices for submatrix
10160    submat - the submatrix
10161 
10162    Level: intermediate
10163 
10164 .seealso: MatGetLocalSubMatrix()
10165 @*/
10166 PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10167 {
10168   PetscErrorCode ierr;
10169 
10170   PetscFunctionBegin;
10171   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10172   PetscValidHeaderSpecific(isrow,IS_CLASSID,2);
10173   PetscValidHeaderSpecific(iscol,IS_CLASSID,3);
10174   PetscCheckSameComm(isrow,2,iscol,3);
10175   PetscValidPointer(submat,4);
10176   if (*submat) {
10177     PetscValidHeaderSpecific(*submat,MAT_CLASSID,4);
10178   }
10179 
10180   if (mat->ops->restorelocalsubmatrix) {
10181     ierr = (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);CHKERRQ(ierr);
10182   } else {
10183     ierr = MatDestroy(submat);CHKERRQ(ierr);
10184   }
10185   *submat = NULL;
10186   PetscFunctionReturn(0);
10187 }
10188 
10189 /* --------------------------------------------------------*/
10190 /*@
10191    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
10192 
10193    Collective on Mat
10194 
10195    Input Parameter:
10196 .  mat - the matrix
10197 
10198    Output Parameter:
10199 .  is - if any rows have zero diagonals this contains the list of them
10200 
10201    Level: developer
10202 
10203 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10204 @*/
10205 PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
10206 {
10207   PetscErrorCode ierr;
10208 
10209   PetscFunctionBegin;
10210   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10211   PetscValidType(mat,1);
10212   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10213   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10214 
10215   if (!mat->ops->findzerodiagonals) {
10216     Vec                diag;
10217     const PetscScalar *a;
10218     PetscInt          *rows;
10219     PetscInt           rStart, rEnd, r, nrow = 0;
10220 
10221     ierr = MatCreateVecs(mat, &diag, NULL);CHKERRQ(ierr);
10222     ierr = MatGetDiagonal(mat, diag);CHKERRQ(ierr);
10223     ierr = MatGetOwnershipRange(mat, &rStart, &rEnd);CHKERRQ(ierr);
10224     ierr = VecGetArrayRead(diag, &a);CHKERRQ(ierr);
10225     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
10226     ierr = PetscMalloc1(nrow, &rows);CHKERRQ(ierr);
10227     nrow = 0;
10228     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
10229     ierr = VecRestoreArrayRead(diag, &a);CHKERRQ(ierr);
10230     ierr = VecDestroy(&diag);CHKERRQ(ierr);
10231     ierr = ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);CHKERRQ(ierr);
10232   } else {
10233     ierr = (*mat->ops->findzerodiagonals)(mat, is);CHKERRQ(ierr);
10234   }
10235   PetscFunctionReturn(0);
10236 }
10237 
10238 /*@
10239    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
10240 
10241    Collective on Mat
10242 
10243    Input Parameter:
10244 .  mat - the matrix
10245 
10246    Output Parameter:
10247 .  is - contains the list of rows with off block diagonal entries
10248 
10249    Level: developer
10250 
10251 .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10252 @*/
10253 PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
10254 {
10255   PetscErrorCode ierr;
10256 
10257   PetscFunctionBegin;
10258   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10259   PetscValidType(mat,1);
10260   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10261   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10262 
10263   if (!mat->ops->findoffblockdiagonalentries) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find off block diagonal entries defined");
10264   ierr = (*mat->ops->findoffblockdiagonalentries)(mat,is);CHKERRQ(ierr);
10265   PetscFunctionReturn(0);
10266 }
10267 
10268 /*@C
10269   MatInvertBlockDiagonal - Inverts the block diagonal entries.
10270 
10271   Collective on Mat
10272 
10273   Input Parameters:
10274 . mat - the matrix
10275 
10276   Output Parameters:
10277 . values - the block inverses in column major order (FORTRAN-like)
10278 
10279    Note:
10280    This routine is not available from Fortran.
10281 
10282   Level: advanced
10283 
10284 .seealso: MatInvertBockDiagonalMat
10285 @*/
10286 PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
10287 {
10288   PetscErrorCode ierr;
10289 
10290   PetscFunctionBegin;
10291   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10292   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10293   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10294   if (!mat->ops->invertblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10295   ierr = (*mat->ops->invertblockdiagonal)(mat,values);CHKERRQ(ierr);
10296   PetscFunctionReturn(0);
10297 }
10298 
10299 /*@C
10300   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.
10301 
10302   Collective on Mat
10303 
10304   Input Parameters:
10305 + mat - the matrix
10306 . nblocks - the number of blocks
10307 - bsizes - the size of each block
10308 
10309   Output Parameters:
10310 . values - the block inverses in column major order (FORTRAN-like)
10311 
10312    Note:
10313    This routine is not available from Fortran.
10314 
10315   Level: advanced
10316 
10317 .seealso: MatInvertBockDiagonal()
10318 @*/
10319 PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
10320 {
10321   PetscErrorCode ierr;
10322 
10323   PetscFunctionBegin;
10324   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10325   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10326   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10327   if (!mat->ops->invertvariableblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10328   ierr = (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);CHKERRQ(ierr);
10329   PetscFunctionReturn(0);
10330 }
10331 
10332 /*@
10333   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A
10334 
10335   Collective on Mat
10336 
10337   Input Parameters:
10338 . A - the matrix
10339 
10340   Output Parameters:
10341 . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.
10342 
10343   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C
10344 
10345   Level: advanced
10346 
10347 .seealso: MatInvertBockDiagonal()
10348 @*/
10349 PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
10350 {
10351   PetscErrorCode     ierr;
10352   const PetscScalar *vals;
10353   PetscInt          *dnnz;
10354   PetscInt           M,N,m,n,rstart,rend,bs,i,j;
10355 
10356   PetscFunctionBegin;
10357   ierr = MatInvertBlockDiagonal(A,&vals);CHKERRQ(ierr);
10358   ierr = MatGetBlockSize(A,&bs);CHKERRQ(ierr);
10359   ierr = MatGetSize(A,&M,&N);CHKERRQ(ierr);
10360   ierr = MatGetLocalSize(A,&m,&n);CHKERRQ(ierr);
10361   ierr = MatSetSizes(C,m,n,M,N);CHKERRQ(ierr);
10362   ierr = MatSetBlockSize(C,bs);CHKERRQ(ierr);
10363   ierr = PetscMalloc1(m/bs,&dnnz);CHKERRQ(ierr);
10364   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
10365   ierr = MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);CHKERRQ(ierr);
10366   ierr = PetscFree(dnnz);CHKERRQ(ierr);
10367   ierr = MatGetOwnershipRange(C,&rstart,&rend);CHKERRQ(ierr);
10368   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);CHKERRQ(ierr);
10369   for (i = rstart/bs; i < rend/bs; i++) {
10370     ierr = MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);CHKERRQ(ierr);
10371   }
10372   ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10373   ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
10374   ierr = MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);CHKERRQ(ierr);
10375   PetscFunctionReturn(0);
10376 }
10377 
10378 /*@C
10379     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
10380     via MatTransposeColoringCreate().
10381 
10382     Collective on MatTransposeColoring
10383 
10384     Input Parameter:
10385 .   c - coloring context
10386 
10387     Level: intermediate
10388 
10389 .seealso: MatTransposeColoringCreate()
10390 @*/
10391 PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10392 {
10393   PetscErrorCode       ierr;
10394   MatTransposeColoring matcolor=*c;
10395 
10396   PetscFunctionBegin;
10397   if (!matcolor) PetscFunctionReturn(0);
10398   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; PetscFunctionReturn(0);}
10399 
10400   ierr = PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);CHKERRQ(ierr);
10401   ierr = PetscFree(matcolor->rows);CHKERRQ(ierr);
10402   ierr = PetscFree(matcolor->den2sp);CHKERRQ(ierr);
10403   ierr = PetscFree(matcolor->colorforcol);CHKERRQ(ierr);
10404   ierr = PetscFree(matcolor->columns);CHKERRQ(ierr);
10405   if (matcolor->brows>0) {
10406     ierr = PetscFree(matcolor->lstart);CHKERRQ(ierr);
10407   }
10408   ierr = PetscHeaderDestroy(c);CHKERRQ(ierr);
10409   PetscFunctionReturn(0);
10410 }
10411 
10412 /*@C
10413     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10414     a MatTransposeColoring context has been created, computes a dense B^T by Apply
10415     MatTransposeColoring to sparse B.
10416 
10417     Collective on MatTransposeColoring
10418 
10419     Input Parameters:
10420 +   B - sparse matrix B
10421 .   Btdense - symbolic dense matrix B^T
10422 -   coloring - coloring context created with MatTransposeColoringCreate()
10423 
10424     Output Parameter:
10425 .   Btdense - dense matrix B^T
10426 
10427     Level: advanced
10428 
10429      Notes:
10430     These are used internally for some implementations of MatRARt()
10431 
10432 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()
10433 
10434 @*/
10435 PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10436 {
10437   PetscErrorCode ierr;
10438 
10439   PetscFunctionBegin;
10440   PetscValidHeaderSpecific(B,MAT_CLASSID,1);
10441   PetscValidHeaderSpecific(Btdense,MAT_CLASSID,2);
10442   PetscValidHeaderSpecific(coloring,MAT_TRANSPOSECOLORING_CLASSID,3);
10443 
10444   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10445   ierr = (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);CHKERRQ(ierr);
10446   PetscFunctionReturn(0);
10447 }
10448 
10449 /*@C
10450     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10451     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10452     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10453     Csp from Cden.
10454 
10455     Collective on MatTransposeColoring
10456 
10457     Input Parameters:
10458 +   coloring - coloring context created with MatTransposeColoringCreate()
10459 -   Cden - matrix product of a sparse matrix and a dense matrix Btdense
10460 
10461     Output Parameter:
10462 .   Csp - sparse matrix
10463 
10464     Level: advanced
10465 
10466      Notes:
10467     These are used internally for some implementations of MatRARt()
10468 
10469 .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
10470 
10471 @*/
10472 PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10473 {
10474   PetscErrorCode ierr;
10475 
10476   PetscFunctionBegin;
10477   PetscValidHeaderSpecific(matcoloring,MAT_TRANSPOSECOLORING_CLASSID,1);
10478   PetscValidHeaderSpecific(Cden,MAT_CLASSID,2);
10479   PetscValidHeaderSpecific(Csp,MAT_CLASSID,3);
10480 
10481   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10482   ierr = (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);CHKERRQ(ierr);
10483   PetscFunctionReturn(0);
10484 }
10485 
10486 /*@C
10487    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
10488 
10489    Collective on Mat
10490 
10491    Input Parameters:
10492 +  mat - the matrix product C
10493 -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
10494 
10495     Output Parameter:
10496 .   color - the new coloring context
10497 
10498     Level: intermediate
10499 
10500 .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
10501            MatTransColoringApplyDenToSp()
10502 @*/
10503 PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10504 {
10505   MatTransposeColoring c;
10506   MPI_Comm             comm;
10507   PetscErrorCode       ierr;
10508 
10509   PetscFunctionBegin;
10510   ierr = PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10511   ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
10512   ierr = PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);CHKERRQ(ierr);
10513 
10514   c->ctype = iscoloring->ctype;
10515   if (mat->ops->transposecoloringcreate) {
10516     ierr = (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);CHKERRQ(ierr);
10517   } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for this matrix type");
10518 
10519   *color = c;
10520   ierr   = PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);CHKERRQ(ierr);
10521   PetscFunctionReturn(0);
10522 }
10523 
10524 /*@
10525       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10526         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10527         same, otherwise it will be larger
10528 
10529      Not Collective
10530 
10531   Input Parameter:
10532 .    A  - the matrix
10533 
10534   Output Parameter:
10535 .    state - the current state
10536 
10537   Notes:
10538     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10539          different matrices
10540 
10541   Level: intermediate
10542 
10543 @*/
10544 PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10545 {
10546   PetscFunctionBegin;
10547   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10548   *state = mat->nonzerostate;
10549   PetscFunctionReturn(0);
10550 }
10551 
10552 /*@
10553       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10554                  matrices from each processor
10555 
10556     Collective
10557 
10558    Input Parameters:
10559 +    comm - the communicators the parallel matrix will live on
10560 .    seqmat - the input sequential matrices
10561 .    n - number of local columns (or PETSC_DECIDE)
10562 -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10563 
10564    Output Parameter:
10565 .    mpimat - the parallel matrix generated
10566 
10567     Level: advanced
10568 
10569    Notes:
10570     The number of columns of the matrix in EACH processor MUST be the same.
10571 
10572 @*/
10573 PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10574 {
10575   PetscErrorCode ierr;
10576 
10577   PetscFunctionBegin;
10578   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10579   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");
10580 
10581   ierr = PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10582   ierr = (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);CHKERRQ(ierr);
10583   ierr = PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);CHKERRQ(ierr);
10584   PetscFunctionReturn(0);
10585 }
10586 
10587 /*@
10588      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10589                  ranks' ownership ranges.
10590 
10591     Collective on A
10592 
10593    Input Parameters:
10594 +    A   - the matrix to create subdomains from
10595 -    N   - requested number of subdomains
10596 
10597 
10598    Output Parameters:
10599 +    n   - number of subdomains resulting on this rank
10600 -    iss - IS list with indices of subdomains on this rank
10601 
10602     Level: advanced
10603 
10604     Notes:
10605     number of subdomains must be smaller than the communicator size
10606 @*/
10607 PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10608 {
10609   MPI_Comm        comm,subcomm;
10610   PetscMPIInt     size,rank,color;
10611   PetscInt        rstart,rend,k;
10612   PetscErrorCode  ierr;
10613 
10614   PetscFunctionBegin;
10615   ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr);
10616   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
10617   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
10618   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);
10619   *n = 1;
10620   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10621   color = rank/k;
10622   ierr = MPI_Comm_split(comm,color,rank,&subcomm);CHKERRQ(ierr);
10623   ierr = PetscMalloc1(1,iss);CHKERRQ(ierr);
10624   ierr = MatGetOwnershipRange(A,&rstart,&rend);CHKERRQ(ierr);
10625   ierr = ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);CHKERRQ(ierr);
10626   ierr = MPI_Comm_free(&subcomm);CHKERRQ(ierr);
10627   PetscFunctionReturn(0);
10628 }
10629 
10630 /*@
10631    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.
10632 
10633    If the interpolation and restriction operators are the same, uses MatPtAP.
10634    If they are not the same, use MatMatMatMult.
10635 
10636    Once the coarse grid problem is constructed, correct for interpolation operators
10637    that are not of full rank, which can legitimately happen in the case of non-nested
10638    geometric multigrid.
10639 
10640    Input Parameters:
10641 +  restrct - restriction operator
10642 .  dA - fine grid matrix
10643 .  interpolate - interpolation operator
10644 .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10645 -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate
10646 
10647    Output Parameters:
10648 .  A - the Galerkin coarse matrix
10649 
10650    Options Database Key:
10651 .  -pc_mg_galerkin <both,pmat,mat,none>
10652 
10653    Level: developer
10654 
10655 .seealso: MatPtAP(), MatMatMatMult()
10656 @*/
10657 PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10658 {
10659   PetscErrorCode ierr;
10660   IS             zerorows;
10661   Vec            diag;
10662 
10663   PetscFunctionBegin;
10664   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10665   /* Construct the coarse grid matrix */
10666   if (interpolate == restrct) {
10667     ierr = MatPtAP(dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10668   } else {
10669     ierr = MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);CHKERRQ(ierr);
10670   }
10671 
10672   /* If the interpolation matrix is not of full rank, A will have zero rows.
10673      This can legitimately happen in the case of non-nested geometric multigrid.
10674      In that event, we set the rows of the matrix to the rows of the identity,
10675      ignoring the equations (as the RHS will also be zero). */
10676 
10677   ierr = MatFindZeroRows(*A, &zerorows);CHKERRQ(ierr);
10678 
10679   if (zerorows != NULL) { /* if there are any zero rows */
10680     ierr = MatCreateVecs(*A, &diag, NULL);CHKERRQ(ierr);
10681     ierr = MatGetDiagonal(*A, diag);CHKERRQ(ierr);
10682     ierr = VecISSet(diag, zerorows, 1.0);CHKERRQ(ierr);
10683     ierr = MatDiagonalSet(*A, diag, INSERT_VALUES);CHKERRQ(ierr);
10684     ierr = VecDestroy(&diag);CHKERRQ(ierr);
10685     ierr = ISDestroy(&zerorows);CHKERRQ(ierr);
10686   }
10687   PetscFunctionReturn(0);
10688 }
10689 
10690 /*@C
10691     MatSetOperation - Allows user to set a matrix operation for any matrix type
10692 
10693    Logically Collective on Mat
10694 
10695     Input Parameters:
10696 +   mat - the matrix
10697 .   op - the name of the operation
10698 -   f - the function that provides the operation
10699 
10700    Level: developer
10701 
10702     Usage:
10703 $      extern PetscErrorCode usermult(Mat,Vec,Vec);
10704 $      ierr = MatCreateXXX(comm,...&A);
10705 $      ierr = MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
10706 
10707     Notes:
10708     See the file include/petscmat.h for a complete list of matrix
10709     operations, which all have the form MATOP_<OPERATION>, where
10710     <OPERATION> is the name (in all capital letters) of the
10711     user interface routine (e.g., MatMult() -> MATOP_MULT).
10712 
10713     All user-provided functions (except for MATOP_DESTROY) should have the same calling
10714     sequence as the usual matrix interface routines, since they
10715     are intended to be accessed via the usual matrix interface
10716     routines, e.g.,
10717 $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)
10718 
10719     In particular each function MUST return an error code of 0 on success and
10720     nonzero on failure.
10721 
10722     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.
10723 
10724 .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10725 @*/
10726 PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10727 {
10728   PetscFunctionBegin;
10729   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10730   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10731     mat->ops->viewnative = mat->ops->view;
10732   }
10733   (((void(**)(void))mat->ops)[op]) = f;
10734   PetscFunctionReturn(0);
10735 }
10736 
10737 /*@C
10738     MatGetOperation - Gets a matrix operation for any matrix type.
10739 
10740     Not Collective
10741 
10742     Input Parameters:
10743 +   mat - the matrix
10744 -   op - the name of the operation
10745 
10746     Output Parameter:
10747 .   f - the function that provides the operation
10748 
10749     Level: developer
10750 
10751     Usage:
10752 $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
10753 $      ierr = MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);
10754 
10755     Notes:
10756     See the file include/petscmat.h for a complete list of matrix
10757     operations, which all have the form MATOP_<OPERATION>, where
10758     <OPERATION> is the name (in all capital letters) of the
10759     user interface routine (e.g., MatMult() -> MATOP_MULT).
10760 
10761     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.
10762 
10763 .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
10764 @*/
10765 PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
10766 {
10767   PetscFunctionBegin;
10768   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10769   *f = (((void (**)(void))mat->ops)[op]);
10770   PetscFunctionReturn(0);
10771 }
10772 
10773 /*@
10774     MatHasOperation - Determines whether the given matrix supports the particular
10775     operation.
10776 
10777    Not Collective
10778 
10779    Input Parameters:
10780 +  mat - the matrix
10781 -  op - the operation, for example, MATOP_GET_DIAGONAL
10782 
10783    Output Parameter:
10784 .  has - either PETSC_TRUE or PETSC_FALSE
10785 
10786    Level: advanced
10787 
10788    Notes:
10789    See the file include/petscmat.h for a complete list of matrix
10790    operations, which all have the form MATOP_<OPERATION>, where
10791    <OPERATION> is the name (in all capital letters) of the
10792    user-level routine.  E.g., MatNorm() -> MATOP_NORM.
10793 
10794 .seealso: MatCreateShell()
10795 @*/
10796 PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
10797 {
10798   PetscErrorCode ierr;
10799 
10800   PetscFunctionBegin;
10801   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10802   PetscValidType(mat,1);
10803   PetscValidPointer(has,3);
10804   if (mat->ops->hasoperation) {
10805     ierr = (*mat->ops->hasoperation)(mat,op,has);CHKERRQ(ierr);
10806   } else {
10807     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
10808     else {
10809       *has = PETSC_FALSE;
10810       if (op == MATOP_CREATE_SUBMATRIX) {
10811         PetscMPIInt size;
10812 
10813         ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
10814         if (size == 1) {
10815           ierr = MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);CHKERRQ(ierr);
10816         }
10817       }
10818     }
10819   }
10820   PetscFunctionReturn(0);
10821 }
10822 
10823 /*@
10824     MatHasCongruentLayouts - Determines whether the rows and columns layouts
10825     of the matrix are congruent
10826 
10827    Collective on mat
10828 
10829    Input Parameters:
10830 .  mat - the matrix
10831 
10832    Output Parameter:
10833 .  cong - either PETSC_TRUE or PETSC_FALSE
10834 
10835    Level: beginner
10836 
10837    Notes:
10838 
10839 .seealso: MatCreate(), MatSetSizes()
10840 @*/
10841 PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
10842 {
10843   PetscErrorCode ierr;
10844 
10845   PetscFunctionBegin;
10846   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10847   PetscValidType(mat,1);
10848   PetscValidPointer(cong,2);
10849   if (!mat->rmap || !mat->cmap) {
10850     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
10851     PetscFunctionReturn(0);
10852   }
10853   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
10854     ierr = PetscLayoutCompare(mat->rmap,mat->cmap,cong);CHKERRQ(ierr);
10855     if (*cong) mat->congruentlayouts = 1;
10856     else       mat->congruentlayouts = 0;
10857   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
10858   PetscFunctionReturn(0);
10859 }
10860 
10861 /*@
10862     MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
10863     e.g., matrx product of MatPtAP.
10864 
10865    Collective on mat
10866 
10867    Input Parameters:
10868 .  mat - the matrix
10869 
10870    Output Parameter:
10871 .  mat - the matrix with intermediate data structures released
10872 
10873    Level: advanced
10874 
10875    Notes:
10876 
10877 .seealso: MatPtAP(), MatMatMult()
10878 @*/
10879 PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
10880 {
10881   PetscErrorCode ierr;
10882 
10883   PetscFunctionBegin;
10884   PetscValidHeaderSpecific(mat,MAT_CLASSID,1);
10885   PetscValidType(mat,1);
10886   if (mat->ops->freeintermediatedatastructures) {
10887     ierr = (*mat->ops->freeintermediatedatastructures)(mat);CHKERRQ(ierr);
10888   }
10889   PetscFunctionReturn(0);
10890 }
10891