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