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