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