xref: /petsc/src/mat/impls/aij/mpi/superlu_dist/superlu_dist.c (revision b7d2c1105ed25030b31b0eecd0bf8096e3517f08)
1 
2 /*
3         Provides an interface to the SuperLU_DIST sparse solver
4 */
5 
6 #include <../src/mat/impls/aij/seq/aij.h>
7 #include <../src/mat/impls/aij/mpi/mpiaij.h>
8 #if defined(PETSC_HAVE_STDLIB_H) /* This is to get around weird problem with SuperLU on cray */
9 #include <stdlib.h>
10 #endif
11 
12 #if defined(PETSC_USE_64BIT_INDICES)
13 /* ugly SuperLU_Dist variable telling it to use long long int */
14 #define _LONGINT
15 #endif
16 
17 EXTERN_C_BEGIN
18 #if defined(PETSC_USE_COMPLEX)
19 #include <superlu_zdefs.h>
20 #else
21 #include <superlu_ddefs.h>
22 #endif
23 EXTERN_C_END
24 
25 /*
26     GLOBAL - The sparse matrix and right hand side are all stored initially on process 0. Should be called centralized
27     DISTRIBUTED - The sparse matrix and right hand size are initially stored across the entire MPI communicator.
28 */
29 typedef enum {GLOBAL,DISTRIBUTED} SuperLU_MatInputMode;
30 const char *SuperLU_MatInputModes[] = {"GLOBAL","DISTRIBUTED","SuperLU_MatInputMode","PETSC_",0};
31 
32 typedef struct {
33   int_t                  nprow,npcol,*row,*col;
34   gridinfo_t             grid;
35   superlu_dist_options_t options;
36   SuperMatrix            A_sup;
37   ScalePermstruct_t      ScalePermstruct;
38   LUstruct_t             LUstruct;
39   int                    StatPrint;
40   SuperLU_MatInputMode   MatInputMode;
41   SOLVEstruct_t          SOLVEstruct;
42   fact_t                 FactPattern;
43   MPI_Comm               comm_superlu;
44 #if defined(PETSC_USE_COMPLEX)
45   doublecomplex          *val;
46 #else
47   double                 *val;
48 #endif
49   PetscBool              matsolve_iscalled,matmatsolve_iscalled;
50   PetscBool              CleanUpSuperLU_Dist;  /* Flag to clean up (non-global) SuperLU objects during Destroy */
51 } Mat_SuperLU_DIST;
52 
53 
54 #undef __FUNCT__
55 #define __FUNCT__ "MatSuperluDistGetDiagU_SuperLU_DIST"
56 PetscErrorCode MatSuperluDistGetDiagU_SuperLU_DIST(Mat F,PetscScalar *diagU)
57 {
58   Mat_SuperLU_DIST  *lu= (Mat_SuperLU_DIST*)F->data;
59 
60   PetscFunctionBegin;
61 #if defined(PETSC_USE_COMPLEX)
62   PetscStackCall("SuperLU_DIST:pzGetDiagU",pzGetDiagU(F->rmap->N,&lu->LUstruct,&lu->grid,(doublecomplex*)diagU));
63 #else
64   PetscStackCall("SuperLU_DIST:pdGetDiagU",pdGetDiagU(F->rmap->N,&lu->LUstruct,&lu->grid,diagU));
65 #endif
66   PetscFunctionReturn(0);
67 }
68 
69 #undef __FUNCT__
70 #define __FUNCT__ "MatSuperluDistGetDiagU"
71 PetscErrorCode MatSuperluDistGetDiagU(Mat F,PetscScalar *diagU)
72 {
73   PetscErrorCode    ierr;
74 
75   PetscFunctionBegin;
76   PetscValidHeaderSpecific(F,MAT_CLASSID,1);
77   ierr = PetscTryMethod(F,"MatSuperluDistGetDiagU_C",(Mat,PetscScalar*),(F,diagU));CHKERRQ(ierr);
78   PetscFunctionReturn(0);
79 }
80 
81 #undef __FUNCT__
82 #define __FUNCT__ "MatDestroy_SuperLU_DIST"
83 static PetscErrorCode MatDestroy_SuperLU_DIST(Mat A)
84 {
85   PetscErrorCode   ierr;
86   Mat_SuperLU_DIST *lu = (Mat_SuperLU_DIST*)A->data;
87 
88   PetscFunctionBegin;
89   if (lu->CleanUpSuperLU_Dist) {
90     /* Deallocate SuperLU_DIST storage */
91     if (lu->MatInputMode == GLOBAL) {
92       PetscStackCall("SuperLU_DIST:Destroy_CompCol_Matrix_dist",Destroy_CompCol_Matrix_dist(&lu->A_sup));
93     } else {
94       PetscStackCall("SuperLU_DIST:Destroy_CompRowLoc_Matrix_dist",Destroy_CompRowLoc_Matrix_dist(&lu->A_sup));
95       if (lu->options.SolveInitialized) {
96 #if defined(PETSC_USE_COMPLEX)
97         PetscStackCall("SuperLU_DIST:zSolveFinalize",zSolveFinalize(&lu->options, &lu->SOLVEstruct));
98 #else
99         PetscStackCall("SuperLU_DIST:dSolveFinalize",dSolveFinalize(&lu->options, &lu->SOLVEstruct));
100 #endif
101       }
102     }
103     PetscStackCall("SuperLU_DIST:Destroy_LU",Destroy_LU(A->cmap->N, &lu->grid, &lu->LUstruct));
104     PetscStackCall("SuperLU_DIST:ScalePermstructFree",ScalePermstructFree(&lu->ScalePermstruct));
105     PetscStackCall("SuperLU_DIST:LUstructFree",LUstructFree(&lu->LUstruct));
106 
107     /* Release the SuperLU_DIST process grid. */
108     PetscStackCall("SuperLU_DIST:superlu_gridexit",superlu_gridexit(&lu->grid));
109     ierr = MPI_Comm_free(&(lu->comm_superlu));CHKERRQ(ierr);
110   }
111   ierr = PetscFree(A->data);CHKERRQ(ierr);
112   /* clear composed functions */
113   ierr = PetscObjectComposeFunction((PetscObject)A,"MatFactorGetSolverPackage_C",NULL);CHKERRQ(ierr);
114   ierr = PetscObjectComposeFunction((PetscObject)A,"MatSuperluDistGetDiagU_C",NULL);CHKERRQ(ierr);
115 
116   PetscFunctionReturn(0);
117 }
118 
119 #undef __FUNCT__
120 #define __FUNCT__ "MatSolve_SuperLU_DIST"
121 static PetscErrorCode MatSolve_SuperLU_DIST(Mat A,Vec b_mpi,Vec x)
122 {
123   Mat_SuperLU_DIST *lu = (Mat_SuperLU_DIST*)A->data;
124   PetscErrorCode   ierr;
125   PetscMPIInt      size;
126   PetscInt         m=A->rmap->n,M=A->rmap->N,N=A->cmap->N;
127   SuperLUStat_t    stat;
128   double           berr[1];
129   PetscScalar      *bptr;
130   PetscInt         nrhs=1;
131   Vec              x_seq;
132   IS               iden;
133   VecScatter       scat;
134   int              info; /* SuperLU_Dist info code is ALWAYS an int, even with long long indices */
135   static PetscBool cite = PETSC_FALSE;
136 
137   PetscFunctionBegin;
138   if (lu->options.Fact != FACTORED) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"SuperLU_DIST options.Fact mush equal FACTORED");
139   ierr = PetscCitationsRegister("@article{lidemmel03,\n  author = {Xiaoye S. Li and James W. Demmel},\n  title = {{SuperLU_DIST}: A Scalable Distributed-Memory Sparse Direct\n           Solver for Unsymmetric Linear Systems},\n  journal = {ACM Trans. Mathematical Software},\n  volume = {29},\n  number = {2},\n  pages = {110-140},\n  year = 2003\n}\n",&cite);CHKERRQ(ierr);
140 
141   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRQ(ierr);
142   if (size > 1 && lu->MatInputMode == GLOBAL) {
143     /* global mat input, convert b to x_seq */
144     ierr = VecCreateSeq(PETSC_COMM_SELF,N,&x_seq);CHKERRQ(ierr);
145     ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iden);CHKERRQ(ierr);
146     ierr = VecScatterCreate(b_mpi,iden,x_seq,iden,&scat);CHKERRQ(ierr);
147     ierr = ISDestroy(&iden);CHKERRQ(ierr);
148 
149     ierr = VecScatterBegin(scat,b_mpi,x_seq,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
150     ierr = VecScatterEnd(scat,b_mpi,x_seq,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
151     ierr = VecGetArray(x_seq,&bptr);CHKERRQ(ierr);
152   } else { /* size==1 || distributed mat input */
153     if (lu->options.SolveInitialized && !lu->matsolve_iscalled) {
154       /* see comments in MatMatSolve() */
155 #if defined(PETSC_USE_COMPLEX)
156       PetscStackCall("SuperLU_DIST:zSolveFinalize",zSolveFinalize(&lu->options, &lu->SOLVEstruct));
157 #else
158       PetscStackCall("SuperLU_DIST:dSolveFinalize",dSolveFinalize(&lu->options, &lu->SOLVEstruct));
159 #endif
160       lu->options.SolveInitialized = NO;
161     }
162     ierr = VecCopy(b_mpi,x);CHKERRQ(ierr);
163     ierr = VecGetArray(x,&bptr);CHKERRQ(ierr);
164   }
165 
166   PetscStackCall("SuperLU_DIST:PStatInit",PStatInit(&stat));        /* Initialize the statistics variables. */
167   if (lu->MatInputMode == GLOBAL) {
168 #if defined(PETSC_USE_COMPLEX)
169     PetscStackCall("SuperLU_DIST:pzgssvx_ABglobal",pzgssvx_ABglobal(&lu->options,&lu->A_sup,&lu->ScalePermstruct,(doublecomplex*)bptr,M,nrhs,&lu->grid,&lu->LUstruct,berr,&stat,&info));
170 #else
171     PetscStackCall("SuperLU_DIST:pdgssvx_ABglobal",pdgssvx_ABglobal(&lu->options, &lu->A_sup, &lu->ScalePermstruct,bptr,M,nrhs,&lu->grid,&lu->LUstruct,berr,&stat,&info));
172 #endif
173   } else { /* distributed mat input */
174 #if defined(PETSC_USE_COMPLEX)
175     PetscStackCall("SuperLU_DIST:pzgssvx",pzgssvx(&lu->options,&lu->A_sup,&lu->ScalePermstruct,(doublecomplex*)bptr,m,nrhs,&lu->grid,&lu->LUstruct,&lu->SOLVEstruct,berr,&stat,&info));
176 #else
177     PetscStackCall("SuperLU_DIST:pdgssvx",pdgssvx(&lu->options,&lu->A_sup,&lu->ScalePermstruct,bptr,m,nrhs,&lu->grid,&lu->LUstruct,&lu->SOLVEstruct,berr,&stat,&info));
178 #endif
179   }
180   if (info) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"pdgssvx fails, info: %d\n",info);
181 
182   if (lu->options.PrintStat) PStatPrint(&lu->options, &stat, &lu->grid);      /* Print the statistics. */
183   PetscStackCall("SuperLU_DIST:PStatFree",PStatFree(&stat));
184 
185   if (size > 1 && lu->MatInputMode == GLOBAL) {
186     /* convert seq x to mpi x */
187     ierr = VecRestoreArray(x_seq,&bptr);CHKERRQ(ierr);
188     ierr = VecScatterBegin(scat,x_seq,x,INSERT_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
189     ierr = VecScatterEnd(scat,x_seq,x,INSERT_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
190     ierr = VecScatterDestroy(&scat);CHKERRQ(ierr);
191     ierr = VecDestroy(&x_seq);CHKERRQ(ierr);
192   } else {
193     ierr = VecRestoreArray(x,&bptr);CHKERRQ(ierr);
194 
195     lu->matsolve_iscalled    = PETSC_TRUE;
196     lu->matmatsolve_iscalled = PETSC_FALSE;
197   }
198   PetscFunctionReturn(0);
199 }
200 
201 #undef __FUNCT__
202 #define __FUNCT__ "MatMatSolve_SuperLU_DIST"
203 static PetscErrorCode MatMatSolve_SuperLU_DIST(Mat A,Mat B_mpi,Mat X)
204 {
205   Mat_SuperLU_DIST *lu = (Mat_SuperLU_DIST*)A->data;
206   PetscErrorCode   ierr;
207   PetscMPIInt      size;
208   PetscInt         M=A->rmap->N,m=A->rmap->n,nrhs;
209   SuperLUStat_t    stat;
210   double           berr[1];
211   PetscScalar      *bptr;
212   int              info; /* SuperLU_Dist info code is ALWAYS an int, even with long long indices */
213   PetscBool        flg;
214 
215   PetscFunctionBegin;
216   if (lu->options.Fact != FACTORED) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"SuperLU_DIST options.Fact mush equal FACTORED");
217   ierr = PetscObjectTypeCompareAny((PetscObject)B_mpi,&flg,MATSEQDENSE,MATMPIDENSE,NULL);CHKERRQ(ierr);
218   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
219   ierr = PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);CHKERRQ(ierr);
220   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");
221 
222   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRQ(ierr);
223   if (size > 1 && lu->MatInputMode == GLOBAL) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatInputMode=GLOBAL for nproc %d>1 is not supported",size);
224   /* size==1 or distributed mat input */
225   if (lu->options.SolveInitialized && !lu->matmatsolve_iscalled) {
226     /* communication pattern of SOLVEstruct is unlikely created for matmatsolve,
227        thus destroy it and create a new SOLVEstruct.
228        Otherwise it may result in memory corruption or incorrect solution
229        See src/mat/examples/tests/ex125.c */
230 #if defined(PETSC_USE_COMPLEX)
231     PetscStackCall("SuperLU_DIST:zSolveFinalize",zSolveFinalize(&lu->options, &lu->SOLVEstruct));
232 #else
233     PetscStackCall("SuperLU_DIST:dSolveFinalize",dSolveFinalize(&lu->options, &lu->SOLVEstruct));
234 #endif
235     lu->options.SolveInitialized = NO;
236   }
237   ierr = MatCopy(B_mpi,X,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
238 
239   ierr = MatGetSize(B_mpi,NULL,&nrhs);CHKERRQ(ierr);
240 
241   PetscStackCall("SuperLU_DIST:PStatInit",PStatInit(&stat));        /* Initialize the statistics variables. */
242   ierr = MatDenseGetArray(X,&bptr);CHKERRQ(ierr);
243   if (lu->MatInputMode == GLOBAL) { /* size == 1 */
244 #if defined(PETSC_USE_COMPLEX)
245     PetscStackCall("SuperLU_DIST:pzgssvx_ABglobal",pzgssvx_ABglobal(&lu->options, &lu->A_sup, &lu->ScalePermstruct,(doublecomplex*)bptr, M, nrhs,&lu->grid, &lu->LUstruct, berr, &stat, &info));
246 #else
247     PetscStackCall("SuperLU_DIST:pdgssvx_ABglobal",pdgssvx_ABglobal(&lu->options, &lu->A_sup, &lu->ScalePermstruct,bptr, M, nrhs, &lu->grid, &lu->LUstruct, berr, &stat, &info));
248 #endif
249   } else { /* distributed mat input */
250 #if defined(PETSC_USE_COMPLEX)
251     PetscStackCall("SuperLU_DIST:pzgssvx",pzgssvx(&lu->options,&lu->A_sup,&lu->ScalePermstruct,(doublecomplex*)bptr,m,nrhs,&lu->grid, &lu->LUstruct,&lu->SOLVEstruct,berr,&stat,&info));
252 #else
253     PetscStackCall("SuperLU_DIST:pdgssvx",pdgssvx(&lu->options,&lu->A_sup,&lu->ScalePermstruct,bptr,m,nrhs,&lu->grid,&lu->LUstruct,&lu->SOLVEstruct,berr,&stat,&info));
254 #endif
255   }
256   if (info) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"pdgssvx fails, info: %d\n",info);
257   ierr = MatDenseRestoreArray(X,&bptr);CHKERRQ(ierr);
258 
259   if (lu->options.PrintStat) PStatPrint(&lu->options, &stat, &lu->grid); /* Print the statistics. */
260   PetscStackCall("SuperLU_DIST:PStatFree",PStatFree(&stat));
261   lu->matsolve_iscalled    = PETSC_FALSE;
262   lu->matmatsolve_iscalled = PETSC_TRUE;
263   PetscFunctionReturn(0);
264 }
265 
266 
267 #undef __FUNCT__
268 #define __FUNCT__ "MatLUFactorNumeric_SuperLU_DIST"
269 static PetscErrorCode MatLUFactorNumeric_SuperLU_DIST(Mat F,Mat A,const MatFactorInfo *info)
270 {
271   Mat              *tseq,A_seq = NULL;
272   Mat_SeqAIJ       *aa,*bb;
273   Mat_SuperLU_DIST *lu = (Mat_SuperLU_DIST*)(F)->data;
274   PetscErrorCode   ierr;
275   PetscInt         M=A->rmap->N,N=A->cmap->N,i,*ai,*aj,*bi,*bj,nz,rstart,*garray,
276                    m=A->rmap->n, colA_start,j,jcol,jB,countA,countB,*bjj,*ajj;
277   int              sinfo;   /* SuperLU_Dist info flag is always an int even with long long indices */
278   PetscMPIInt      size;
279   SuperLUStat_t    stat;
280   double           *berr=0;
281   IS               isrow;
282 #if defined(PETSC_USE_COMPLEX)
283   doublecomplex    *av, *bv;
284 #else
285   double           *av, *bv;
286 #endif
287 
288   PetscFunctionBegin;
289   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRQ(ierr);
290 
291   if (lu->MatInputMode == GLOBAL) { /* global mat input */
292     if (size > 1) { /* convert mpi A to seq mat A */
293       ierr = ISCreateStride(PETSC_COMM_SELF,M,0,1,&isrow);CHKERRQ(ierr);
294       ierr = MatGetSubMatrices(A,1,&isrow,&isrow,MAT_INITIAL_MATRIX,&tseq);CHKERRQ(ierr);
295       ierr = ISDestroy(&isrow);CHKERRQ(ierr);
296 
297       A_seq = *tseq;
298       ierr  = PetscFree(tseq);CHKERRQ(ierr);
299       aa    = (Mat_SeqAIJ*)A_seq->data;
300     } else {
301       PetscBool flg;
302       ierr = PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&flg);CHKERRQ(ierr);
303       if (flg) {
304         Mat_MPIAIJ *At = (Mat_MPIAIJ*)A->data;
305         A = At->A;
306       }
307       aa =  (Mat_SeqAIJ*)A->data;
308     }
309 
310     /* Convert Petsc NR matrix to SuperLU_DIST NC.
311        Note: memories of lu->val, col and row are allocated by CompRow_to_CompCol_dist()! */
312     if (lu->options.Fact != DOFACT) {/* successive numeric factorization, sparsity pattern is reused. */
313       PetscStackCall("SuperLU_DIST:Destroy_CompCol_Matrix_dist",Destroy_CompCol_Matrix_dist(&lu->A_sup));
314       if (lu->FactPattern == SamePattern_SameRowPerm) {
315         lu->options.Fact = SamePattern_SameRowPerm; /* matrix has similar numerical values */
316       } else { /* lu->FactPattern == SamePattern */
317         PetscStackCall("SuperLU_DIST:Destroy_LU",Destroy_LU(N, &lu->grid, &lu->LUstruct));
318         lu->options.Fact = SamePattern;
319       }
320     }
321 #if defined(PETSC_USE_COMPLEX)
322     PetscStackCall("SuperLU_DIST:zCompRow_to_CompCol_dist",zCompRow_to_CompCol_dist(M,N,aa->nz,(doublecomplex*)aa->a,(int_t*)aa->j,(int_t*)aa->i,&lu->val,&lu->col, &lu->row));
323 #else
324     PetscStackCall("SuperLU_DIST:dCompRow_to_CompCol_dist",dCompRow_to_CompCol_dist(M,N,aa->nz,aa->a,(int_t*)aa->j,(int_t*)aa->i,&lu->val, &lu->col, &lu->row));
325 #endif
326 
327     /* Create compressed column matrix A_sup. */
328 #if defined(PETSC_USE_COMPLEX)
329     PetscStackCall("SuperLU_DIST:zCreate_CompCol_Matrix_dist",zCreate_CompCol_Matrix_dist(&lu->A_sup, M, N, aa->nz, lu->val, lu->col, lu->row, SLU_NC, SLU_Z, SLU_GE));
330 #else
331     PetscStackCall("SuperLU_DIST:dCreate_CompCol_Matrix_dist",dCreate_CompCol_Matrix_dist(&lu->A_sup, M, N, aa->nz, lu->val, lu->col, lu->row, SLU_NC, SLU_D, SLU_GE));
332 #endif
333   } else { /* distributed mat input */
334     Mat_MPIAIJ *mat = (Mat_MPIAIJ*)A->data;
335     aa=(Mat_SeqAIJ*)(mat->A)->data;
336     bb=(Mat_SeqAIJ*)(mat->B)->data;
337     ai=aa->i; aj=aa->j;
338     bi=bb->i; bj=bb->j;
339 #if defined(PETSC_USE_COMPLEX)
340     av=(doublecomplex*)aa->a;
341     bv=(doublecomplex*)bb->a;
342 #else
343     av=aa->a;
344     bv=bb->a;
345 #endif
346     rstart = A->rmap->rstart;
347     nz     = aa->nz + bb->nz;
348     garray = mat->garray;
349 
350     if (lu->options.Fact == DOFACT) { /* first numeric factorization */
351 #if defined(PETSC_USE_COMPLEX)
352       PetscStackCall("SuperLU_DIST:zallocateA_dist",zallocateA_dist(m, nz, &lu->val, &lu->col, &lu->row));
353 #else
354       PetscStackCall("SuperLU_DIST:dallocateA_dist",dallocateA_dist(m, nz, &lu->val, &lu->col, &lu->row));
355 #endif
356     } else { /* successive numeric factorization, sparsity pattern and perm_c are reused. */
357       if (lu->FactPattern == SamePattern_SameRowPerm) {
358         lu->options.Fact = SamePattern_SameRowPerm; /* matrix has similar numerical values */
359       } else if (lu->FactPattern == SamePattern) {
360         PetscStackCall("SuperLU_DIST:Destroy_LU",Destroy_LU(N, &lu->grid, &lu->LUstruct)); /* Deallocate L and U matrices. */
361         lu->options.Fact = SamePattern;
362       } else if (lu->FactPattern == DOFACT) {
363         PetscStackCall("SuperLU_DIST:Destroy_CompRowLoc_Matrix_dist",Destroy_CompRowLoc_Matrix_dist(&lu->A_sup));
364         PetscStackCall("SuperLU_DIST:Destroy_LU",Destroy_LU(N, &lu->grid, &lu->LUstruct));
365         lu->options.Fact = DOFACT;
366 
367 #if defined(PETSC_USE_COMPLEX)
368       PetscStackCall("SuperLU_DIST:zallocateA_dist",zallocateA_dist(m, nz, &lu->val, &lu->col, &lu->row));
369 #else
370       PetscStackCall("SuperLU_DIST:dallocateA_dist",dallocateA_dist(m, nz, &lu->val, &lu->col, &lu->row));
371 #endif
372       } else {
373         SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"options.Fact must be one of SamePattern SamePattern_SameRowPerm DOFACT");
374       }
375     }
376     nz = 0;
377     for (i=0; i<m; i++) {
378       lu->row[i] = nz;
379       countA     = ai[i+1] - ai[i];
380       countB     = bi[i+1] - bi[i];
381       if (aj) {
382         ajj = aj + ai[i]; /* ptr to the beginning of this row */
383       } else {
384         ajj = NULL;
385       }
386       bjj = bj + bi[i];
387 
388       /* B part, smaller col index */
389       if (aj) {
390         colA_start = rstart + ajj[0]; /* the smallest global col index of A */
391       } else { /* superlu_dist does not require matrix has diagonal entries, thus aj=NULL would work */
392         colA_start = rstart;
393       }
394       jB         = 0;
395       for (j=0; j<countB; j++) {
396         jcol = garray[bjj[j]];
397         if (jcol > colA_start) {
398           jB = j;
399           break;
400         }
401         lu->col[nz]   = jcol;
402         lu->val[nz++] = *bv++;
403         if (j==countB-1) jB = countB;
404       }
405 
406       /* A part */
407       for (j=0; j<countA; j++) {
408         lu->col[nz]   = rstart + ajj[j];
409         lu->val[nz++] = *av++;
410       }
411 
412       /* B part, larger col index */
413       for (j=jB; j<countB; j++) {
414         lu->col[nz]   = garray[bjj[j]];
415         lu->val[nz++] = *bv++;
416       }
417     }
418     lu->row[m] = nz;
419 
420     if (lu->options.Fact == DOFACT) {
421 #if defined(PETSC_USE_COMPLEX)
422       PetscStackCall("SuperLU_DIST:zCreate_CompRowLoc_Matrix_dist",zCreate_CompRowLoc_Matrix_dist(&lu->A_sup, M, N, nz, m, rstart,lu->val, lu->col, lu->row, SLU_NR_loc, SLU_Z, SLU_GE));
423 #else
424       PetscStackCall("SuperLU_DIST:dCreate_CompRowLoc_Matrix_dist",dCreate_CompRowLoc_Matrix_dist(&lu->A_sup, M, N, nz, m, rstart,lu->val, lu->col, lu->row, SLU_NR_loc, SLU_D, SLU_GE));
425 #endif
426     }
427   }
428 
429   /* Factor the matrix. */
430   PetscStackCall("SuperLU_DIST:PStatInit",PStatInit(&stat));   /* Initialize the statistics variables. */
431   if (lu->MatInputMode == GLOBAL) { /* global mat input */
432 #if defined(PETSC_USE_COMPLEX)
433     PetscStackCall("SuperLU_DIST:pzgssvx_ABglobal",pzgssvx_ABglobal(&lu->options, &lu->A_sup, &lu->ScalePermstruct, 0, M, 0,&lu->grid, &lu->LUstruct, berr, &stat, &sinfo));
434 #else
435     PetscStackCall("SuperLU_DIST:pdgssvx_ABglobal",pdgssvx_ABglobal(&lu->options, &lu->A_sup, &lu->ScalePermstruct, 0, M, 0,&lu->grid, &lu->LUstruct, berr, &stat, &sinfo));
436 #endif
437   } else { /* distributed mat input */
438 #if defined(PETSC_USE_COMPLEX)
439     PetscStackCall("SuperLU_DIST:pzgssvx",pzgssvx(&lu->options, &lu->A_sup, &lu->ScalePermstruct, 0, m, 0, &lu->grid,&lu->LUstruct, &lu->SOLVEstruct, berr, &stat, &sinfo));
440 #else
441     PetscStackCall("SuperLU_DIST:pdgssvx",pdgssvx(&lu->options, &lu->A_sup, &lu->ScalePermstruct, 0, m, 0, &lu->grid,&lu->LUstruct, &lu->SOLVEstruct, berr, &stat, &sinfo));
442 #endif
443   }
444 
445   if (sinfo > 0) {
446     if (A->erroriffailure) {
447       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_MAT_LU_ZRPVT,"Zero pivot in row %D",sinfo);
448     } else {
449       if (sinfo <= lu->A_sup.ncol) {
450         F->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
451         ierr = PetscInfo1(F,"U(i,i) is exactly zero, i= %D\n",sinfo);CHKERRQ(ierr);
452       } else if (sinfo > lu->A_sup.ncol) {
453         /*
454          number of bytes allocated when memory allocation
455          failure occurred, plus A->ncol.
456          */
457         F->factorerrortype = MAT_FACTOR_OUTMEMORY;
458         ierr = PetscInfo1(F,"Number of bytes allocated when memory allocation fails %D\n",sinfo);CHKERRQ(ierr);
459       }
460     }
461   } else if (sinfo < 0) {
462     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB, "info = %D, argument in p*gssvx() had an illegal value", sinfo);
463   }
464 
465   if (lu->MatInputMode == GLOBAL && size > 1) {
466     ierr = MatDestroy(&A_seq);CHKERRQ(ierr);
467   }
468 
469   if (lu->options.PrintStat) {
470     PStatPrint(&lu->options, &stat, &lu->grid);  /* Print the statistics. */
471   }
472   PetscStackCall("SuperLU_DIST:PStatFree",PStatFree(&stat));
473   (F)->assembled    = PETSC_TRUE;
474   (F)->preallocated = PETSC_TRUE;
475   lu->options.Fact  = FACTORED; /* The factored form of A is supplied. Local option used by this func. only */
476   PetscFunctionReturn(0);
477 }
478 
479 /* Note the Petsc r and c permutations are ignored */
480 #undef __FUNCT__
481 #define __FUNCT__ "MatLUFactorSymbolic_SuperLU_DIST"
482 static PetscErrorCode MatLUFactorSymbolic_SuperLU_DIST(Mat F,Mat A,IS r,IS c,const MatFactorInfo *info)
483 {
484   Mat_SuperLU_DIST *lu = (Mat_SuperLU_DIST*)F->data;
485   PetscInt         M   = A->rmap->N,N=A->cmap->N;
486 
487   PetscFunctionBegin;
488   /* Initialize the SuperLU process grid. */
489   PetscStackCall("SuperLU_DIST:superlu_gridinit",superlu_gridinit(lu->comm_superlu, lu->nprow, lu->npcol, &lu->grid));
490 
491   /* Initialize ScalePermstruct and LUstruct. */
492   PetscStackCall("SuperLU_DIST:ScalePermstructInit",ScalePermstructInit(M, N, &lu->ScalePermstruct));
493   PetscStackCall("SuperLU_DIST:LUstructInit",LUstructInit(N, &lu->LUstruct));
494   F->ops->lufactornumeric = MatLUFactorNumeric_SuperLU_DIST;
495   F->ops->solve           = MatSolve_SuperLU_DIST;
496   F->ops->matsolve        = MatMatSolve_SuperLU_DIST;
497   lu->CleanUpSuperLU_Dist = PETSC_TRUE;
498   PetscFunctionReturn(0);
499 }
500 
501 #undef __FUNCT__
502 #define __FUNCT__ "MatFactorGetSolverPackage_aij_superlu_dist"
503 static PetscErrorCode MatFactorGetSolverPackage_aij_superlu_dist(Mat A,const MatSolverPackage *type)
504 {
505   PetscFunctionBegin;
506   *type = MATSOLVERSUPERLU_DIST;
507   PetscFunctionReturn(0);
508 }
509 
510 #undef __FUNCT__
511 #define __FUNCT__ "MatFactorInfo_SuperLU_DIST"
512 static PetscErrorCode MatFactorInfo_SuperLU_DIST(Mat A,PetscViewer viewer)
513 {
514   Mat_SuperLU_DIST       *lu=(Mat_SuperLU_DIST*)A->data;
515   superlu_dist_options_t options;
516   PetscErrorCode         ierr;
517 
518   PetscFunctionBegin;
519   /* check if matrix is superlu_dist type */
520   if (A->ops->solve != MatSolve_SuperLU_DIST) PetscFunctionReturn(0);
521 
522   options = lu->options;
523   ierr    = PetscViewerASCIIPrintf(viewer,"SuperLU_DIST run parameters:\n");CHKERRQ(ierr);
524   ierr    = PetscViewerASCIIPrintf(viewer,"  Process grid nprow %D x npcol %D \n",lu->nprow,lu->npcol);CHKERRQ(ierr);
525   ierr    = PetscViewerASCIIPrintf(viewer,"  Equilibrate matrix %s \n",PetscBools[options.Equil != NO]);CHKERRQ(ierr);
526   ierr    = PetscViewerASCIIPrintf(viewer,"  Matrix input mode %d \n",lu->MatInputMode);CHKERRQ(ierr);
527   ierr    = PetscViewerASCIIPrintf(viewer,"  Replace tiny pivots %s \n",PetscBools[options.ReplaceTinyPivot != NO]);CHKERRQ(ierr);
528   ierr    = PetscViewerASCIIPrintf(viewer,"  Use iterative refinement %s \n",PetscBools[options.IterRefine == SLU_DOUBLE]);CHKERRQ(ierr);
529   ierr    = PetscViewerASCIIPrintf(viewer,"  Processors in row %d col partition %d \n",lu->nprow,lu->npcol);CHKERRQ(ierr);
530   ierr    = PetscViewerASCIIPrintf(viewer,"  Row permutation %s \n",(options.RowPerm == NOROWPERM) ? "NATURAL" : "LargeDiag");CHKERRQ(ierr);
531 
532   switch (options.ColPerm) {
533   case NATURAL:
534     ierr = PetscViewerASCIIPrintf(viewer,"  Column permutation NATURAL\n");CHKERRQ(ierr);
535     break;
536   case MMD_AT_PLUS_A:
537     ierr = PetscViewerASCIIPrintf(viewer,"  Column permutation MMD_AT_PLUS_A\n");CHKERRQ(ierr);
538     break;
539   case MMD_ATA:
540     ierr = PetscViewerASCIIPrintf(viewer,"  Column permutation MMD_ATA\n");CHKERRQ(ierr);
541     break;
542   case METIS_AT_PLUS_A:
543     ierr = PetscViewerASCIIPrintf(viewer,"  Column permutation METIS_AT_PLUS_A\n");CHKERRQ(ierr);
544     break;
545   case PARMETIS:
546     ierr = PetscViewerASCIIPrintf(viewer,"  Column permutation PARMETIS\n");CHKERRQ(ierr);
547     break;
548   default:
549     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Unknown column permutation");
550   }
551 
552   ierr = PetscViewerASCIIPrintf(viewer,"  Parallel symbolic factorization %s \n",PetscBools[options.ParSymbFact != NO]);CHKERRQ(ierr);
553 
554   if (lu->FactPattern == SamePattern) {
555     ierr = PetscViewerASCIIPrintf(viewer,"  Repeated factorization SamePattern\n");CHKERRQ(ierr);
556   } else if (lu->FactPattern == SamePattern_SameRowPerm) {
557     ierr = PetscViewerASCIIPrintf(viewer,"  Repeated factorization SamePattern_SameRowPerm\n");CHKERRQ(ierr);
558   } else if (lu->FactPattern == DOFACT) {
559     ierr = PetscViewerASCIIPrintf(viewer,"  Repeated factorization DOFACT\n");CHKERRQ(ierr);
560   } else {
561     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Unknown factorization pattern");
562   }
563   PetscFunctionReturn(0);
564 }
565 
566 #undef __FUNCT__
567 #define __FUNCT__ "MatView_SuperLU_DIST"
568 static PetscErrorCode MatView_SuperLU_DIST(Mat A,PetscViewer viewer)
569 {
570   PetscErrorCode    ierr;
571   PetscBool         iascii;
572   PetscViewerFormat format;
573 
574   PetscFunctionBegin;
575   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
576   if (iascii) {
577     ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
578     if (format == PETSC_VIEWER_ASCII_INFO) {
579       ierr = MatFactorInfo_SuperLU_DIST(A,viewer);CHKERRQ(ierr);
580     }
581   }
582   PetscFunctionReturn(0);
583 }
584 
585 #undef __FUNCT__
586 #define __FUNCT__ "MatGetFactor_aij_superlu_dist"
587 static PetscErrorCode MatGetFactor_aij_superlu_dist(Mat A,MatFactorType ftype,Mat *F)
588 {
589   Mat                    B;
590   Mat_SuperLU_DIST       *lu;
591   PetscErrorCode         ierr;
592   PetscInt               M=A->rmap->N,N=A->cmap->N,indx;
593   PetscMPIInt            size;
594   superlu_dist_options_t options;
595   PetscBool              flg;
596   const char             *colperm[]     = {"NATURAL","MMD_AT_PLUS_A","MMD_ATA","METIS_AT_PLUS_A","PARMETIS"};
597   const char             *rowperm[]     = {"LargeDiag","NATURAL"};
598   const char             *factPattern[] = {"SamePattern","SamePattern_SameRowPerm","DOFACT"};
599   PetscBool              set;
600 
601   PetscFunctionBegin;
602   /* Create the factorization matrix */
603   ierr = MatCreate(PetscObjectComm((PetscObject)A),&B);CHKERRQ(ierr);
604   ierr = MatSetSizes(B,A->rmap->n,A->cmap->n,M,N);CHKERRQ(ierr);
605   ierr = PetscStrallocpy("superlu_dist",&((PetscObject)B)->type_name);CHKERRQ(ierr);
606   ierr = MatSetUp(B);CHKERRQ(ierr);
607   B->ops->getinfo          = MatGetInfo_External;
608   B->ops->lufactorsymbolic = MatLUFactorSymbolic_SuperLU_DIST;
609   B->ops->view             = MatView_SuperLU_DIST;
610   B->ops->destroy          = MatDestroy_SuperLU_DIST;
611 
612   B->factortype = MAT_FACTOR_LU;
613 
614   /* set solvertype */
615   ierr = PetscFree(B->solvertype);CHKERRQ(ierr);
616   ierr = PetscStrallocpy(MATSOLVERSUPERLU_DIST,&B->solvertype);CHKERRQ(ierr);
617 
618   ierr    = PetscNewLog(B,&lu);CHKERRQ(ierr);
619   B->data = lu;
620 
621   /* Set the default input options:
622      options.Fact              = DOFACT;
623      options.Equil             = YES;
624      options.ParSymbFact       = NO;
625      options.ColPerm           = METIS_AT_PLUS_A;
626      options.RowPerm           = LargeDiag;
627      options.ReplaceTinyPivot  = YES;
628      options.IterRefine        = DOUBLE;
629      options.Trans             = NOTRANS;
630      options.SolveInitialized  = NO; -hold the communication pattern used MatSolve() and MatMatSolve()
631      options.RefineInitialized = NO;
632      options.PrintStat         = YES;
633   */
634   set_default_options_dist(&options);
635 
636   ierr = MPI_Comm_dup(PetscObjectComm((PetscObject)A),&(lu->comm_superlu));CHKERRQ(ierr);
637   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);CHKERRQ(ierr);
638   /* Default num of process columns and rows */
639   lu->npcol = (int_t) (0.5 + PetscSqrtReal((PetscReal)size));
640   if (!lu->npcol) lu->npcol = 1;
641   while (lu->npcol > 0) {
642     lu->nprow = (int_t) (size/lu->npcol);
643     if (size == lu->nprow * lu->npcol) break;
644     lu->npcol--;
645   }
646 
647   ierr = PetscOptionsBegin(PetscObjectComm((PetscObject)A),((PetscObject)A)->prefix,"SuperLU_Dist Options","Mat");CHKERRQ(ierr);
648   ierr = PetscOptionsInt("-mat_superlu_dist_r","Number rows in processor partition","None",lu->nprow,(PetscInt*)&lu->nprow,NULL);CHKERRQ(ierr);
649   ierr = PetscOptionsInt("-mat_superlu_dist_c","Number columns in processor partition","None",lu->npcol,(PetscInt*)&lu->npcol,NULL);CHKERRQ(ierr);
650   if (size != lu->nprow * lu->npcol) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of processes %d must equal to nprow %d * npcol %d",size,lu->nprow,lu->npcol);
651 
652   lu->MatInputMode = DISTRIBUTED;
653 
654   ierr = PetscOptionsEnum("-mat_superlu_dist_matinput","Matrix input mode (global or distributed)","None",SuperLU_MatInputModes,(PetscEnum)lu->MatInputMode,(PetscEnum*)&lu->MatInputMode,NULL);CHKERRQ(ierr);
655   if (lu->MatInputMode == DISTRIBUTED && size == 1) lu->MatInputMode = GLOBAL;
656 
657   ierr = PetscOptionsBool("-mat_superlu_dist_equil","Equilibrate matrix","None",options.Equil ? PETSC_TRUE : PETSC_FALSE,&flg,&set);CHKERRQ(ierr);
658   if (set && !flg) options.Equil = NO;
659 
660   ierr = PetscOptionsEList("-mat_superlu_dist_rowperm","Row permutation","None",rowperm,2,rowperm[0],&indx,&flg);CHKERRQ(ierr);
661   if (flg) {
662     switch (indx) {
663     case 0:
664       options.RowPerm = LargeDiag;
665       break;
666     case 1:
667       options.RowPerm = NOROWPERM;
668       break;
669     }
670   }
671 
672   ierr = PetscOptionsEList("-mat_superlu_dist_colperm","Column permutation","None",colperm,5,colperm[3],&indx,&flg);CHKERRQ(ierr);
673   if (flg) {
674     switch (indx) {
675     case 0:
676       options.ColPerm = NATURAL;
677       break;
678     case 1:
679       options.ColPerm = MMD_AT_PLUS_A;
680       break;
681     case 2:
682       options.ColPerm = MMD_ATA;
683       break;
684     case 3:
685       options.ColPerm = METIS_AT_PLUS_A;
686       break;
687     case 4:
688       options.ColPerm = PARMETIS;   /* only works for np>1 */
689       break;
690     default:
691       SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Unknown column permutation");
692     }
693   }
694 
695   options.ReplaceTinyPivot = NO;
696   ierr = PetscOptionsBool("-mat_superlu_dist_replacetinypivot","Replace tiny pivots","None",options.ReplaceTinyPivot ? PETSC_TRUE : PETSC_FALSE,&flg,&set);CHKERRQ(ierr);
697   if (set && flg) options.ReplaceTinyPivot = YES;
698 
699   options.ParSymbFact = NO;
700   ierr = PetscOptionsBool("-mat_superlu_dist_parsymbfact","Parallel symbolic factorization","None",PETSC_FALSE,&flg,&set);CHKERRQ(ierr);
701   if (set && flg && size>1) {
702     if (lu->MatInputMode == GLOBAL) {
703 #if defined(PETSC_USE_INFO)
704       ierr = PetscInfo(A,"Warning: '-mat_superlu_dist_parsymbfact' is ignored because MatInputMode=GLOBAL\n");CHKERRQ(ierr);
705 #endif
706     } else {
707 #if defined(PETSC_HAVE_PARMETIS)
708       options.ParSymbFact = YES;
709       options.ColPerm     = PARMETIS;   /* in v2.2, PARMETIS is forced for ParSymbFact regardless of user ordering setting */
710 #else
711       SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"parsymbfact needs PARMETIS");
712 #endif
713     }
714   }
715 
716   lu->FactPattern = SamePattern;
717   ierr = PetscOptionsEList("-mat_superlu_dist_fact","Sparsity pattern for repeated matrix factorization","None",factPattern,3,factPattern[0],&indx,&flg);CHKERRQ(ierr);
718   if (flg) {
719     switch (indx) {
720     case 0:
721       lu->FactPattern = SamePattern;
722       break;
723     case 1:
724       lu->FactPattern = SamePattern_SameRowPerm;
725       break;
726     case 2:
727       lu->FactPattern = DOFACT;
728       break;
729     }
730   }
731 
732   options.IterRefine = NOREFINE;
733   ierr               = PetscOptionsBool("-mat_superlu_dist_iterrefine","Use iterative refinement","None",options.IterRefine == NOREFINE ? PETSC_FALSE : PETSC_TRUE ,&flg,&set);CHKERRQ(ierr);
734   if (set) {
735     if (flg) options.IterRefine = SLU_DOUBLE;
736     else options.IterRefine = NOREFINE;
737   }
738 
739   if (PetscLogPrintInfo) options.PrintStat = YES;
740   else options.PrintStat = NO;
741   ierr = PetscOptionsBool("-mat_superlu_dist_statprint","Print factorization information","None",(PetscBool)options.PrintStat,(PetscBool*)&options.PrintStat,NULL);CHKERRQ(ierr);
742   ierr = PetscOptionsEnd();CHKERRQ(ierr);
743 
744   lu->options              = options;
745   lu->options.Fact         = DOFACT;
746   lu->matsolve_iscalled    = PETSC_FALSE;
747   lu->matmatsolve_iscalled = PETSC_FALSE;
748 
749   ierr = PetscObjectComposeFunction((PetscObject)B,"MatFactorGetSolverPackage_C",MatFactorGetSolverPackage_aij_superlu_dist);CHKERRQ(ierr);
750   ierr = PetscObjectComposeFunction((PetscObject)B,"MatSuperluDistGetDiagU_C",MatSuperluDistGetDiagU_SuperLU_DIST);CHKERRQ(ierr);
751 
752   *F = B;
753   PetscFunctionReturn(0);
754 }
755 
756 #undef __FUNCT__
757 #define __FUNCT__ "MatSolverPackageRegister_SuperLU_DIST"
758 PETSC_EXTERN PetscErrorCode MatSolverPackageRegister_SuperLU_DIST(void)
759 {
760   PetscErrorCode ierr;
761   PetscFunctionBegin;
762   ierr = MatSolverPackageRegister(MATSOLVERSUPERLU_DIST,MATMPIAIJ,  MAT_FACTOR_LU,MatGetFactor_aij_superlu_dist);CHKERRQ(ierr);
763   ierr = MatSolverPackageRegister(MATSOLVERSUPERLU_DIST,MATSEQAIJ,  MAT_FACTOR_LU,MatGetFactor_aij_superlu_dist);CHKERRQ(ierr);
764   PetscFunctionReturn(0);
765 }
766 
767 /*MC
768   MATSOLVERSUPERLU_DIST - Parallel direct solver package for LU factorization
769 
770   Use ./configure --download-superlu_dist --download-parmetis --download-metis --download-ptscotch  to have PETSc installed with SuperLU_DIST
771 
772   Use -pc_type lu -pc_factor_mat_solver_package superlu_dist to us this direct solver
773 
774    Works with AIJ matrices
775 
776   Options Database Keys:
777 + -mat_superlu_dist_r <n> - number of rows in processor partition
778 . -mat_superlu_dist_c <n> - number of columns in processor partition
779 . -mat_superlu_dist_matinput <0,1> - matrix input mode; 0=global, 1=distributed
780 . -mat_superlu_dist_equil - equilibrate the matrix
781 . -mat_superlu_dist_rowperm <LargeDiag,NATURAL> - row permutation
782 . -mat_superlu_dist_colperm <MMD_AT_PLUS_A,MMD_ATA,NATURAL> - column permutation
783 . -mat_superlu_dist_replacetinypivot - replace tiny pivots
784 . -mat_superlu_dist_fact <SamePattern> - (choose one of) SamePattern SamePattern_SameRowPerm DOFACT
785 . -mat_superlu_dist_iterrefine - use iterative refinement
786 - -mat_superlu_dist_statprint - print factorization information
787 
788    Level: beginner
789 
790 .seealso: PCLU
791 
792 .seealso: PCFactorSetMatSolverPackage(), MatSolverPackage
793 
794 M*/
795