xref: /petsc/src/mat/impls/aij/mpi/mpiaij.c (revision c79c55279c2f638f1e2600b27e73cde5e9f73b5c)
18a729477SBarry Smith 
2c6db04a5SJed Brown #include <../src/mat/impls/aij/mpi/mpiaij.h>   /*I "petscmat.h" I*/
39a6d0b0bSJed Brown #include <petsc-private/vecimpl.h>
4c6db04a5SJed Brown #include <petscblaslapack.h>
50c312b8eSJed Brown #include <petscsf.h>
68a729477SBarry Smith 
701bebe75SBarry Smith /*MC
801bebe75SBarry Smith    MATAIJ - MATAIJ = "aij" - A matrix type to be used for sparse matrices.
901bebe75SBarry Smith 
1001bebe75SBarry Smith    This matrix type is identical to MATSEQAIJ when constructed with a single process communicator,
1101bebe75SBarry Smith    and MATMPIAIJ otherwise.  As a result, for single process communicators,
1201bebe75SBarry Smith   MatSeqAIJSetPreallocation is supported, and similarly MatMPIAIJSetPreallocation is supported
1301bebe75SBarry Smith   for communicators controlling multiple processes.  It is recommended that you call both of
1401bebe75SBarry Smith   the above preallocation routines for simplicity.
1501bebe75SBarry Smith 
1601bebe75SBarry Smith    Options Database Keys:
1701bebe75SBarry Smith . -mat_type aij - sets the matrix type to "aij" during a call to MatSetFromOptions()
1801bebe75SBarry Smith 
199ae82921SPaul Mullowney   Developer Notes: Subclasses include MATAIJCUSP, MATAIJCUSPARSE, MATAIJPERM, MATAIJCRL, and also automatically switches over to use inodes when
2001bebe75SBarry Smith    enough exist.
2101bebe75SBarry Smith 
2201bebe75SBarry Smith   Level: beginner
2301bebe75SBarry Smith 
2469b1f4b7SBarry Smith .seealso: MatCreateAIJ(), MatCreateSeqAIJ(), MATSEQAIJ,MATMPIAIJ
2501bebe75SBarry Smith M*/
2601bebe75SBarry Smith 
2701bebe75SBarry Smith /*MC
2801bebe75SBarry Smith    MATAIJCRL - MATAIJCRL = "aijcrl" - A matrix type to be used for sparse matrices.
2901bebe75SBarry Smith 
3001bebe75SBarry Smith    This matrix type is identical to MATSEQAIJCRL when constructed with a single process communicator,
3101bebe75SBarry Smith    and MATMPIAIJCRL otherwise.  As a result, for single process communicators,
3201bebe75SBarry Smith    MatSeqAIJSetPreallocation() is supported, and similarly MatMPIAIJSetPreallocation() is supported
3301bebe75SBarry Smith   for communicators controlling multiple processes.  It is recommended that you call both of
3401bebe75SBarry Smith   the above preallocation routines for simplicity.
3501bebe75SBarry Smith 
3601bebe75SBarry Smith    Options Database Keys:
3701bebe75SBarry Smith . -mat_type aijcrl - sets the matrix type to "aijcrl" during a call to MatSetFromOptions()
3801bebe75SBarry Smith 
3901bebe75SBarry Smith   Level: beginner
4001bebe75SBarry Smith 
4101bebe75SBarry Smith .seealso: MatCreateMPIAIJCRL,MATSEQAIJCRL,MATMPIAIJCRL, MATSEQAIJCRL, MATMPIAIJCRL
4201bebe75SBarry Smith M*/
4301bebe75SBarry Smith 
44dd6ea824SBarry Smith #undef __FUNCT__
45f2c98031SJed Brown #define __FUNCT__ "MatFindNonzeroRows_MPIAIJ"
46f2c98031SJed Brown PetscErrorCode MatFindNonzeroRows_MPIAIJ(Mat M,IS *keptrows)
4727d4218bSShri Abhyankar {
4827d4218bSShri Abhyankar   PetscErrorCode  ierr;
4927d4218bSShri Abhyankar   Mat_MPIAIJ      *mat = (Mat_MPIAIJ*)M->data;
5027d4218bSShri Abhyankar   Mat_SeqAIJ      *a   = (Mat_SeqAIJ*)mat->A->data;
5127d4218bSShri Abhyankar   Mat_SeqAIJ      *b   = (Mat_SeqAIJ*)mat->B->data;
5227d4218bSShri Abhyankar   const PetscInt  *ia,*ib;
5327d4218bSShri Abhyankar   const MatScalar *aa,*bb;
5427d4218bSShri Abhyankar   PetscInt        na,nb,i,j,*rows,cnt=0,n0rows;
5527d4218bSShri Abhyankar   PetscInt        m = M->rmap->n,rstart = M->rmap->rstart;
5627d4218bSShri Abhyankar 
5727d4218bSShri Abhyankar   PetscFunctionBegin;
5827d4218bSShri Abhyankar   *keptrows = 0;
5927d4218bSShri Abhyankar   ia        = a->i;
6027d4218bSShri Abhyankar   ib        = b->i;
6127d4218bSShri Abhyankar   for (i=0; i<m; i++) {
6227d4218bSShri Abhyankar     na = ia[i+1] - ia[i];
6327d4218bSShri Abhyankar     nb = ib[i+1] - ib[i];
6427d4218bSShri Abhyankar     if (!na && !nb) {
6527d4218bSShri Abhyankar       cnt++;
6627d4218bSShri Abhyankar       goto ok1;
6727d4218bSShri Abhyankar     }
6827d4218bSShri Abhyankar     aa = a->a + ia[i];
6927d4218bSShri Abhyankar     for (j=0; j<na; j++) {
7027d4218bSShri Abhyankar       if (aa[j] != 0.0) goto ok1;
7127d4218bSShri Abhyankar     }
7227d4218bSShri Abhyankar     bb = b->a + ib[i];
7327d4218bSShri Abhyankar     for (j=0; j <nb; j++) {
7427d4218bSShri Abhyankar       if (bb[j] != 0.0) goto ok1;
7527d4218bSShri Abhyankar     }
7627d4218bSShri Abhyankar     cnt++;
7727d4218bSShri Abhyankar ok1:;
7827d4218bSShri Abhyankar   }
79ce94432eSBarry Smith   ierr = MPI_Allreduce(&cnt,&n0rows,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)M));CHKERRQ(ierr);
8027d4218bSShri Abhyankar   if (!n0rows) PetscFunctionReturn(0);
8127d4218bSShri Abhyankar   ierr = PetscMalloc((M->rmap->n-cnt)*sizeof(PetscInt),&rows);CHKERRQ(ierr);
8227d4218bSShri Abhyankar   cnt  = 0;
8327d4218bSShri Abhyankar   for (i=0; i<m; i++) {
8427d4218bSShri Abhyankar     na = ia[i+1] - ia[i];
8527d4218bSShri Abhyankar     nb = ib[i+1] - ib[i];
8627d4218bSShri Abhyankar     if (!na && !nb) continue;
8727d4218bSShri Abhyankar     aa = a->a + ia[i];
8827d4218bSShri Abhyankar     for (j=0; j<na;j++) {
8927d4218bSShri Abhyankar       if (aa[j] != 0.0) {
9027d4218bSShri Abhyankar         rows[cnt++] = rstart + i;
9127d4218bSShri Abhyankar         goto ok2;
9227d4218bSShri Abhyankar       }
9327d4218bSShri Abhyankar     }
9427d4218bSShri Abhyankar     bb = b->a + ib[i];
9527d4218bSShri Abhyankar     for (j=0; j<nb; j++) {
9627d4218bSShri Abhyankar       if (bb[j] != 0.0) {
9727d4218bSShri Abhyankar         rows[cnt++] = rstart + i;
9827d4218bSShri Abhyankar         goto ok2;
9927d4218bSShri Abhyankar       }
10027d4218bSShri Abhyankar     }
10127d4218bSShri Abhyankar ok2:;
10227d4218bSShri Abhyankar   }
103ce94432eSBarry Smith   ierr = ISCreateGeneral(PetscObjectComm((PetscObject)M),cnt,rows,PETSC_OWN_POINTER,keptrows);CHKERRQ(ierr);
10427d4218bSShri Abhyankar   PetscFunctionReturn(0);
10527d4218bSShri Abhyankar }
10627d4218bSShri Abhyankar 
10727d4218bSShri Abhyankar #undef __FUNCT__
108f1f41ecbSJed Brown #define __FUNCT__ "MatFindZeroDiagonals_MPIAIJ"
109f1f41ecbSJed Brown PetscErrorCode MatFindZeroDiagonals_MPIAIJ(Mat M,IS *zrows)
110f1f41ecbSJed Brown {
111f1f41ecbSJed Brown   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)M->data;
112f1f41ecbSJed Brown   PetscErrorCode ierr;
113f1f41ecbSJed Brown   PetscInt       i,rstart,nrows,*rows;
114f1f41ecbSJed Brown 
115f1f41ecbSJed Brown   PetscFunctionBegin;
1160298fd71SBarry Smith   *zrows = NULL;
117f1f41ecbSJed Brown   ierr   = MatFindZeroDiagonals_SeqAIJ_Private(aij->A,&nrows,&rows);CHKERRQ(ierr);
1180298fd71SBarry Smith   ierr   = MatGetOwnershipRange(M,&rstart,NULL);CHKERRQ(ierr);
119f1f41ecbSJed Brown   for (i=0; i<nrows; i++) rows[i] += rstart;
120ce94432eSBarry Smith   ierr = ISCreateGeneral(PetscObjectComm((PetscObject)M),nrows,rows,PETSC_OWN_POINTER,zrows);CHKERRQ(ierr);
121f1f41ecbSJed Brown   PetscFunctionReturn(0);
122f1f41ecbSJed Brown }
123f1f41ecbSJed Brown 
124f1f41ecbSJed Brown #undef __FUNCT__
1250716a85fSBarry Smith #define __FUNCT__ "MatGetColumnNorms_MPIAIJ"
1260716a85fSBarry Smith PetscErrorCode MatGetColumnNorms_MPIAIJ(Mat A,NormType type,PetscReal *norms)
1270716a85fSBarry Smith {
1280716a85fSBarry Smith   PetscErrorCode ierr;
1290716a85fSBarry Smith   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)A->data;
1300716a85fSBarry Smith   PetscInt       i,n,*garray = aij->garray;
1310716a85fSBarry Smith   Mat_SeqAIJ     *a_aij = (Mat_SeqAIJ*) aij->A->data;
1320716a85fSBarry Smith   Mat_SeqAIJ     *b_aij = (Mat_SeqAIJ*) aij->B->data;
1330716a85fSBarry Smith   PetscReal      *work;
1340716a85fSBarry Smith 
1350716a85fSBarry Smith   PetscFunctionBegin;
1360298fd71SBarry Smith   ierr = MatGetSize(A,NULL,&n);CHKERRQ(ierr);
1370716a85fSBarry Smith   ierr = PetscMalloc(n*sizeof(PetscReal),&work);CHKERRQ(ierr);
1380716a85fSBarry Smith   ierr = PetscMemzero(work,n*sizeof(PetscReal));CHKERRQ(ierr);
1390716a85fSBarry Smith   if (type == NORM_2) {
1400716a85fSBarry Smith     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
1410716a85fSBarry Smith       work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]*a_aij->a[i]);
1420716a85fSBarry Smith     }
1430716a85fSBarry Smith     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
1440716a85fSBarry Smith       work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]*b_aij->a[i]);
1450716a85fSBarry Smith     }
1460716a85fSBarry Smith   } else if (type == NORM_1) {
1470716a85fSBarry Smith     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
1480716a85fSBarry Smith       work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]);
1490716a85fSBarry Smith     }
1500716a85fSBarry Smith     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
1510716a85fSBarry Smith       work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]);
1520716a85fSBarry Smith     }
1530716a85fSBarry Smith   } else if (type == NORM_INFINITY) {
1540716a85fSBarry Smith     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
1550716a85fSBarry Smith       work[A->cmap->rstart + a_aij->j[i]] = PetscMax(PetscAbsScalar(a_aij->a[i]), work[A->cmap->rstart + a_aij->j[i]]);
1560716a85fSBarry Smith     }
1570716a85fSBarry Smith     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
1580716a85fSBarry Smith       work[garray[b_aij->j[i]]] = PetscMax(PetscAbsScalar(b_aij->a[i]),work[garray[b_aij->j[i]]]);
1590716a85fSBarry Smith     }
1600716a85fSBarry Smith 
161ce94432eSBarry Smith   } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Unknown NormType");
1620716a85fSBarry Smith   if (type == NORM_INFINITY) {
1630716a85fSBarry Smith     ierr = MPI_Allreduce(work,norms,n,MPIU_REAL,MPIU_MAX,A->hdr.comm);CHKERRQ(ierr);
1640716a85fSBarry Smith   } else {
1650716a85fSBarry Smith     ierr = MPI_Allreduce(work,norms,n,MPIU_REAL,MPIU_SUM,A->hdr.comm);CHKERRQ(ierr);
1660716a85fSBarry Smith   }
1670716a85fSBarry Smith   ierr = PetscFree(work);CHKERRQ(ierr);
1680716a85fSBarry Smith   if (type == NORM_2) {
1698f1a2a5eSBarry Smith     for (i=0; i<n; i++) norms[i] = PetscSqrtReal(norms[i]);
1700716a85fSBarry Smith   }
1710716a85fSBarry Smith   PetscFunctionReturn(0);
1720716a85fSBarry Smith }
1730716a85fSBarry Smith 
1740716a85fSBarry Smith #undef __FUNCT__
175dd6ea824SBarry Smith #define __FUNCT__ "MatDistribute_MPIAIJ"
176dd6ea824SBarry Smith /*
177dd6ea824SBarry Smith     Distributes a SeqAIJ matrix across a set of processes. Code stolen from
178dd6ea824SBarry Smith     MatLoad_MPIAIJ(). Horrible lack of reuse. Should be a routine for each matrix type.
179dd6ea824SBarry Smith 
180dd6ea824SBarry Smith     Only for square matrices
181b30237c6SBarry Smith 
182b30237c6SBarry Smith     Used by a preconditioner, hence PETSC_EXTERN
183dd6ea824SBarry Smith */
1845a576424SJed Brown PETSC_EXTERN PetscErrorCode MatDistribute_MPIAIJ(MPI_Comm comm,Mat gmat,PetscInt m,MatReuse reuse,Mat *inmat)
185dd6ea824SBarry Smith {
186dd6ea824SBarry Smith   PetscMPIInt    rank,size;
187efcf75d5SBarry Smith   PetscInt       *rowners,*dlens,*olens,i,rstart,rend,j,jj,nz,*gmataj,cnt,row,*ld,bses[2];
188dd6ea824SBarry Smith   PetscErrorCode ierr;
189dd6ea824SBarry Smith   Mat            mat;
190dd6ea824SBarry Smith   Mat_SeqAIJ     *gmata;
191dd6ea824SBarry Smith   PetscMPIInt    tag;
192dd6ea824SBarry Smith   MPI_Status     status;
193ace3abfcSBarry Smith   PetscBool      aij;
194dd6ea824SBarry Smith   MatScalar      *gmataa,*ao,*ad,*gmataarestore=0;
195dd6ea824SBarry Smith 
196dd6ea824SBarry Smith   PetscFunctionBegin;
197dd6ea824SBarry Smith   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
198dd6ea824SBarry Smith   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
199dd6ea824SBarry Smith   if (!rank) {
200251f4c67SDmitry Karpeev     ierr = PetscObjectTypeCompare((PetscObject)gmat,MATSEQAIJ,&aij);CHKERRQ(ierr);
201ce94432eSBarry Smith     if (!aij) SETERRQ1(PetscObjectComm((PetscObject)gmat),PETSC_ERR_SUP,"Currently no support for input matrix of type %s\n",((PetscObject)gmat)->type_name);
202dd6ea824SBarry Smith   }
203dd6ea824SBarry Smith   if (reuse == MAT_INITIAL_MATRIX) {
204dd6ea824SBarry Smith     ierr = MatCreate(comm,&mat);CHKERRQ(ierr);
205dd6ea824SBarry Smith     ierr = MatSetSizes(mat,m,m,PETSC_DETERMINE,PETSC_DETERMINE);CHKERRQ(ierr);
206efcf75d5SBarry Smith     if (!rank) {
207efcf75d5SBarry Smith       bses[0] = gmat->rmap->bs;
208efcf75d5SBarry Smith       bses[1] = gmat->cmap->bs;
209efcf75d5SBarry Smith     }
210efcf75d5SBarry Smith     ierr = MPI_Bcast(bses,2,MPIU_INT,0,comm);CHKERRQ(ierr);
211efcf75d5SBarry Smith     ierr = MatSetBlockSizes(mat,bses[0],bses[1]);CHKERRQ(ierr);
212dd6ea824SBarry Smith     ierr = MatSetType(mat,MATAIJ);CHKERRQ(ierr);
213dd6ea824SBarry Smith     ierr = PetscMalloc((size+1)*sizeof(PetscInt),&rowners);CHKERRQ(ierr);
214dd6ea824SBarry Smith     ierr = PetscMalloc2(m,PetscInt,&dlens,m,PetscInt,&olens);CHKERRQ(ierr);
215dd6ea824SBarry Smith     ierr = MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);CHKERRQ(ierr);
2162205254eSKarl Rupp 
217dd6ea824SBarry Smith     rowners[0] = 0;
2182205254eSKarl Rupp     for (i=2; i<=size; i++) rowners[i] += rowners[i-1];
219dd6ea824SBarry Smith     rstart = rowners[rank];
220dd6ea824SBarry Smith     rend   = rowners[rank+1];
221dd6ea824SBarry Smith     ierr   = PetscObjectGetNewTag((PetscObject)mat,&tag);CHKERRQ(ierr);
222dd6ea824SBarry Smith     if (!rank) {
223dd6ea824SBarry Smith       gmata = (Mat_SeqAIJ*) gmat->data;
224dd6ea824SBarry Smith       /* send row lengths to all processors */
225dd6ea824SBarry Smith       for (i=0; i<m; i++) dlens[i] = gmata->ilen[i];
226dd6ea824SBarry Smith       for (i=1; i<size; i++) {
227dd6ea824SBarry Smith         ierr = MPI_Send(gmata->ilen + rowners[i],rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);CHKERRQ(ierr);
228dd6ea824SBarry Smith       }
229dd6ea824SBarry Smith       /* determine number diagonal and off-diagonal counts */
230dd6ea824SBarry Smith       ierr = PetscMemzero(olens,m*sizeof(PetscInt));CHKERRQ(ierr);
231dd6ea824SBarry Smith       ierr = PetscMalloc(m*sizeof(PetscInt),&ld);CHKERRQ(ierr);
232dd6ea824SBarry Smith       ierr = PetscMemzero(ld,m*sizeof(PetscInt));CHKERRQ(ierr);
233dd6ea824SBarry Smith       jj   = 0;
234dd6ea824SBarry Smith       for (i=0; i<m; i++) {
235dd6ea824SBarry Smith         for (j=0; j<dlens[i]; j++) {
236dd6ea824SBarry Smith           if (gmata->j[jj] < rstart) ld[i]++;
237dd6ea824SBarry Smith           if (gmata->j[jj] < rstart || gmata->j[jj] >= rend) olens[i]++;
238dd6ea824SBarry Smith           jj++;
239dd6ea824SBarry Smith         }
240dd6ea824SBarry Smith       }
241dd6ea824SBarry Smith       /* send column indices to other processes */
242dd6ea824SBarry Smith       for (i=1; i<size; i++) {
243dd6ea824SBarry Smith         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
244dd6ea824SBarry Smith         ierr = MPI_Send(&nz,1,MPIU_INT,i,tag,comm);CHKERRQ(ierr);
245dd6ea824SBarry Smith         ierr = MPI_Send(gmata->j + gmata->i[rowners[i]],nz,MPIU_INT,i,tag,comm);CHKERRQ(ierr);
246dd6ea824SBarry Smith       }
247dd6ea824SBarry Smith 
248dd6ea824SBarry Smith       /* send numerical values to other processes */
249dd6ea824SBarry Smith       for (i=1; i<size; i++) {
250dd6ea824SBarry Smith         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
251dd6ea824SBarry Smith         ierr = MPI_Send(gmata->a + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);CHKERRQ(ierr);
252dd6ea824SBarry Smith       }
253dd6ea824SBarry Smith       gmataa = gmata->a;
254dd6ea824SBarry Smith       gmataj = gmata->j;
255dd6ea824SBarry Smith 
256dd6ea824SBarry Smith     } else {
257dd6ea824SBarry Smith       /* receive row lengths */
258dd6ea824SBarry Smith       ierr = MPI_Recv(dlens,m,MPIU_INT,0,tag,comm,&status);CHKERRQ(ierr);
259dd6ea824SBarry Smith       /* receive column indices */
260dd6ea824SBarry Smith       ierr = MPI_Recv(&nz,1,MPIU_INT,0,tag,comm,&status);CHKERRQ(ierr);
261dd6ea824SBarry Smith       ierr = PetscMalloc2(nz,PetscScalar,&gmataa,nz,PetscInt,&gmataj);CHKERRQ(ierr);
262dd6ea824SBarry Smith       ierr = MPI_Recv(gmataj,nz,MPIU_INT,0,tag,comm,&status);CHKERRQ(ierr);
263dd6ea824SBarry Smith       /* determine number diagonal and off-diagonal counts */
264dd6ea824SBarry Smith       ierr = PetscMemzero(olens,m*sizeof(PetscInt));CHKERRQ(ierr);
265dd6ea824SBarry Smith       ierr = PetscMalloc(m*sizeof(PetscInt),&ld);CHKERRQ(ierr);
266dd6ea824SBarry Smith       ierr = PetscMemzero(ld,m*sizeof(PetscInt));CHKERRQ(ierr);
267dd6ea824SBarry Smith       jj   = 0;
268dd6ea824SBarry Smith       for (i=0; i<m; i++) {
269dd6ea824SBarry Smith         for (j=0; j<dlens[i]; j++) {
270dd6ea824SBarry Smith           if (gmataj[jj] < rstart) ld[i]++;
271dd6ea824SBarry Smith           if (gmataj[jj] < rstart || gmataj[jj] >= rend) olens[i]++;
272dd6ea824SBarry Smith           jj++;
273dd6ea824SBarry Smith         }
274dd6ea824SBarry Smith       }
275dd6ea824SBarry Smith       /* receive numerical values */
276dd6ea824SBarry Smith       ierr = PetscMemzero(gmataa,nz*sizeof(PetscScalar));CHKERRQ(ierr);
277dd6ea824SBarry Smith       ierr = MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);CHKERRQ(ierr);
278dd6ea824SBarry Smith     }
279dd6ea824SBarry Smith     /* set preallocation */
280dd6ea824SBarry Smith     for (i=0; i<m; i++) {
281dd6ea824SBarry Smith       dlens[i] -= olens[i];
282dd6ea824SBarry Smith     }
283dd6ea824SBarry Smith     ierr = MatSeqAIJSetPreallocation(mat,0,dlens);CHKERRQ(ierr);
284dd6ea824SBarry Smith     ierr = MatMPIAIJSetPreallocation(mat,0,dlens,0,olens);CHKERRQ(ierr);
285dd6ea824SBarry Smith 
286dd6ea824SBarry Smith     for (i=0; i<m; i++) {
287dd6ea824SBarry Smith       dlens[i] += olens[i];
288dd6ea824SBarry Smith     }
289dd6ea824SBarry Smith     cnt = 0;
290dd6ea824SBarry Smith     for (i=0; i<m; i++) {
291dd6ea824SBarry Smith       row  = rstart + i;
292dd6ea824SBarry Smith       ierr = MatSetValues(mat,1,&row,dlens[i],gmataj+cnt,gmataa+cnt,INSERT_VALUES);CHKERRQ(ierr);
293dd6ea824SBarry Smith       cnt += dlens[i];
294dd6ea824SBarry Smith     }
295dd6ea824SBarry Smith     if (rank) {
296dd6ea824SBarry Smith       ierr = PetscFree2(gmataa,gmataj);CHKERRQ(ierr);
297dd6ea824SBarry Smith     }
298dd6ea824SBarry Smith     ierr = PetscFree2(dlens,olens);CHKERRQ(ierr);
299dd6ea824SBarry Smith     ierr = PetscFree(rowners);CHKERRQ(ierr);
3002205254eSKarl Rupp 
301dd6ea824SBarry Smith     ((Mat_MPIAIJ*)(mat->data))->ld = ld;
3022205254eSKarl Rupp 
303dd6ea824SBarry Smith     *inmat = mat;
304dd6ea824SBarry Smith   } else {   /* column indices are already set; only need to move over numerical values from process 0 */
305dd6ea824SBarry Smith     Mat_SeqAIJ *Ad = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->A->data;
306dd6ea824SBarry Smith     Mat_SeqAIJ *Ao = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->B->data;
307dd6ea824SBarry Smith     mat  = *inmat;
308dd6ea824SBarry Smith     ierr = PetscObjectGetNewTag((PetscObject)mat,&tag);CHKERRQ(ierr);
309dd6ea824SBarry Smith     if (!rank) {
310dd6ea824SBarry Smith       /* send numerical values to other processes */
311dd6ea824SBarry Smith       gmata  = (Mat_SeqAIJ*) gmat->data;
312dd6ea824SBarry Smith       ierr   = MatGetOwnershipRanges(mat,(const PetscInt**)&rowners);CHKERRQ(ierr);
313dd6ea824SBarry Smith       gmataa = gmata->a;
314dd6ea824SBarry Smith       for (i=1; i<size; i++) {
315dd6ea824SBarry Smith         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
316dd6ea824SBarry Smith         ierr = MPI_Send(gmataa + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);CHKERRQ(ierr);
317dd6ea824SBarry Smith       }
318dd6ea824SBarry Smith       nz = gmata->i[rowners[1]]-gmata->i[rowners[0]];
319dd6ea824SBarry Smith     } else {
320dd6ea824SBarry Smith       /* receive numerical values from process 0*/
321dd6ea824SBarry Smith       nz   = Ad->nz + Ao->nz;
322dd6ea824SBarry Smith       ierr = PetscMalloc(nz*sizeof(PetscScalar),&gmataa);CHKERRQ(ierr); gmataarestore = gmataa;
323dd6ea824SBarry Smith       ierr = MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);CHKERRQ(ierr);
324dd6ea824SBarry Smith     }
325dd6ea824SBarry Smith     /* transfer numerical values into the diagonal A and off diagonal B parts of mat */
326dd6ea824SBarry Smith     ld = ((Mat_MPIAIJ*)(mat->data))->ld;
327dd6ea824SBarry Smith     ad = Ad->a;
328dd6ea824SBarry Smith     ao = Ao->a;
329d0f46423SBarry Smith     if (mat->rmap->n) {
330dd6ea824SBarry Smith       i  = 0;
331dd6ea824SBarry Smith       nz = ld[i];                                   ierr = PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar));CHKERRQ(ierr); ao += nz; gmataa += nz;
332dd6ea824SBarry Smith       nz = Ad->i[i+1] - Ad->i[i];                   ierr = PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar));CHKERRQ(ierr); ad += nz; gmataa += nz;
333dd6ea824SBarry Smith     }
334d0f46423SBarry Smith     for (i=1; i<mat->rmap->n; i++) {
335dd6ea824SBarry Smith       nz = Ao->i[i] - Ao->i[i-1] - ld[i-1] + ld[i]; ierr = PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar));CHKERRQ(ierr); ao += nz; gmataa += nz;
336dd6ea824SBarry Smith       nz = Ad->i[i+1] - Ad->i[i];                   ierr = PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar));CHKERRQ(ierr); ad += nz; gmataa += nz;
337dd6ea824SBarry Smith     }
338dd6ea824SBarry Smith     i--;
339d0f46423SBarry Smith     if (mat->rmap->n) {
34022d28d08SBarry Smith       nz = Ao->i[i+1] - Ao->i[i] - ld[i];           ierr = PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar));CHKERRQ(ierr);
341dd6ea824SBarry Smith     }
342dd6ea824SBarry Smith     if (rank) {
343dd6ea824SBarry Smith       ierr = PetscFree(gmataarestore);CHKERRQ(ierr);
344dd6ea824SBarry Smith     }
345dd6ea824SBarry Smith   }
346dd6ea824SBarry Smith   ierr = MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
347dd6ea824SBarry Smith   ierr = MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
348dd6ea824SBarry Smith   PetscFunctionReturn(0);
349dd6ea824SBarry Smith }
350dd6ea824SBarry Smith 
3510f5bd95cSBarry Smith /*
3520f5bd95cSBarry Smith   Local utility routine that creates a mapping from the global column
3539e25ed09SBarry Smith number to the local number in the off-diagonal part of the local
3540f5bd95cSBarry Smith storage of the matrix.  When PETSC_USE_CTABLE is used this is scalable at
3550f5bd95cSBarry Smith a slightly higher hash table cost; without it it is not scalable (each processor
3560f5bd95cSBarry Smith has an order N integer array but is fast to acess.
3579e25ed09SBarry Smith */
3584a2ae208SSatish Balay #undef __FUNCT__
359ab9863d7SBarry Smith #define __FUNCT__ "MatCreateColmap_MPIAIJ_Private"
360ab9863d7SBarry Smith PetscErrorCode MatCreateColmap_MPIAIJ_Private(Mat mat)
3619e25ed09SBarry Smith {
36244a69424SLois Curfman McInnes   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
3636849ba73SBarry Smith   PetscErrorCode ierr;
364d0f46423SBarry Smith   PetscInt       n = aij->B->cmap->n,i;
365dbb450caSBarry Smith 
3663a40ed3dSBarry Smith   PetscFunctionBegin;
3675e1f6667SBarry Smith   if (!aij->garray) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MPIAIJ Matrix was assembled but is missing garray");
368aa482453SBarry Smith #if defined(PETSC_USE_CTABLE)
369e23dfa41SBarry Smith   ierr = PetscTableCreate(n,mat->cmap->N+1,&aij->colmap);CHKERRQ(ierr);
370b1fc9764SSatish Balay   for (i=0; i<n; i++) {
3713861aac3SJed Brown     ierr = PetscTableAdd(aij->colmap,aij->garray[i]+1,i+1,INSERT_VALUES);CHKERRQ(ierr);
372b1fc9764SSatish Balay   }
373b1fc9764SSatish Balay #else
374d0f46423SBarry Smith   ierr = PetscMalloc((mat->cmap->N+1)*sizeof(PetscInt),&aij->colmap);CHKERRQ(ierr);
375d0f46423SBarry Smith   ierr = PetscLogObjectMemory(mat,mat->cmap->N*sizeof(PetscInt));CHKERRQ(ierr);
376d0f46423SBarry Smith   ierr = PetscMemzero(aij->colmap,mat->cmap->N*sizeof(PetscInt));CHKERRQ(ierr);
377905e6a2fSBarry Smith   for (i=0; i<n; i++) aij->colmap[aij->garray[i]] = i+1;
378b1fc9764SSatish Balay #endif
3793a40ed3dSBarry Smith   PetscFunctionReturn(0);
3809e25ed09SBarry Smith }
3819e25ed09SBarry Smith 
38230770e4dSSatish Balay #define MatSetValues_SeqAIJ_A_Private(row,col,value,addv) \
3830520107fSSatish Balay { \
384db4deed7SKarl Rupp     if (col <= lastcol1)  low1 = 0;     \
385db4deed7SKarl Rupp     else                 high1 = nrow1; \
386fd3458f5SBarry Smith     lastcol1 = col;\
387fd3458f5SBarry Smith     while (high1-low1 > 5) { \
388fd3458f5SBarry Smith       t = (low1+high1)/2; \
389fd3458f5SBarry Smith       if (rp1[t] > col) high1 = t; \
390fd3458f5SBarry Smith       else              low1  = t; \
391ba4e3ef2SSatish Balay     } \
392fd3458f5SBarry Smith       for (_i=low1; _i<high1; _i++) { \
393fd3458f5SBarry Smith         if (rp1[_i] > col) break; \
394fd3458f5SBarry Smith         if (rp1[_i] == col) { \
395fd3458f5SBarry Smith           if (addv == ADD_VALUES) ap1[_i] += value;   \
396fd3458f5SBarry Smith           else                    ap1[_i] = value; \
39730770e4dSSatish Balay           goto a_noinsert; \
3980520107fSSatish Balay         } \
3990520107fSSatish Balay       }  \
400e44c0bd4SBarry Smith       if (value == 0.0 && ignorezeroentries) {low1 = 0; high1 = nrow1;goto a_noinsert;} \
401e44c0bd4SBarry Smith       if (nonew == 1) {low1 = 0; high1 = nrow1; goto a_noinsert;}                \
402e32f2f54SBarry Smith       if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
403fef13f97SBarry Smith       MatSeqXAIJReallocateAIJ(A,am,1,nrow1,row,col,rmax1,aa,ai,aj,rp1,ap1,aimax,nonew,MatScalar); \
404669a8dbcSSatish Balay       N = nrow1++ - 1; a->nz++; high1++; \
4050520107fSSatish Balay       /* shift up all the later entries in this row */ \
4060520107fSSatish Balay       for (ii=N; ii>=_i; ii--) { \
407fd3458f5SBarry Smith         rp1[ii+1] = rp1[ii]; \
408fd3458f5SBarry Smith         ap1[ii+1] = ap1[ii]; \
4090520107fSSatish Balay       } \
410fd3458f5SBarry Smith       rp1[_i] = col;  \
411fd3458f5SBarry Smith       ap1[_i] = value;  \
41230770e4dSSatish Balay       a_noinsert: ; \
413fd3458f5SBarry Smith       ailen[row] = nrow1; \
4140520107fSSatish Balay }
4150a198c4cSBarry Smith 
416085a36d4SBarry Smith 
41730770e4dSSatish Balay #define MatSetValues_SeqAIJ_B_Private(row,col,value,addv) \
41830770e4dSSatish Balay   { \
419db4deed7SKarl Rupp     if (col <= lastcol2) low2 = 0;                        \
420db4deed7SKarl Rupp     else high2 = nrow2;                                   \
421fd3458f5SBarry Smith     lastcol2 = col;                                       \
422fd3458f5SBarry Smith     while (high2-low2 > 5) {                              \
423fd3458f5SBarry Smith       t = (low2+high2)/2;                                 \
424fd3458f5SBarry Smith       if (rp2[t] > col) high2 = t;                        \
425fd3458f5SBarry Smith       else             low2  = t;                         \
426ba4e3ef2SSatish Balay     }                                                     \
427fd3458f5SBarry Smith     for (_i=low2; _i<high2; _i++) {                       \
428fd3458f5SBarry Smith       if (rp2[_i] > col) break;                           \
429fd3458f5SBarry Smith       if (rp2[_i] == col) {                               \
430fd3458f5SBarry Smith         if (addv == ADD_VALUES) ap2[_i] += value;         \
431fd3458f5SBarry Smith         else                    ap2[_i] = value;          \
43230770e4dSSatish Balay         goto b_noinsert;                                  \
43330770e4dSSatish Balay       }                                                   \
43430770e4dSSatish Balay     }                                                     \
435e44c0bd4SBarry Smith     if (value == 0.0 && ignorezeroentries) {low2 = 0; high2 = nrow2; goto b_noinsert;} \
436e44c0bd4SBarry Smith     if (nonew == 1) {low2 = 0; high2 = nrow2; goto b_noinsert;}                        \
437e32f2f54SBarry Smith     if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
438fef13f97SBarry Smith     MatSeqXAIJReallocateAIJ(B,bm,1,nrow2,row,col,rmax2,ba,bi,bj,rp2,ap2,bimax,nonew,MatScalar); \
439669a8dbcSSatish Balay     N = nrow2++ - 1; b->nz++; high2++;                    \
44030770e4dSSatish Balay     /* shift up all the later entries in this row */      \
44130770e4dSSatish Balay     for (ii=N; ii>=_i; ii--) {                            \
442fd3458f5SBarry Smith       rp2[ii+1] = rp2[ii];                                \
443fd3458f5SBarry Smith       ap2[ii+1] = ap2[ii];                                \
44430770e4dSSatish Balay     }                                                     \
445fd3458f5SBarry Smith     rp2[_i] = col;                                        \
446fd3458f5SBarry Smith     ap2[_i] = value;                                      \
44730770e4dSSatish Balay     b_noinsert: ;                                         \
448fd3458f5SBarry Smith     bilen[row] = nrow2;                                   \
44930770e4dSSatish Balay   }
45030770e4dSSatish Balay 
4514a2ae208SSatish Balay #undef __FUNCT__
4522fd7e33dSBarry Smith #define __FUNCT__ "MatSetValuesRow_MPIAIJ"
4532fd7e33dSBarry Smith PetscErrorCode MatSetValuesRow_MPIAIJ(Mat A,PetscInt row,const PetscScalar v[])
4542fd7e33dSBarry Smith {
4552fd7e33dSBarry Smith   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)A->data;
4562fd7e33dSBarry Smith   Mat_SeqAIJ     *a   = (Mat_SeqAIJ*)mat->A->data,*b = (Mat_SeqAIJ*)mat->B->data;
4572fd7e33dSBarry Smith   PetscErrorCode ierr;
4582fd7e33dSBarry Smith   PetscInt       l,*garray = mat->garray,diag;
4592fd7e33dSBarry Smith 
4602fd7e33dSBarry Smith   PetscFunctionBegin;
4612fd7e33dSBarry Smith   /* code only works for square matrices A */
4622fd7e33dSBarry Smith 
4632fd7e33dSBarry Smith   /* find size of row to the left of the diagonal part */
4642fd7e33dSBarry Smith   ierr = MatGetOwnershipRange(A,&diag,0);CHKERRQ(ierr);
4652fd7e33dSBarry Smith   row  = row - diag;
4662fd7e33dSBarry Smith   for (l=0; l<b->i[row+1]-b->i[row]; l++) {
4672fd7e33dSBarry Smith     if (garray[b->j[b->i[row]+l]] > diag) break;
4682fd7e33dSBarry Smith   }
4692fd7e33dSBarry Smith   ierr = PetscMemcpy(b->a+b->i[row],v,l*sizeof(PetscScalar));CHKERRQ(ierr);
4702fd7e33dSBarry Smith 
4712fd7e33dSBarry Smith   /* diagonal part */
4722fd7e33dSBarry Smith   ierr = PetscMemcpy(a->a+a->i[row],v+l,(a->i[row+1]-a->i[row])*sizeof(PetscScalar));CHKERRQ(ierr);
4732fd7e33dSBarry Smith 
4742fd7e33dSBarry Smith   /* right of diagonal part */
4752fd7e33dSBarry Smith   ierr = PetscMemcpy(b->a+b->i[row]+l,v+l+a->i[row+1]-a->i[row],(b->i[row+1]-b->i[row]-l)*sizeof(PetscScalar));CHKERRQ(ierr);
4762fd7e33dSBarry Smith   PetscFunctionReturn(0);
4772fd7e33dSBarry Smith }
4782fd7e33dSBarry Smith 
4792fd7e33dSBarry Smith #undef __FUNCT__
4804a2ae208SSatish Balay #define __FUNCT__ "MatSetValues_MPIAIJ"
481b1d57f15SBarry Smith PetscErrorCode MatSetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
4828a729477SBarry Smith {
48344a69424SLois Curfman McInnes   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
48487828ca2SBarry Smith   PetscScalar    value;
485dfbe8321SBarry Smith   PetscErrorCode ierr;
486d0f46423SBarry Smith   PetscInt       i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
487d0f46423SBarry Smith   PetscInt       cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
488ace3abfcSBarry Smith   PetscBool      roworiented = aij->roworiented;
4898a729477SBarry Smith 
4900520107fSSatish Balay   /* Some Variables required in the macro */
4914ee7247eSSatish Balay   Mat        A                 = aij->A;
4924ee7247eSSatish Balay   Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
49357809a77SBarry Smith   PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
494a77337e4SBarry Smith   MatScalar  *aa               = a->a;
495ace3abfcSBarry Smith   PetscBool  ignorezeroentries = a->ignorezeroentries;
49630770e4dSSatish Balay   Mat        B                 = aij->B;
49730770e4dSSatish Balay   Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
498d0f46423SBarry Smith   PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
499a77337e4SBarry Smith   MatScalar  *ba               = b->a;
50030770e4dSSatish Balay 
501fd3458f5SBarry Smith   PetscInt  *rp1,*rp2,ii,nrow1,nrow2,_i,rmax1,rmax2,N,low1,high1,low2,high2,t,lastcol1,lastcol2;
5028d76821aSHong Zhang   PetscInt  nonew;
503a77337e4SBarry Smith   MatScalar *ap1,*ap2;
5044ee7247eSSatish Balay 
5053a40ed3dSBarry Smith   PetscFunctionBegin;
50671fd2e92SBarry Smith   if (v) PetscValidScalarPointer(v,6);
5078a729477SBarry Smith   for (i=0; i<m; i++) {
5085ef9f2a5SBarry Smith     if (im[i] < 0) continue;
5092515c552SBarry Smith #if defined(PETSC_USE_DEBUG)
510e32f2f54SBarry Smith     if (im[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",im[i],mat->rmap->N-1);
5110a198c4cSBarry Smith #endif
5124b0e389bSBarry Smith     if (im[i] >= rstart && im[i] < rend) {
5134b0e389bSBarry Smith       row      = im[i] - rstart;
514fd3458f5SBarry Smith       lastcol1 = -1;
515fd3458f5SBarry Smith       rp1      = aj + ai[row];
516fd3458f5SBarry Smith       ap1      = aa + ai[row];
517fd3458f5SBarry Smith       rmax1    = aimax[row];
518fd3458f5SBarry Smith       nrow1    = ailen[row];
519fd3458f5SBarry Smith       low1     = 0;
520fd3458f5SBarry Smith       high1    = nrow1;
521fd3458f5SBarry Smith       lastcol2 = -1;
522fd3458f5SBarry Smith       rp2      = bj + bi[row];
523d498b1e9SBarry Smith       ap2      = ba + bi[row];
524fd3458f5SBarry Smith       rmax2    = bimax[row];
525d498b1e9SBarry Smith       nrow2    = bilen[row];
526fd3458f5SBarry Smith       low2     = 0;
527fd3458f5SBarry Smith       high2    = nrow2;
528fd3458f5SBarry Smith 
5291eb62cbbSBarry Smith       for (j=0; j<n; j++) {
530db4deed7SKarl Rupp         if (v) {
531db4deed7SKarl Rupp           if (roworiented) value = v[i*n+j];
532db4deed7SKarl Rupp           else             value = v[i+j*m];
533db4deed7SKarl Rupp         } else value = 0.0;
534abc0a331SBarry Smith         if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES)) continue;
535fd3458f5SBarry Smith         if (in[j] >= cstart && in[j] < cend) {
536fd3458f5SBarry Smith           col   = in[j] - cstart;
5378d76821aSHong Zhang           nonew = a->nonew;
53830770e4dSSatish Balay           MatSetValues_SeqAIJ_A_Private(row,col,value,addv);
539273d9f13SBarry Smith         } else if (in[j] < 0) continue;
5402515c552SBarry Smith #if defined(PETSC_USE_DEBUG)
541cb9801acSJed Brown         else if (in[j] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[j],mat->cmap->N-1);
5420a198c4cSBarry Smith #endif
5431eb62cbbSBarry Smith         else {
544227d817aSBarry Smith           if (mat->was_assembled) {
545905e6a2fSBarry Smith             if (!aij->colmap) {
546ab9863d7SBarry Smith               ierr = MatCreateColmap_MPIAIJ_Private(mat);CHKERRQ(ierr);
547905e6a2fSBarry Smith             }
548aa482453SBarry Smith #if defined(PETSC_USE_CTABLE)
5490f5bd95cSBarry Smith             ierr = PetscTableFind(aij->colmap,in[j]+1,&col);CHKERRQ(ierr);
550fa46199cSSatish Balay             col--;
551b1fc9764SSatish Balay #else
552905e6a2fSBarry Smith             col = aij->colmap[in[j]] - 1;
553b1fc9764SSatish Balay #endif
5540e9bae81SBarry Smith             if (col < 0 && !((Mat_SeqAIJ*)(aij->B->data))->nonew) {
555ab9863d7SBarry Smith               ierr = MatDisAssemble_MPIAIJ(mat);CHKERRQ(ierr);
5564b0e389bSBarry Smith               col  =  in[j];
5579bf004c3SSatish Balay               /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
558f9508a3cSSatish Balay               B     = aij->B;
559f9508a3cSSatish Balay               b     = (Mat_SeqAIJ*)B->data;
560e44c0bd4SBarry Smith               bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j; ba = b->a;
561d498b1e9SBarry Smith               rp2   = bj + bi[row];
562d498b1e9SBarry Smith               ap2   = ba + bi[row];
563d498b1e9SBarry Smith               rmax2 = bimax[row];
564d498b1e9SBarry Smith               nrow2 = bilen[row];
565d498b1e9SBarry Smith               low2  = 0;
566d498b1e9SBarry Smith               high2 = nrow2;
567d0f46423SBarry Smith               bm    = aij->B->rmap->n;
568f9508a3cSSatish Balay               ba    = b->a;
5690e9bae81SBarry Smith             } else if (col < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", im[i], in[j]);
570c48de900SBarry Smith           } else col = in[j];
5718d76821aSHong Zhang           nonew = b->nonew;
57230770e4dSSatish Balay           MatSetValues_SeqAIJ_B_Private(row,col,value,addv);
5731eb62cbbSBarry Smith         }
5741eb62cbbSBarry Smith       }
5755ef9f2a5SBarry Smith     } else {
5764cb17eb5SBarry Smith       if (mat->nooffprocentries) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Setting off process row %D even though MatSetOption(,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE) was set",im[i]);
57790f02eecSBarry Smith       if (!aij->donotstash) {
5785080c13bSMatthew G Knepley         mat->assembled = PETSC_FALSE;
579d36fbae8SSatish Balay         if (roworiented) {
580ace3abfcSBarry Smith           ierr = MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));CHKERRQ(ierr);
581d36fbae8SSatish Balay         } else {
582ace3abfcSBarry Smith           ierr = MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));CHKERRQ(ierr);
5834b0e389bSBarry Smith         }
5841eb62cbbSBarry Smith       }
5858a729477SBarry Smith     }
58690f02eecSBarry Smith   }
5873a40ed3dSBarry Smith   PetscFunctionReturn(0);
5888a729477SBarry Smith }
5898a729477SBarry Smith 
5904a2ae208SSatish Balay #undef __FUNCT__
5914a2ae208SSatish Balay #define __FUNCT__ "MatGetValues_MPIAIJ"
592b1d57f15SBarry Smith PetscErrorCode MatGetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
593b49de8d1SLois Curfman McInnes {
594b49de8d1SLois Curfman McInnes   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
595dfbe8321SBarry Smith   PetscErrorCode ierr;
596d0f46423SBarry Smith   PetscInt       i,j,rstart = mat->rmap->rstart,rend = mat->rmap->rend;
597d0f46423SBarry Smith   PetscInt       cstart = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
598b49de8d1SLois Curfman McInnes 
5993a40ed3dSBarry Smith   PetscFunctionBegin;
600b49de8d1SLois Curfman McInnes   for (i=0; i<m; i++) {
601e32f2f54SBarry Smith     if (idxm[i] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",idxm[i]);*/
602e32f2f54SBarry Smith     if (idxm[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",idxm[i],mat->rmap->N-1);
603b49de8d1SLois Curfman McInnes     if (idxm[i] >= rstart && idxm[i] < rend) {
604b49de8d1SLois Curfman McInnes       row = idxm[i] - rstart;
605b49de8d1SLois Curfman McInnes       for (j=0; j<n; j++) {
606e32f2f54SBarry Smith         if (idxn[j] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",idxn[j]); */
607e32f2f54SBarry Smith         if (idxn[j] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",idxn[j],mat->cmap->N-1);
608b49de8d1SLois Curfman McInnes         if (idxn[j] >= cstart && idxn[j] < cend) {
609b49de8d1SLois Curfman McInnes           col  = idxn[j] - cstart;
610b49de8d1SLois Curfman McInnes           ierr = MatGetValues(aij->A,1,&row,1,&col,v+i*n+j);CHKERRQ(ierr);
611fa852ad4SSatish Balay         } else {
612905e6a2fSBarry Smith           if (!aij->colmap) {
613ab9863d7SBarry Smith             ierr = MatCreateColmap_MPIAIJ_Private(mat);CHKERRQ(ierr);
614905e6a2fSBarry Smith           }
615aa482453SBarry Smith #if defined(PETSC_USE_CTABLE)
6160f5bd95cSBarry Smith           ierr = PetscTableFind(aij->colmap,idxn[j]+1,&col);CHKERRQ(ierr);
617fa46199cSSatish Balay           col--;
618b1fc9764SSatish Balay #else
619905e6a2fSBarry Smith           col = aij->colmap[idxn[j]] - 1;
620b1fc9764SSatish Balay #endif
621e60e1c95SSatish Balay           if ((col < 0) || (aij->garray[col] != idxn[j])) *(v+i*n+j) = 0.0;
622d9d09a02SSatish Balay           else {
623b49de8d1SLois Curfman McInnes             ierr = MatGetValues(aij->B,1,&row,1,&col,v+i*n+j);CHKERRQ(ierr);
624b49de8d1SLois Curfman McInnes           }
625b49de8d1SLois Curfman McInnes         }
626b49de8d1SLois Curfman McInnes       }
627f23aa3ddSBarry Smith     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local values currently supported");
628b49de8d1SLois Curfman McInnes   }
6293a40ed3dSBarry Smith   PetscFunctionReturn(0);
630b49de8d1SLois Curfman McInnes }
631bc5ccf88SSatish Balay 
632bd0c2dcbSBarry Smith extern PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat,Vec,Vec);
633bd0c2dcbSBarry Smith 
6344a2ae208SSatish Balay #undef __FUNCT__
6354a2ae208SSatish Balay #define __FUNCT__ "MatAssemblyBegin_MPIAIJ"
636dfbe8321SBarry Smith PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat,MatAssemblyType mode)
637bc5ccf88SSatish Balay {
638bc5ccf88SSatish Balay   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
639dfbe8321SBarry Smith   PetscErrorCode ierr;
640b1d57f15SBarry Smith   PetscInt       nstash,reallocs;
641bc5ccf88SSatish Balay   InsertMode     addv;
642bc5ccf88SSatish Balay 
643bc5ccf88SSatish Balay   PetscFunctionBegin;
6442205254eSKarl Rupp   if (aij->donotstash || mat->nooffprocentries) PetscFunctionReturn(0);
645bc5ccf88SSatish Balay 
646bc5ccf88SSatish Balay   /* make sure all processors are either in INSERTMODE or ADDMODE */
647ce94432eSBarry Smith   ierr = MPI_Allreduce((PetscEnum*)&mat->insertmode,(PetscEnum*)&addv,1,MPIU_ENUM,MPI_BOR,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
648ce94432eSBarry Smith   if (addv == (ADD_VALUES|INSERT_VALUES)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Some processors inserted others added");
649bc5ccf88SSatish Balay   mat->insertmode = addv; /* in case this processor had no cache */
650bc5ccf88SSatish Balay 
651d0f46423SBarry Smith   ierr = MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);CHKERRQ(ierr);
6528798bf22SSatish Balay   ierr = MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);CHKERRQ(ierr);
653ae15b995SBarry Smith   ierr = PetscInfo2(aij->A,"Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);CHKERRQ(ierr);
654bc5ccf88SSatish Balay   PetscFunctionReturn(0);
655bc5ccf88SSatish Balay }
656bc5ccf88SSatish Balay 
6574a2ae208SSatish Balay #undef __FUNCT__
6584a2ae208SSatish Balay #define __FUNCT__ "MatAssemblyEnd_MPIAIJ"
659dfbe8321SBarry Smith PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat,MatAssemblyType mode)
660bc5ccf88SSatish Balay {
661bc5ccf88SSatish Balay   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
66291c97fd4SSatish Balay   Mat_SeqAIJ     *a   = (Mat_SeqAIJ*)aij->A->data;
6636849ba73SBarry Smith   PetscErrorCode ierr;
664b1d57f15SBarry Smith   PetscMPIInt    n;
665b1d57f15SBarry Smith   PetscInt       i,j,rstart,ncols,flg;
666e44c0bd4SBarry Smith   PetscInt       *row,*col;
667ace3abfcSBarry Smith   PetscBool      other_disassembled;
66887828ca2SBarry Smith   PetscScalar    *val;
669bc5ccf88SSatish Balay   InsertMode     addv = mat->insertmode;
670bc5ccf88SSatish Balay 
67191c97fd4SSatish Balay   /* do not use 'b = (Mat_SeqAIJ*)aij->B->data' as B can be reset in disassembly */
6726e111a19SKarl Rupp 
673bc5ccf88SSatish Balay   PetscFunctionBegin;
6744cb17eb5SBarry Smith   if (!aij->donotstash && !mat->nooffprocentries) {
675a2d1c673SSatish Balay     while (1) {
6768798bf22SSatish Balay       ierr = MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);CHKERRQ(ierr);
677a2d1c673SSatish Balay       if (!flg) break;
678a2d1c673SSatish Balay 
679bc5ccf88SSatish Balay       for (i=0; i<n; ) {
680bc5ccf88SSatish Balay         /* Now identify the consecutive vals belonging to the same row */
6812205254eSKarl Rupp         for (j=i,rstart=row[j]; j<n; j++) {
6822205254eSKarl Rupp           if (row[j] != rstart) break;
6832205254eSKarl Rupp         }
684bc5ccf88SSatish Balay         if (j < n) ncols = j-i;
685bc5ccf88SSatish Balay         else       ncols = n-i;
686bc5ccf88SSatish Balay         /* Now assemble all these values with a single function call */
687bc5ccf88SSatish Balay         ierr = MatSetValues_MPIAIJ(mat,1,row+i,ncols,col+i,val+i,addv);CHKERRQ(ierr);
6882205254eSKarl Rupp 
689bc5ccf88SSatish Balay         i = j;
690bc5ccf88SSatish Balay       }
691bc5ccf88SSatish Balay     }
6928798bf22SSatish Balay     ierr = MatStashScatterEnd_Private(&mat->stash);CHKERRQ(ierr);
693bc5ccf88SSatish Balay   }
694bc5ccf88SSatish Balay   ierr = MatAssemblyBegin(aij->A,mode);CHKERRQ(ierr);
695bc5ccf88SSatish Balay   ierr = MatAssemblyEnd(aij->A,mode);CHKERRQ(ierr);
696bc5ccf88SSatish Balay 
697bc5ccf88SSatish Balay   /* determine if any processor has disassembled, if so we must
698bc5ccf88SSatish Balay      also disassemble ourselfs, in order that we may reassemble. */
699bc5ccf88SSatish Balay   /*
700bc5ccf88SSatish Balay      if nonzero structure of submatrix B cannot change then we know that
701bc5ccf88SSatish Balay      no processor disassembled thus we can skip this stuff
702bc5ccf88SSatish Balay   */
703bc5ccf88SSatish Balay   if (!((Mat_SeqAIJ*)aij->B->data)->nonew) {
704ce94432eSBarry Smith     ierr = MPI_Allreduce(&mat->was_assembled,&other_disassembled,1,MPIU_BOOL,MPI_PROD,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
705bc5ccf88SSatish Balay     if (mat->was_assembled && !other_disassembled) {
706ab9863d7SBarry Smith       ierr = MatDisAssemble_MPIAIJ(mat);CHKERRQ(ierr);
707ad59fb31SSatish Balay     }
708ad59fb31SSatish Balay   }
709bc5ccf88SSatish Balay   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
710bc5ccf88SSatish Balay     ierr = MatSetUpMultiply_MPIAIJ(mat);CHKERRQ(ierr);
711bc5ccf88SSatish Balay   }
7124e0d8c25SBarry Smith   ierr = MatSetOption(aij->B,MAT_USE_INODES,PETSC_FALSE);CHKERRQ(ierr);
7134e35b6f3SSatish Balay   ierr = MatSetOption(aij->B,MAT_CHECK_COMPRESSED_ROW,PETSC_FALSE);CHKERRQ(ierr);
714bc5ccf88SSatish Balay   ierr = MatAssemblyBegin(aij->B,mode);CHKERRQ(ierr);
715bc5ccf88SSatish Balay   ierr = MatAssemblyEnd(aij->B,mode);CHKERRQ(ierr);
716bc5ccf88SSatish Balay 
7171d79065fSBarry Smith   ierr = PetscFree2(aij->rowvalues,aij->rowindices);CHKERRQ(ierr);
7182205254eSKarl Rupp 
719606d414cSSatish Balay   aij->rowvalues = 0;
720a30b2313SHong Zhang 
721a30b2313SHong Zhang   /* used by MatAXPY() */
72291c97fd4SSatish Balay   a->xtoy = 0; ((Mat_SeqAIJ*)aij->B->data)->xtoy = 0;   /* b->xtoy = 0 */
72391c97fd4SSatish Balay   a->XtoY = 0; ((Mat_SeqAIJ*)aij->B->data)->XtoY = 0;   /* b->XtoY = 0 */
724a30b2313SHong Zhang 
7256bf464f9SBarry Smith   ierr = VecDestroy(&aij->diag);CHKERRQ(ierr);
726bd0c2dcbSBarry Smith   if (a->inode.size) mat->ops->multdiagonalblock = MatMultDiagonalBlock_MPIAIJ;
727bc5ccf88SSatish Balay   PetscFunctionReturn(0);
728bc5ccf88SSatish Balay }
729bc5ccf88SSatish Balay 
7304a2ae208SSatish Balay #undef __FUNCT__
7314a2ae208SSatish Balay #define __FUNCT__ "MatZeroEntries_MPIAIJ"
732dfbe8321SBarry Smith PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
7331eb62cbbSBarry Smith {
73444a69424SLois Curfman McInnes   Mat_MPIAIJ     *l = (Mat_MPIAIJ*)A->data;
735dfbe8321SBarry Smith   PetscErrorCode ierr;
7363a40ed3dSBarry Smith 
7373a40ed3dSBarry Smith   PetscFunctionBegin;
73878b31e54SBarry Smith   ierr = MatZeroEntries(l->A);CHKERRQ(ierr);
73978b31e54SBarry Smith   ierr = MatZeroEntries(l->B);CHKERRQ(ierr);
7403a40ed3dSBarry Smith   PetscFunctionReturn(0);
7411eb62cbbSBarry Smith }
7421eb62cbbSBarry Smith 
7434a2ae208SSatish Balay #undef __FUNCT__
7444a2ae208SSatish Balay #define __FUNCT__ "MatZeroRows_MPIAIJ"
7452b40b63fSBarry Smith PetscErrorCode MatZeroRows_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
7461eb62cbbSBarry Smith {
74744a69424SLois Curfman McInnes   Mat_MPIAIJ        *l = (Mat_MPIAIJ*)A->data;
7486849ba73SBarry Smith   PetscErrorCode    ierr;
7497adad957SLisandro Dalcin   PetscMPIInt       size = l->size,imdex,n,rank = l->rank,tag = ((PetscObject)A)->tag,lastidx = -1;
750d0f46423SBarry Smith   PetscInt          i,*owners = A->rmap->range;
751b1d57f15SBarry Smith   PetscInt          *nprocs,j,idx,nsends,row;
752b1d57f15SBarry Smith   PetscInt          nmax,*svalues,*starts,*owner,nrecvs;
753b1d57f15SBarry Smith   PetscInt          *rvalues,count,base,slen,*source;
754d0f46423SBarry Smith   PetscInt          *lens,*lrows,*values,rstart=A->rmap->rstart;
755ce94432eSBarry Smith   MPI_Comm          comm;
7561eb62cbbSBarry Smith   MPI_Request       *send_waits,*recv_waits;
7571eb62cbbSBarry Smith   MPI_Status        recv_status,*send_status;
75897b48c8fSBarry Smith   const PetscScalar *xx;
75997b48c8fSBarry Smith   PetscScalar       *bb;
7606543fbbaSBarry Smith #if defined(PETSC_DEBUG)
761ace3abfcSBarry Smith   PetscBool found = PETSC_FALSE;
7626543fbbaSBarry Smith #endif
7631eb62cbbSBarry Smith 
7643a40ed3dSBarry Smith   PetscFunctionBegin;
765ce94432eSBarry Smith   ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr);
7661eb62cbbSBarry Smith   /*  first count number of contributors to each processor */
767b1d57f15SBarry Smith   ierr = PetscMalloc(2*size*sizeof(PetscInt),&nprocs);CHKERRQ(ierr);
768b1d57f15SBarry Smith   ierr = PetscMemzero(nprocs,2*size*sizeof(PetscInt));CHKERRQ(ierr);
769b1d57f15SBarry Smith   ierr = PetscMalloc((N+1)*sizeof(PetscInt),&owner);CHKERRQ(ierr); /* see note*/
7706543fbbaSBarry Smith   j    = 0;
7711eb62cbbSBarry Smith   for (i=0; i<N; i++) {
7726543fbbaSBarry Smith     if (lastidx > (idx = rows[i])) j = 0;
7736543fbbaSBarry Smith     lastidx = idx;
7746543fbbaSBarry Smith     for (; j<size; j++) {
7751eb62cbbSBarry Smith       if (idx >= owners[j] && idx < owners[j+1]) {
7766543fbbaSBarry Smith         nprocs[2*j]++;
7776543fbbaSBarry Smith         nprocs[2*j+1] = 1;
7786543fbbaSBarry Smith         owner[i]      = j;
7796543fbbaSBarry Smith #if defined(PETSC_DEBUG)
7806543fbbaSBarry Smith         found = PETSC_TRUE;
7816543fbbaSBarry Smith #endif
7826543fbbaSBarry Smith         break;
7831eb62cbbSBarry Smith       }
7841eb62cbbSBarry Smith     }
7856543fbbaSBarry Smith #if defined(PETSC_DEBUG)
786e32f2f54SBarry Smith     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Index out of range");
7876543fbbaSBarry Smith     found = PETSC_FALSE;
7886543fbbaSBarry Smith #endif
7891eb62cbbSBarry Smith   }
7902205254eSKarl Rupp   nsends = 0;
7912205254eSKarl Rupp   for (i=0; i<size; i++) nsends += nprocs[2*i+1];
7921eb62cbbSBarry Smith 
7937367270fSBarry Smith   if (A->nooffproczerorows) {
7947367270fSBarry Smith     if (nsends > 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"You called MatSetOption(,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) but set an off process zero row");
7957367270fSBarry Smith     nrecvs = nsends;
7967367270fSBarry Smith     nmax   = N;
7977367270fSBarry Smith   } else {
7981eb62cbbSBarry Smith     /* inform other processors of number of messages and max length*/
799c1dc657dSBarry Smith     ierr = PetscMaxSum(comm,nprocs,&nmax,&nrecvs);CHKERRQ(ierr);
8007367270fSBarry Smith   }
8011eb62cbbSBarry Smith 
8021eb62cbbSBarry Smith   /* post receives:   */
803b1d57f15SBarry Smith   ierr = PetscMalloc((nrecvs+1)*(nmax+1)*sizeof(PetscInt),&rvalues);CHKERRQ(ierr);
804b0a32e0cSBarry Smith   ierr = PetscMalloc((nrecvs+1)*sizeof(MPI_Request),&recv_waits);CHKERRQ(ierr);
8051eb62cbbSBarry Smith   for (i=0; i<nrecvs; i++) {
806b1d57f15SBarry Smith     ierr = MPI_Irecv(rvalues+nmax*i,nmax,MPIU_INT,MPI_ANY_SOURCE,tag,comm,recv_waits+i);CHKERRQ(ierr);
8071eb62cbbSBarry Smith   }
8081eb62cbbSBarry Smith 
8091eb62cbbSBarry Smith   /* do sends:
8101eb62cbbSBarry Smith       1) starts[i] gives the starting index in svalues for stuff going to
8111eb62cbbSBarry Smith          the ith processor
8121eb62cbbSBarry Smith   */
813b1d57f15SBarry Smith   ierr = PetscMalloc((N+1)*sizeof(PetscInt),&svalues);CHKERRQ(ierr);
814b0a32e0cSBarry Smith   ierr = PetscMalloc((nsends+1)*sizeof(MPI_Request),&send_waits);CHKERRQ(ierr);
815b1d57f15SBarry Smith   ierr = PetscMalloc((size+1)*sizeof(PetscInt),&starts);CHKERRQ(ierr);
8161eb62cbbSBarry Smith 
8171eb62cbbSBarry Smith   starts[0] = 0;
8182205254eSKarl Rupp   for (i=1; i<size; i++) starts[i] = starts[i-1] + nprocs[2*i-2];
8192205254eSKarl Rupp   for (i=0; i<N; i++) svalues[starts[owner[i]]++] = rows[i];
8202205254eSKarl Rupp 
8212205254eSKarl Rupp   starts[0] = 0;
8222205254eSKarl Rupp   for (i=1; i<size+1; i++) starts[i] = starts[i-1] + nprocs[2*i-2];
8231eb62cbbSBarry Smith   count = 0;
82417699dbbSLois Curfman McInnes   for (i=0; i<size; i++) {
825c1dc657dSBarry Smith     if (nprocs[2*i+1]) {
826b1d57f15SBarry Smith       ierr = MPI_Isend(svalues+starts[i],nprocs[2*i],MPIU_INT,i,tag,comm,send_waits+count++);CHKERRQ(ierr);
8271eb62cbbSBarry Smith     }
8281eb62cbbSBarry Smith   }
829606d414cSSatish Balay   ierr = PetscFree(starts);CHKERRQ(ierr);
8301eb62cbbSBarry Smith 
83117699dbbSLois Curfman McInnes   base = owners[rank];
8321eb62cbbSBarry Smith 
8331eb62cbbSBarry Smith   /*  wait on receives */
8341d79065fSBarry Smith   ierr  = PetscMalloc2(nrecvs,PetscInt,&lens,nrecvs,PetscInt,&source);CHKERRQ(ierr);
8351eb62cbbSBarry Smith   count = nrecvs; slen = 0;
8361eb62cbbSBarry Smith   while (count) {
837ca161407SBarry Smith     ierr = MPI_Waitany(nrecvs,recv_waits,&imdex,&recv_status);CHKERRQ(ierr);
8381eb62cbbSBarry Smith     /* unpack receives into our local space */
839b1d57f15SBarry Smith     ierr = MPI_Get_count(&recv_status,MPIU_INT,&n);CHKERRQ(ierr);
8402205254eSKarl Rupp 
841d6dfbf8fSBarry Smith     source[imdex] = recv_status.MPI_SOURCE;
842d6dfbf8fSBarry Smith     lens[imdex]   = n;
8431eb62cbbSBarry Smith     slen         += n;
8441eb62cbbSBarry Smith     count--;
8451eb62cbbSBarry Smith   }
846606d414cSSatish Balay   ierr = PetscFree(recv_waits);CHKERRQ(ierr);
8471eb62cbbSBarry Smith 
8481eb62cbbSBarry Smith   /* move the data into the send scatter */
849b1d57f15SBarry Smith   ierr  = PetscMalloc((slen+1)*sizeof(PetscInt),&lrows);CHKERRQ(ierr);
8501eb62cbbSBarry Smith   count = 0;
8511eb62cbbSBarry Smith   for (i=0; i<nrecvs; i++) {
8521eb62cbbSBarry Smith     values = rvalues + i*nmax;
8532205254eSKarl Rupp     for (j=0; j<lens[i]; j++) lrows[count++] = values[j] - base;
8541eb62cbbSBarry Smith   }
855606d414cSSatish Balay   ierr = PetscFree(rvalues);CHKERRQ(ierr);
8561d79065fSBarry Smith   ierr = PetscFree2(lens,source);CHKERRQ(ierr);
857606d414cSSatish Balay   ierr = PetscFree(owner);CHKERRQ(ierr);
858606d414cSSatish Balay   ierr = PetscFree(nprocs);CHKERRQ(ierr);
8591eb62cbbSBarry Smith 
86097b48c8fSBarry Smith   /* fix right hand side if needed */
86197b48c8fSBarry Smith   if (x && b) {
86297b48c8fSBarry Smith     ierr = VecGetArrayRead(x,&xx);CHKERRQ(ierr);
86397b48c8fSBarry Smith     ierr = VecGetArray(b,&bb);CHKERRQ(ierr);
8642205254eSKarl Rupp     for (i=0; i<slen; i++) bb[lrows[i]] = diag*xx[lrows[i]];
86597b48c8fSBarry Smith     ierr = VecRestoreArrayRead(x,&xx);CHKERRQ(ierr);
86697b48c8fSBarry Smith     ierr = VecRestoreArray(b,&bb);CHKERRQ(ierr);
86797b48c8fSBarry Smith   }
8686eb55b6aSBarry Smith   /*
8696eb55b6aSBarry Smith         Zero the required rows. If the "diagonal block" of the matrix
870a8c7a070SBarry Smith      is square and the user wishes to set the diagonal we use separate
8716eb55b6aSBarry Smith      code so that MatSetValues() is not called for each diagonal allocating
8726eb55b6aSBarry Smith      new memory, thus calling lots of mallocs and slowing things down.
8736eb55b6aSBarry Smith 
8746eb55b6aSBarry Smith   */
875e2d53e46SBarry Smith   /* must zero l->B before l->A because the (diag) case below may put values into l->B*/
8762b40b63fSBarry Smith   ierr = MatZeroRows(l->B,slen,lrows,0.0,0,0);CHKERRQ(ierr);
877d0f46423SBarry Smith   if ((diag != 0.0) && (l->A->rmap->N == l->A->cmap->N)) {
8782b40b63fSBarry Smith     ierr = MatZeroRows(l->A,slen,lrows,diag,0,0);CHKERRQ(ierr);
879f4df32b1SMatthew Knepley   } else if (diag != 0.0) {
8802b40b63fSBarry Smith     ierr = MatZeroRows(l->A,slen,lrows,0.0,0,0);CHKERRQ(ierr);
8812205254eSKarl Rupp     if (((Mat_SeqAIJ*)l->A->data)->nonew) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatZeroRows() on rectangular matrices cannot be used with the Mat options\nMAT_NEW_NONZERO_LOCATIONS,MAT_NEW_NONZERO_LOCATION_ERR,MAT_NEW_NONZERO_ALLOCATION_ERR");
882e2d53e46SBarry Smith     for (i = 0; i < slen; i++) {
883e2d53e46SBarry Smith       row  = lrows[i] + rstart;
884f4df32b1SMatthew Knepley       ierr = MatSetValues(A,1,&row,1,&row,&diag,INSERT_VALUES);CHKERRQ(ierr);
885e2d53e46SBarry Smith     }
886e2d53e46SBarry Smith     ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
887e2d53e46SBarry Smith     ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
8886eb55b6aSBarry Smith   } else {
8892b40b63fSBarry Smith     ierr = MatZeroRows(l->A,slen,lrows,0.0,0,0);CHKERRQ(ierr);
8906eb55b6aSBarry Smith   }
891606d414cSSatish Balay   ierr = PetscFree(lrows);CHKERRQ(ierr);
89272dacd9aSBarry Smith 
8931eb62cbbSBarry Smith   /* wait on sends */
8941eb62cbbSBarry Smith   if (nsends) {
895b0a32e0cSBarry Smith     ierr = PetscMalloc(nsends*sizeof(MPI_Status),&send_status);CHKERRQ(ierr);
896ca161407SBarry Smith     ierr = MPI_Waitall(nsends,send_waits,send_status);CHKERRQ(ierr);
897606d414cSSatish Balay     ierr = PetscFree(send_status);CHKERRQ(ierr);
8981eb62cbbSBarry Smith   }
899606d414cSSatish Balay   ierr = PetscFree(send_waits);CHKERRQ(ierr);
900606d414cSSatish Balay   ierr = PetscFree(svalues);CHKERRQ(ierr);
9013a40ed3dSBarry Smith   PetscFunctionReturn(0);
9021eb62cbbSBarry Smith }
9031eb62cbbSBarry Smith 
9044a2ae208SSatish Balay #undef __FUNCT__
9059c7c4993SBarry Smith #define __FUNCT__ "MatZeroRowsColumns_MPIAIJ"
9069c7c4993SBarry Smith PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
9079c7c4993SBarry Smith {
9089c7c4993SBarry Smith   Mat_MPIAIJ        *l = (Mat_MPIAIJ*)A->data;
9099c7c4993SBarry Smith   PetscErrorCode    ierr;
9109c7c4993SBarry Smith   PetscMPIInt       size = l->size,imdex,n,rank = l->rank,tag = ((PetscObject)A)->tag,lastidx = -1;
9119c7c4993SBarry Smith   PetscInt          i,*owners = A->rmap->range;
912564f14d6SBarry Smith   PetscInt          *nprocs,j,idx,nsends;
9139c7c4993SBarry Smith   PetscInt          nmax,*svalues,*starts,*owner,nrecvs;
9149c7c4993SBarry Smith   PetscInt          *rvalues,count,base,slen,*source;
915564f14d6SBarry Smith   PetscInt          *lens,*lrows,*values,m;
916ce94432eSBarry Smith   MPI_Comm          comm;
9179c7c4993SBarry Smith   MPI_Request       *send_waits,*recv_waits;
9189c7c4993SBarry Smith   MPI_Status        recv_status,*send_status;
9199c7c4993SBarry Smith   const PetscScalar *xx;
920564f14d6SBarry Smith   PetscScalar       *bb,*mask;
921564f14d6SBarry Smith   Vec               xmask,lmask;
922564f14d6SBarry Smith   Mat_SeqAIJ        *aij = (Mat_SeqAIJ*)l->B->data;
923564f14d6SBarry Smith   const PetscInt    *aj, *ii,*ridx;
924564f14d6SBarry Smith   PetscScalar       *aa;
9259c7c4993SBarry Smith #if defined(PETSC_DEBUG)
9269c7c4993SBarry Smith   PetscBool found = PETSC_FALSE;
9279c7c4993SBarry Smith #endif
9289c7c4993SBarry Smith 
9299c7c4993SBarry Smith   PetscFunctionBegin;
930ce94432eSBarry Smith   ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr);
9319c7c4993SBarry Smith   /*  first count number of contributors to each processor */
9329c7c4993SBarry Smith   ierr = PetscMalloc(2*size*sizeof(PetscInt),&nprocs);CHKERRQ(ierr);
9339c7c4993SBarry Smith   ierr = PetscMemzero(nprocs,2*size*sizeof(PetscInt));CHKERRQ(ierr);
9349c7c4993SBarry Smith   ierr = PetscMalloc((N+1)*sizeof(PetscInt),&owner);CHKERRQ(ierr); /* see note*/
9359c7c4993SBarry Smith   j    = 0;
9369c7c4993SBarry Smith   for (i=0; i<N; i++) {
9379c7c4993SBarry Smith     if (lastidx > (idx = rows[i])) j = 0;
9389c7c4993SBarry Smith     lastidx = idx;
9399c7c4993SBarry Smith     for (; j<size; j++) {
9409c7c4993SBarry Smith       if (idx >= owners[j] && idx < owners[j+1]) {
9419c7c4993SBarry Smith         nprocs[2*j]++;
9429c7c4993SBarry Smith         nprocs[2*j+1] = 1;
9439c7c4993SBarry Smith         owner[i]      = j;
9449c7c4993SBarry Smith #if defined(PETSC_DEBUG)
9459c7c4993SBarry Smith         found = PETSC_TRUE;
9469c7c4993SBarry Smith #endif
9479c7c4993SBarry Smith         break;
9489c7c4993SBarry Smith       }
9499c7c4993SBarry Smith     }
9509c7c4993SBarry Smith #if defined(PETSC_DEBUG)
9519c7c4993SBarry Smith     if (!found) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Index out of range");
9529c7c4993SBarry Smith     found = PETSC_FALSE;
9539c7c4993SBarry Smith #endif
9549c7c4993SBarry Smith   }
9552205254eSKarl Rupp   nsends = 0;  for (i=0; i<size; i++) nsends += nprocs[2*i+1];
9569c7c4993SBarry Smith 
9579c7c4993SBarry Smith   /* inform other processors of number of messages and max length*/
9589c7c4993SBarry Smith   ierr = PetscMaxSum(comm,nprocs,&nmax,&nrecvs);CHKERRQ(ierr);
9599c7c4993SBarry Smith 
9609c7c4993SBarry Smith   /* post receives:   */
9619c7c4993SBarry Smith   ierr = PetscMalloc((nrecvs+1)*(nmax+1)*sizeof(PetscInt),&rvalues);CHKERRQ(ierr);
9629c7c4993SBarry Smith   ierr = PetscMalloc((nrecvs+1)*sizeof(MPI_Request),&recv_waits);CHKERRQ(ierr);
9639c7c4993SBarry Smith   for (i=0; i<nrecvs; i++) {
9649c7c4993SBarry Smith     ierr = MPI_Irecv(rvalues+nmax*i,nmax,MPIU_INT,MPI_ANY_SOURCE,tag,comm,recv_waits+i);CHKERRQ(ierr);
9659c7c4993SBarry Smith   }
9669c7c4993SBarry Smith 
9679c7c4993SBarry Smith   /* do sends:
9689c7c4993SBarry Smith       1) starts[i] gives the starting index in svalues for stuff going to
9699c7c4993SBarry Smith          the ith processor
9709c7c4993SBarry Smith   */
9719c7c4993SBarry Smith   ierr = PetscMalloc((N+1)*sizeof(PetscInt),&svalues);CHKERRQ(ierr);
9729c7c4993SBarry Smith   ierr = PetscMalloc((nsends+1)*sizeof(MPI_Request),&send_waits);CHKERRQ(ierr);
9739c7c4993SBarry Smith   ierr = PetscMalloc((size+1)*sizeof(PetscInt),&starts);CHKERRQ(ierr);
9749c7c4993SBarry Smith 
9759c7c4993SBarry Smith   starts[0] = 0;
9762205254eSKarl Rupp   for (i=1; i<size; i++) starts[i] = starts[i-1] + nprocs[2*i-2];
9772205254eSKarl Rupp   for (i=0; i<N; i++) svalues[starts[owner[i]]++] = rows[i];
9782205254eSKarl Rupp 
9792205254eSKarl Rupp   starts[0] = 0;
9802205254eSKarl Rupp   for (i=1; i<size+1; i++) starts[i] = starts[i-1] + nprocs[2*i-2];
9819c7c4993SBarry Smith   count = 0;
9829c7c4993SBarry Smith   for (i=0; i<size; i++) {
9839c7c4993SBarry Smith     if (nprocs[2*i+1]) {
9849c7c4993SBarry Smith       ierr = MPI_Isend(svalues+starts[i],nprocs[2*i],MPIU_INT,i,tag,comm,send_waits+count++);CHKERRQ(ierr);
9859c7c4993SBarry Smith     }
9869c7c4993SBarry Smith   }
9879c7c4993SBarry Smith   ierr = PetscFree(starts);CHKERRQ(ierr);
9889c7c4993SBarry Smith 
9899c7c4993SBarry Smith   base = owners[rank];
9909c7c4993SBarry Smith 
9919c7c4993SBarry Smith   /*  wait on receives */
9929c7c4993SBarry Smith   ierr  = PetscMalloc2(nrecvs,PetscInt,&lens,nrecvs,PetscInt,&source);CHKERRQ(ierr);
9939c7c4993SBarry Smith   count = nrecvs; slen = 0;
9949c7c4993SBarry Smith   while (count) {
9959c7c4993SBarry Smith     ierr = MPI_Waitany(nrecvs,recv_waits,&imdex,&recv_status);CHKERRQ(ierr);
9969c7c4993SBarry Smith     /* unpack receives into our local space */
9979c7c4993SBarry Smith     ierr = MPI_Get_count(&recv_status,MPIU_INT,&n);CHKERRQ(ierr);
9982205254eSKarl Rupp 
9999c7c4993SBarry Smith     source[imdex] = recv_status.MPI_SOURCE;
10009c7c4993SBarry Smith     lens[imdex]   = n;
10019c7c4993SBarry Smith     slen         += n;
10029c7c4993SBarry Smith     count--;
10039c7c4993SBarry Smith   }
10049c7c4993SBarry Smith   ierr = PetscFree(recv_waits);CHKERRQ(ierr);
10059c7c4993SBarry Smith 
10069c7c4993SBarry Smith   /* move the data into the send scatter */
10079c7c4993SBarry Smith   ierr  = PetscMalloc((slen+1)*sizeof(PetscInt),&lrows);CHKERRQ(ierr);
10089c7c4993SBarry Smith   count = 0;
10099c7c4993SBarry Smith   for (i=0; i<nrecvs; i++) {
10109c7c4993SBarry Smith     values = rvalues + i*nmax;
10112205254eSKarl Rupp     for (j=0; j<lens[i]; j++) lrows[count++] = values[j] - base;
10129c7c4993SBarry Smith   }
10139c7c4993SBarry Smith   ierr = PetscFree(rvalues);CHKERRQ(ierr);
10149c7c4993SBarry Smith   ierr = PetscFree2(lens,source);CHKERRQ(ierr);
10159c7c4993SBarry Smith   ierr = PetscFree(owner);CHKERRQ(ierr);
10169c7c4993SBarry Smith   ierr = PetscFree(nprocs);CHKERRQ(ierr);
1017564f14d6SBarry Smith   /* lrows are the local rows to be zeroed, slen is the number of local rows */
10189c7c4993SBarry Smith 
1019564f14d6SBarry Smith   /* zero diagonal part of matrix */
1020564f14d6SBarry Smith   ierr = MatZeroRowsColumns(l->A,slen,lrows,diag,x,b);CHKERRQ(ierr);
10219c7c4993SBarry Smith 
1022564f14d6SBarry Smith   /* handle off diagonal part of matrix */
10230298fd71SBarry Smith   ierr = MatGetVecs(A,&xmask,NULL);CHKERRQ(ierr);
1024564f14d6SBarry Smith   ierr = VecDuplicate(l->lvec,&lmask);CHKERRQ(ierr);
1025564f14d6SBarry Smith   ierr = VecGetArray(xmask,&bb);CHKERRQ(ierr);
10262205254eSKarl Rupp   for (i=0; i<slen; i++) bb[lrows[i]] = 1;
1027564f14d6SBarry Smith   ierr = VecRestoreArray(xmask,&bb);CHKERRQ(ierr);
1028564f14d6SBarry Smith   ierr = VecScatterBegin(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1029564f14d6SBarry Smith   ierr = VecScatterEnd(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
10306bf464f9SBarry Smith   ierr = VecDestroy(&xmask);CHKERRQ(ierr);
1031377aa5a1SBarry Smith   if (x) {
1032564f14d6SBarry Smith     ierr = VecScatterBegin(l->Mvctx,x,l->lvec,ADD_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1033564f14d6SBarry Smith     ierr = VecScatterEnd(l->Mvctx,x,l->lvec,ADD_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1034564f14d6SBarry Smith     ierr = VecGetArrayRead(l->lvec,&xx);CHKERRQ(ierr);
1035564f14d6SBarry Smith     ierr = VecGetArray(b,&bb);CHKERRQ(ierr);
1036377aa5a1SBarry Smith   }
1037377aa5a1SBarry Smith   ierr = VecGetArray(lmask,&mask);CHKERRQ(ierr);
1038564f14d6SBarry Smith 
1039564f14d6SBarry Smith   /* remove zeroed rows of off diagonal matrix */
1040564f14d6SBarry Smith   ii = aij->i;
1041564f14d6SBarry Smith   for (i=0; i<slen; i++) {
1042564f14d6SBarry Smith     ierr = PetscMemzero(aij->a + ii[lrows[i]],(ii[lrows[i]+1] - ii[lrows[i]])*sizeof(PetscScalar));CHKERRQ(ierr);
10439c7c4993SBarry Smith   }
1044564f14d6SBarry Smith 
1045564f14d6SBarry Smith   /* loop over all elements of off process part of matrix zeroing removed columns*/
1046564f14d6SBarry Smith   if (aij->compressedrow.use) {
1047564f14d6SBarry Smith     m    = aij->compressedrow.nrows;
1048564f14d6SBarry Smith     ii   = aij->compressedrow.i;
1049564f14d6SBarry Smith     ridx = aij->compressedrow.rindex;
1050564f14d6SBarry Smith     for (i=0; i<m; i++) {
1051564f14d6SBarry Smith       n  = ii[i+1] - ii[i];
1052564f14d6SBarry Smith       aj = aij->j + ii[i];
1053564f14d6SBarry Smith       aa = aij->a + ii[i];
1054564f14d6SBarry Smith 
1055564f14d6SBarry Smith       for (j=0; j<n; j++) {
105625266a92SSatish Balay         if (PetscAbsScalar(mask[*aj])) {
1057377aa5a1SBarry Smith           if (b) bb[*ridx] -= *aa*xx[*aj];
1058564f14d6SBarry Smith           *aa = 0.0;
1059564f14d6SBarry Smith         }
1060564f14d6SBarry Smith         aa++;
1061564f14d6SBarry Smith         aj++;
1062564f14d6SBarry Smith       }
1063564f14d6SBarry Smith       ridx++;
1064564f14d6SBarry Smith     }
1065564f14d6SBarry Smith   } else { /* do not use compressed row format */
1066564f14d6SBarry Smith     m = l->B->rmap->n;
1067564f14d6SBarry Smith     for (i=0; i<m; i++) {
1068564f14d6SBarry Smith       n  = ii[i+1] - ii[i];
1069564f14d6SBarry Smith       aj = aij->j + ii[i];
1070564f14d6SBarry Smith       aa = aij->a + ii[i];
1071564f14d6SBarry Smith       for (j=0; j<n; j++) {
107225266a92SSatish Balay         if (PetscAbsScalar(mask[*aj])) {
1073377aa5a1SBarry Smith           if (b) bb[i] -= *aa*xx[*aj];
1074564f14d6SBarry Smith           *aa = 0.0;
1075564f14d6SBarry Smith         }
1076564f14d6SBarry Smith         aa++;
1077564f14d6SBarry Smith         aj++;
1078564f14d6SBarry Smith       }
1079564f14d6SBarry Smith     }
1080564f14d6SBarry Smith   }
1081377aa5a1SBarry Smith   if (x) {
1082564f14d6SBarry Smith     ierr = VecRestoreArray(b,&bb);CHKERRQ(ierr);
1083564f14d6SBarry Smith     ierr = VecRestoreArrayRead(l->lvec,&xx);CHKERRQ(ierr);
1084377aa5a1SBarry Smith   }
1085377aa5a1SBarry Smith   ierr = VecRestoreArray(lmask,&mask);CHKERRQ(ierr);
10866bf464f9SBarry Smith   ierr = VecDestroy(&lmask);CHKERRQ(ierr);
10879c7c4993SBarry Smith   ierr = PetscFree(lrows);CHKERRQ(ierr);
10889c7c4993SBarry Smith 
10899c7c4993SBarry Smith   /* wait on sends */
10909c7c4993SBarry Smith   if (nsends) {
10919c7c4993SBarry Smith     ierr = PetscMalloc(nsends*sizeof(MPI_Status),&send_status);CHKERRQ(ierr);
10929c7c4993SBarry Smith     ierr = MPI_Waitall(nsends,send_waits,send_status);CHKERRQ(ierr);
10939c7c4993SBarry Smith     ierr = PetscFree(send_status);CHKERRQ(ierr);
10949c7c4993SBarry Smith   }
10959c7c4993SBarry Smith   ierr = PetscFree(send_waits);CHKERRQ(ierr);
10969c7c4993SBarry Smith   ierr = PetscFree(svalues);CHKERRQ(ierr);
10979c7c4993SBarry Smith   PetscFunctionReturn(0);
10989c7c4993SBarry Smith }
10999c7c4993SBarry Smith 
11009c7c4993SBarry Smith #undef __FUNCT__
11014a2ae208SSatish Balay #define __FUNCT__ "MatMult_MPIAIJ"
1102dfbe8321SBarry Smith PetscErrorCode MatMult_MPIAIJ(Mat A,Vec xx,Vec yy)
11031eb62cbbSBarry Smith {
1104416022c9SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1105dfbe8321SBarry Smith   PetscErrorCode ierr;
1106b1d57f15SBarry Smith   PetscInt       nt;
1107416022c9SBarry Smith 
11083a40ed3dSBarry Smith   PetscFunctionBegin;
1109a2ce50c7SBarry Smith   ierr = VecGetLocalSize(xx,&nt);CHKERRQ(ierr);
111065e19b50SBarry Smith   if (nt != A->cmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible partition of A (%D) and xx (%D)",A->cmap->n,nt);
1111ca9f406cSSatish Balay   ierr = VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1112f830108cSBarry Smith   ierr = (*a->A->ops->mult)(a->A,xx,yy);CHKERRQ(ierr);
1113ca9f406cSSatish Balay   ierr = VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1114f830108cSBarry Smith   ierr = (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);CHKERRQ(ierr);
11153a40ed3dSBarry Smith   PetscFunctionReturn(0);
11161eb62cbbSBarry Smith }
11171eb62cbbSBarry Smith 
11184a2ae208SSatish Balay #undef __FUNCT__
1119bd0c2dcbSBarry Smith #define __FUNCT__ "MatMultDiagonalBlock_MPIAIJ"
1120bd0c2dcbSBarry Smith PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A,Vec bb,Vec xx)
1121bd0c2dcbSBarry Smith {
1122bd0c2dcbSBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1123bd0c2dcbSBarry Smith   PetscErrorCode ierr;
1124bd0c2dcbSBarry Smith 
1125bd0c2dcbSBarry Smith   PetscFunctionBegin;
1126bd0c2dcbSBarry Smith   ierr = MatMultDiagonalBlock(a->A,bb,xx);CHKERRQ(ierr);
1127bd0c2dcbSBarry Smith   PetscFunctionReturn(0);
1128bd0c2dcbSBarry Smith }
1129bd0c2dcbSBarry Smith 
1130bd0c2dcbSBarry Smith #undef __FUNCT__
11314a2ae208SSatish Balay #define __FUNCT__ "MatMultAdd_MPIAIJ"
1132dfbe8321SBarry Smith PetscErrorCode MatMultAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1133da3a660dSBarry Smith {
1134416022c9SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1135dfbe8321SBarry Smith   PetscErrorCode ierr;
11363a40ed3dSBarry Smith 
11373a40ed3dSBarry Smith   PetscFunctionBegin;
1138ca9f406cSSatish Balay   ierr = VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1139f830108cSBarry Smith   ierr = (*a->A->ops->multadd)(a->A,xx,yy,zz);CHKERRQ(ierr);
1140ca9f406cSSatish Balay   ierr = VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1141f830108cSBarry Smith   ierr = (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);CHKERRQ(ierr);
11423a40ed3dSBarry Smith   PetscFunctionReturn(0);
1143da3a660dSBarry Smith }
1144da3a660dSBarry Smith 
11454a2ae208SSatish Balay #undef __FUNCT__
11464a2ae208SSatish Balay #define __FUNCT__ "MatMultTranspose_MPIAIJ"
1147dfbe8321SBarry Smith PetscErrorCode MatMultTranspose_MPIAIJ(Mat A,Vec xx,Vec yy)
1148da3a660dSBarry Smith {
1149416022c9SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1150dfbe8321SBarry Smith   PetscErrorCode ierr;
1151ace3abfcSBarry Smith   PetscBool      merged;
1152da3a660dSBarry Smith 
11533a40ed3dSBarry Smith   PetscFunctionBegin;
1154a5ff213dSBarry Smith   ierr = VecScatterGetMerged(a->Mvctx,&merged);CHKERRQ(ierr);
1155da3a660dSBarry Smith   /* do nondiagonal part */
11567c922b88SBarry Smith   ierr = (*a->B->ops->multtranspose)(a->B,xx,a->lvec);CHKERRQ(ierr);
1157a5ff213dSBarry Smith   if (!merged) {
1158da3a660dSBarry Smith     /* send it on its way */
1159ca9f406cSSatish Balay     ierr = VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
1160da3a660dSBarry Smith     /* do local part */
11617c922b88SBarry Smith     ierr = (*a->A->ops->multtranspose)(a->A,xx,yy);CHKERRQ(ierr);
1162da3a660dSBarry Smith     /* receive remote parts: note this assumes the values are not actually */
1163a5ff213dSBarry Smith     /* added in yy until the next line, */
1164ca9f406cSSatish Balay     ierr = VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
1165a5ff213dSBarry Smith   } else {
1166a5ff213dSBarry Smith     /* do local part */
1167a5ff213dSBarry Smith     ierr = (*a->A->ops->multtranspose)(a->A,xx,yy);CHKERRQ(ierr);
1168a5ff213dSBarry Smith     /* send it on its way */
1169ca9f406cSSatish Balay     ierr = VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
1170a5ff213dSBarry Smith     /* values actually were received in the Begin() but we need to call this nop */
1171ca9f406cSSatish Balay     ierr = VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
1172a5ff213dSBarry Smith   }
11733a40ed3dSBarry Smith   PetscFunctionReturn(0);
1174da3a660dSBarry Smith }
1175da3a660dSBarry Smith 
1176cd0d46ebSvictorle #undef __FUNCT__
11775fbd3699SBarry Smith #define __FUNCT__ "MatIsTranspose_MPIAIJ"
11787087cfbeSBarry Smith PetscErrorCode  MatIsTranspose_MPIAIJ(Mat Amat,Mat Bmat,PetscReal tol,PetscBool  *f)
1179cd0d46ebSvictorle {
11804f423910Svictorle   MPI_Comm       comm;
1181cd0d46ebSvictorle   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ*) Amat->data, *Bij;
118266501d38Svictorle   Mat            Adia = Aij->A, Bdia, Aoff,Boff,*Aoffs,*Boffs;
1183cd0d46ebSvictorle   IS             Me,Notme;
11846849ba73SBarry Smith   PetscErrorCode ierr;
1185b1d57f15SBarry Smith   PetscInt       M,N,first,last,*notme,i;
1186b1d57f15SBarry Smith   PetscMPIInt    size;
1187cd0d46ebSvictorle 
1188cd0d46ebSvictorle   PetscFunctionBegin;
118942e5f5b4Svictorle   /* Easy test: symmetric diagonal block */
119066501d38Svictorle   Bij  = (Mat_MPIAIJ*) Bmat->data; Bdia = Bij->A;
11915485867bSBarry Smith   ierr = MatIsTranspose(Adia,Bdia,tol,f);CHKERRQ(ierr);
1192cd0d46ebSvictorle   if (!*f) PetscFunctionReturn(0);
11934f423910Svictorle   ierr = PetscObjectGetComm((PetscObject)Amat,&comm);CHKERRQ(ierr);
1194b1d57f15SBarry Smith   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
1195b1d57f15SBarry Smith   if (size == 1) PetscFunctionReturn(0);
119642e5f5b4Svictorle 
119742e5f5b4Svictorle   /* Hard test: off-diagonal block. This takes a MatGetSubMatrix. */
1198cd0d46ebSvictorle   ierr = MatGetSize(Amat,&M,&N);CHKERRQ(ierr);
1199cd0d46ebSvictorle   ierr = MatGetOwnershipRange(Amat,&first,&last);CHKERRQ(ierr);
1200b1d57f15SBarry Smith   ierr = PetscMalloc((N-last+first)*sizeof(PetscInt),&notme);CHKERRQ(ierr);
1201cd0d46ebSvictorle   for (i=0; i<first; i++) notme[i] = i;
1202cd0d46ebSvictorle   for (i=last; i<M; i++) notme[i-last+first] = i;
120370b3c8c7SBarry Smith   ierr = ISCreateGeneral(MPI_COMM_SELF,N-last+first,notme,PETSC_COPY_VALUES,&Notme);CHKERRQ(ierr);
1204268466fbSBarry Smith   ierr = ISCreateStride(MPI_COMM_SELF,last-first,first,1,&Me);CHKERRQ(ierr);
1205268466fbSBarry Smith   ierr = MatGetSubMatrices(Amat,1,&Me,&Notme,MAT_INITIAL_MATRIX,&Aoffs);CHKERRQ(ierr);
120666501d38Svictorle   Aoff = Aoffs[0];
1207268466fbSBarry Smith   ierr = MatGetSubMatrices(Bmat,1,&Notme,&Me,MAT_INITIAL_MATRIX,&Boffs);CHKERRQ(ierr);
120866501d38Svictorle   Boff = Boffs[0];
12095485867bSBarry Smith   ierr = MatIsTranspose(Aoff,Boff,tol,f);CHKERRQ(ierr);
121066501d38Svictorle   ierr = MatDestroyMatrices(1,&Aoffs);CHKERRQ(ierr);
121166501d38Svictorle   ierr = MatDestroyMatrices(1,&Boffs);CHKERRQ(ierr);
12126bf464f9SBarry Smith   ierr = ISDestroy(&Me);CHKERRQ(ierr);
12136bf464f9SBarry Smith   ierr = ISDestroy(&Notme);CHKERRQ(ierr);
12143e0d0d19SHong Zhang   ierr = PetscFree(notme);CHKERRQ(ierr);
1215cd0d46ebSvictorle   PetscFunctionReturn(0);
1216cd0d46ebSvictorle }
1217cd0d46ebSvictorle 
12184a2ae208SSatish Balay #undef __FUNCT__
12194a2ae208SSatish Balay #define __FUNCT__ "MatMultTransposeAdd_MPIAIJ"
1220dfbe8321SBarry Smith PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1221da3a660dSBarry Smith {
1222416022c9SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1223dfbe8321SBarry Smith   PetscErrorCode ierr;
1224da3a660dSBarry Smith 
12253a40ed3dSBarry Smith   PetscFunctionBegin;
1226da3a660dSBarry Smith   /* do nondiagonal part */
12277c922b88SBarry Smith   ierr = (*a->B->ops->multtranspose)(a->B,xx,a->lvec);CHKERRQ(ierr);
1228da3a660dSBarry Smith   /* send it on its way */
1229ca9f406cSSatish Balay   ierr = VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
1230da3a660dSBarry Smith   /* do local part */
12317c922b88SBarry Smith   ierr = (*a->A->ops->multtransposeadd)(a->A,xx,yy,zz);CHKERRQ(ierr);
1232a5ff213dSBarry Smith   /* receive remote parts */
1233ca9f406cSSatish Balay   ierr = VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
12343a40ed3dSBarry Smith   PetscFunctionReturn(0);
1235da3a660dSBarry Smith }
1236da3a660dSBarry Smith 
12371eb62cbbSBarry Smith /*
12381eb62cbbSBarry Smith   This only works correctly for square matrices where the subblock A->A is the
12391eb62cbbSBarry Smith    diagonal block
12401eb62cbbSBarry Smith */
12414a2ae208SSatish Balay #undef __FUNCT__
12424a2ae208SSatish Balay #define __FUNCT__ "MatGetDiagonal_MPIAIJ"
1243dfbe8321SBarry Smith PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A,Vec v)
12441eb62cbbSBarry Smith {
1245dfbe8321SBarry Smith   PetscErrorCode ierr;
1246416022c9SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
12473a40ed3dSBarry Smith 
12483a40ed3dSBarry Smith   PetscFunctionBegin;
1249ce94432eSBarry Smith   if (A->rmap->N != A->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block");
1250e7e72b3dSBarry Smith   if (A->rmap->rstart != A->cmap->rstart || A->rmap->rend != A->cmap->rend) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"row partition must equal col partition");
12513a40ed3dSBarry Smith   ierr = MatGetDiagonal(a->A,v);CHKERRQ(ierr);
12523a40ed3dSBarry Smith   PetscFunctionReturn(0);
12531eb62cbbSBarry Smith }
12541eb62cbbSBarry Smith 
12554a2ae208SSatish Balay #undef __FUNCT__
12564a2ae208SSatish Balay #define __FUNCT__ "MatScale_MPIAIJ"
1257f4df32b1SMatthew Knepley PetscErrorCode MatScale_MPIAIJ(Mat A,PetscScalar aa)
1258052efed2SBarry Smith {
1259052efed2SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1260dfbe8321SBarry Smith   PetscErrorCode ierr;
12613a40ed3dSBarry Smith 
12623a40ed3dSBarry Smith   PetscFunctionBegin;
1263f4df32b1SMatthew Knepley   ierr = MatScale(a->A,aa);CHKERRQ(ierr);
1264f4df32b1SMatthew Knepley   ierr = MatScale(a->B,aa);CHKERRQ(ierr);
12653a40ed3dSBarry Smith   PetscFunctionReturn(0);
1266052efed2SBarry Smith }
1267052efed2SBarry Smith 
12684a2ae208SSatish Balay #undef __FUNCT__
12694a2ae208SSatish Balay #define __FUNCT__ "MatDestroy_MPIAIJ"
1270dfbe8321SBarry Smith PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
12711eb62cbbSBarry Smith {
127244a69424SLois Curfman McInnes   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
1273dfbe8321SBarry Smith   PetscErrorCode ierr;
127483e2fdc7SBarry Smith 
12753a40ed3dSBarry Smith   PetscFunctionBegin;
1276aa482453SBarry Smith #if defined(PETSC_USE_LOG)
1277d0f46423SBarry Smith   PetscLogObjectState((PetscObject)mat,"Rows=%D, Cols=%D",mat->rmap->N,mat->cmap->N);
1278a5a9c739SBarry Smith #endif
12798798bf22SSatish Balay   ierr = MatStashDestroy_Private(&mat->stash);CHKERRQ(ierr);
12806bf464f9SBarry Smith   ierr = VecDestroy(&aij->diag);CHKERRQ(ierr);
12816bf464f9SBarry Smith   ierr = MatDestroy(&aij->A);CHKERRQ(ierr);
12826bf464f9SBarry Smith   ierr = MatDestroy(&aij->B);CHKERRQ(ierr);
1283aa482453SBarry Smith #if defined(PETSC_USE_CTABLE)
12846bc0bbbfSBarry Smith   ierr = PetscTableDestroy(&aij->colmap);CHKERRQ(ierr);
1285b1fc9764SSatish Balay #else
128605b42c5fSBarry Smith   ierr = PetscFree(aij->colmap);CHKERRQ(ierr);
1287b1fc9764SSatish Balay #endif
128805b42c5fSBarry Smith   ierr = PetscFree(aij->garray);CHKERRQ(ierr);
12896bf464f9SBarry Smith   ierr = VecDestroy(&aij->lvec);CHKERRQ(ierr);
12906bf464f9SBarry Smith   ierr = VecScatterDestroy(&aij->Mvctx);CHKERRQ(ierr);
129103095fedSBarry Smith   ierr = PetscFree2(aij->rowvalues,aij->rowindices);CHKERRQ(ierr);
12928aa348c1SBarry Smith   ierr = PetscFree(aij->ld);CHKERRQ(ierr);
1293bf0cc555SLisandro Dalcin   ierr = PetscFree(mat->data);CHKERRQ(ierr);
1294901853e0SKris Buschelman 
1295dbd8c25aSHong Zhang   ierr = PetscObjectChangeTypeName((PetscObject)mat,0);CHKERRQ(ierr);
1296bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatStoreValues_C",NULL);CHKERRQ(ierr);
1297bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatRetrieveValues_C",NULL);CHKERRQ(ierr);
1298bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatGetDiagonalBlock_C",NULL);CHKERRQ(ierr);
1299bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatIsTranspose_C",NULL);CHKERRQ(ierr);
1300bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocation_C",NULL);CHKERRQ(ierr);
1301bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocationCSR_C",NULL);CHKERRQ(ierr);
1302bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatDiagonalScaleLocal_C",NULL);CHKERRQ(ierr);
1303bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_mpisbaij_C",NULL);CHKERRQ(ierr);
13043a40ed3dSBarry Smith   PetscFunctionReturn(0);
13051eb62cbbSBarry Smith }
1306ee50ffe9SBarry Smith 
13074a2ae208SSatish Balay #undef __FUNCT__
13088e2fed03SBarry Smith #define __FUNCT__ "MatView_MPIAIJ_Binary"
1309dfbe8321SBarry Smith PetscErrorCode MatView_MPIAIJ_Binary(Mat mat,PetscViewer viewer)
13108e2fed03SBarry Smith {
13118e2fed03SBarry Smith   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
13128e2fed03SBarry Smith   Mat_SeqAIJ     *A   = (Mat_SeqAIJ*)aij->A->data;
13138e2fed03SBarry Smith   Mat_SeqAIJ     *B   = (Mat_SeqAIJ*)aij->B->data;
13146849ba73SBarry Smith   PetscErrorCode ierr;
131532dcc486SBarry Smith   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
13166f69ff64SBarry Smith   int            fd;
1317a788621eSSatish Balay   PetscInt       nz,header[4],*row_lengths,*range=0,rlen,i;
1318d0f46423SBarry Smith   PetscInt       nzmax,*column_indices,j,k,col,*garray = aij->garray,cnt,cstart = mat->cmap->rstart,rnz;
13198e2fed03SBarry Smith   PetscScalar    *column_values;
132085ebf7a4SBarry Smith   PetscInt       message_count,flowcontrolcount;
1321b37d52dbSMark F. Adams   FILE           *file;
13228e2fed03SBarry Smith 
13238e2fed03SBarry Smith   PetscFunctionBegin;
1324ce94432eSBarry Smith   ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);CHKERRQ(ierr);
1325ce94432eSBarry Smith   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);CHKERRQ(ierr);
13268e2fed03SBarry Smith   nz   = A->nz + B->nz;
1327958c9bccSBarry Smith   if (!rank) {
13280700a824SBarry Smith     header[0] = MAT_FILE_CLASSID;
1329d0f46423SBarry Smith     header[1] = mat->rmap->N;
1330d0f46423SBarry Smith     header[2] = mat->cmap->N;
13312205254eSKarl Rupp 
1332ce94432eSBarry Smith     ierr = MPI_Reduce(&nz,&header[3],1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
13338e2fed03SBarry Smith     ierr = PetscViewerBinaryGetDescriptor(viewer,&fd);CHKERRQ(ierr);
13346f69ff64SBarry Smith     ierr = PetscBinaryWrite(fd,header,4,PETSC_INT,PETSC_TRUE);CHKERRQ(ierr);
13358e2fed03SBarry Smith     /* get largest number of rows any processor has */
1336d0f46423SBarry Smith     rlen  = mat->rmap->n;
1337d0f46423SBarry Smith     range = mat->rmap->range;
13382205254eSKarl Rupp     for (i=1; i<size; i++) rlen = PetscMax(rlen,range[i+1] - range[i]);
13398e2fed03SBarry Smith   } else {
1340ce94432eSBarry Smith     ierr = MPI_Reduce(&nz,0,1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
1341d0f46423SBarry Smith     rlen = mat->rmap->n;
13428e2fed03SBarry Smith   }
13438e2fed03SBarry Smith 
13448e2fed03SBarry Smith   /* load up the local row counts */
1345b1d57f15SBarry Smith   ierr = PetscMalloc((rlen+1)*sizeof(PetscInt),&row_lengths);CHKERRQ(ierr);
13462205254eSKarl Rupp   for (i=0; i<mat->rmap->n; i++) row_lengths[i] = A->i[i+1] - A->i[i] + B->i[i+1] - B->i[i];
13478e2fed03SBarry Smith 
13488e2fed03SBarry Smith   /* store the row lengths to the file */
134985ebf7a4SBarry Smith   ierr = PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);CHKERRQ(ierr);
1350958c9bccSBarry Smith   if (!rank) {
1351d0f46423SBarry Smith     ierr = PetscBinaryWrite(fd,row_lengths,mat->rmap->n,PETSC_INT,PETSC_TRUE);CHKERRQ(ierr);
13528e2fed03SBarry Smith     for (i=1; i<size; i++) {
1353639ff905SBarry Smith       ierr = PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);CHKERRQ(ierr);
13548e2fed03SBarry Smith       rlen = range[i+1] - range[i];
1355ce94432eSBarry Smith       ierr = MPIULong_Recv(row_lengths,rlen,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
13566f69ff64SBarry Smith       ierr = PetscBinaryWrite(fd,row_lengths,rlen,PETSC_INT,PETSC_TRUE);CHKERRQ(ierr);
13578e2fed03SBarry Smith     }
1358639ff905SBarry Smith     ierr = PetscViewerFlowControlEndMaster(viewer,&message_count);CHKERRQ(ierr);
13598e2fed03SBarry Smith   } else {
1360639ff905SBarry Smith     ierr = PetscViewerFlowControlStepWorker(viewer,rank,&message_count);CHKERRQ(ierr);
1361ce94432eSBarry Smith     ierr = MPIULong_Send(row_lengths,mat->rmap->n,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
1362639ff905SBarry Smith     ierr = PetscViewerFlowControlEndWorker(viewer,&message_count);CHKERRQ(ierr);
13638e2fed03SBarry Smith   }
13648e2fed03SBarry Smith   ierr = PetscFree(row_lengths);CHKERRQ(ierr);
13658e2fed03SBarry Smith 
13668e2fed03SBarry Smith   /* load up the local column indices */
13671147fc2aSKarl Rupp   nzmax = nz; /* th processor needs space a largest processor needs */
1368ce94432eSBarry Smith   ierr  = MPI_Reduce(&nz,&nzmax,1,MPIU_INT,MPI_MAX,0,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
1369b1d57f15SBarry Smith   ierr  = PetscMalloc((nzmax+1)*sizeof(PetscInt),&column_indices);CHKERRQ(ierr);
13708e2fed03SBarry Smith   cnt   = 0;
1371d0f46423SBarry Smith   for (i=0; i<mat->rmap->n; i++) {
13728e2fed03SBarry Smith     for (j=B->i[i]; j<B->i[i+1]; j++) {
13738e2fed03SBarry Smith       if ((col = garray[B->j[j]]) > cstart) break;
13748e2fed03SBarry Smith       column_indices[cnt++] = col;
13758e2fed03SBarry Smith     }
13762205254eSKarl Rupp     for (k=A->i[i]; k<A->i[i+1]; k++) column_indices[cnt++] = A->j[k] + cstart;
13772205254eSKarl Rupp     for (; j<B->i[i+1]; j++) column_indices[cnt++] = garray[B->j[j]];
13788e2fed03SBarry Smith   }
1379e32f2f54SBarry Smith   if (cnt != A->nz + B->nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: cnt = %D nz = %D",cnt,A->nz+B->nz);
13808e2fed03SBarry Smith 
13818e2fed03SBarry Smith   /* store the column indices to the file */
138285ebf7a4SBarry Smith   ierr = PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);CHKERRQ(ierr);
1383958c9bccSBarry Smith   if (!rank) {
13848e2fed03SBarry Smith     MPI_Status status;
13856f69ff64SBarry Smith     ierr = PetscBinaryWrite(fd,column_indices,nz,PETSC_INT,PETSC_TRUE);CHKERRQ(ierr);
13868e2fed03SBarry Smith     for (i=1; i<size; i++) {
1387639ff905SBarry Smith       ierr = PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);CHKERRQ(ierr);
1388ce94432eSBarry Smith       ierr = MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);CHKERRQ(ierr);
1389e32f2f54SBarry Smith       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1390ce94432eSBarry Smith       ierr = MPIULong_Recv(column_indices,rnz,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
13916f69ff64SBarry Smith       ierr = PetscBinaryWrite(fd,column_indices,rnz,PETSC_INT,PETSC_TRUE);CHKERRQ(ierr);
13928e2fed03SBarry Smith     }
1393639ff905SBarry Smith     ierr = PetscViewerFlowControlEndMaster(viewer,&message_count);CHKERRQ(ierr);
13948e2fed03SBarry Smith   } else {
1395639ff905SBarry Smith     ierr = PetscViewerFlowControlStepWorker(viewer,rank,&message_count);CHKERRQ(ierr);
1396ce94432eSBarry Smith     ierr = MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
1397ce94432eSBarry Smith     ierr = MPIULong_Send(column_indices,nz,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
1398639ff905SBarry Smith     ierr = PetscViewerFlowControlEndWorker(viewer,&message_count);CHKERRQ(ierr);
13998e2fed03SBarry Smith   }
14008e2fed03SBarry Smith   ierr = PetscFree(column_indices);CHKERRQ(ierr);
14018e2fed03SBarry Smith 
14028e2fed03SBarry Smith   /* load up the local column values */
14038e2fed03SBarry Smith   ierr = PetscMalloc((nzmax+1)*sizeof(PetscScalar),&column_values);CHKERRQ(ierr);
14048e2fed03SBarry Smith   cnt  = 0;
1405d0f46423SBarry Smith   for (i=0; i<mat->rmap->n; i++) {
14068e2fed03SBarry Smith     for (j=B->i[i]; j<B->i[i+1]; j++) {
14078e2fed03SBarry Smith       if (garray[B->j[j]] > cstart) break;
14088e2fed03SBarry Smith       column_values[cnt++] = B->a[j];
14098e2fed03SBarry Smith     }
14102205254eSKarl Rupp     for (k=A->i[i]; k<A->i[i+1]; k++) column_values[cnt++] = A->a[k];
14112205254eSKarl Rupp     for (; j<B->i[i+1]; j++) column_values[cnt++] = B->a[j];
14128e2fed03SBarry Smith   }
1413e32f2f54SBarry Smith   if (cnt != A->nz + B->nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal PETSc error: cnt = %D nz = %D",cnt,A->nz+B->nz);
14148e2fed03SBarry Smith 
14158e2fed03SBarry Smith   /* store the column values to the file */
141685ebf7a4SBarry Smith   ierr = PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);CHKERRQ(ierr);
1417958c9bccSBarry Smith   if (!rank) {
14188e2fed03SBarry Smith     MPI_Status status;
14196f69ff64SBarry Smith     ierr = PetscBinaryWrite(fd,column_values,nz,PETSC_SCALAR,PETSC_TRUE);CHKERRQ(ierr);
14208e2fed03SBarry Smith     for (i=1; i<size; i++) {
1421639ff905SBarry Smith       ierr = PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);CHKERRQ(ierr);
1422ce94432eSBarry Smith       ierr = MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);CHKERRQ(ierr);
1423e32f2f54SBarry Smith       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1424ce94432eSBarry Smith       ierr = MPIULong_Recv(column_values,rnz,MPIU_SCALAR,i,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
14256f69ff64SBarry Smith       ierr = PetscBinaryWrite(fd,column_values,rnz,PETSC_SCALAR,PETSC_TRUE);CHKERRQ(ierr);
14268e2fed03SBarry Smith     }
1427639ff905SBarry Smith     ierr = PetscViewerFlowControlEndMaster(viewer,&message_count);CHKERRQ(ierr);
14288e2fed03SBarry Smith   } else {
1429639ff905SBarry Smith     ierr = PetscViewerFlowControlStepWorker(viewer,rank,&message_count);CHKERRQ(ierr);
1430ce94432eSBarry Smith     ierr = MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
1431ce94432eSBarry Smith     ierr = MPIULong_Send(column_values,nz,MPIU_SCALAR,0,tag,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
1432639ff905SBarry Smith     ierr = PetscViewerFlowControlEndWorker(viewer,&message_count);CHKERRQ(ierr);
14338e2fed03SBarry Smith   }
14348e2fed03SBarry Smith   ierr = PetscFree(column_values);CHKERRQ(ierr);
1435b37d52dbSMark F. Adams 
1436b37d52dbSMark F. Adams   ierr = PetscViewerBinaryGetInfoPointer(viewer,&file);CHKERRQ(ierr);
14372205254eSKarl Rupp   if (file) fprintf(file,"-matload_block_size %d\n",(int)mat->rmap->bs);
14388e2fed03SBarry Smith   PetscFunctionReturn(0);
14398e2fed03SBarry Smith }
14408e2fed03SBarry Smith 
14419804daf3SBarry Smith #include <petscdraw.h>
14428e2fed03SBarry Smith #undef __FUNCT__
14434a2ae208SSatish Balay #define __FUNCT__ "MatView_MPIAIJ_ASCIIorDraworSocket"
1444dfbe8321SBarry Smith PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
1445416022c9SBarry Smith {
144644a69424SLois Curfman McInnes   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*)mat->data;
1447dfbe8321SBarry Smith   PetscErrorCode    ierr;
144832dcc486SBarry Smith   PetscMPIInt       rank = aij->rank,size = aij->size;
1449ace3abfcSBarry Smith   PetscBool         isdraw,iascii,isbinary;
1450b0a32e0cSBarry Smith   PetscViewer       sviewer;
1451f3ef73ceSBarry Smith   PetscViewerFormat format;
1452416022c9SBarry Smith 
14533a40ed3dSBarry Smith   PetscFunctionBegin;
1454251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
1455251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
1456251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
145732077d6dSBarry Smith   if (iascii) {
1458b0a32e0cSBarry Smith     ierr = PetscViewerGetFormat(viewer,&format);CHKERRQ(ierr);
1459456192e2SBarry Smith     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
14604e220ebcSLois Curfman McInnes       MatInfo   info;
1461ace3abfcSBarry Smith       PetscBool inodes;
1462923f20ffSKris Buschelman 
1463ce94432eSBarry Smith       ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);CHKERRQ(ierr);
1464888f2ed8SSatish Balay       ierr = MatGetInfo(mat,MAT_LOCAL,&info);CHKERRQ(ierr);
14650298fd71SBarry Smith       ierr = MatInodeGetInodeSizes(aij->A,NULL,(PetscInt**)&inodes,NULL);CHKERRQ(ierr);
14667b23a99aSBarry Smith       ierr = PetscViewerASCIISynchronizedAllow(viewer,PETSC_TRUE);CHKERRQ(ierr);
1467923f20ffSKris Buschelman       if (!inodes) {
146877431f27SBarry Smith         ierr = PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, not using I-node routines\n",
1469d0f46423SBarry Smith                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);CHKERRQ(ierr);
14706831982aSBarry Smith       } else {
147177431f27SBarry Smith         ierr = PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, using I-node routines\n",
1472d0f46423SBarry Smith                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);CHKERRQ(ierr);
14736831982aSBarry Smith       }
1474888f2ed8SSatish Balay       ierr = MatGetInfo(aij->A,MAT_LOCAL,&info);CHKERRQ(ierr);
147577431f27SBarry Smith       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);CHKERRQ(ierr);
1476888f2ed8SSatish Balay       ierr = MatGetInfo(aij->B,MAT_LOCAL,&info);CHKERRQ(ierr);
147777431f27SBarry Smith       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);CHKERRQ(ierr);
1478b0a32e0cSBarry Smith       ierr = PetscViewerFlush(viewer);CHKERRQ(ierr);
14797b23a99aSBarry Smith       ierr = PetscViewerASCIISynchronizedAllow(viewer,PETSC_FALSE);CHKERRQ(ierr);
148007d81ca4SBarry Smith       ierr = PetscViewerASCIIPrintf(viewer,"Information on VecScatter used in matrix-vector product: \n");CHKERRQ(ierr);
1481a40aa06bSLois Curfman McInnes       ierr = VecScatterView(aij->Mvctx,viewer);CHKERRQ(ierr);
14823a40ed3dSBarry Smith       PetscFunctionReturn(0);
1483fb9695e5SSatish Balay     } else if (format == PETSC_VIEWER_ASCII_INFO) {
1484923f20ffSKris Buschelman       PetscInt inodecount,inodelimit,*inodes;
1485923f20ffSKris Buschelman       ierr = MatInodeGetInodeSizes(aij->A,&inodecount,&inodes,&inodelimit);CHKERRQ(ierr);
1486923f20ffSKris Buschelman       if (inodes) {
1487923f20ffSKris Buschelman         ierr = PetscViewerASCIIPrintf(viewer,"using I-node (on process 0) routines: found %D nodes, limit used is %D\n",inodecount,inodelimit);CHKERRQ(ierr);
1488d38fa0fbSBarry Smith       } else {
1489d38fa0fbSBarry Smith         ierr = PetscViewerASCIIPrintf(viewer,"not using I-node (on process 0) routines\n");CHKERRQ(ierr);
1490d38fa0fbSBarry Smith       }
14913a40ed3dSBarry Smith       PetscFunctionReturn(0);
14924aedb280SBarry Smith     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
14934aedb280SBarry Smith       PetscFunctionReturn(0);
149408480c60SBarry Smith     }
14958e2fed03SBarry Smith   } else if (isbinary) {
14968e2fed03SBarry Smith     if (size == 1) {
14977adad957SLisandro Dalcin       ierr = PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);CHKERRQ(ierr);
14988e2fed03SBarry Smith       ierr = MatView(aij->A,viewer);CHKERRQ(ierr);
14998e2fed03SBarry Smith     } else {
15008e2fed03SBarry Smith       ierr = MatView_MPIAIJ_Binary(mat,viewer);CHKERRQ(ierr);
15018e2fed03SBarry Smith     }
15028e2fed03SBarry Smith     PetscFunctionReturn(0);
15030f5bd95cSBarry Smith   } else if (isdraw) {
1504b0a32e0cSBarry Smith     PetscDraw draw;
1505ace3abfcSBarry Smith     PetscBool isnull;
1506b0a32e0cSBarry Smith     ierr = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
1507b0a32e0cSBarry Smith     ierr = PetscDrawIsNull(draw,&isnull);CHKERRQ(ierr); if (isnull) PetscFunctionReturn(0);
150819bcc07fSBarry Smith   }
150919bcc07fSBarry Smith 
151017699dbbSLois Curfman McInnes   if (size == 1) {
15117adad957SLisandro Dalcin     ierr = PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);CHKERRQ(ierr);
151278b31e54SBarry Smith     ierr = MatView(aij->A,viewer);CHKERRQ(ierr);
15133a40ed3dSBarry Smith   } else {
151495373324SBarry Smith     /* assemble the entire matrix onto first processor. */
151595373324SBarry Smith     Mat        A;
1516ec8511deSBarry Smith     Mat_SeqAIJ *Aloc;
1517d0f46423SBarry Smith     PetscInt   M = mat->rmap->N,N = mat->cmap->N,m,*ai,*aj,row,*cols,i,*ct;
1518dd6ea824SBarry Smith     MatScalar  *a;
15192ee70a88SLois Curfman McInnes 
152032a366e4SMatthew Knepley     if (mat->rmap->N > 1024) {
1521ace3abfcSBarry Smith       PetscBool flg = PETSC_FALSE;
152232a366e4SMatthew Knepley 
15230298fd71SBarry Smith       ierr = PetscOptionsGetBool(((PetscObject) mat)->prefix, "-mat_ascii_output_large", &flg,NULL);CHKERRQ(ierr);
1524ce94432eSBarry Smith       if (!flg) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"ASCII matrix output not allowed for matrices with more than 1024 rows, use binary format instead.\nYou can override this restriction using -mat_ascii_output_large.");
152532a366e4SMatthew Knepley     }
15260805154bSBarry Smith 
1527ce94432eSBarry Smith     ierr = MatCreate(PetscObjectComm((PetscObject)mat),&A);CHKERRQ(ierr);
152817699dbbSLois Curfman McInnes     if (!rank) {
1529f69a0ea3SMatthew Knepley       ierr = MatSetSizes(A,M,N,M,N);CHKERRQ(ierr);
15303a40ed3dSBarry Smith     } else {
1531f69a0ea3SMatthew Knepley       ierr = MatSetSizes(A,0,0,M,N);CHKERRQ(ierr);
153295373324SBarry Smith     }
1533f204ca49SKris Buschelman     /* This is just a temporary matrix, so explicitly using MATMPIAIJ is probably best */
1534f204ca49SKris Buschelman     ierr = MatSetType(A,MATMPIAIJ);CHKERRQ(ierr);
15350298fd71SBarry Smith     ierr = MatMPIAIJSetPreallocation(A,0,NULL,0,NULL);CHKERRQ(ierr);
15362b82e772SSatish Balay     ierr = MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);CHKERRQ(ierr);
153752e6d16bSBarry Smith     ierr = PetscLogObjectParent(mat,A);CHKERRQ(ierr);
1538416022c9SBarry Smith 
153995373324SBarry Smith     /* copy over the A part */
1540ec8511deSBarry Smith     Aloc = (Mat_SeqAIJ*)aij->A->data;
1541d0f46423SBarry Smith     m    = aij->A->rmap->n; ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1542d0f46423SBarry Smith     row  = mat->rmap->rstart;
15432205254eSKarl Rupp     for (i=0; i<ai[m]; i++) aj[i] += mat->cmap->rstart;
154495373324SBarry Smith     for (i=0; i<m; i++) {
1545416022c9SBarry Smith       ierr = MatSetValues(A,1,&row,ai[i+1]-ai[i],aj,a,INSERT_VALUES);CHKERRQ(ierr);
154626fbe8dcSKarl Rupp       row++;
154726fbe8dcSKarl Rupp       a += ai[i+1]-ai[i]; aj += ai[i+1]-ai[i];
154895373324SBarry Smith     }
15492ee70a88SLois Curfman McInnes     aj = Aloc->j;
15502205254eSKarl Rupp     for (i=0; i<ai[m]; i++) aj[i] -= mat->cmap->rstart;
155195373324SBarry Smith 
155295373324SBarry Smith     /* copy over the B part */
1553ec8511deSBarry Smith     Aloc = (Mat_SeqAIJ*)aij->B->data;
1554d0f46423SBarry Smith     m    = aij->B->rmap->n;  ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1555d0f46423SBarry Smith     row  = mat->rmap->rstart;
1556b1d57f15SBarry Smith     ierr = PetscMalloc((ai[m]+1)*sizeof(PetscInt),&cols);CHKERRQ(ierr);
1557b0a32e0cSBarry Smith     ct   = cols;
15582205254eSKarl Rupp     for (i=0; i<ai[m]; i++) cols[i] = aij->garray[aj[i]];
155995373324SBarry Smith     for (i=0; i<m; i++) {
1560416022c9SBarry Smith       ierr = MatSetValues(A,1,&row,ai[i+1]-ai[i],cols,a,INSERT_VALUES);CHKERRQ(ierr);
15612205254eSKarl Rupp       row++;
15622205254eSKarl Rupp       a += ai[i+1]-ai[i]; cols += ai[i+1]-ai[i];
156395373324SBarry Smith     }
1564606d414cSSatish Balay     ierr = PetscFree(ct);CHKERRQ(ierr);
15656d4a8577SBarry Smith     ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
15666d4a8577SBarry Smith     ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
156755843e3eSBarry Smith     /*
156855843e3eSBarry Smith        Everyone has to call to draw the matrix since the graphics waits are
1569b0a32e0cSBarry Smith        synchronized across all processors that share the PetscDraw object
157055843e3eSBarry Smith     */
1571b0a32e0cSBarry Smith     ierr = PetscViewerGetSingleton(viewer,&sviewer);CHKERRQ(ierr);
1572e03a110bSBarry Smith     if (!rank) {
15737adad957SLisandro Dalcin       ierr = PetscObjectSetName((PetscObject)((Mat_MPIAIJ*)(A->data))->A,((PetscObject)mat)->name);CHKERRQ(ierr);
15747566de4bSShri Abhyankar       /* Set the type name to MATMPIAIJ so that the correct type can be printed out by PetscObjectPrintClassNamePrefixType() in MatView_SeqAIJ_ASCII()*/
15757566de4bSShri Abhyankar       PetscStrcpy(((PetscObject)((Mat_MPIAIJ*)(A->data))->A)->type_name,MATMPIAIJ);
15766831982aSBarry Smith       ierr = MatView(((Mat_MPIAIJ*)(A->data))->A,sviewer);CHKERRQ(ierr);
157795373324SBarry Smith     }
1578b0a32e0cSBarry Smith     ierr = PetscViewerRestoreSingleton(viewer,&sviewer);CHKERRQ(ierr);
15796bf464f9SBarry Smith     ierr = MatDestroy(&A);CHKERRQ(ierr);
158095373324SBarry Smith   }
15813a40ed3dSBarry Smith   PetscFunctionReturn(0);
15821eb62cbbSBarry Smith }
15831eb62cbbSBarry Smith 
15844a2ae208SSatish Balay #undef __FUNCT__
15854a2ae208SSatish Balay #define __FUNCT__ "MatView_MPIAIJ"
1586dfbe8321SBarry Smith PetscErrorCode MatView_MPIAIJ(Mat mat,PetscViewer viewer)
1587416022c9SBarry Smith {
1588dfbe8321SBarry Smith   PetscErrorCode ierr;
1589ace3abfcSBarry Smith   PetscBool      iascii,isdraw,issocket,isbinary;
1590416022c9SBarry Smith 
15913a40ed3dSBarry Smith   PetscFunctionBegin;
1592251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
1593251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
1594251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1595251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSOCKET,&issocket);CHKERRQ(ierr);
159632077d6dSBarry Smith   if (iascii || isdraw || isbinary || issocket) {
15977b2a1423SBarry Smith     ierr = MatView_MPIAIJ_ASCIIorDraworSocket(mat,viewer);CHKERRQ(ierr);
1598416022c9SBarry Smith   }
15993a40ed3dSBarry Smith   PetscFunctionReturn(0);
1600416022c9SBarry Smith }
1601416022c9SBarry Smith 
16024a2ae208SSatish Balay #undef __FUNCT__
160341f059aeSBarry Smith #define __FUNCT__ "MatSOR_MPIAIJ"
160441f059aeSBarry Smith PetscErrorCode MatSOR_MPIAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
16058a729477SBarry Smith {
160644a69424SLois Curfman McInnes   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1607dfbe8321SBarry Smith   PetscErrorCode ierr;
16086987fefcSBarry Smith   Vec            bb1 = 0;
1609ace3abfcSBarry Smith   PetscBool      hasop;
16108a729477SBarry Smith 
16113a40ed3dSBarry Smith   PetscFunctionBegin;
1612a2b30743SBarry Smith   if (flag == SOR_APPLY_UPPER) {
161341f059aeSBarry Smith     ierr = (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);CHKERRQ(ierr);
1614a2b30743SBarry Smith     PetscFunctionReturn(0);
1615a2b30743SBarry Smith   }
1616a2b30743SBarry Smith 
16174e980039SJed Brown   if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) {
16184e980039SJed Brown     ierr = VecDuplicate(bb,&bb1);CHKERRQ(ierr);
16194e980039SJed Brown   }
16204e980039SJed Brown 
1621c16cb8f2SBarry Smith   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1622da3a660dSBarry Smith     if (flag & SOR_ZERO_INITIAL_GUESS) {
162341f059aeSBarry Smith       ierr = (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);CHKERRQ(ierr);
16242798e883SHong Zhang       its--;
1625da3a660dSBarry Smith     }
16262798e883SHong Zhang 
16272798e883SHong Zhang     while (its--) {
1628ca9f406cSSatish Balay       ierr = VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1629ca9f406cSSatish Balay       ierr = VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
16302798e883SHong Zhang 
1631c14dc6b6SHong Zhang       /* update rhs: bb1 = bb - B*x */
1632efb30889SBarry Smith       ierr = VecScale(mat->lvec,-1.0);CHKERRQ(ierr);
1633c14dc6b6SHong Zhang       ierr = (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);CHKERRQ(ierr);
16342798e883SHong Zhang 
1635c14dc6b6SHong Zhang       /* local sweep */
163641f059aeSBarry Smith       ierr = (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,1,xx);CHKERRQ(ierr);
16372798e883SHong Zhang     }
16383a40ed3dSBarry Smith   } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1639da3a660dSBarry Smith     if (flag & SOR_ZERO_INITIAL_GUESS) {
164041f059aeSBarry Smith       ierr = (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);CHKERRQ(ierr);
16412798e883SHong Zhang       its--;
1642da3a660dSBarry Smith     }
16432798e883SHong Zhang     while (its--) {
1644ca9f406cSSatish Balay       ierr = VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1645ca9f406cSSatish Balay       ierr = VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
16462798e883SHong Zhang 
1647c14dc6b6SHong Zhang       /* update rhs: bb1 = bb - B*x */
1648efb30889SBarry Smith       ierr = VecScale(mat->lvec,-1.0);CHKERRQ(ierr);
1649c14dc6b6SHong Zhang       ierr = (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);CHKERRQ(ierr);
1650c14dc6b6SHong Zhang 
1651c14dc6b6SHong Zhang       /* local sweep */
165241f059aeSBarry Smith       ierr = (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_FORWARD_SWEEP,fshift,lits,1,xx);CHKERRQ(ierr);
16532798e883SHong Zhang     }
16543a40ed3dSBarry Smith   } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1655da3a660dSBarry Smith     if (flag & SOR_ZERO_INITIAL_GUESS) {
165641f059aeSBarry Smith       ierr = (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);CHKERRQ(ierr);
16572798e883SHong Zhang       its--;
1658da3a660dSBarry Smith     }
16592798e883SHong Zhang     while (its--) {
1660ca9f406cSSatish Balay       ierr = VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1661ca9f406cSSatish Balay       ierr = VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
16622798e883SHong Zhang 
1663c14dc6b6SHong Zhang       /* update rhs: bb1 = bb - B*x */
1664efb30889SBarry Smith       ierr = VecScale(mat->lvec,-1.0);CHKERRQ(ierr);
1665c14dc6b6SHong Zhang       ierr = (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);CHKERRQ(ierr);
16662798e883SHong Zhang 
1667c14dc6b6SHong Zhang       /* local sweep */
166841f059aeSBarry Smith       ierr = (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_BACKWARD_SWEEP,fshift,lits,1,xx);CHKERRQ(ierr);
16692798e883SHong Zhang     }
1670a7420bb7SBarry Smith   } else if (flag & SOR_EISENSTAT) {
1671a7420bb7SBarry Smith     Vec xx1;
1672a7420bb7SBarry Smith 
1673a7420bb7SBarry Smith     ierr = VecDuplicate(bb,&xx1);CHKERRQ(ierr);
167441f059aeSBarry Smith     ierr = (*mat->A->ops->sor)(mat->A,bb,omega,(MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_BACKWARD_SWEEP),fshift,lits,1,xx);CHKERRQ(ierr);
1675a7420bb7SBarry Smith 
1676a7420bb7SBarry Smith     ierr = VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1677a7420bb7SBarry Smith     ierr = VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
1678a7420bb7SBarry Smith     if (!mat->diag) {
16790298fd71SBarry Smith       ierr = MatGetVecs(matin,&mat->diag,NULL);CHKERRQ(ierr);
1680a7420bb7SBarry Smith       ierr = MatGetDiagonal(matin,mat->diag);CHKERRQ(ierr);
1681a7420bb7SBarry Smith     }
1682bd0c2dcbSBarry Smith     ierr = MatHasOperation(matin,MATOP_MULT_DIAGONAL_BLOCK,&hasop);CHKERRQ(ierr);
1683bd0c2dcbSBarry Smith     if (hasop) {
1684bd0c2dcbSBarry Smith       ierr = MatMultDiagonalBlock(matin,xx,bb1);CHKERRQ(ierr);
1685bd0c2dcbSBarry Smith     } else {
1686a7420bb7SBarry Smith       ierr = VecPointwiseMult(bb1,mat->diag,xx);CHKERRQ(ierr);
1687bd0c2dcbSBarry Smith     }
1688887ee2caSBarry Smith     ierr = VecAYPX(bb1,(omega-2.0)/omega,bb);CHKERRQ(ierr);
1689887ee2caSBarry Smith 
1690a7420bb7SBarry Smith     ierr = MatMultAdd(mat->B,mat->lvec,bb1,bb1);CHKERRQ(ierr);
1691a7420bb7SBarry Smith 
1692a7420bb7SBarry Smith     /* local sweep */
169341f059aeSBarry Smith     ierr = (*mat->A->ops->sor)(mat->A,bb1,omega,(MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_FORWARD_SWEEP),fshift,lits,1,xx1);CHKERRQ(ierr);
1694a7420bb7SBarry Smith     ierr = VecAXPY(xx,1.0,xx1);CHKERRQ(ierr);
16956bf464f9SBarry Smith     ierr = VecDestroy(&xx1);CHKERRQ(ierr);
1696ce94432eSBarry Smith   } else SETERRQ(PetscObjectComm((PetscObject)matin),PETSC_ERR_SUP,"Parallel SOR not supported");
1697c14dc6b6SHong Zhang 
16986bf464f9SBarry Smith   ierr = VecDestroy(&bb1);CHKERRQ(ierr);
16993a40ed3dSBarry Smith   PetscFunctionReturn(0);
17008a729477SBarry Smith }
1701a66be287SLois Curfman McInnes 
17024a2ae208SSatish Balay #undef __FUNCT__
170342e855d1Svictor #define __FUNCT__ "MatPermute_MPIAIJ"
170442e855d1Svictor PetscErrorCode MatPermute_MPIAIJ(Mat A,IS rowp,IS colp,Mat *B)
170542e855d1Svictor {
170672e6a0cfSJed Brown   Mat            aA,aB,Aperm;
170772e6a0cfSJed Brown   const PetscInt *rwant,*cwant,*gcols,*ai,*bi,*aj,*bj;
170872e6a0cfSJed Brown   PetscScalar    *aa,*ba;
170972e6a0cfSJed Brown   PetscInt       i,j,m,n,ng,anz,bnz,*dnnz,*onnz,*tdnnz,*tonnz,*rdest,*cdest,*work,*gcdest;
171072e6a0cfSJed Brown   PetscSF        rowsf,sf;
17110298fd71SBarry Smith   IS             parcolp = NULL;
171272e6a0cfSJed Brown   PetscBool      done;
171342e855d1Svictor   PetscErrorCode ierr;
171442e855d1Svictor 
171542e855d1Svictor   PetscFunctionBegin;
171672e6a0cfSJed Brown   ierr = MatGetLocalSize(A,&m,&n);CHKERRQ(ierr);
171772e6a0cfSJed Brown   ierr = ISGetIndices(rowp,&rwant);CHKERRQ(ierr);
171872e6a0cfSJed Brown   ierr = ISGetIndices(colp,&cwant);CHKERRQ(ierr);
171972e6a0cfSJed Brown   ierr = PetscMalloc3(PetscMax(m,n),PetscInt,&work,m,PetscInt,&rdest,n,PetscInt,&cdest);CHKERRQ(ierr);
172072e6a0cfSJed Brown 
172172e6a0cfSJed Brown   /* Invert row permutation to find out where my rows should go */
1722ce94432eSBarry Smith   ierr = PetscSFCreate(PetscObjectComm((PetscObject)A),&rowsf);CHKERRQ(ierr);
17230298fd71SBarry Smith   ierr = PetscSFSetGraphLayout(rowsf,A->rmap,A->rmap->n,NULL,PETSC_OWN_POINTER,rwant);CHKERRQ(ierr);
1724e9e74f11SJed Brown   ierr = PetscSFSetFromOptions(rowsf);CHKERRQ(ierr);
172572e6a0cfSJed Brown   for (i=0; i<m; i++) work[i] = A->rmap->rstart + i;
17268bfbc91cSJed Brown   ierr = PetscSFReduceBegin(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);CHKERRQ(ierr);
17278bfbc91cSJed Brown   ierr = PetscSFReduceEnd(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);CHKERRQ(ierr);
172872e6a0cfSJed Brown 
172972e6a0cfSJed Brown   /* Invert column permutation to find out where my columns should go */
1730ce94432eSBarry Smith   ierr = PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);CHKERRQ(ierr);
17310298fd71SBarry Smith   ierr = PetscSFSetGraphLayout(sf,A->cmap,A->cmap->n,NULL,PETSC_OWN_POINTER,cwant);CHKERRQ(ierr);
1732e9e74f11SJed Brown   ierr = PetscSFSetFromOptions(sf);CHKERRQ(ierr);
173372e6a0cfSJed Brown   for (i=0; i<n; i++) work[i] = A->cmap->rstart + i;
17348bfbc91cSJed Brown   ierr = PetscSFReduceBegin(sf,MPIU_INT,work,cdest,MPIU_REPLACE);CHKERRQ(ierr);
17358bfbc91cSJed Brown   ierr = PetscSFReduceEnd(sf,MPIU_INT,work,cdest,MPIU_REPLACE);CHKERRQ(ierr);
173672e6a0cfSJed Brown   ierr = PetscSFDestroy(&sf);CHKERRQ(ierr);
173772e6a0cfSJed Brown 
173872e6a0cfSJed Brown   ierr = ISRestoreIndices(rowp,&rwant);CHKERRQ(ierr);
173972e6a0cfSJed Brown   ierr = ISRestoreIndices(colp,&cwant);CHKERRQ(ierr);
174072e6a0cfSJed Brown   ierr = MatMPIAIJGetSeqAIJ(A,&aA,&aB,&gcols);CHKERRQ(ierr);
174172e6a0cfSJed Brown 
174272e6a0cfSJed Brown   /* Find out where my gcols should go */
17430298fd71SBarry Smith   ierr = MatGetSize(aB,NULL,&ng);CHKERRQ(ierr);
174472e6a0cfSJed Brown   ierr = PetscMalloc(ng*sizeof(PetscInt),&gcdest);CHKERRQ(ierr);
1745ce94432eSBarry Smith   ierr = PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);CHKERRQ(ierr);
17460298fd71SBarry Smith   ierr = PetscSFSetGraphLayout(sf,A->cmap,ng,NULL,PETSC_OWN_POINTER,gcols);CHKERRQ(ierr);
1747e9e74f11SJed Brown   ierr = PetscSFSetFromOptions(sf);CHKERRQ(ierr);
174872e6a0cfSJed Brown   ierr = PetscSFBcastBegin(sf,MPIU_INT,cdest,gcdest);CHKERRQ(ierr);
174972e6a0cfSJed Brown   ierr = PetscSFBcastEnd(sf,MPIU_INT,cdest,gcdest);CHKERRQ(ierr);
175072e6a0cfSJed Brown   ierr = PetscSFDestroy(&sf);CHKERRQ(ierr);
175172e6a0cfSJed Brown 
175272e6a0cfSJed Brown   ierr = PetscMalloc4(m,PetscInt,&dnnz,m,PetscInt,&onnz,m,PetscInt,&tdnnz,m,PetscInt,&tonnz);CHKERRQ(ierr);
175372e6a0cfSJed Brown   ierr = PetscMemzero(dnnz,m*sizeof(PetscInt));CHKERRQ(ierr);
175472e6a0cfSJed Brown   ierr = PetscMemzero(onnz,m*sizeof(PetscInt));CHKERRQ(ierr);
175572e6a0cfSJed Brown   ierr = MatGetRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);CHKERRQ(ierr);
175672e6a0cfSJed Brown   ierr = MatGetRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);CHKERRQ(ierr);
175772e6a0cfSJed Brown   for (i=0; i<m; i++) {
175872e6a0cfSJed Brown     PetscInt row = rdest[i],rowner;
175972e6a0cfSJed Brown     ierr = PetscLayoutFindOwner(A->rmap,row,&rowner);CHKERRQ(ierr);
176072e6a0cfSJed Brown     for (j=ai[i]; j<ai[i+1]; j++) {
176172e6a0cfSJed Brown       PetscInt cowner,col = cdest[aj[j]];
176272e6a0cfSJed Brown       ierr = PetscLayoutFindOwner(A->cmap,col,&cowner);CHKERRQ(ierr); /* Could build an index for the columns to eliminate this search */
176372e6a0cfSJed Brown       if (rowner == cowner) dnnz[i]++;
176472e6a0cfSJed Brown       else onnz[i]++;
176572e6a0cfSJed Brown     }
176672e6a0cfSJed Brown     for (j=bi[i]; j<bi[i+1]; j++) {
176772e6a0cfSJed Brown       PetscInt cowner,col = gcdest[bj[j]];
176872e6a0cfSJed Brown       ierr = PetscLayoutFindOwner(A->cmap,col,&cowner);CHKERRQ(ierr);
176972e6a0cfSJed Brown       if (rowner == cowner) dnnz[i]++;
177072e6a0cfSJed Brown       else onnz[i]++;
177172e6a0cfSJed Brown     }
177272e6a0cfSJed Brown   }
177372e6a0cfSJed Brown   ierr = PetscMemzero(tdnnz,m*sizeof(PetscInt));CHKERRQ(ierr);
177472e6a0cfSJed Brown   ierr = PetscMemzero(tonnz,m*sizeof(PetscInt));CHKERRQ(ierr);
177572e6a0cfSJed Brown   ierr = PetscSFBcastBegin(rowsf,MPIU_INT,dnnz,tdnnz);CHKERRQ(ierr);
177672e6a0cfSJed Brown   ierr = PetscSFBcastEnd(rowsf,MPIU_INT,dnnz,tdnnz);CHKERRQ(ierr);
177772e6a0cfSJed Brown   ierr = PetscSFBcastBegin(rowsf,MPIU_INT,onnz,tonnz);CHKERRQ(ierr);
177872e6a0cfSJed Brown   ierr = PetscSFBcastEnd(rowsf,MPIU_INT,onnz,tonnz);CHKERRQ(ierr);
177972e6a0cfSJed Brown   ierr = PetscSFDestroy(&rowsf);CHKERRQ(ierr);
178072e6a0cfSJed Brown 
1781ce94432eSBarry Smith   ierr = MatCreateAIJ(PetscObjectComm((PetscObject)A),A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N,0,tdnnz,0,tonnz,&Aperm);CHKERRQ(ierr);
178272e6a0cfSJed Brown   ierr = MatSeqAIJGetArray(aA,&aa);CHKERRQ(ierr);
178372e6a0cfSJed Brown   ierr = MatSeqAIJGetArray(aB,&ba);CHKERRQ(ierr);
178472e6a0cfSJed Brown   for (i=0; i<m; i++) {
178572e6a0cfSJed Brown     PetscInt *acols = dnnz,*bcols = onnz; /* Repurpose now-unneeded arrays */
178672e6a0cfSJed Brown     PetscInt rowlen;
178772e6a0cfSJed Brown     rowlen = ai[i+1] - ai[i];
178872e6a0cfSJed Brown     for (j=0; j<rowlen; j++) acols[j] = cdest[aj[ai[i]+j]];
178972e6a0cfSJed Brown     ierr   = MatSetValues(Aperm,1,&rdest[i],rowlen,acols,aa+ai[i],INSERT_VALUES);CHKERRQ(ierr);
179072e6a0cfSJed Brown     rowlen = bi[i+1] - bi[i];
179172e6a0cfSJed Brown     for (j=0; j<rowlen; j++) bcols[j] = gcdest[bj[bi[i]+j]];
179272e6a0cfSJed Brown     ierr = MatSetValues(Aperm,1,&rdest[i],rowlen,bcols,ba+bi[i],INSERT_VALUES);CHKERRQ(ierr);
179372e6a0cfSJed Brown   }
179472e6a0cfSJed Brown   ierr = MatAssemblyBegin(Aperm,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
179572e6a0cfSJed Brown   ierr = MatAssemblyEnd(Aperm,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
179672e6a0cfSJed Brown   ierr = MatRestoreRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);CHKERRQ(ierr);
179772e6a0cfSJed Brown   ierr = MatRestoreRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);CHKERRQ(ierr);
179872e6a0cfSJed Brown   ierr = MatSeqAIJRestoreArray(aA,&aa);CHKERRQ(ierr);
179972e6a0cfSJed Brown   ierr = MatSeqAIJRestoreArray(aB,&ba);CHKERRQ(ierr);
180072e6a0cfSJed Brown   ierr = PetscFree4(dnnz,onnz,tdnnz,tonnz);CHKERRQ(ierr);
180172e6a0cfSJed Brown   ierr = PetscFree3(work,rdest,cdest);CHKERRQ(ierr);
180272e6a0cfSJed Brown   ierr = PetscFree(gcdest);CHKERRQ(ierr);
180372e6a0cfSJed Brown   if (parcolp) {ierr = ISDestroy(&colp);CHKERRQ(ierr);}
180472e6a0cfSJed Brown   *B = Aperm;
180542e855d1Svictor   PetscFunctionReturn(0);
180642e855d1Svictor }
180742e855d1Svictor 
180842e855d1Svictor #undef __FUNCT__
18094a2ae208SSatish Balay #define __FUNCT__ "MatGetInfo_MPIAIJ"
1810dfbe8321SBarry Smith PetscErrorCode MatGetInfo_MPIAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1811a66be287SLois Curfman McInnes {
1812a66be287SLois Curfman McInnes   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1813a66be287SLois Curfman McInnes   Mat            A    = mat->A,B = mat->B;
1814dfbe8321SBarry Smith   PetscErrorCode ierr;
1815329f5518SBarry Smith   PetscReal      isend[5],irecv[5];
1816a66be287SLois Curfman McInnes 
18173a40ed3dSBarry Smith   PetscFunctionBegin;
18184e220ebcSLois Curfman McInnes   info->block_size = 1.0;
18194e220ebcSLois Curfman McInnes   ierr             = MatGetInfo(A,MAT_LOCAL,info);CHKERRQ(ierr);
18202205254eSKarl Rupp 
18214e220ebcSLois Curfman McInnes   isend[0] = info->nz_used; isend[1] = info->nz_allocated; isend[2] = info->nz_unneeded;
18224e220ebcSLois Curfman McInnes   isend[3] = info->memory;  isend[4] = info->mallocs;
18232205254eSKarl Rupp 
18244e220ebcSLois Curfman McInnes   ierr = MatGetInfo(B,MAT_LOCAL,info);CHKERRQ(ierr);
18252205254eSKarl Rupp 
18264e220ebcSLois Curfman McInnes   isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
18274e220ebcSLois Curfman McInnes   isend[3] += info->memory;  isend[4] += info->mallocs;
1828a66be287SLois Curfman McInnes   if (flag == MAT_LOCAL) {
18294e220ebcSLois Curfman McInnes     info->nz_used      = isend[0];
18304e220ebcSLois Curfman McInnes     info->nz_allocated = isend[1];
18314e220ebcSLois Curfman McInnes     info->nz_unneeded  = isend[2];
18324e220ebcSLois Curfman McInnes     info->memory       = isend[3];
18334e220ebcSLois Curfman McInnes     info->mallocs      = isend[4];
1834a66be287SLois Curfman McInnes   } else if (flag == MAT_GLOBAL_MAX) {
1835ce94432eSBarry Smith     ierr = MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)matin));CHKERRQ(ierr);
18362205254eSKarl Rupp 
18374e220ebcSLois Curfman McInnes     info->nz_used      = irecv[0];
18384e220ebcSLois Curfman McInnes     info->nz_allocated = irecv[1];
18394e220ebcSLois Curfman McInnes     info->nz_unneeded  = irecv[2];
18404e220ebcSLois Curfman McInnes     info->memory       = irecv[3];
18414e220ebcSLois Curfman McInnes     info->mallocs      = irecv[4];
1842a66be287SLois Curfman McInnes   } else if (flag == MAT_GLOBAL_SUM) {
1843ce94432eSBarry Smith     ierr = MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)matin));CHKERRQ(ierr);
18442205254eSKarl Rupp 
18454e220ebcSLois Curfman McInnes     info->nz_used      = irecv[0];
18464e220ebcSLois Curfman McInnes     info->nz_allocated = irecv[1];
18474e220ebcSLois Curfman McInnes     info->nz_unneeded  = irecv[2];
18484e220ebcSLois Curfman McInnes     info->memory       = irecv[3];
18494e220ebcSLois Curfman McInnes     info->mallocs      = irecv[4];
1850a66be287SLois Curfman McInnes   }
18514e220ebcSLois Curfman McInnes   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
18524e220ebcSLois Curfman McInnes   info->fill_ratio_needed = 0;
18534e220ebcSLois Curfman McInnes   info->factor_mallocs    = 0;
18543a40ed3dSBarry Smith   PetscFunctionReturn(0);
1855a66be287SLois Curfman McInnes }
1856a66be287SLois Curfman McInnes 
18574a2ae208SSatish Balay #undef __FUNCT__
18584a2ae208SSatish Balay #define __FUNCT__ "MatSetOption_MPIAIJ"
1859ace3abfcSBarry Smith PetscErrorCode MatSetOption_MPIAIJ(Mat A,MatOption op,PetscBool flg)
1860c74985f6SBarry Smith {
1861c0bbcb79SLois Curfman McInnes   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1862dfbe8321SBarry Smith   PetscErrorCode ierr;
1863c74985f6SBarry Smith 
18643a40ed3dSBarry Smith   PetscFunctionBegin;
186512c028f9SKris Buschelman   switch (op) {
1866512a5fc5SBarry Smith   case MAT_NEW_NONZERO_LOCATIONS:
186712c028f9SKris Buschelman   case MAT_NEW_NONZERO_ALLOCATION_ERR:
186828b2fa4aSMatthew Knepley   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1869a9817697SBarry Smith   case MAT_KEEP_NONZERO_PATTERN:
187012c028f9SKris Buschelman   case MAT_NEW_NONZERO_LOCATION_ERR:
187112c028f9SKris Buschelman   case MAT_USE_INODES:
187212c028f9SKris Buschelman   case MAT_IGNORE_ZERO_ENTRIES:
1873fa1f0d2cSMatthew G Knepley     MatCheckPreallocated(A,1);
18744e0d8c25SBarry Smith     ierr = MatSetOption(a->A,op,flg);CHKERRQ(ierr);
18754e0d8c25SBarry Smith     ierr = MatSetOption(a->B,op,flg);CHKERRQ(ierr);
187612c028f9SKris Buschelman     break;
187712c028f9SKris Buschelman   case MAT_ROW_ORIENTED:
18784e0d8c25SBarry Smith     a->roworiented = flg;
18792205254eSKarl Rupp 
18804e0d8c25SBarry Smith     ierr = MatSetOption(a->A,op,flg);CHKERRQ(ierr);
18814e0d8c25SBarry Smith     ierr = MatSetOption(a->B,op,flg);CHKERRQ(ierr);
188212c028f9SKris Buschelman     break;
18834e0d8c25SBarry Smith   case MAT_NEW_DIAGONALS:
1884290bbb0aSBarry Smith     ierr = PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);CHKERRQ(ierr);
188512c028f9SKris Buschelman     break;
188612c028f9SKris Buschelman   case MAT_IGNORE_OFF_PROC_ENTRIES:
18875c0f0b64SBarry Smith     a->donotstash = flg;
188812c028f9SKris Buschelman     break;
1889ffa07934SHong Zhang   case MAT_SPD:
1890ffa07934SHong Zhang     A->spd_set = PETSC_TRUE;
1891ffa07934SHong Zhang     A->spd     = flg;
1892ffa07934SHong Zhang     if (flg) {
1893ffa07934SHong Zhang       A->symmetric                  = PETSC_TRUE;
1894ffa07934SHong Zhang       A->structurally_symmetric     = PETSC_TRUE;
1895ffa07934SHong Zhang       A->symmetric_set              = PETSC_TRUE;
1896ffa07934SHong Zhang       A->structurally_symmetric_set = PETSC_TRUE;
1897ffa07934SHong Zhang     }
1898ffa07934SHong Zhang     break;
189977e54ba9SKris Buschelman   case MAT_SYMMETRIC:
19004e0d8c25SBarry Smith     ierr = MatSetOption(a->A,op,flg);CHKERRQ(ierr);
190125f421beSHong Zhang     break;
190277e54ba9SKris Buschelman   case MAT_STRUCTURALLY_SYMMETRIC:
1903eeffb40dSHong Zhang     ierr = MatSetOption(a->A,op,flg);CHKERRQ(ierr);
1904eeffb40dSHong Zhang     break;
1905bf108f30SBarry Smith   case MAT_HERMITIAN:
1906eeffb40dSHong Zhang     ierr = MatSetOption(a->A,op,flg);CHKERRQ(ierr);
1907eeffb40dSHong Zhang     break;
1908bf108f30SBarry Smith   case MAT_SYMMETRY_ETERNAL:
19094e0d8c25SBarry Smith     ierr = MatSetOption(a->A,op,flg);CHKERRQ(ierr);
191077e54ba9SKris Buschelman     break;
191112c028f9SKris Buschelman   default:
1912e32f2f54SBarry Smith     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unknown option %d",op);
19133a40ed3dSBarry Smith   }
19143a40ed3dSBarry Smith   PetscFunctionReturn(0);
1915c74985f6SBarry Smith }
1916c74985f6SBarry Smith 
19174a2ae208SSatish Balay #undef __FUNCT__
19184a2ae208SSatish Balay #define __FUNCT__ "MatGetRow_MPIAIJ"
1919b1d57f15SBarry Smith PetscErrorCode MatGetRow_MPIAIJ(Mat matin,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
192039e00950SLois Curfman McInnes {
1921154123eaSLois Curfman McInnes   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
192287828ca2SBarry Smith   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
19236849ba73SBarry Smith   PetscErrorCode ierr;
1924d0f46423SBarry Smith   PetscInt       i,*cworkA,*cworkB,**pcA,**pcB,cstart = matin->cmap->rstart;
1925d0f46423SBarry Smith   PetscInt       nztot,nzA,nzB,lrow,rstart = matin->rmap->rstart,rend = matin->rmap->rend;
1926b1d57f15SBarry Smith   PetscInt       *cmap,*idx_p;
192739e00950SLois Curfman McInnes 
19283a40ed3dSBarry Smith   PetscFunctionBegin;
1929e32f2f54SBarry Smith   if (mat->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Already active");
19307a0afa10SBarry Smith   mat->getrowactive = PETSC_TRUE;
19317a0afa10SBarry Smith 
193270f0671dSBarry Smith   if (!mat->rowvalues && (idx || v)) {
19337a0afa10SBarry Smith     /*
19347a0afa10SBarry Smith         allocate enough space to hold information from the longest row.
19357a0afa10SBarry Smith     */
19367a0afa10SBarry Smith     Mat_SeqAIJ *Aa = (Mat_SeqAIJ*)mat->A->data,*Ba = (Mat_SeqAIJ*)mat->B->data;
1937b1d57f15SBarry Smith     PetscInt   max = 1,tmp;
1938d0f46423SBarry Smith     for (i=0; i<matin->rmap->n; i++) {
19397a0afa10SBarry Smith       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i];
19402205254eSKarl Rupp       if (max < tmp) max = tmp;
19417a0afa10SBarry Smith     }
19421d79065fSBarry Smith     ierr = PetscMalloc2(max,PetscScalar,&mat->rowvalues,max,PetscInt,&mat->rowindices);CHKERRQ(ierr);
19437a0afa10SBarry Smith   }
19447a0afa10SBarry Smith 
1945e7e72b3dSBarry Smith   if (row < rstart || row >= rend) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only local rows");
1946abc0e9e4SLois Curfman McInnes   lrow = row - rstart;
194739e00950SLois Curfman McInnes 
1948154123eaSLois Curfman McInnes   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1949154123eaSLois Curfman McInnes   if (!v)   {pvA = 0; pvB = 0;}
1950154123eaSLois Curfman McInnes   if (!idx) {pcA = 0; if (!v) pcB = 0;}
1951f830108cSBarry Smith   ierr  = (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);CHKERRQ(ierr);
1952f830108cSBarry Smith   ierr  = (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);CHKERRQ(ierr);
1953154123eaSLois Curfman McInnes   nztot = nzA + nzB;
1954154123eaSLois Curfman McInnes 
195570f0671dSBarry Smith   cmap = mat->garray;
1956154123eaSLois Curfman McInnes   if (v  || idx) {
1957154123eaSLois Curfman McInnes     if (nztot) {
1958154123eaSLois Curfman McInnes       /* Sort by increasing column numbers, assuming A and B already sorted */
1959b1d57f15SBarry Smith       PetscInt imark = -1;
1960154123eaSLois Curfman McInnes       if (v) {
196170f0671dSBarry Smith         *v = v_p = mat->rowvalues;
196239e00950SLois Curfman McInnes         for (i=0; i<nzB; i++) {
196370f0671dSBarry Smith           if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1964154123eaSLois Curfman McInnes           else break;
1965154123eaSLois Curfman McInnes         }
1966154123eaSLois Curfman McInnes         imark = i;
196770f0671dSBarry Smith         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
196870f0671dSBarry Smith         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
1969154123eaSLois Curfman McInnes       }
1970154123eaSLois Curfman McInnes       if (idx) {
197170f0671dSBarry Smith         *idx = idx_p = mat->rowindices;
197270f0671dSBarry Smith         if (imark > -1) {
197370f0671dSBarry Smith           for (i=0; i<imark; i++) {
197470f0671dSBarry Smith             idx_p[i] = cmap[cworkB[i]];
197570f0671dSBarry Smith           }
197670f0671dSBarry Smith         } else {
1977154123eaSLois Curfman McInnes           for (i=0; i<nzB; i++) {
197870f0671dSBarry Smith             if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1979154123eaSLois Curfman McInnes             else break;
1980154123eaSLois Curfman McInnes           }
1981154123eaSLois Curfman McInnes           imark = i;
198270f0671dSBarry Smith         }
198370f0671dSBarry Smith         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart + cworkA[i];
198470f0671dSBarry Smith         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]];
198539e00950SLois Curfman McInnes       }
19863f97c4b0SBarry Smith     } else {
19871ca473b0SSatish Balay       if (idx) *idx = 0;
19881ca473b0SSatish Balay       if (v)   *v   = 0;
19891ca473b0SSatish Balay     }
1990154123eaSLois Curfman McInnes   }
199139e00950SLois Curfman McInnes   *nz  = nztot;
1992f830108cSBarry Smith   ierr = (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);CHKERRQ(ierr);
1993f830108cSBarry Smith   ierr = (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);CHKERRQ(ierr);
19943a40ed3dSBarry Smith   PetscFunctionReturn(0);
199539e00950SLois Curfman McInnes }
199639e00950SLois Curfman McInnes 
19974a2ae208SSatish Balay #undef __FUNCT__
19984a2ae208SSatish Balay #define __FUNCT__ "MatRestoreRow_MPIAIJ"
1999b1d57f15SBarry Smith PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
200039e00950SLois Curfman McInnes {
20017a0afa10SBarry Smith   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
20023a40ed3dSBarry Smith 
20033a40ed3dSBarry Smith   PetscFunctionBegin;
2004e7e72b3dSBarry Smith   if (!aij->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"MatGetRow() must be called first");
20057a0afa10SBarry Smith   aij->getrowactive = PETSC_FALSE;
20063a40ed3dSBarry Smith   PetscFunctionReturn(0);
200739e00950SLois Curfman McInnes }
200839e00950SLois Curfman McInnes 
20094a2ae208SSatish Balay #undef __FUNCT__
20104a2ae208SSatish Balay #define __FUNCT__ "MatNorm_MPIAIJ"
2011dfbe8321SBarry Smith PetscErrorCode MatNorm_MPIAIJ(Mat mat,NormType type,PetscReal *norm)
2012855ac2c5SLois Curfman McInnes {
2013855ac2c5SLois Curfman McInnes   Mat_MPIAIJ     *aij  = (Mat_MPIAIJ*)mat->data;
2014ec8511deSBarry Smith   Mat_SeqAIJ     *amat = (Mat_SeqAIJ*)aij->A->data,*bmat = (Mat_SeqAIJ*)aij->B->data;
2015dfbe8321SBarry Smith   PetscErrorCode ierr;
2016d0f46423SBarry Smith   PetscInt       i,j,cstart = mat->cmap->rstart;
2017329f5518SBarry Smith   PetscReal      sum = 0.0;
2018a77337e4SBarry Smith   MatScalar      *v;
201904ca555eSLois Curfman McInnes 
20203a40ed3dSBarry Smith   PetscFunctionBegin;
202117699dbbSLois Curfman McInnes   if (aij->size == 1) {
202214183eadSLois Curfman McInnes     ierr =  MatNorm(aij->A,type,norm);CHKERRQ(ierr);
202337fa93a5SLois Curfman McInnes   } else {
202404ca555eSLois Curfman McInnes     if (type == NORM_FROBENIUS) {
202504ca555eSLois Curfman McInnes       v = amat->a;
202604ca555eSLois Curfman McInnes       for (i=0; i<amat->nz; i++) {
2027329f5518SBarry Smith         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
202804ca555eSLois Curfman McInnes       }
202904ca555eSLois Curfman McInnes       v = bmat->a;
203004ca555eSLois Curfman McInnes       for (i=0; i<bmat->nz; i++) {
2031329f5518SBarry Smith         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
203204ca555eSLois Curfman McInnes       }
2033ce94432eSBarry Smith       ierr  = MPI_Allreduce(&sum,norm,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
20348f1a2a5eSBarry Smith       *norm = PetscSqrtReal(*norm);
20353a40ed3dSBarry Smith     } else if (type == NORM_1) { /* max column norm */
2036329f5518SBarry Smith       PetscReal *tmp,*tmp2;
2037b1d57f15SBarry Smith       PetscInt  *jj,*garray = aij->garray;
2038d0f46423SBarry Smith       ierr  = PetscMalloc((mat->cmap->N+1)*sizeof(PetscReal),&tmp);CHKERRQ(ierr);
2039d0f46423SBarry Smith       ierr  = PetscMalloc((mat->cmap->N+1)*sizeof(PetscReal),&tmp2);CHKERRQ(ierr);
2040d0f46423SBarry Smith       ierr  = PetscMemzero(tmp,mat->cmap->N*sizeof(PetscReal));CHKERRQ(ierr);
204104ca555eSLois Curfman McInnes       *norm = 0.0;
204204ca555eSLois Curfman McInnes       v     = amat->a; jj = amat->j;
204304ca555eSLois Curfman McInnes       for (j=0; j<amat->nz; j++) {
2044bfec09a0SHong Zhang         tmp[cstart + *jj++] += PetscAbsScalar(*v);  v++;
204504ca555eSLois Curfman McInnes       }
204604ca555eSLois Curfman McInnes       v = bmat->a; jj = bmat->j;
204704ca555eSLois Curfman McInnes       for (j=0; j<bmat->nz; j++) {
2048bfec09a0SHong Zhang         tmp[garray[*jj++]] += PetscAbsScalar(*v); v++;
204904ca555eSLois Curfman McInnes       }
2050ce94432eSBarry Smith       ierr = MPI_Allreduce(tmp,tmp2,mat->cmap->N,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
2051d0f46423SBarry Smith       for (j=0; j<mat->cmap->N; j++) {
205204ca555eSLois Curfman McInnes         if (tmp2[j] > *norm) *norm = tmp2[j];
205304ca555eSLois Curfman McInnes       }
2054606d414cSSatish Balay       ierr = PetscFree(tmp);CHKERRQ(ierr);
2055606d414cSSatish Balay       ierr = PetscFree(tmp2);CHKERRQ(ierr);
20563a40ed3dSBarry Smith     } else if (type == NORM_INFINITY) { /* max row norm */
2057329f5518SBarry Smith       PetscReal ntemp = 0.0;
2058d0f46423SBarry Smith       for (j=0; j<aij->A->rmap->n; j++) {
2059bfec09a0SHong Zhang         v   = amat->a + amat->i[j];
206004ca555eSLois Curfman McInnes         sum = 0.0;
206104ca555eSLois Curfman McInnes         for (i=0; i<amat->i[j+1]-amat->i[j]; i++) {
2062cddf8d76SBarry Smith           sum += PetscAbsScalar(*v); v++;
206304ca555eSLois Curfman McInnes         }
2064bfec09a0SHong Zhang         v = bmat->a + bmat->i[j];
206504ca555eSLois Curfman McInnes         for (i=0; i<bmat->i[j+1]-bmat->i[j]; i++) {
2066cddf8d76SBarry Smith           sum += PetscAbsScalar(*v); v++;
206704ca555eSLois Curfman McInnes         }
2068515d9167SLois Curfman McInnes         if (sum > ntemp) ntemp = sum;
206904ca555eSLois Curfman McInnes       }
2070ce94432eSBarry Smith       ierr = MPI_Allreduce(&ntemp,norm,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)mat));CHKERRQ(ierr);
2071ce94432eSBarry Smith     } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No support for two norm");
207237fa93a5SLois Curfman McInnes   }
20733a40ed3dSBarry Smith   PetscFunctionReturn(0);
2074855ac2c5SLois Curfman McInnes }
2075855ac2c5SLois Curfman McInnes 
20764a2ae208SSatish Balay #undef __FUNCT__
20774a2ae208SSatish Balay #define __FUNCT__ "MatTranspose_MPIAIJ"
2078fc4dec0aSBarry Smith PetscErrorCode MatTranspose_MPIAIJ(Mat A,MatReuse reuse,Mat *matout)
2079b7c46309SBarry Smith {
2080b7c46309SBarry Smith   Mat_MPIAIJ     *a   = (Mat_MPIAIJ*)A->data;
2081da668accSHong Zhang   Mat_SeqAIJ     *Aloc=(Mat_SeqAIJ*)a->A->data,*Bloc=(Mat_SeqAIJ*)a->B->data;
2082dfbe8321SBarry Smith   PetscErrorCode ierr;
208380bcc5a1SJed Brown   PetscInt       M      = A->rmap->N,N = A->cmap->N,ma,na,mb,nb,*ai,*aj,*bi,*bj,row,*cols,*cols_tmp,i;
2084d0f46423SBarry Smith   PetscInt       cstart = A->cmap->rstart,ncol;
20853a40ed3dSBarry Smith   Mat            B;
2086a77337e4SBarry Smith   MatScalar      *array;
2087b7c46309SBarry Smith 
20883a40ed3dSBarry Smith   PetscFunctionBegin;
2089ce94432eSBarry Smith   if (reuse == MAT_REUSE_MATRIX && A == *matout && M != N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Square matrix only for in-place");
2090da668accSHong Zhang 
209180bcc5a1SJed Brown   ma = A->rmap->n; na = A->cmap->n; mb = a->B->rmap->n; nb = a->B->cmap->n;
2092da668accSHong Zhang   ai = Aloc->i; aj = Aloc->j;
2093da668accSHong Zhang   bi = Bloc->i; bj = Bloc->j;
2094fc73b1b3SBarry Smith   if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
209580bcc5a1SJed Brown     PetscInt             *d_nnz,*g_nnz,*o_nnz;
209680bcc5a1SJed Brown     PetscSFNode          *oloc;
2097713c93b4SJed Brown     PETSC_UNUSED PetscSF sf;
209880bcc5a1SJed Brown 
209980bcc5a1SJed Brown     ierr = PetscMalloc4(na,PetscInt,&d_nnz,na,PetscInt,&o_nnz,nb,PetscInt,&g_nnz,nb,PetscSFNode,&oloc);CHKERRQ(ierr);
210080bcc5a1SJed Brown     /* compute d_nnz for preallocation */
210180bcc5a1SJed Brown     ierr = PetscMemzero(d_nnz,na*sizeof(PetscInt));CHKERRQ(ierr);
2102da668accSHong Zhang     for (i=0; i<ai[ma]; i++) {
2103da668accSHong Zhang       d_nnz[aj[i]]++;
2104da668accSHong Zhang       aj[i] += cstart; /* global col index to be used by MatSetValues() */
2105d4bb536fSBarry Smith     }
210680bcc5a1SJed Brown     /* compute local off-diagonal contributions */
21070beca09bSJed Brown     ierr = PetscMemzero(g_nnz,nb*sizeof(PetscInt));CHKERRQ(ierr);
210880bcc5a1SJed Brown     for (i=0; i<bi[ma]; i++) g_nnz[bj[i]]++;
210980bcc5a1SJed Brown     /* map those to global */
2110ce94432eSBarry Smith     ierr = PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);CHKERRQ(ierr);
21110298fd71SBarry Smith     ierr = PetscSFSetGraphLayout(sf,A->cmap,nb,NULL,PETSC_USE_POINTER,a->garray);CHKERRQ(ierr);
2112e9e74f11SJed Brown     ierr = PetscSFSetFromOptions(sf);CHKERRQ(ierr);
211380bcc5a1SJed Brown     ierr = PetscMemzero(o_nnz,na*sizeof(PetscInt));CHKERRQ(ierr);
211480bcc5a1SJed Brown     ierr = PetscSFReduceBegin(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);CHKERRQ(ierr);
211580bcc5a1SJed Brown     ierr = PetscSFReduceEnd(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);CHKERRQ(ierr);
211680bcc5a1SJed Brown     ierr = PetscSFDestroy(&sf);CHKERRQ(ierr);
2117d4bb536fSBarry Smith 
2118ce94432eSBarry Smith     ierr = MatCreate(PetscObjectComm((PetscObject)A),&B);CHKERRQ(ierr);
2119d0f46423SBarry Smith     ierr = MatSetSizes(B,A->cmap->n,A->rmap->n,N,M);CHKERRQ(ierr);
2120a2f3521dSMark F. Adams     ierr = MatSetBlockSizes(B,A->cmap->bs,A->rmap->bs);CHKERRQ(ierr);
21217adad957SLisandro Dalcin     ierr = MatSetType(B,((PetscObject)A)->type_name);CHKERRQ(ierr);
212280bcc5a1SJed Brown     ierr = MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);CHKERRQ(ierr);
212380bcc5a1SJed Brown     ierr = PetscFree4(d_nnz,o_nnz,g_nnz,oloc);CHKERRQ(ierr);
2124fc4dec0aSBarry Smith   } else {
2125fc4dec0aSBarry Smith     B    = *matout;
21266ffab4bbSHong Zhang     ierr = MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);CHKERRQ(ierr);
21272205254eSKarl Rupp     for (i=0; i<ai[ma]; i++) aj[i] += cstart; /* global col index to be used by MatSetValues() */
2128fc4dec0aSBarry Smith   }
2129b7c46309SBarry Smith 
2130b7c46309SBarry Smith   /* copy over the A part */
2131da668accSHong Zhang   array = Aloc->a;
2132d0f46423SBarry Smith   row   = A->rmap->rstart;
2133da668accSHong Zhang   for (i=0; i<ma; i++) {
2134da668accSHong Zhang     ncol = ai[i+1]-ai[i];
2135da668accSHong Zhang     ierr = MatSetValues(B,ncol,aj,1,&row,array,INSERT_VALUES);CHKERRQ(ierr);
21362205254eSKarl Rupp     row++;
21372205254eSKarl Rupp     array += ncol; aj += ncol;
2138b7c46309SBarry Smith   }
2139b7c46309SBarry Smith   aj = Aloc->j;
2140da668accSHong Zhang   for (i=0; i<ai[ma]; i++) aj[i] -= cstart; /* resume local col index */
2141b7c46309SBarry Smith 
2142b7c46309SBarry Smith   /* copy over the B part */
2143fc73b1b3SBarry Smith   ierr  = PetscMalloc(bi[mb]*sizeof(PetscInt),&cols);CHKERRQ(ierr);
2144fc73b1b3SBarry Smith   ierr  = PetscMemzero(cols,bi[mb]*sizeof(PetscInt));CHKERRQ(ierr);
2145da668accSHong Zhang   array = Bloc->a;
2146d0f46423SBarry Smith   row   = A->rmap->rstart;
21472205254eSKarl Rupp   for (i=0; i<bi[mb]; i++) cols[i] = a->garray[bj[i]];
214861a2fbbaSHong Zhang   cols_tmp = cols;
2149da668accSHong Zhang   for (i=0; i<mb; i++) {
2150da668accSHong Zhang     ncol = bi[i+1]-bi[i];
215161a2fbbaSHong Zhang     ierr = MatSetValues(B,ncol,cols_tmp,1,&row,array,INSERT_VALUES);CHKERRQ(ierr);
21522205254eSKarl Rupp     row++;
21532205254eSKarl Rupp     array += ncol; cols_tmp += ncol;
2154b7c46309SBarry Smith   }
2155fc73b1b3SBarry Smith   ierr = PetscFree(cols);CHKERRQ(ierr);
2156fc73b1b3SBarry Smith 
21576d4a8577SBarry Smith   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
21586d4a8577SBarry Smith   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2159815cbec1SBarry Smith   if (reuse == MAT_INITIAL_MATRIX || *matout != A) {
21600de55854SLois Curfman McInnes     *matout = B;
21610de55854SLois Curfman McInnes   } else {
2162eb6b5d47SBarry Smith     ierr = MatHeaderMerge(A,B);CHKERRQ(ierr);
21630de55854SLois Curfman McInnes   }
21643a40ed3dSBarry Smith   PetscFunctionReturn(0);
2165b7c46309SBarry Smith }
2166b7c46309SBarry Smith 
21674a2ae208SSatish Balay #undef __FUNCT__
21684a2ae208SSatish Balay #define __FUNCT__ "MatDiagonalScale_MPIAIJ"
2169dfbe8321SBarry Smith PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat,Vec ll,Vec rr)
2170a008b906SSatish Balay {
21714b967eb1SSatish Balay   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
21724b967eb1SSatish Balay   Mat            a    = aij->A,b = aij->B;
2173dfbe8321SBarry Smith   PetscErrorCode ierr;
2174b1d57f15SBarry Smith   PetscInt       s1,s2,s3;
2175a008b906SSatish Balay 
21763a40ed3dSBarry Smith   PetscFunctionBegin;
21774b967eb1SSatish Balay   ierr = MatGetLocalSize(mat,&s2,&s3);CHKERRQ(ierr);
21784b967eb1SSatish Balay   if (rr) {
2179e1311b90SBarry Smith     ierr = VecGetLocalSize(rr,&s1);CHKERRQ(ierr);
2180e32f2f54SBarry Smith     if (s1!=s3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
21814b967eb1SSatish Balay     /* Overlap communication with computation. */
2182ca9f406cSSatish Balay     ierr = VecScatterBegin(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
2183a008b906SSatish Balay   }
21844b967eb1SSatish Balay   if (ll) {
2185e1311b90SBarry Smith     ierr = VecGetLocalSize(ll,&s1);CHKERRQ(ierr);
2186e32f2f54SBarry Smith     if (s1!=s2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
2187f830108cSBarry Smith     ierr = (*b->ops->diagonalscale)(b,ll,0);CHKERRQ(ierr);
21884b967eb1SSatish Balay   }
21894b967eb1SSatish Balay   /* scale  the diagonal block */
2190f830108cSBarry Smith   ierr = (*a->ops->diagonalscale)(a,ll,rr);CHKERRQ(ierr);
21914b967eb1SSatish Balay 
21924b967eb1SSatish Balay   if (rr) {
21934b967eb1SSatish Balay     /* Do a scatter end and then right scale the off-diagonal block */
2194ca9f406cSSatish Balay     ierr = VecScatterEnd(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
2195f830108cSBarry Smith     ierr = (*b->ops->diagonalscale)(b,0,aij->lvec);CHKERRQ(ierr);
21964b967eb1SSatish Balay   }
21973a40ed3dSBarry Smith   PetscFunctionReturn(0);
2198a008b906SSatish Balay }
2199a008b906SSatish Balay 
22004a2ae208SSatish Balay #undef __FUNCT__
22014a2ae208SSatish Balay #define __FUNCT__ "MatSetUnfactored_MPIAIJ"
2202dfbe8321SBarry Smith PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
2203bb5a7306SBarry Smith {
2204bb5a7306SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2205dfbe8321SBarry Smith   PetscErrorCode ierr;
22063a40ed3dSBarry Smith 
22073a40ed3dSBarry Smith   PetscFunctionBegin;
2208bb5a7306SBarry Smith   ierr = MatSetUnfactored(a->A);CHKERRQ(ierr);
22093a40ed3dSBarry Smith   PetscFunctionReturn(0);
2210bb5a7306SBarry Smith }
2211bb5a7306SBarry Smith 
22124a2ae208SSatish Balay #undef __FUNCT__
22134a2ae208SSatish Balay #define __FUNCT__ "MatEqual_MPIAIJ"
2214ace3abfcSBarry Smith PetscErrorCode MatEqual_MPIAIJ(Mat A,Mat B,PetscBool  *flag)
2215d4bb536fSBarry Smith {
2216d4bb536fSBarry Smith   Mat_MPIAIJ     *matB = (Mat_MPIAIJ*)B->data,*matA = (Mat_MPIAIJ*)A->data;
2217d4bb536fSBarry Smith   Mat            a,b,c,d;
2218ace3abfcSBarry Smith   PetscBool      flg;
2219dfbe8321SBarry Smith   PetscErrorCode ierr;
2220d4bb536fSBarry Smith 
22213a40ed3dSBarry Smith   PetscFunctionBegin;
2222d4bb536fSBarry Smith   a = matA->A; b = matA->B;
2223d4bb536fSBarry Smith   c = matB->A; d = matB->B;
2224d4bb536fSBarry Smith 
2225d4bb536fSBarry Smith   ierr = MatEqual(a,c,&flg);CHKERRQ(ierr);
2226abc0a331SBarry Smith   if (flg) {
2227d4bb536fSBarry Smith     ierr = MatEqual(b,d,&flg);CHKERRQ(ierr);
2228d4bb536fSBarry Smith   }
2229ce94432eSBarry Smith   ierr = MPI_Allreduce(&flg,flag,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));CHKERRQ(ierr);
22303a40ed3dSBarry Smith   PetscFunctionReturn(0);
2231d4bb536fSBarry Smith }
2232d4bb536fSBarry Smith 
22334a2ae208SSatish Balay #undef __FUNCT__
22344a2ae208SSatish Balay #define __FUNCT__ "MatCopy_MPIAIJ"
2235dfbe8321SBarry Smith PetscErrorCode MatCopy_MPIAIJ(Mat A,Mat B,MatStructure str)
2236cb5b572fSBarry Smith {
2237dfbe8321SBarry Smith   PetscErrorCode ierr;
2238cb5b572fSBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2239cb5b572fSBarry Smith   Mat_MPIAIJ     *b = (Mat_MPIAIJ*)B->data;
2240cb5b572fSBarry Smith 
2241cb5b572fSBarry Smith   PetscFunctionBegin;
224233f4a19fSKris Buschelman   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
224333f4a19fSKris Buschelman   if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
2244cb5b572fSBarry Smith     /* because of the column compression in the off-processor part of the matrix a->B,
2245cb5b572fSBarry Smith        the number of columns in a->B and b->B may be different, hence we cannot call
2246cb5b572fSBarry Smith        the MatCopy() directly on the two parts. If need be, we can provide a more
2247cb5b572fSBarry Smith        efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2248cb5b572fSBarry Smith        then copying the submatrices */
2249cb5b572fSBarry Smith     ierr = MatCopy_Basic(A,B,str);CHKERRQ(ierr);
2250cb5b572fSBarry Smith   } else {
2251cb5b572fSBarry Smith     ierr = MatCopy(a->A,b->A,str);CHKERRQ(ierr);
2252cb5b572fSBarry Smith     ierr = MatCopy(a->B,b->B,str);CHKERRQ(ierr);
2253cb5b572fSBarry Smith   }
2254cb5b572fSBarry Smith   PetscFunctionReturn(0);
2255cb5b572fSBarry Smith }
2256cb5b572fSBarry Smith 
22574a2ae208SSatish Balay #undef __FUNCT__
22584994cf47SJed Brown #define __FUNCT__ "MatSetUp_MPIAIJ"
22594994cf47SJed Brown PetscErrorCode MatSetUp_MPIAIJ(Mat A)
2260273d9f13SBarry Smith {
2261dfbe8321SBarry Smith   PetscErrorCode ierr;
2262273d9f13SBarry Smith 
2263273d9f13SBarry Smith   PetscFunctionBegin;
2264273d9f13SBarry Smith   ierr =  MatMPIAIJSetPreallocation(A,PETSC_DEFAULT,0,PETSC_DEFAULT,0);CHKERRQ(ierr);
2265273d9f13SBarry Smith   PetscFunctionReturn(0);
2266273d9f13SBarry Smith }
2267273d9f13SBarry Smith 
2268ac90fabeSBarry Smith #undef __FUNCT__
226995b7e79eSJed Brown #define __FUNCT__ "MatAXPYGetPreallocation_MPIAIJ"
227095b7e79eSJed Brown /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
227195b7e79eSJed Brown static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y,const PetscInt *yltog,Mat X,const PetscInt *xltog,PetscInt *nnz)
227295b7e79eSJed Brown {
227395b7e79eSJed Brown   PetscInt       i,m=Y->rmap->N;
227495b7e79eSJed Brown   Mat_SeqAIJ     *x  = (Mat_SeqAIJ*)X->data;
227595b7e79eSJed Brown   Mat_SeqAIJ     *y  = (Mat_SeqAIJ*)Y->data;
227695b7e79eSJed Brown   const PetscInt *xi = x->i,*yi = y->i;
227795b7e79eSJed Brown 
227895b7e79eSJed Brown   PetscFunctionBegin;
227995b7e79eSJed Brown   /* Set the number of nonzeros in the new matrix */
228095b7e79eSJed Brown   for (i=0; i<m; i++) {
228195b7e79eSJed Brown     PetscInt       j,k,nzx = xi[i+1] - xi[i],nzy = yi[i+1] - yi[i];
228295b7e79eSJed Brown     const PetscInt *xj = x->j+xi[i],*yj = y->j+yi[i];
228395b7e79eSJed Brown     nnz[i] = 0;
228495b7e79eSJed Brown     for (j=0,k=0; j<nzx; j++) {                   /* Point in X */
228595b7e79eSJed Brown       for (; k<nzy && yltog[yj[k]]<xltog[xj[j]]; k++) nnz[i]++; /* Catch up to X */
228695b7e79eSJed Brown       if (k<nzy && yltog[yj[k]]==xltog[xj[j]]) k++;             /* Skip duplicate */
228795b7e79eSJed Brown       nnz[i]++;
228895b7e79eSJed Brown     }
228995b7e79eSJed Brown     for (; k<nzy; k++) nnz[i]++;
229095b7e79eSJed Brown   }
229195b7e79eSJed Brown   PetscFunctionReturn(0);
229295b7e79eSJed Brown }
229395b7e79eSJed Brown 
229495b7e79eSJed Brown #undef __FUNCT__
2295ac90fabeSBarry Smith #define __FUNCT__ "MatAXPY_MPIAIJ"
2296f4df32b1SMatthew Knepley PetscErrorCode MatAXPY_MPIAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
2297ac90fabeSBarry Smith {
2298dfbe8321SBarry Smith   PetscErrorCode ierr;
2299b1d57f15SBarry Smith   PetscInt       i;
2300ac90fabeSBarry Smith   Mat_MPIAIJ     *xx = (Mat_MPIAIJ*)X->data,*yy = (Mat_MPIAIJ*)Y->data;
23014ce68768SBarry Smith   PetscBLASInt   bnz,one=1;
2302ac90fabeSBarry Smith   Mat_SeqAIJ     *x,*y;
2303ac90fabeSBarry Smith 
2304ac90fabeSBarry Smith   PetscFunctionBegin;
2305ac90fabeSBarry Smith   if (str == SAME_NONZERO_PATTERN) {
2306f4df32b1SMatthew Knepley     PetscScalar alpha = a;
2307ac90fabeSBarry Smith     x    = (Mat_SeqAIJ*)xx->A->data;
2308c5df96a5SBarry Smith     ierr = PetscBLASIntCast(x->nz,&bnz);CHKERRQ(ierr);
2309ac90fabeSBarry Smith     y    = (Mat_SeqAIJ*)yy->A->data;
23108b83055fSJed Brown     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2311ac90fabeSBarry Smith     x    = (Mat_SeqAIJ*)xx->B->data;
2312ac90fabeSBarry Smith     y    = (Mat_SeqAIJ*)yy->B->data;
2313c5df96a5SBarry Smith     ierr = PetscBLASIntCast(x->nz,&bnz);CHKERRQ(ierr);
23148b83055fSJed Brown     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2315a30b2313SHong Zhang   } else if (str == SUBSET_NONZERO_PATTERN) {
2316f4df32b1SMatthew Knepley     ierr = MatAXPY_SeqAIJ(yy->A,a,xx->A,str);CHKERRQ(ierr);
2317c537a176SHong Zhang 
2318c537a176SHong Zhang     x = (Mat_SeqAIJ*)xx->B->data;
2319a30b2313SHong Zhang     y = (Mat_SeqAIJ*)yy->B->data;
2320a30b2313SHong Zhang     if (y->xtoy && y->XtoY != xx->B) {
2321a30b2313SHong Zhang       ierr = PetscFree(y->xtoy);CHKERRQ(ierr);
23226bf464f9SBarry Smith       ierr = MatDestroy(&y->XtoY);CHKERRQ(ierr);
2323c537a176SHong Zhang     }
2324a30b2313SHong Zhang     if (!y->xtoy) { /* get xtoy */
2325d0f46423SBarry Smith       ierr    = MatAXPYGetxtoy_Private(xx->B->rmap->n,x->i,x->j,xx->garray,y->i,y->j,yy->garray,&y->xtoy);CHKERRQ(ierr);
2326a30b2313SHong Zhang       y->XtoY = xx->B;
2327407f6b05SHong Zhang       ierr    = PetscObjectReference((PetscObject)xx->B);CHKERRQ(ierr);
2328c537a176SHong Zhang     }
2329f4df32b1SMatthew Knepley     for (i=0; i<x->nz; i++) y->a[y->xtoy[i]] += a*(x->a[i]);
2330ac90fabeSBarry Smith   } else {
23319f5f6813SShri Abhyankar     Mat      B;
23329f5f6813SShri Abhyankar     PetscInt *nnz_d,*nnz_o;
23339f5f6813SShri Abhyankar     ierr = PetscMalloc(yy->A->rmap->N*sizeof(PetscInt),&nnz_d);CHKERRQ(ierr);
23349f5f6813SShri Abhyankar     ierr = PetscMalloc(yy->B->rmap->N*sizeof(PetscInt),&nnz_o);CHKERRQ(ierr);
2335ce94432eSBarry Smith     ierr = MatCreate(PetscObjectComm((PetscObject)Y),&B);CHKERRQ(ierr);
2336bc5a2726SShri Abhyankar     ierr = PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);CHKERRQ(ierr);
23379f5f6813SShri Abhyankar     ierr = MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);CHKERRQ(ierr);
2338a2f3521dSMark F. Adams     ierr = MatSetBlockSizes(B,Y->rmap->bs,Y->cmap->bs);CHKERRQ(ierr);
23399f5f6813SShri Abhyankar     ierr = MatSetType(B,MATMPIAIJ);CHKERRQ(ierr);
23409f5f6813SShri Abhyankar     ierr = MatAXPYGetPreallocation_SeqAIJ(yy->A,xx->A,nnz_d);CHKERRQ(ierr);
234195b7e79eSJed Brown     ierr = MatAXPYGetPreallocation_MPIAIJ(yy->B,yy->garray,xx->B,xx->garray,nnz_o);CHKERRQ(ierr);
2342ecd8bba6SJed Brown     ierr = MatMPIAIJSetPreallocation(B,0,nnz_d,0,nnz_o);CHKERRQ(ierr);
23439f5f6813SShri Abhyankar     ierr = MatAXPY_BasicWithPreallocation(B,Y,a,X,str);CHKERRQ(ierr);
2344a2ea699eSBarry Smith     ierr = MatHeaderReplace(Y,B);CHKERRQ(ierr);
23459f5f6813SShri Abhyankar     ierr = PetscFree(nnz_d);CHKERRQ(ierr);
23469f5f6813SShri Abhyankar     ierr = PetscFree(nnz_o);CHKERRQ(ierr);
2347ac90fabeSBarry Smith   }
2348ac90fabeSBarry Smith   PetscFunctionReturn(0);
2349ac90fabeSBarry Smith }
2350ac90fabeSBarry Smith 
23517087cfbeSBarry Smith extern PetscErrorCode  MatConjugate_SeqAIJ(Mat);
2352354c94deSBarry Smith 
2353354c94deSBarry Smith #undef __FUNCT__
2354354c94deSBarry Smith #define __FUNCT__ "MatConjugate_MPIAIJ"
23557087cfbeSBarry Smith PetscErrorCode  MatConjugate_MPIAIJ(Mat mat)
2356354c94deSBarry Smith {
2357354c94deSBarry Smith #if defined(PETSC_USE_COMPLEX)
2358354c94deSBarry Smith   PetscErrorCode ierr;
2359354c94deSBarry Smith   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
2360354c94deSBarry Smith 
2361354c94deSBarry Smith   PetscFunctionBegin;
2362354c94deSBarry Smith   ierr = MatConjugate_SeqAIJ(aij->A);CHKERRQ(ierr);
2363354c94deSBarry Smith   ierr = MatConjugate_SeqAIJ(aij->B);CHKERRQ(ierr);
2364354c94deSBarry Smith #else
2365354c94deSBarry Smith   PetscFunctionBegin;
2366354c94deSBarry Smith #endif
2367354c94deSBarry Smith   PetscFunctionReturn(0);
2368354c94deSBarry Smith }
2369354c94deSBarry Smith 
237099cafbc1SBarry Smith #undef __FUNCT__
237199cafbc1SBarry Smith #define __FUNCT__ "MatRealPart_MPIAIJ"
237299cafbc1SBarry Smith PetscErrorCode MatRealPart_MPIAIJ(Mat A)
237399cafbc1SBarry Smith {
237499cafbc1SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
237599cafbc1SBarry Smith   PetscErrorCode ierr;
237699cafbc1SBarry Smith 
237799cafbc1SBarry Smith   PetscFunctionBegin;
237899cafbc1SBarry Smith   ierr = MatRealPart(a->A);CHKERRQ(ierr);
237999cafbc1SBarry Smith   ierr = MatRealPart(a->B);CHKERRQ(ierr);
238099cafbc1SBarry Smith   PetscFunctionReturn(0);
238199cafbc1SBarry Smith }
238299cafbc1SBarry Smith 
238399cafbc1SBarry Smith #undef __FUNCT__
238499cafbc1SBarry Smith #define __FUNCT__ "MatImaginaryPart_MPIAIJ"
238599cafbc1SBarry Smith PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
238699cafbc1SBarry Smith {
238799cafbc1SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
238899cafbc1SBarry Smith   PetscErrorCode ierr;
238999cafbc1SBarry Smith 
239099cafbc1SBarry Smith   PetscFunctionBegin;
239199cafbc1SBarry Smith   ierr = MatImaginaryPart(a->A);CHKERRQ(ierr);
239299cafbc1SBarry Smith   ierr = MatImaginaryPart(a->B);CHKERRQ(ierr);
239399cafbc1SBarry Smith   PetscFunctionReturn(0);
239499cafbc1SBarry Smith }
239599cafbc1SBarry Smith 
2396519f805aSKarl Rupp #if defined(PETSC_HAVE_PBGL)
2397103bf8bdSMatthew Knepley 
2398103bf8bdSMatthew Knepley #include <boost/parallel/mpi/bsp_process_group.hpp>
2399a2c909beSMatthew Knepley #include <boost/graph/distributed/ilu_default_graph.hpp>
2400a2c909beSMatthew Knepley #include <boost/graph/distributed/ilu_0_block.hpp>
2401a2c909beSMatthew Knepley #include <boost/graph/distributed/ilu_preconditioner.hpp>
2402103bf8bdSMatthew Knepley #include <boost/graph/distributed/petsc/interface.hpp>
2403a2c909beSMatthew Knepley #include <boost/multi_array.hpp>
2404d0f46423SBarry Smith #include <boost/parallel/distributed_property_map->hpp>
2405103bf8bdSMatthew Knepley 
2406103bf8bdSMatthew Knepley #undef __FUNCT__
2407103bf8bdSMatthew Knepley #define __FUNCT__ "MatILUFactorSymbolic_MPIAIJ"
2408103bf8bdSMatthew Knepley /*
2409103bf8bdSMatthew Knepley   This uses the parallel ILU factorization of Peter Gottschling <pgottsch@osl.iu.edu>
2410103bf8bdSMatthew Knepley */
24110481f469SBarry Smith PetscErrorCode MatILUFactorSymbolic_MPIAIJ(Mat fact,Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
2412103bf8bdSMatthew Knepley {
2413a2c909beSMatthew Knepley   namespace petsc = boost::distributed::petsc;
2414a2c909beSMatthew Knepley 
2415a2c909beSMatthew Knepley   namespace graph_dist = boost::graph::distributed;
2416a2c909beSMatthew Knepley   using boost::graph::distributed::ilu_default::process_group_type;
2417a2c909beSMatthew Knepley   using boost::graph::ilu_permuted;
2418a2c909beSMatthew Knepley 
2419ace3abfcSBarry Smith   PetscBool      row_identity, col_identity;
2420776b82aeSLisandro Dalcin   PetscContainer c;
2421103bf8bdSMatthew Knepley   PetscInt       m, n, M, N;
2422103bf8bdSMatthew Knepley   PetscErrorCode ierr;
2423103bf8bdSMatthew Knepley 
2424103bf8bdSMatthew Knepley   PetscFunctionBegin;
2425e32f2f54SBarry Smith   if (info->levels != 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only levels = 0 supported for parallel ilu");
2426103bf8bdSMatthew Knepley   ierr = ISIdentity(isrow, &row_identity);CHKERRQ(ierr);
2427103bf8bdSMatthew Knepley   ierr = ISIdentity(iscol, &col_identity);CHKERRQ(ierr);
2428f23aa3ddSBarry Smith   if (!row_identity || !col_identity) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Row and column permutations must be identity for parallel ILU");
2429103bf8bdSMatthew Knepley 
2430103bf8bdSMatthew Knepley   process_group_type pg;
2431a2c909beSMatthew Knepley   typedef graph_dist::ilu_default::ilu_level_graph_type lgraph_type;
2432a2c909beSMatthew Knepley   lgraph_type  *lgraph_p   = new lgraph_type(petsc::num_global_vertices(A), pg, petsc::matrix_distribution(A, pg));
2433a2c909beSMatthew Knepley   lgraph_type& level_graph = *lgraph_p;
2434a2c909beSMatthew Knepley   graph_dist::ilu_default::graph_type&            graph(level_graph.graph);
2435a2c909beSMatthew Knepley 
2436103bf8bdSMatthew Knepley   petsc::read_matrix(A, graph, get(boost::edge_weight, graph));
2437a2c909beSMatthew Knepley   ilu_permuted(level_graph);
2438103bf8bdSMatthew Knepley 
2439103bf8bdSMatthew Knepley   /* put together the new matrix */
2440ce94432eSBarry Smith   ierr = MatCreate(PetscObjectComm((PetscObject)A), fact);CHKERRQ(ierr);
2441103bf8bdSMatthew Knepley   ierr = MatGetLocalSize(A, &m, &n);CHKERRQ(ierr);
2442103bf8bdSMatthew Knepley   ierr = MatGetSize(A, &M, &N);CHKERRQ(ierr);
2443719d5645SBarry Smith   ierr = MatSetSizes(fact, m, n, M, N);CHKERRQ(ierr);
2444a2f3521dSMark F. Adams   ierr = MatSetBlockSizes(fact,A->rmap->bs,A->cmap->bs);CHKERRQ(ierr);
2445719d5645SBarry Smith   ierr = MatSetType(fact, ((PetscObject)A)->type_name);CHKERRQ(ierr);
2446719d5645SBarry Smith   ierr = MatAssemblyBegin(fact, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2447719d5645SBarry Smith   ierr = MatAssemblyEnd(fact, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2448103bf8bdSMatthew Knepley 
2449ce94432eSBarry Smith   ierr = PetscContainerCreate(PetscObjectComm((PetscObject)A), &c);
2450776b82aeSLisandro Dalcin   ierr = PetscContainerSetPointer(c, lgraph_p);
2451719d5645SBarry Smith   ierr = PetscObjectCompose((PetscObject) (fact), "graph", (PetscObject) c);
2452bf0cc555SLisandro Dalcin   ierr = PetscContainerDestroy(&c);
2453103bf8bdSMatthew Knepley   PetscFunctionReturn(0);
2454103bf8bdSMatthew Knepley }
2455103bf8bdSMatthew Knepley 
2456103bf8bdSMatthew Knepley #undef __FUNCT__
2457103bf8bdSMatthew Knepley #define __FUNCT__ "MatLUFactorNumeric_MPIAIJ"
24580481f469SBarry Smith PetscErrorCode MatLUFactorNumeric_MPIAIJ(Mat B,Mat A, const MatFactorInfo *info)
2459103bf8bdSMatthew Knepley {
2460103bf8bdSMatthew Knepley   PetscFunctionBegin;
2461103bf8bdSMatthew Knepley   PetscFunctionReturn(0);
2462103bf8bdSMatthew Knepley }
2463103bf8bdSMatthew Knepley 
2464103bf8bdSMatthew Knepley #undef __FUNCT__
2465103bf8bdSMatthew Knepley #define __FUNCT__ "MatSolve_MPIAIJ"
2466103bf8bdSMatthew Knepley /*
2467103bf8bdSMatthew Knepley   This uses the parallel ILU factorization of Peter Gottschling <pgottsch@osl.iu.edu>
2468103bf8bdSMatthew Knepley */
2469103bf8bdSMatthew Knepley PetscErrorCode MatSolve_MPIAIJ(Mat A, Vec b, Vec x)
2470103bf8bdSMatthew Knepley {
2471a2c909beSMatthew Knepley   namespace graph_dist = boost::graph::distributed;
2472a2c909beSMatthew Knepley 
2473a2c909beSMatthew Knepley   typedef graph_dist::ilu_default::ilu_level_graph_type lgraph_type;
2474a2c909beSMatthew Knepley   lgraph_type    *lgraph_p;
2475776b82aeSLisandro Dalcin   PetscContainer c;
2476103bf8bdSMatthew Knepley   PetscErrorCode ierr;
2477103bf8bdSMatthew Knepley 
2478103bf8bdSMatthew Knepley   PetscFunctionBegin;
2479103bf8bdSMatthew Knepley   ierr = PetscObjectQuery((PetscObject) A, "graph", (PetscObject*) &c);CHKERRQ(ierr);
2480776b82aeSLisandro Dalcin   ierr = PetscContainerGetPointer(c, (void**) &lgraph_p);CHKERRQ(ierr);
2481103bf8bdSMatthew Knepley   ierr = VecCopy(b, x);CHKERRQ(ierr);
2482a2c909beSMatthew Knepley 
2483a2c909beSMatthew Knepley   PetscScalar *array_x;
2484a2c909beSMatthew Knepley   ierr = VecGetArray(x, &array_x);CHKERRQ(ierr);
2485a2c909beSMatthew Knepley   PetscInt sx;
2486a2c909beSMatthew Knepley   ierr = VecGetSize(x, &sx);CHKERRQ(ierr);
2487a2c909beSMatthew Knepley 
2488a2c909beSMatthew Knepley   PetscScalar *array_b;
2489a2c909beSMatthew Knepley   ierr = VecGetArray(b, &array_b);CHKERRQ(ierr);
2490a2c909beSMatthew Knepley   PetscInt sb;
2491a2c909beSMatthew Knepley   ierr = VecGetSize(b, &sb);CHKERRQ(ierr);
2492a2c909beSMatthew Knepley 
2493a2c909beSMatthew Knepley   lgraph_type& level_graph = *lgraph_p;
2494a2c909beSMatthew Knepley   graph_dist::ilu_default::graph_type&            graph(level_graph.graph);
2495a2c909beSMatthew Knepley 
2496a2c909beSMatthew Knepley   typedef boost::multi_array_ref<PetscScalar, 1> array_ref_type;
24972205254eSKarl Rupp   array_ref_type                                 ref_b(array_b, boost::extents[num_vertices(graph)]);
24982205254eSKarl Rupp   array_ref_type                                 ref_x(array_x, boost::extents[num_vertices(graph)]);
2499a2c909beSMatthew Knepley 
2500a2c909beSMatthew Knepley   typedef boost::iterator_property_map<array_ref_type::iterator,
2501a2c909beSMatthew Knepley                                        boost::property_map<graph_dist::ilu_default::graph_type, boost::vertex_index_t>::type>  gvector_type;
25022205254eSKarl Rupp   gvector_type                                   vector_b(ref_b.begin(), get(boost::vertex_index, graph));
25032205254eSKarl Rupp   gvector_type                                   vector_x(ref_x.begin(), get(boost::vertex_index, graph));
2504a2c909beSMatthew Knepley 
2505a2c909beSMatthew Knepley   ilu_set_solve(*lgraph_p, vector_b, vector_x);
2506103bf8bdSMatthew Knepley   PetscFunctionReturn(0);
2507103bf8bdSMatthew Knepley }
2508103bf8bdSMatthew Knepley #endif
2509103bf8bdSMatthew Knepley 
251069db28dcSHong Zhang #undef __FUNCT__
25115cc03489SHong Zhang #define __FUNCT__ "MatDestroy_MatRedundant"
25125cc03489SHong Zhang PetscErrorCode MatDestroy_MatRedundant(Mat A)
251369db28dcSHong Zhang {
251469db28dcSHong Zhang   PetscErrorCode ierr;
25155cc03489SHong Zhang   Mat_Redundant  *redund;
251669db28dcSHong Zhang   PetscInt       i;
25175cc03489SHong Zhang   PetscMPIInt    size;
251869db28dcSHong Zhang 
251969db28dcSHong Zhang   PetscFunctionBegin;
25205cc03489SHong Zhang   ierr = MPI_Comm_size(((PetscObject)A)->comm,&size);CHKERRQ(ierr);
25215cc03489SHong Zhang   if (size == 1) {
25225cc03489SHong Zhang     Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
25235cc03489SHong Zhang     redund = a->redundant;
25245cc03489SHong Zhang   } else {
25255cc03489SHong Zhang     Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
25265cc03489SHong Zhang     redund = a->redundant;
25275cc03489SHong Zhang   }
25285cc03489SHong Zhang   if (redund){
2529*c79c5527SHong Zhang     if (redund->matseq) { /* via MatGetSubMatrices()  */
25304388c78fSHong Zhang       ierr = ISDestroy(&redund->isrow);CHKERRQ(ierr);
25314388c78fSHong Zhang       ierr = ISDestroy(&redund->iscol);CHKERRQ(ierr);
25324388c78fSHong Zhang       ierr = MatDestroy(&redund->matseq[0]);CHKERRQ(ierr);
25334388c78fSHong Zhang       ierr = PetscFree(redund->matseq);CHKERRQ(ierr);
25344388c78fSHong Zhang     } else {
25351d79065fSBarry Smith       ierr = PetscFree2(redund->send_rank,redund->recv_rank);CHKERRQ(ierr);
253669db28dcSHong Zhang       ierr = PetscFree(redund->sbuf_j);CHKERRQ(ierr);
253769db28dcSHong Zhang       ierr = PetscFree(redund->sbuf_a);CHKERRQ(ierr);
253869db28dcSHong Zhang       for (i=0; i<redund->nrecvs; i++) {
253969db28dcSHong Zhang         ierr = PetscFree(redund->rbuf_j[i]);CHKERRQ(ierr);
254069db28dcSHong Zhang         ierr = PetscFree(redund->rbuf_a[i]);CHKERRQ(ierr);
254169db28dcSHong Zhang       }
25421d79065fSBarry Smith       ierr = PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);CHKERRQ(ierr);
2543*c79c5527SHong Zhang     }
25440b291e46SHong Zhang 
25450b291e46SHong Zhang     if (redund->psubcomm) {
25460b291e46SHong Zhang       ierr = PetscSubcommDestroy(&redund->psubcomm);CHKERRQ(ierr);
25470b291e46SHong Zhang     }
25485cc03489SHong Zhang     ierr = redund->Destroy(A);CHKERRQ(ierr);
254969db28dcSHong Zhang     ierr = PetscFree(redund);CHKERRQ(ierr);
2550bf0cc555SLisandro Dalcin   }
255169db28dcSHong Zhang   PetscFunctionReturn(0);
255269db28dcSHong Zhang }
255369db28dcSHong Zhang 
255469db28dcSHong Zhang #undef __FUNCT__
2555e37c6257SHong Zhang #define __FUNCT__ "MatGetRedundantMatrix_MPIAIJ_psubcomm"
2556e37c6257SHong Zhang PetscErrorCode MatGetRedundantMatrix_MPIAIJ_psubcomm(Mat mat,PetscInt nsubcomm,PetscSubcomm psubcomm,MatReuse reuse,Mat *matredundant)
2557b4617e5dSHong Zhang {
2558b4617e5dSHong Zhang   PetscMPIInt    rank,size;
2559b4617e5dSHong Zhang   MPI_Comm       comm,subcomm=psubcomm->comm;
2560b4617e5dSHong Zhang   PetscErrorCode ierr;
256134d19554SHong Zhang   PetscInt       nsends=0,nrecvs=0,i,rownz_max=0,M=mat->rmap->N,N=mat->cmap->N;
25625cc03489SHong Zhang   PetscMPIInt    *send_rank= NULL,*recv_rank=NULL,subrank,subsize;
2563b4617e5dSHong Zhang   PetscInt       *rowrange = mat->rmap->range;
2564b4617e5dSHong Zhang   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
2565b4617e5dSHong Zhang   Mat            A = aij->A,B=aij->B,C=*matredundant;
2566b4617e5dSHong Zhang   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*b=(Mat_SeqAIJ*)B->data;
2567b4617e5dSHong Zhang   PetscScalar    *sbuf_a;
2568b4617e5dSHong Zhang   PetscInt       nzlocal=a->nz+b->nz;
2569b4617e5dSHong Zhang   PetscInt       j,cstart=mat->cmap->rstart,cend=mat->cmap->rend,row,nzA,nzB,ncols,*cworkA,*cworkB;
257034d19554SHong Zhang   PetscInt       rstart=mat->rmap->rstart,rend=mat->rmap->rend,*bmap=aij->garray;
2571b4617e5dSHong Zhang   PetscInt       *cols,ctmp,lwrite,*rptr,l,*sbuf_j;
2572b4617e5dSHong Zhang   MatScalar      *aworkA,*aworkB;
2573b4617e5dSHong Zhang   PetscScalar    *vals;
2574b4617e5dSHong Zhang   PetscMPIInt    tag1,tag2,tag3,imdex;
2575b4617e5dSHong Zhang   MPI_Request    *s_waits1=NULL,*s_waits2=NULL,*s_waits3=NULL;
2576b4617e5dSHong Zhang   MPI_Request    *r_waits1=NULL,*r_waits2=NULL,*r_waits3=NULL;
2577b4617e5dSHong Zhang   MPI_Status     recv_status,*send_status;
2578b4617e5dSHong Zhang   PetscInt       *sbuf_nz=NULL,*rbuf_nz=NULL,count;
2579b4617e5dSHong Zhang   PetscInt       **rbuf_j=NULL;
2580b4617e5dSHong Zhang   PetscScalar    **rbuf_a=NULL;
2581b4617e5dSHong Zhang   Mat_Redundant  *redund =NULL;
25823c79b8e7SHong Zhang   PetscBool      flg=PETSC_FALSE;
2583b4617e5dSHong Zhang 
2584b4617e5dSHong Zhang   PetscFunctionBegin;
2585b4617e5dSHong Zhang   ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
2586b4617e5dSHong Zhang   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
2587b4617e5dSHong Zhang   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
25885cc03489SHong Zhang   ierr = MPI_Comm_rank(subcomm,&subrank);CHKERRQ(ierr);
25895cc03489SHong Zhang   ierr = MPI_Comm_size(subcomm,&subsize);CHKERRQ(ierr);
2590d3b23db5SHong Zhang 
25913c79b8e7SHong Zhang   /* ---------- new imples: use MatGetSubMatrices() ------------*/
25923c79b8e7SHong Zhang   ierr = PetscOptionsGetBool(NULL,"-new",&flg,NULL);CHKERRQ(ierr);
25933c79b8e7SHong Zhang   if (flg) {
25943c79b8e7SHong Zhang     Mat        *matseq;
25953c79b8e7SHong Zhang     IS         isrow,iscol;
25963c79b8e7SHong Zhang     PetscInt   mloc_sub,rstart,rend;
25973c79b8e7SHong Zhang 
25983c79b8e7SHong Zhang     if (reuse == MAT_INITIAL_MATRIX) {
25993c79b8e7SHong Zhang       /* create a local sequential matrix matseq[0] */
2600dd065a40SHong Zhang       mloc_sub = PETSC_DECIDE;
2601dd065a40SHong Zhang       ierr = PetscSplitOwnership(subcomm,&mloc_sub,&M);CHKERRQ(ierr);
2602dd065a40SHong Zhang       ierr = MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);CHKERRQ(ierr);
2603dd065a40SHong Zhang       rstart = rend - mloc_sub;
26044388c78fSHong Zhang       /* printf("[%d] Use MatGetSubMatrices()...rows %d - %d, mloc_sub %d\n",rank,rstart,rend,mloc_sub); */
26053c79b8e7SHong Zhang       ierr = ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);CHKERRQ(ierr);
26063c79b8e7SHong Zhang       ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);CHKERRQ(ierr);
26073c79b8e7SHong Zhang     } else { /* reuse == MAT_REUSE_MATRIX */
26083c79b8e7SHong Zhang       if (subsize == 1) {
26093c79b8e7SHong Zhang         Mat_SeqAIJ *c = (Mat_SeqAIJ*)C->data;
26103c79b8e7SHong Zhang         redund = c->redundant;
26113c79b8e7SHong Zhang       } else {
26123c79b8e7SHong Zhang         Mat_MPIAIJ *c = (Mat_MPIAIJ*)C->data;
26133c79b8e7SHong Zhang         redund = c->redundant;
26143c79b8e7SHong Zhang       }
26153c79b8e7SHong Zhang 
26163c79b8e7SHong Zhang       isrow = redund->isrow;
26173c79b8e7SHong Zhang       iscol = redund->iscol;
26183c79b8e7SHong Zhang       matseq = redund->matseq;
26193c79b8e7SHong Zhang     }
26203c79b8e7SHong Zhang 
26213c79b8e7SHong Zhang     ierr = MatGetSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);CHKERRQ(ierr);
26224388c78fSHong Zhang     /*
26233c79b8e7SHong Zhang     if (rank==0) {
26243c79b8e7SHong Zhang       printf("[%d] matsub:\n",rank);
26253c79b8e7SHong Zhang       ierr = MatView(matseq[0],PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr);
26263c79b8e7SHong Zhang     }
26273c79b8e7SHong Zhang     ierr = MPI_Barrier(comm);CHKERRQ(ierr);
26284388c78fSHong Zhang      */
26293c79b8e7SHong Zhang 
26303c79b8e7SHong Zhang     /* Create matredundant by concatenating matseq[0] from processors in this subcomm */
26314388c78fSHong Zhang     /*
26323c79b8e7SHong Zhang     if (reuse == MAT_REUSE_MATRIX) {
26333c79b8e7SHong Zhang       if (!rank) printf("matredundant:\n");
26343c79b8e7SHong Zhang       ierr = MatView(*matredundant,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
26353c79b8e7SHong Zhang     }
26364388c78fSHong Zhang      */
26373c79b8e7SHong Zhang     ierr = MatCreateMPIAIJConcatenateSeqAIJ(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);CHKERRQ(ierr);
26384388c78fSHong Zhang     /*
26393c79b8e7SHong Zhang     if (nsubcomm == 1) {
26403c79b8e7SHong Zhang       if (!rank) printf( "matredundant\n");
26413c79b8e7SHong Zhang       ierr = MatView(*matredundant,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
26424388c78fSHong Zhang      } */
26433c79b8e7SHong Zhang 
26443c79b8e7SHong Zhang     if (reuse == MAT_INITIAL_MATRIX) {
26453c79b8e7SHong Zhang       /* create a supporting struct and attach it to C for reuse */
26463c79b8e7SHong Zhang       ierr = PetscNewLog(*matredundant,Mat_Redundant,&redund);CHKERRQ(ierr);
26473c79b8e7SHong Zhang       if (subsize == 1) {
26483c79b8e7SHong Zhang         Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
26493c79b8e7SHong Zhang         c->redundant = redund;
26503c79b8e7SHong Zhang       } else {
26513c79b8e7SHong Zhang         Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
26523c79b8e7SHong Zhang         c->redundant = redund;
26533c79b8e7SHong Zhang       }
26543c79b8e7SHong Zhang 
26553c79b8e7SHong Zhang       redund->isrow     = isrow;
26563c79b8e7SHong Zhang       redund->iscol     = iscol;
26573c79b8e7SHong Zhang       redund->matseq    = matseq;
26583c79b8e7SHong Zhang       redund->psubcomm  = NULL;
26593c79b8e7SHong Zhang 
26603c79b8e7SHong Zhang       redund->Destroy               = (*matredundant)->ops->destroy;
26613c79b8e7SHong Zhang       (*matredundant)->ops->destroy = MatDestroy_MatRedundant;
26623c79b8e7SHong Zhang     }
26633c79b8e7SHong Zhang     PetscFunctionReturn(0);
26643c79b8e7SHong Zhang   }
26653c79b8e7SHong Zhang   /* ----------------------------------------------------*/
26663c79b8e7SHong Zhang 
2667b4617e5dSHong Zhang   if (reuse == MAT_REUSE_MATRIX) {
2668b4617e5dSHong Zhang     if (M != mat->rmap->N || N != mat->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. Wrong global size");
26695cc03489SHong Zhang     if (subsize == 1) {
26705cc03489SHong Zhang       Mat_SeqAIJ *c = (Mat_SeqAIJ*)C->data;
26715cc03489SHong Zhang       redund = c->redundant;
26725cc03489SHong Zhang     } else {
26735cc03489SHong Zhang       Mat_MPIAIJ *c = (Mat_MPIAIJ*)C->data;
26745cc03489SHong Zhang       redund = c->redundant;
26755cc03489SHong Zhang     }
2676b4617e5dSHong Zhang     if (nzlocal != redund->nzlocal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. Wrong nzlocal");
2677b4617e5dSHong Zhang 
2678b4617e5dSHong Zhang     nsends    = redund->nsends;
2679b4617e5dSHong Zhang     nrecvs    = redund->nrecvs;
2680b4617e5dSHong Zhang     send_rank = redund->send_rank;
2681b4617e5dSHong Zhang     recv_rank = redund->recv_rank;
2682b4617e5dSHong Zhang     sbuf_nz   = redund->sbuf_nz;
2683b4617e5dSHong Zhang     rbuf_nz   = redund->rbuf_nz;
2684b4617e5dSHong Zhang     sbuf_j    = redund->sbuf_j;
2685b4617e5dSHong Zhang     sbuf_a    = redund->sbuf_a;
2686b4617e5dSHong Zhang     rbuf_j    = redund->rbuf_j;
2687b4617e5dSHong Zhang     rbuf_a    = redund->rbuf_a;
2688b4617e5dSHong Zhang   }
2689b4617e5dSHong Zhang 
2690b4617e5dSHong Zhang   if (reuse == MAT_INITIAL_MATRIX) {
2691b4617e5dSHong Zhang     PetscInt    nleftover,np_subcomm;
2692b4617e5dSHong Zhang 
2693b4617e5dSHong Zhang     /* get the destination processors' id send_rank, nsends and nrecvs */
2694b4617e5dSHong Zhang     ierr = PetscMalloc2(size,PetscMPIInt,&send_rank,size,PetscMPIInt,&recv_rank);CHKERRQ(ierr);
2695b4617e5dSHong Zhang 
2696b4617e5dSHong Zhang     np_subcomm = size/nsubcomm;
2697b4617e5dSHong Zhang     nleftover  = size - nsubcomm*np_subcomm;
2698b4617e5dSHong Zhang 
2699b4617e5dSHong Zhang     nsends = 0; nrecvs = 0;
2700e37c6257SHong Zhang     if (psubcomm->type == PETSC_SUBCOMM_INTERLACED) {
2701e37c6257SHong Zhang       /* -------------------------------------------*/
2702b4617e5dSHong Zhang       for (i=0; i<size; i++) {
2703b4617e5dSHong Zhang         if (subrank == i/nsubcomm && i != rank) { /* my_subrank == other's subrank */
2704b4617e5dSHong Zhang           send_rank[nsends]   = i; nsends++;
2705b4617e5dSHong Zhang           recv_rank[nrecvs++] = i;
2706e37c6257SHong Zhang           /* printf("[%d] send to and recv from [%d]\n",rank,i); */
2707b4617e5dSHong Zhang         }
2708b4617e5dSHong Zhang       }
2709b4617e5dSHong Zhang       if (rank >= size - nleftover) { /* this proc is a leftover processor */
2710b4617e5dSHong Zhang         i = size-nleftover-1;
2711b4617e5dSHong Zhang         j = 0;
2712b4617e5dSHong Zhang         while (j < nsubcomm - nleftover) {
2713b4617e5dSHong Zhang           send_rank[nsends++] = i;
2714b4617e5dSHong Zhang           i--; j++;
2715e37c6257SHong Zhang           /* printf("[%d] send to [%d]\n",rank,i); */
2716b4617e5dSHong Zhang         }
2717b4617e5dSHong Zhang       }
2718b4617e5dSHong Zhang 
2719b4617e5dSHong Zhang       if (nleftover && subsize == size/nsubcomm && subrank==subsize-1) { /* this proc recvs from leftover processors */
2720b4617e5dSHong Zhang         for (i=0; i<nleftover; i++) {
2721b4617e5dSHong Zhang           recv_rank[nrecvs++] = size-nleftover+i;
2722e37c6257SHong Zhang           /* printf("[%d] recv from [%d]\n",rank,i); */
2723b4617e5dSHong Zhang         }
2724b4617e5dSHong Zhang       }
2725e37c6257SHong Zhang     } else if (psubcomm->type == PETSC_SUBCOMM_CONTIGUOUS) {
2726e37c6257SHong Zhang       /* --------------------------------------------------*/
2727e37c6257SHong Zhang       PetscInt color,subcommstart;
2728e37c6257SHong Zhang       subcommstart=0;
2729e37c6257SHong Zhang       for (color=0; color<nsubcomm; color++) {
2730e37c6257SHong Zhang         if (psubcomm->color != color) {
2731e37c6257SHong Zhang           for (i=0; i<psubcomm->subsize[color]; i++) {
2732e37c6257SHong Zhang             if (subrank == i) { /* my_subrank == other's subrank */
2733e37c6257SHong Zhang               send_rank[nsends++] = subcommstart+i;
2734e37c6257SHong Zhang               recv_rank[nrecvs++] = subcommstart+i;
2735e37c6257SHong Zhang               /* printf("[%d] send to and recv from [%d]\n",rank,subcommstart+i); */
2736e37c6257SHong Zhang             }
2737e37c6257SHong Zhang           }
2738e37c6257SHong Zhang         }
2739e37c6257SHong Zhang         subcommstart += psubcomm->subsize[color];
2740e37c6257SHong Zhang       }
2741e37c6257SHong Zhang       if (nleftover && subrank == size/nsubcomm) { /* this proc is a leftover proc, send to subcomm that does not have leftover proc */
2742e37c6257SHong Zhang         subcommstart=0;
2743e37c6257SHong Zhang         for (color=0; color<nsubcomm; color++) {
2744e37c6257SHong Zhang           subcommstart += psubcomm->subsize[color];
2745e37c6257SHong Zhang           if (psubcomm->color == color) continue;
2746e37c6257SHong Zhang           if (psubcomm->subsize[color] == size/nsubcomm) { /* subcomm does not have leftover proc */
2747e37c6257SHong Zhang             send_rank[nsends++] = subcommstart -1; /* send to the last proc of subcomm[color] */
2748e37c6257SHong Zhang             /* printf("[%d] leftover send to [%d] \n",rank,subcommstart -1); */
2749e37c6257SHong Zhang           }
2750e37c6257SHong Zhang         }
2751e37c6257SHong Zhang       }
2752e37c6257SHong Zhang 
2753e37c6257SHong Zhang       if (nleftover && subsize == size/nsubcomm && subrank==subsize-1) { /* this proc recvs from leftover processors */
2754e37c6257SHong Zhang         subcommstart=0;
2755e37c6257SHong Zhang         for (color=0; color<nsubcomm; color++) {
2756e37c6257SHong Zhang           subcommstart += psubcomm->subsize[color];
2757e37c6257SHong Zhang           if (psubcomm->subsize[color] > size/nsubcomm) { /* subcomm has leftover proc */
2758e37c6257SHong Zhang             recv_rank[nrecvs++] = subcommstart -1; /* recv from the last proc of subcomm[color] */
2759e37c6257SHong Zhang             /* printf("[%d] recv from [%d]\n",rank,subcommstart -1); */
2760e37c6257SHong Zhang           }
2761e37c6257SHong Zhang         }
2762e37c6257SHong Zhang       }
2763b3a4ddeeSHong Zhang     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for PetscSubcomm type %D",psubcomm->type);
2764b4617e5dSHong Zhang 
2765b4617e5dSHong Zhang     /* allocate sbuf_j, sbuf_a */
2766b4617e5dSHong Zhang     i    = nzlocal + rowrange[rank+1] - rowrange[rank] + 2;
2767b4617e5dSHong Zhang     ierr = PetscMalloc(i*sizeof(PetscInt),&sbuf_j);CHKERRQ(ierr);
2768b4617e5dSHong Zhang     ierr = PetscMalloc((nzlocal+1)*sizeof(PetscScalar),&sbuf_a);CHKERRQ(ierr);
2769e37c6257SHong Zhang     /*
2770e37c6257SHong Zhang     ierr = PetscSynchronizedPrintf(comm,"[%d] nsends %d, nrecvs %d\n",rank,nsends,nrecvs);CHKERRQ(ierr);
2771e37c6257SHong Zhang     ierr = PetscSynchronizedFlush(comm);CHKERRQ(ierr);
2772e37c6257SHong Zhang      */
2773b4617e5dSHong Zhang   } /* endof if (reuse == MAT_INITIAL_MATRIX) */
2774b4617e5dSHong Zhang 
2775b4617e5dSHong Zhang   /* copy mat's local entries into the buffers */
2776b4617e5dSHong Zhang   if (reuse == MAT_INITIAL_MATRIX) {
2777b4617e5dSHong Zhang     rownz_max = 0;
2778b4617e5dSHong Zhang     rptr      = sbuf_j;
2779b4617e5dSHong Zhang     cols      = sbuf_j + rend-rstart + 1;
2780b4617e5dSHong Zhang     vals      = sbuf_a;
2781b4617e5dSHong Zhang     rptr[0]   = 0;
2782b4617e5dSHong Zhang     for (i=0; i<rend-rstart; i++) {
2783b4617e5dSHong Zhang       row    = i + rstart;
2784b4617e5dSHong Zhang       nzA    = a->i[i+1] - a->i[i]; nzB = b->i[i+1] - b->i[i];
2785b4617e5dSHong Zhang       ncols  = nzA + nzB;
2786b4617e5dSHong Zhang       cworkA = a->j + a->i[i]; cworkB = b->j + b->i[i];
2787b4617e5dSHong Zhang       aworkA = a->a + a->i[i]; aworkB = b->a + b->i[i];
2788b4617e5dSHong Zhang       /* load the column indices for this row into cols */
2789b4617e5dSHong Zhang       lwrite = 0;
2790b4617e5dSHong Zhang       for (l=0; l<nzB; l++) {
2791b4617e5dSHong Zhang         if ((ctmp = bmap[cworkB[l]]) < cstart) {
2792b4617e5dSHong Zhang           vals[lwrite]   = aworkB[l];
2793b4617e5dSHong Zhang           cols[lwrite++] = ctmp;
2794b4617e5dSHong Zhang         }
2795b4617e5dSHong Zhang       }
2796b4617e5dSHong Zhang       for (l=0; l<nzA; l++) {
2797b4617e5dSHong Zhang         vals[lwrite]   = aworkA[l];
2798b4617e5dSHong Zhang         cols[lwrite++] = cstart + cworkA[l];
2799b4617e5dSHong Zhang       }
2800b4617e5dSHong Zhang       for (l=0; l<nzB; l++) {
2801b4617e5dSHong Zhang         if ((ctmp = bmap[cworkB[l]]) >= cend) {
2802b4617e5dSHong Zhang           vals[lwrite]   = aworkB[l];
2803b4617e5dSHong Zhang           cols[lwrite++] = ctmp;
2804b4617e5dSHong Zhang         }
2805b4617e5dSHong Zhang       }
2806b4617e5dSHong Zhang       vals     += ncols;
2807b4617e5dSHong Zhang       cols     += ncols;
2808b4617e5dSHong Zhang       rptr[i+1] = rptr[i] + ncols;
2809b4617e5dSHong Zhang       if (rownz_max < ncols) rownz_max = ncols;
2810b4617e5dSHong Zhang     }
2811b4617e5dSHong Zhang     if (rptr[rend-rstart] != a->nz + b->nz) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_PLIB, "rptr[%d] %d != %d + %d",rend-rstart,rptr[rend-rstart+1],a->nz,b->nz);
2812b4617e5dSHong Zhang   } else { /* only copy matrix values into sbuf_a */
2813b4617e5dSHong Zhang     rptr    = sbuf_j;
2814b4617e5dSHong Zhang     vals    = sbuf_a;
2815b4617e5dSHong Zhang     rptr[0] = 0;
2816b4617e5dSHong Zhang     for (i=0; i<rend-rstart; i++) {
2817b4617e5dSHong Zhang       row    = i + rstart;
2818b4617e5dSHong Zhang       nzA    = a->i[i+1] - a->i[i]; nzB = b->i[i+1] - b->i[i];
2819b4617e5dSHong Zhang       ncols  = nzA + nzB;
2820b4617e5dSHong Zhang       cworkB = b->j + b->i[i];
2821b4617e5dSHong Zhang       aworkA = a->a + a->i[i];
2822b4617e5dSHong Zhang       aworkB = b->a + b->i[i];
2823b4617e5dSHong Zhang       lwrite = 0;
2824b4617e5dSHong Zhang       for (l=0; l<nzB; l++) {
2825b4617e5dSHong Zhang         if ((ctmp = bmap[cworkB[l]]) < cstart) vals[lwrite++] = aworkB[l];
2826b4617e5dSHong Zhang       }
2827b4617e5dSHong Zhang       for (l=0; l<nzA; l++) vals[lwrite++] = aworkA[l];
2828b4617e5dSHong Zhang       for (l=0; l<nzB; l++) {
2829b4617e5dSHong Zhang         if ((ctmp = bmap[cworkB[l]]) >= cend) vals[lwrite++] = aworkB[l];
2830b4617e5dSHong Zhang       }
2831b4617e5dSHong Zhang       vals     += ncols;
2832b4617e5dSHong Zhang       rptr[i+1] = rptr[i] + ncols;
2833b4617e5dSHong Zhang     }
2834b4617e5dSHong Zhang   } /* endof if (reuse == MAT_INITIAL_MATRIX) */
2835b4617e5dSHong Zhang 
2836b4617e5dSHong Zhang   /* send nzlocal to others, and recv other's nzlocal */
2837b4617e5dSHong Zhang   /*--------------------------------------------------*/
2838b4617e5dSHong Zhang   if (reuse == MAT_INITIAL_MATRIX) {
2839b4617e5dSHong Zhang     ierr = PetscMalloc2(3*(nsends + nrecvs)+1,MPI_Request,&s_waits3,nsends+1,MPI_Status,&send_status);CHKERRQ(ierr);
2840b4617e5dSHong Zhang 
2841b4617e5dSHong Zhang     s_waits2 = s_waits3 + nsends;
2842b4617e5dSHong Zhang     s_waits1 = s_waits2 + nsends;
2843b4617e5dSHong Zhang     r_waits1 = s_waits1 + nsends;
2844b4617e5dSHong Zhang     r_waits2 = r_waits1 + nrecvs;
2845b4617e5dSHong Zhang     r_waits3 = r_waits2 + nrecvs;
2846b4617e5dSHong Zhang   } else {
2847b4617e5dSHong Zhang     ierr = PetscMalloc2(nsends + nrecvs +1,MPI_Request,&s_waits3,nsends+1,MPI_Status,&send_status);CHKERRQ(ierr);
2848b4617e5dSHong Zhang 
2849b4617e5dSHong Zhang     r_waits3 = s_waits3 + nsends;
2850b4617e5dSHong Zhang   }
2851b4617e5dSHong Zhang 
2852b4617e5dSHong Zhang   ierr = PetscObjectGetNewTag((PetscObject)mat,&tag3);CHKERRQ(ierr);
2853b4617e5dSHong Zhang   if (reuse == MAT_INITIAL_MATRIX) {
2854b4617e5dSHong Zhang     /* get new tags to keep the communication clean */
2855b4617e5dSHong Zhang     ierr = PetscObjectGetNewTag((PetscObject)mat,&tag1);CHKERRQ(ierr);
2856b4617e5dSHong Zhang     ierr = PetscObjectGetNewTag((PetscObject)mat,&tag2);CHKERRQ(ierr);
2857b4617e5dSHong Zhang     ierr = PetscMalloc4(nsends,PetscInt,&sbuf_nz,nrecvs,PetscInt,&rbuf_nz,nrecvs,PetscInt*,&rbuf_j,nrecvs,PetscScalar*,&rbuf_a);CHKERRQ(ierr);
2858b4617e5dSHong Zhang 
2859b4617e5dSHong Zhang     /* post receives of other's nzlocal */
2860b4617e5dSHong Zhang     for (i=0; i<nrecvs; i++) {
2861b4617e5dSHong Zhang       ierr = MPI_Irecv(rbuf_nz+i,1,MPIU_INT,MPI_ANY_SOURCE,tag1,comm,r_waits1+i);CHKERRQ(ierr);
2862b4617e5dSHong Zhang     }
2863b4617e5dSHong Zhang     /* send nzlocal to others */
2864b4617e5dSHong Zhang     for (i=0; i<nsends; i++) {
2865b4617e5dSHong Zhang       sbuf_nz[i] = nzlocal;
2866b4617e5dSHong Zhang       ierr       = MPI_Isend(sbuf_nz+i,1,MPIU_INT,send_rank[i],tag1,comm,s_waits1+i);CHKERRQ(ierr);
2867b4617e5dSHong Zhang     }
2868b4617e5dSHong Zhang     /* wait on receives of nzlocal; allocate space for rbuf_j, rbuf_a */
2869b4617e5dSHong Zhang     count = nrecvs;
2870b4617e5dSHong Zhang     while (count) {
2871b4617e5dSHong Zhang       ierr = MPI_Waitany(nrecvs,r_waits1,&imdex,&recv_status);CHKERRQ(ierr);
2872b4617e5dSHong Zhang 
2873b4617e5dSHong Zhang       recv_rank[imdex] = recv_status.MPI_SOURCE;
2874b4617e5dSHong Zhang       /* allocate rbuf_a and rbuf_j; then post receives of rbuf_j */
2875b4617e5dSHong Zhang       ierr = PetscMalloc((rbuf_nz[imdex]+1)*sizeof(PetscScalar),&rbuf_a[imdex]);CHKERRQ(ierr);
2876b4617e5dSHong Zhang 
2877b4617e5dSHong Zhang       i = rowrange[recv_status.MPI_SOURCE+1] - rowrange[recv_status.MPI_SOURCE]; /* number of expected mat->i */
2878b4617e5dSHong Zhang 
2879b4617e5dSHong Zhang       rbuf_nz[imdex] += i + 2;
2880b4617e5dSHong Zhang 
2881b4617e5dSHong Zhang       ierr = PetscMalloc(rbuf_nz[imdex]*sizeof(PetscInt),&rbuf_j[imdex]);CHKERRQ(ierr);
2882b4617e5dSHong Zhang       ierr = MPI_Irecv(rbuf_j[imdex],rbuf_nz[imdex],MPIU_INT,recv_status.MPI_SOURCE,tag2,comm,r_waits2+imdex);CHKERRQ(ierr);
2883b4617e5dSHong Zhang       count--;
2884b4617e5dSHong Zhang     }
2885b4617e5dSHong Zhang     /* wait on sends of nzlocal */
2886b4617e5dSHong Zhang     if (nsends) {ierr = MPI_Waitall(nsends,s_waits1,send_status);CHKERRQ(ierr);}
2887b4617e5dSHong Zhang     /* send mat->i,j to others, and recv from other's */
2888b4617e5dSHong Zhang     /*------------------------------------------------*/
2889b4617e5dSHong Zhang     for (i=0; i<nsends; i++) {
2890b4617e5dSHong Zhang       j    = nzlocal + rowrange[rank+1] - rowrange[rank] + 1;
2891b4617e5dSHong Zhang       ierr = MPI_Isend(sbuf_j,j,MPIU_INT,send_rank[i],tag2,comm,s_waits2+i);CHKERRQ(ierr);
2892b4617e5dSHong Zhang     }
2893b4617e5dSHong Zhang     /* wait on receives of mat->i,j */
2894b4617e5dSHong Zhang     /*------------------------------*/
2895b4617e5dSHong Zhang     count = nrecvs;
2896b4617e5dSHong Zhang     while (count) {
2897b4617e5dSHong Zhang       ierr = MPI_Waitany(nrecvs,r_waits2,&imdex,&recv_status);CHKERRQ(ierr);
2898b4617e5dSHong Zhang       if (recv_rank[imdex] != recv_status.MPI_SOURCE) SETERRQ2(PETSC_COMM_SELF,1, "recv_rank %d != MPI_SOURCE %d",recv_rank[imdex],recv_status.MPI_SOURCE);
2899b4617e5dSHong Zhang       count--;
2900b4617e5dSHong Zhang     }
2901b4617e5dSHong Zhang     /* wait on sends of mat->i,j */
2902b4617e5dSHong Zhang     /*---------------------------*/
2903b4617e5dSHong Zhang     if (nsends) {
2904b4617e5dSHong Zhang       ierr = MPI_Waitall(nsends,s_waits2,send_status);CHKERRQ(ierr);
2905b4617e5dSHong Zhang     }
2906b4617e5dSHong Zhang   } /* endof if (reuse == MAT_INITIAL_MATRIX) */
2907b4617e5dSHong Zhang 
2908b4617e5dSHong Zhang   /* post receives, send and receive mat->a */
2909b4617e5dSHong Zhang   /*----------------------------------------*/
2910b4617e5dSHong Zhang   for (imdex=0; imdex<nrecvs; imdex++) {
2911b4617e5dSHong Zhang     ierr = MPI_Irecv(rbuf_a[imdex],rbuf_nz[imdex],MPIU_SCALAR,recv_rank[imdex],tag3,comm,r_waits3+imdex);CHKERRQ(ierr);
2912b4617e5dSHong Zhang   }
2913b4617e5dSHong Zhang   for (i=0; i<nsends; i++) {
2914b4617e5dSHong Zhang     ierr = MPI_Isend(sbuf_a,nzlocal,MPIU_SCALAR,send_rank[i],tag3,comm,s_waits3+i);CHKERRQ(ierr);
2915b4617e5dSHong Zhang   }
2916b4617e5dSHong Zhang   count = nrecvs;
2917b4617e5dSHong Zhang   while (count) {
2918b4617e5dSHong Zhang     ierr = MPI_Waitany(nrecvs,r_waits3,&imdex,&recv_status);CHKERRQ(ierr);
2919b4617e5dSHong Zhang     if (recv_rank[imdex] != recv_status.MPI_SOURCE) SETERRQ2(PETSC_COMM_SELF,1, "recv_rank %d != MPI_SOURCE %d",recv_rank[imdex],recv_status.MPI_SOURCE);
2920b4617e5dSHong Zhang     count--;
2921b4617e5dSHong Zhang   }
2922b4617e5dSHong Zhang   if (nsends) {
2923b4617e5dSHong Zhang     ierr = MPI_Waitall(nsends,s_waits3,send_status);CHKERRQ(ierr);
2924b4617e5dSHong Zhang   }
2925b4617e5dSHong Zhang 
2926b4617e5dSHong Zhang   ierr = PetscFree2(s_waits3,send_status);CHKERRQ(ierr);
2927b4617e5dSHong Zhang 
2928b4617e5dSHong Zhang   /* create redundant matrix */
2929b4617e5dSHong Zhang   /*-------------------------*/
2930b4617e5dSHong Zhang   if (reuse == MAT_INITIAL_MATRIX) {
293119171117SHong Zhang     const PetscInt *range;
293219171117SHong Zhang     PetscInt       rstart_sub,rend_sub,mloc_sub;
293319171117SHong Zhang 
2934b4617e5dSHong Zhang     /* compute rownz_max for preallocation */
2935b4617e5dSHong Zhang     for (imdex=0; imdex<nrecvs; imdex++) {
2936b4617e5dSHong Zhang       j    = rowrange[recv_rank[imdex]+1] - rowrange[recv_rank[imdex]];
2937b4617e5dSHong Zhang       rptr = rbuf_j[imdex];
2938b4617e5dSHong Zhang       for (i=0; i<j; i++) {
2939b4617e5dSHong Zhang         ncols = rptr[i+1] - rptr[i];
2940b4617e5dSHong Zhang         if (rownz_max < ncols) rownz_max = ncols;
2941b4617e5dSHong Zhang       }
2942b4617e5dSHong Zhang     }
2943b4617e5dSHong Zhang 
2944b4617e5dSHong Zhang     ierr = MatCreate(subcomm,&C);CHKERRQ(ierr);
294519171117SHong Zhang 
294619171117SHong Zhang     /* get local size of redundant matrix
294719171117SHong Zhang        - mloc_sub is chosen for PETSC_SUBCOMM_INTERLACED, works for other types, but may not efficient! */
294819171117SHong Zhang     ierr = MatGetOwnershipRanges(mat,&range);CHKERRQ(ierr);
294919171117SHong Zhang     rstart_sub = range[nsubcomm*subrank];
295019171117SHong Zhang     if (subrank+1 < subsize) { /* not the last proc in subcomm */
295119171117SHong Zhang       rend_sub = range[nsubcomm*(subrank+1)];
295219171117SHong Zhang     } else {
295319171117SHong Zhang       rend_sub = mat->rmap->N;
295419171117SHong Zhang     }
295519171117SHong Zhang     mloc_sub = rend_sub - rstart_sub;
295619171117SHong Zhang 
295734d19554SHong Zhang     if (M == N) {
2958b4617e5dSHong Zhang       ierr = MatSetSizes(C,mloc_sub,mloc_sub,PETSC_DECIDE,PETSC_DECIDE);CHKERRQ(ierr);
295934d19554SHong Zhang     } else { /* non-square matrix */
296034d19554SHong Zhang       ierr = MatSetSizes(C,mloc_sub,PETSC_DECIDE,PETSC_DECIDE,mat->cmap->N);CHKERRQ(ierr);
296134d19554SHong Zhang     }
2962b4617e5dSHong Zhang     ierr = MatSetBlockSizes(C,mat->rmap->bs,mat->cmap->bs);CHKERRQ(ierr);
2963b4617e5dSHong Zhang     ierr = MatSetFromOptions(C);CHKERRQ(ierr);
2964b4617e5dSHong Zhang     ierr = MatSeqAIJSetPreallocation(C,rownz_max,NULL);CHKERRQ(ierr);
2965b4617e5dSHong Zhang     ierr = MatMPIAIJSetPreallocation(C,rownz_max,NULL,rownz_max,NULL);CHKERRQ(ierr);
2966b4617e5dSHong Zhang   } else {
2967b4617e5dSHong Zhang     C = *matredundant;
2968b4617e5dSHong Zhang   }
2969b4617e5dSHong Zhang 
2970b4617e5dSHong Zhang   /* insert local matrix entries */
2971b4617e5dSHong Zhang   rptr = sbuf_j;
2972b4617e5dSHong Zhang   cols = sbuf_j + rend-rstart + 1;
2973b4617e5dSHong Zhang   vals = sbuf_a;
2974b4617e5dSHong Zhang   for (i=0; i<rend-rstart; i++) {
2975b4617e5dSHong Zhang     row   = i + rstart;
2976b4617e5dSHong Zhang     ncols = rptr[i+1] - rptr[i];
2977b4617e5dSHong Zhang     ierr  = MatSetValues(C,1,&row,ncols,cols,vals,INSERT_VALUES);CHKERRQ(ierr);
2978b4617e5dSHong Zhang     vals += ncols;
2979b4617e5dSHong Zhang     cols += ncols;
2980b4617e5dSHong Zhang   }
2981b4617e5dSHong Zhang   /* insert received matrix entries */
2982b4617e5dSHong Zhang   for (imdex=0; imdex<nrecvs; imdex++) {
2983b4617e5dSHong Zhang     rstart = rowrange[recv_rank[imdex]];
2984b4617e5dSHong Zhang     rend   = rowrange[recv_rank[imdex]+1];
2985e37c6257SHong Zhang     /* printf("[%d] insert rows %d - %d\n",rank,rstart,rend-1); */
2986b4617e5dSHong Zhang     rptr   = rbuf_j[imdex];
2987b4617e5dSHong Zhang     cols   = rbuf_j[imdex] + rend-rstart + 1;
2988b4617e5dSHong Zhang     vals   = rbuf_a[imdex];
2989b4617e5dSHong Zhang     for (i=0; i<rend-rstart; i++) {
2990b4617e5dSHong Zhang       row   = i + rstart;
2991b4617e5dSHong Zhang       ncols = rptr[i+1] - rptr[i];
2992b4617e5dSHong Zhang       ierr  = MatSetValues(C,1,&row,ncols,cols,vals,INSERT_VALUES);CHKERRQ(ierr);
2993b4617e5dSHong Zhang       vals += ncols;
2994b4617e5dSHong Zhang       cols += ncols;
2995b4617e5dSHong Zhang     }
2996b4617e5dSHong Zhang   }
2997b4617e5dSHong Zhang   ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2998b4617e5dSHong Zhang   ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
2999b4617e5dSHong Zhang 
3000b4617e5dSHong Zhang   if (reuse == MAT_INITIAL_MATRIX) {
3001b4617e5dSHong Zhang     *matredundant = C;
30025cc03489SHong Zhang 
3003b4617e5dSHong Zhang     /* create a supporting struct and attach it to C for reuse */
3004b4617e5dSHong Zhang     ierr = PetscNewLog(C,Mat_Redundant,&redund);CHKERRQ(ierr);
30055cc03489SHong Zhang     if (subsize == 1) {
30065cc03489SHong Zhang       Mat_SeqAIJ *c = (Mat_SeqAIJ*)C->data;
30075cc03489SHong Zhang       c->redundant = redund;
30085cc03489SHong Zhang     } else {
30095cc03489SHong Zhang       Mat_MPIAIJ *c = (Mat_MPIAIJ*)C->data;
30105cc03489SHong Zhang       c->redundant = redund;
30115cc03489SHong Zhang     }
3012b4617e5dSHong Zhang 
3013b4617e5dSHong Zhang     redund->nzlocal   = nzlocal;
3014b4617e5dSHong Zhang     redund->nsends    = nsends;
3015b4617e5dSHong Zhang     redund->nrecvs    = nrecvs;
3016b4617e5dSHong Zhang     redund->send_rank = send_rank;
3017b4617e5dSHong Zhang     redund->recv_rank = recv_rank;
3018b4617e5dSHong Zhang     redund->sbuf_nz   = sbuf_nz;
3019b4617e5dSHong Zhang     redund->rbuf_nz   = rbuf_nz;
3020b4617e5dSHong Zhang     redund->sbuf_j    = sbuf_j;
3021b4617e5dSHong Zhang     redund->sbuf_a    = sbuf_a;
3022b4617e5dSHong Zhang     redund->rbuf_j    = rbuf_j;
3023b4617e5dSHong Zhang     redund->rbuf_a    = rbuf_a;
30240b291e46SHong Zhang     redund->psubcomm  = NULL;
3025b4617e5dSHong Zhang 
3026b4617e5dSHong Zhang     redund->Destroy = C->ops->destroy;
3027b4617e5dSHong Zhang     C->ops->destroy = MatDestroy_MatRedundant;
3028b4617e5dSHong Zhang   }
3029b4617e5dSHong Zhang   PetscFunctionReturn(0);
3030b4617e5dSHong Zhang }
3031b4617e5dSHong Zhang 
3032b4617e5dSHong Zhang #undef __FUNCT__
303369db28dcSHong Zhang #define __FUNCT__ "MatGetRedundantMatrix_MPIAIJ"
3034*c79c5527SHong Zhang PetscErrorCode MatGetRedundantMatrix_MPIAIJ(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,PetscSubcomm psubcomm,MatReuse reuse,Mat *matredundant)
303569db28dcSHong Zhang {
3036f38d543fSHong Zhang   PetscErrorCode ierr;
3037*c79c5527SHong Zhang   MPI_Comm       comm;
3038*c79c5527SHong Zhang   PetscMPIInt    size,subsize;
3039*c79c5527SHong Zhang   PetscInt       mloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N;
3040*c79c5527SHong Zhang   Mat_Redundant  *redund =NULL;
304169db28dcSHong Zhang 
304269db28dcSHong Zhang   PetscFunctionBegin;
3043*c79c5527SHong Zhang   if (subcomm == MPI_COMM_NULL) { /* use psubcomm */
3044*c79c5527SHong Zhang     if (reuse ==  MAT_INITIAL_MATRIX) {
3045*c79c5527SHong Zhang       if (psubcomm == NULL) { /* create psubcomm */
3046ce94432eSBarry Smith         ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
304769db28dcSHong Zhang         ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
3048d3b23db5SHong Zhang         ierr = PetscSubcommCreate(comm,&psubcomm);CHKERRQ(ierr);
3049d3b23db5SHong Zhang         ierr = PetscSubcommSetNumber(psubcomm,nsubcomm);CHKERRQ(ierr);
3050*c79c5527SHong Zhang         ierr = PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);CHKERRQ(ierr);
305119171117SHong Zhang         ierr = PetscSubcommSetFromOptions(psubcomm);CHKERRQ(ierr);
3052*c79c5527SHong Zhang       }
3053*c79c5527SHong Zhang       subcomm = psubcomm->comm;
3054*c79c5527SHong Zhang       ierr = MPI_Comm_size(subcomm,&subsize);CHKERRQ(ierr);
3055*c79c5527SHong Zhang     } else { /* retrieve psubcomm */
3056*c79c5527SHong Zhang       ierr = PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);CHKERRQ(ierr);
3057*c79c5527SHong Zhang       ierr = MPI_Comm_size(subcomm,&subsize);CHKERRQ(ierr);
3058*c79c5527SHong Zhang       if (subsize == 1) {
3059*c79c5527SHong Zhang         Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
3060*c79c5527SHong Zhang         psubcomm = c->redundant->psubcomm;
3061*c79c5527SHong Zhang       } else {
3062*c79c5527SHong Zhang         Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
3063*c79c5527SHong Zhang         psubcomm = c->redundant->psubcomm;
3064*c79c5527SHong Zhang       }
3065*c79c5527SHong Zhang     }
3066*c79c5527SHong Zhang   }
3067e37c6257SHong Zhang 
3068*c79c5527SHong Zhang   if (psubcomm->type == PETSC_SUBCOMM_INTERLACED) {
3069e37c6257SHong Zhang      ierr = MatGetRedundantMatrix_MPIAIJ_psubcomm(mat,nsubcomm,psubcomm,reuse,matredundant);CHKERRQ(ierr);
3070*c79c5527SHong Zhang   } else {
3071*c79c5527SHong Zhang     /* via MatGetSubMatrices() */
3072*c79c5527SHong Zhang     Mat  *matseq;
3073*c79c5527SHong Zhang     IS   isrow,iscol;
30740b291e46SHong Zhang 
3075*c79c5527SHong Zhang     if (reuse == MAT_INITIAL_MATRIX) {
3076*c79c5527SHong Zhang       /* create a local sequential matrix matseq[0] */
3077*c79c5527SHong Zhang       mloc_sub = PETSC_DECIDE;
3078*c79c5527SHong Zhang       ierr = PetscSplitOwnership(subcomm,&mloc_sub,&M);CHKERRQ(ierr);
3079*c79c5527SHong Zhang       ierr = MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);CHKERRQ(ierr);
3080*c79c5527SHong Zhang       rstart = rend - mloc_sub;
3081*c79c5527SHong Zhang       ierr = ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);CHKERRQ(ierr);
3082*c79c5527SHong Zhang       ierr = ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);CHKERRQ(ierr);
3083*c79c5527SHong Zhang     } else { /* reuse == MAT_REUSE_MATRIX */
3084*c79c5527SHong Zhang       if (subsize == 1) {
3085*c79c5527SHong Zhang         Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
3086*c79c5527SHong Zhang         redund = c->redundant;
3087*c79c5527SHong Zhang       } else {
3088*c79c5527SHong Zhang         Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
3089*c79c5527SHong Zhang         redund = c->redundant;
3090*c79c5527SHong Zhang       }
3091*c79c5527SHong Zhang 
3092*c79c5527SHong Zhang       isrow  = redund->isrow;
3093*c79c5527SHong Zhang       iscol  = redund->iscol;
3094*c79c5527SHong Zhang       matseq = redund->matseq;
3095*c79c5527SHong Zhang     }
3096*c79c5527SHong Zhang 
3097*c79c5527SHong Zhang     ierr = MatGetSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);CHKERRQ(ierr);
3098*c79c5527SHong Zhang     ierr = MatCreateMPIAIJConcatenateSeqAIJ(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);CHKERRQ(ierr);
3099*c79c5527SHong Zhang 
3100*c79c5527SHong Zhang     if (reuse == MAT_INITIAL_MATRIX) {
3101*c79c5527SHong Zhang       /* create a supporting struct and attach it to C for reuse */
3102*c79c5527SHong Zhang       ierr = PetscNewLog(*matredundant,Mat_Redundant,&redund);CHKERRQ(ierr);
3103*c79c5527SHong Zhang       if (subsize == 1) {
3104*c79c5527SHong Zhang         Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
3105*c79c5527SHong Zhang         c->redundant = redund;
3106*c79c5527SHong Zhang       } else {
3107*c79c5527SHong Zhang         Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
3108*c79c5527SHong Zhang         c->redundant = redund;
3109*c79c5527SHong Zhang       }
3110*c79c5527SHong Zhang       redund->isrow    = isrow;
3111*c79c5527SHong Zhang       redund->iscol    = iscol;
3112*c79c5527SHong Zhang       redund->matseq   = matseq;
3113*c79c5527SHong Zhang       redund->psubcomm = NULL;
3114*c79c5527SHong Zhang       redund->Destroy               = (*matredundant)->ops->destroy;
3115*c79c5527SHong Zhang       (*matredundant)->ops->destroy = MatDestroy_MatRedundant;
3116*c79c5527SHong Zhang     }
3117*c79c5527SHong Zhang   }
3118*c79c5527SHong Zhang 
3119*c79c5527SHong Zhang   if (psubcomm) {  /* free psubcomm in MatDestroy_MatRedundant() */
31200b291e46SHong Zhang     ierr = MPI_Comm_size(psubcomm->comm,&subsize);CHKERRQ(ierr);
31210b291e46SHong Zhang     if (subsize == 1) {
3122c5a91927SHong Zhang       Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
31230b291e46SHong Zhang       c->redundant->psubcomm = psubcomm;
31240b291e46SHong Zhang     } else {
3125c5a91927SHong Zhang       Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
31260b291e46SHong Zhang       c->redundant->psubcomm = psubcomm ;
31270b291e46SHong Zhang     }
312869db28dcSHong Zhang   }
312969db28dcSHong Zhang   PetscFunctionReturn(0);
313069db28dcSHong Zhang }
313169db28dcSHong Zhang 
313203bc72f1SMatthew Knepley #undef __FUNCT__
3133c91732d9SHong Zhang #define __FUNCT__ "MatGetRowMaxAbs_MPIAIJ"
3134c91732d9SHong Zhang PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
3135c91732d9SHong Zhang {
3136c91732d9SHong Zhang   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
3137c91732d9SHong Zhang   PetscErrorCode ierr;
3138c91732d9SHong Zhang   PetscInt       i,*idxb = 0;
3139c91732d9SHong Zhang   PetscScalar    *va,*vb;
3140c91732d9SHong Zhang   Vec            vtmp;
3141c91732d9SHong Zhang 
3142c91732d9SHong Zhang   PetscFunctionBegin;
3143c91732d9SHong Zhang   ierr = MatGetRowMaxAbs(a->A,v,idx);CHKERRQ(ierr);
3144c91732d9SHong Zhang   ierr = VecGetArray(v,&va);CHKERRQ(ierr);
3145c91732d9SHong Zhang   if (idx) {
3146192daf7cSBarry Smith     for (i=0; i<A->rmap->n; i++) {
3147d0f46423SBarry Smith       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
3148c91732d9SHong Zhang     }
3149c91732d9SHong Zhang   }
3150c91732d9SHong Zhang 
3151d0f46423SBarry Smith   ierr = VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);CHKERRQ(ierr);
3152c91732d9SHong Zhang   if (idx) {
3153d0f46423SBarry Smith     ierr = PetscMalloc(A->rmap->n*sizeof(PetscInt),&idxb);CHKERRQ(ierr);
3154c91732d9SHong Zhang   }
3155c91732d9SHong Zhang   ierr = MatGetRowMaxAbs(a->B,vtmp,idxb);CHKERRQ(ierr);
3156c91732d9SHong Zhang   ierr = VecGetArray(vtmp,&vb);CHKERRQ(ierr);
3157c91732d9SHong Zhang 
3158d0f46423SBarry Smith   for (i=0; i<A->rmap->n; i++) {
3159c91732d9SHong Zhang     if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
3160c91732d9SHong Zhang       va[i] = vb[i];
3161c91732d9SHong Zhang       if (idx) idx[i] = a->garray[idxb[i]];
3162c91732d9SHong Zhang     }
3163c91732d9SHong Zhang   }
3164c91732d9SHong Zhang 
3165c91732d9SHong Zhang   ierr = VecRestoreArray(v,&va);CHKERRQ(ierr);
3166c91732d9SHong Zhang   ierr = VecRestoreArray(vtmp,&vb);CHKERRQ(ierr);
3167c91732d9SHong Zhang   ierr = PetscFree(idxb);CHKERRQ(ierr);
31686bf464f9SBarry Smith   ierr = VecDestroy(&vtmp);CHKERRQ(ierr);
3169c91732d9SHong Zhang   PetscFunctionReturn(0);
3170c91732d9SHong Zhang }
3171c91732d9SHong Zhang 
3172c91732d9SHong Zhang #undef __FUNCT__
3173c87e5d42SMatthew Knepley #define __FUNCT__ "MatGetRowMinAbs_MPIAIJ"
3174c87e5d42SMatthew Knepley PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
3175c87e5d42SMatthew Knepley {
3176c87e5d42SMatthew Knepley   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
3177c87e5d42SMatthew Knepley   PetscErrorCode ierr;
3178c87e5d42SMatthew Knepley   PetscInt       i,*idxb = 0;
3179c87e5d42SMatthew Knepley   PetscScalar    *va,*vb;
3180c87e5d42SMatthew Knepley   Vec            vtmp;
3181c87e5d42SMatthew Knepley 
3182c87e5d42SMatthew Knepley   PetscFunctionBegin;
3183c87e5d42SMatthew Knepley   ierr = MatGetRowMinAbs(a->A,v,idx);CHKERRQ(ierr);
3184c87e5d42SMatthew Knepley   ierr = VecGetArray(v,&va);CHKERRQ(ierr);
3185c87e5d42SMatthew Knepley   if (idx) {
3186c87e5d42SMatthew Knepley     for (i=0; i<A->cmap->n; i++) {
3187c87e5d42SMatthew Knepley       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
3188c87e5d42SMatthew Knepley     }
3189c87e5d42SMatthew Knepley   }
3190c87e5d42SMatthew Knepley 
3191c87e5d42SMatthew Knepley   ierr = VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);CHKERRQ(ierr);
3192c87e5d42SMatthew Knepley   if (idx) {
3193c87e5d42SMatthew Knepley     ierr = PetscMalloc(A->rmap->n*sizeof(PetscInt),&idxb);CHKERRQ(ierr);
3194c87e5d42SMatthew Knepley   }
3195c87e5d42SMatthew Knepley   ierr = MatGetRowMinAbs(a->B,vtmp,idxb);CHKERRQ(ierr);
3196c87e5d42SMatthew Knepley   ierr = VecGetArray(vtmp,&vb);CHKERRQ(ierr);
3197c87e5d42SMatthew Knepley 
3198c87e5d42SMatthew Knepley   for (i=0; i<A->rmap->n; i++) {
3199c87e5d42SMatthew Knepley     if (PetscAbsScalar(va[i]) > PetscAbsScalar(vb[i])) {
3200c87e5d42SMatthew Knepley       va[i] = vb[i];
3201c87e5d42SMatthew Knepley       if (idx) idx[i] = a->garray[idxb[i]];
3202c87e5d42SMatthew Knepley     }
3203c87e5d42SMatthew Knepley   }
3204c87e5d42SMatthew Knepley 
3205c87e5d42SMatthew Knepley   ierr = VecRestoreArray(v,&va);CHKERRQ(ierr);
3206c87e5d42SMatthew Knepley   ierr = VecRestoreArray(vtmp,&vb);CHKERRQ(ierr);
3207c87e5d42SMatthew Knepley   ierr = PetscFree(idxb);CHKERRQ(ierr);
32086bf464f9SBarry Smith   ierr = VecDestroy(&vtmp);CHKERRQ(ierr);
3209c87e5d42SMatthew Knepley   PetscFunctionReturn(0);
3210c87e5d42SMatthew Knepley }
3211c87e5d42SMatthew Knepley 
3212c87e5d42SMatthew Knepley #undef __FUNCT__
321303bc72f1SMatthew Knepley #define __FUNCT__ "MatGetRowMin_MPIAIJ"
321403bc72f1SMatthew Knepley PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
321503bc72f1SMatthew Knepley {
321603bc72f1SMatthew Knepley   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
3217d0f46423SBarry Smith   PetscInt       n      = A->rmap->n;
3218d0f46423SBarry Smith   PetscInt       cstart = A->cmap->rstart;
321903bc72f1SMatthew Knepley   PetscInt       *cmap  = mat->garray;
322003bc72f1SMatthew Knepley   PetscInt       *diagIdx, *offdiagIdx;
322103bc72f1SMatthew Knepley   Vec            diagV, offdiagV;
322203bc72f1SMatthew Knepley   PetscScalar    *a, *diagA, *offdiagA;
322303bc72f1SMatthew Knepley   PetscInt       r;
322403bc72f1SMatthew Knepley   PetscErrorCode ierr;
322503bc72f1SMatthew Knepley 
322603bc72f1SMatthew Knepley   PetscFunctionBegin;
322703bc72f1SMatthew Knepley   ierr = PetscMalloc2(n,PetscInt,&diagIdx,n,PetscInt,&offdiagIdx);CHKERRQ(ierr);
3228ce94432eSBarry Smith   ierr = VecCreateSeq(PetscObjectComm((PetscObject)A), n, &diagV);CHKERRQ(ierr);
3229ce94432eSBarry Smith   ierr = VecCreateSeq(PetscObjectComm((PetscObject)A), n, &offdiagV);CHKERRQ(ierr);
323003bc72f1SMatthew Knepley   ierr = MatGetRowMin(mat->A, diagV,    diagIdx);CHKERRQ(ierr);
323103bc72f1SMatthew Knepley   ierr = MatGetRowMin(mat->B, offdiagV, offdiagIdx);CHKERRQ(ierr);
323203bc72f1SMatthew Knepley   ierr = VecGetArray(v,        &a);CHKERRQ(ierr);
323303bc72f1SMatthew Knepley   ierr = VecGetArray(diagV,    &diagA);CHKERRQ(ierr);
323403bc72f1SMatthew Knepley   ierr = VecGetArray(offdiagV, &offdiagA);CHKERRQ(ierr);
323503bc72f1SMatthew Knepley   for (r = 0; r < n; ++r) {
3236028cd4eaSSatish Balay     if (PetscAbsScalar(diagA[r]) <= PetscAbsScalar(offdiagA[r])) {
323703bc72f1SMatthew Knepley       a[r]   = diagA[r];
323803bc72f1SMatthew Knepley       idx[r] = cstart + diagIdx[r];
323903bc72f1SMatthew Knepley     } else {
324003bc72f1SMatthew Knepley       a[r]   = offdiagA[r];
324103bc72f1SMatthew Knepley       idx[r] = cmap[offdiagIdx[r]];
324203bc72f1SMatthew Knepley     }
324303bc72f1SMatthew Knepley   }
324403bc72f1SMatthew Knepley   ierr = VecRestoreArray(v,        &a);CHKERRQ(ierr);
324503bc72f1SMatthew Knepley   ierr = VecRestoreArray(diagV,    &diagA);CHKERRQ(ierr);
324603bc72f1SMatthew Knepley   ierr = VecRestoreArray(offdiagV, &offdiagA);CHKERRQ(ierr);
32476bf464f9SBarry Smith   ierr = VecDestroy(&diagV);CHKERRQ(ierr);
32486bf464f9SBarry Smith   ierr = VecDestroy(&offdiagV);CHKERRQ(ierr);
324903bc72f1SMatthew Knepley   ierr = PetscFree2(diagIdx, offdiagIdx);CHKERRQ(ierr);
325003bc72f1SMatthew Knepley   PetscFunctionReturn(0);
325103bc72f1SMatthew Knepley }
325203bc72f1SMatthew Knepley 
32535494a064SHong Zhang #undef __FUNCT__
3254c87e5d42SMatthew Knepley #define __FUNCT__ "MatGetRowMax_MPIAIJ"
3255c87e5d42SMatthew Knepley PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
3256c87e5d42SMatthew Knepley {
3257c87e5d42SMatthew Knepley   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
3258c87e5d42SMatthew Knepley   PetscInt       n      = A->rmap->n;
3259c87e5d42SMatthew Knepley   PetscInt       cstart = A->cmap->rstart;
3260c87e5d42SMatthew Knepley   PetscInt       *cmap  = mat->garray;
3261c87e5d42SMatthew Knepley   PetscInt       *diagIdx, *offdiagIdx;
3262c87e5d42SMatthew Knepley   Vec            diagV, offdiagV;
3263c87e5d42SMatthew Knepley   PetscScalar    *a, *diagA, *offdiagA;
3264c87e5d42SMatthew Knepley   PetscInt       r;
3265c87e5d42SMatthew Knepley   PetscErrorCode ierr;
3266c87e5d42SMatthew Knepley 
3267c87e5d42SMatthew Knepley   PetscFunctionBegin;
3268c87e5d42SMatthew Knepley   ierr = PetscMalloc2(n,PetscInt,&diagIdx,n,PetscInt,&offdiagIdx);CHKERRQ(ierr);
3269d11e49fbSSatish Balay   ierr = VecCreateSeq(PETSC_COMM_SELF, n, &diagV);CHKERRQ(ierr);
3270d11e49fbSSatish Balay   ierr = VecCreateSeq(PETSC_COMM_SELF, n, &offdiagV);CHKERRQ(ierr);
3271c87e5d42SMatthew Knepley   ierr = MatGetRowMax(mat->A, diagV,    diagIdx);CHKERRQ(ierr);
3272c87e5d42SMatthew Knepley   ierr = MatGetRowMax(mat->B, offdiagV, offdiagIdx);CHKERRQ(ierr);
3273c87e5d42SMatthew Knepley   ierr = VecGetArray(v,        &a);CHKERRQ(ierr);
3274c87e5d42SMatthew Knepley   ierr = VecGetArray(diagV,    &diagA);CHKERRQ(ierr);
3275c87e5d42SMatthew Knepley   ierr = VecGetArray(offdiagV, &offdiagA);CHKERRQ(ierr);
3276c87e5d42SMatthew Knepley   for (r = 0; r < n; ++r) {
3277c87e5d42SMatthew Knepley     if (PetscAbsScalar(diagA[r]) >= PetscAbsScalar(offdiagA[r])) {
3278c87e5d42SMatthew Knepley       a[r]   = diagA[r];
3279c87e5d42SMatthew Knepley       idx[r] = cstart + diagIdx[r];
3280c87e5d42SMatthew Knepley     } else {
3281c87e5d42SMatthew Knepley       a[r]   = offdiagA[r];
3282c87e5d42SMatthew Knepley       idx[r] = cmap[offdiagIdx[r]];
3283c87e5d42SMatthew Knepley     }
3284c87e5d42SMatthew Knepley   }
3285c87e5d42SMatthew Knepley   ierr = VecRestoreArray(v,        &a);CHKERRQ(ierr);
3286c87e5d42SMatthew Knepley   ierr = VecRestoreArray(diagV,    &diagA);CHKERRQ(ierr);
3287c87e5d42SMatthew Knepley   ierr = VecRestoreArray(offdiagV, &offdiagA);CHKERRQ(ierr);
32886bf464f9SBarry Smith   ierr = VecDestroy(&diagV);CHKERRQ(ierr);
32896bf464f9SBarry Smith   ierr = VecDestroy(&offdiagV);CHKERRQ(ierr);
3290c87e5d42SMatthew Knepley   ierr = PetscFree2(diagIdx, offdiagIdx);CHKERRQ(ierr);
3291c87e5d42SMatthew Knepley   PetscFunctionReturn(0);
3292c87e5d42SMatthew Knepley }
3293c87e5d42SMatthew Knepley 
3294c87e5d42SMatthew Knepley #undef __FUNCT__
3295d1adec66SJed Brown #define __FUNCT__ "MatGetSeqNonzeroStructure_MPIAIJ"
3296d1adec66SJed Brown PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat,Mat *newmat)
32975494a064SHong Zhang {
32985494a064SHong Zhang   PetscErrorCode ierr;
3299f6d58c54SBarry Smith   Mat            *dummy;
33005494a064SHong Zhang 
33015494a064SHong Zhang   PetscFunctionBegin;
3302f6d58c54SBarry Smith   ierr    = MatGetSubMatrix_MPIAIJ_All(mat,MAT_DO_NOT_GET_VALUES,MAT_INITIAL_MATRIX,&dummy);CHKERRQ(ierr);
3303f6d58c54SBarry Smith   *newmat = *dummy;
3304f6d58c54SBarry Smith   ierr    = PetscFree(dummy);CHKERRQ(ierr);
33055494a064SHong Zhang   PetscFunctionReturn(0);
33065494a064SHong Zhang }
33075494a064SHong Zhang 
33087087cfbeSBarry Smith extern PetscErrorCode  MatFDColoringApply_AIJ(Mat,MatFDColoring,Vec,MatStructure*,void*);
3309bbead8a2SBarry Smith 
3310bbead8a2SBarry Smith #undef __FUNCT__
3311bbead8a2SBarry Smith #define __FUNCT__ "MatInvertBlockDiagonal_MPIAIJ"
3312713ccfa9SJed Brown PetscErrorCode  MatInvertBlockDiagonal_MPIAIJ(Mat A,const PetscScalar **values)
3313bbead8a2SBarry Smith {
3314bbead8a2SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*) A->data;
3315bbead8a2SBarry Smith   PetscErrorCode ierr;
3316bbead8a2SBarry Smith 
3317bbead8a2SBarry Smith   PetscFunctionBegin;
3318bbead8a2SBarry Smith   ierr = MatInvertBlockDiagonal(a->A,values);CHKERRQ(ierr);
3319bbead8a2SBarry Smith   PetscFunctionReturn(0);
3320bbead8a2SBarry Smith }
3321bbead8a2SBarry Smith 
332273a71a0fSBarry Smith #undef __FUNCT__
332373a71a0fSBarry Smith #define __FUNCT__ "MatSetRandom_MPIAIJ"
332473a71a0fSBarry Smith static PetscErrorCode  MatSetRandom_MPIAIJ(Mat x,PetscRandom rctx)
332573a71a0fSBarry Smith {
332673a71a0fSBarry Smith   PetscErrorCode ierr;
332773a71a0fSBarry Smith   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)x->data;
332873a71a0fSBarry Smith 
332973a71a0fSBarry Smith   PetscFunctionBegin;
333073a71a0fSBarry Smith   ierr = MatSetRandom(aij->A,rctx);CHKERRQ(ierr);
333173a71a0fSBarry Smith   ierr = MatSetRandom(aij->B,rctx);CHKERRQ(ierr);
333273a71a0fSBarry Smith   ierr = MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
333373a71a0fSBarry Smith   ierr = MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
333473a71a0fSBarry Smith   PetscFunctionReturn(0);
333573a71a0fSBarry Smith }
3336bbead8a2SBarry Smith 
33378a729477SBarry Smith /* -------------------------------------------------------------------*/
3338cda55fadSBarry Smith static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
3339cda55fadSBarry Smith                                        MatGetRow_MPIAIJ,
3340cda55fadSBarry Smith                                        MatRestoreRow_MPIAIJ,
3341cda55fadSBarry Smith                                        MatMult_MPIAIJ,
334297304618SKris Buschelman                                 /* 4*/ MatMultAdd_MPIAIJ,
33437c922b88SBarry Smith                                        MatMultTranspose_MPIAIJ,
33447c922b88SBarry Smith                                        MatMultTransposeAdd_MPIAIJ,
3345519f805aSKarl Rupp #if defined(PETSC_HAVE_PBGL)
3346103bf8bdSMatthew Knepley                                        MatSolve_MPIAIJ,
3347103bf8bdSMatthew Knepley #else
3348cda55fadSBarry Smith                                        0,
3349103bf8bdSMatthew Knepley #endif
3350cda55fadSBarry Smith                                        0,
3351cda55fadSBarry Smith                                        0,
335297304618SKris Buschelman                                 /*10*/ 0,
3353cda55fadSBarry Smith                                        0,
3354cda55fadSBarry Smith                                        0,
335541f059aeSBarry Smith                                        MatSOR_MPIAIJ,
3356b7c46309SBarry Smith                                        MatTranspose_MPIAIJ,
335797304618SKris Buschelman                                 /*15*/ MatGetInfo_MPIAIJ,
3358cda55fadSBarry Smith                                        MatEqual_MPIAIJ,
3359cda55fadSBarry Smith                                        MatGetDiagonal_MPIAIJ,
3360cda55fadSBarry Smith                                        MatDiagonalScale_MPIAIJ,
3361cda55fadSBarry Smith                                        MatNorm_MPIAIJ,
336297304618SKris Buschelman                                 /*20*/ MatAssemblyBegin_MPIAIJ,
3363cda55fadSBarry Smith                                        MatAssemblyEnd_MPIAIJ,
3364cda55fadSBarry Smith                                        MatSetOption_MPIAIJ,
3365cda55fadSBarry Smith                                        MatZeroEntries_MPIAIJ,
3366d519adbfSMatthew Knepley                                 /*24*/ MatZeroRows_MPIAIJ,
3367cda55fadSBarry Smith                                        0,
3368519f805aSKarl Rupp #if defined(PETSC_HAVE_PBGL)
3369719d5645SBarry Smith                                        0,
3370103bf8bdSMatthew Knepley #else
3371cda55fadSBarry Smith                                        0,
3372103bf8bdSMatthew Knepley #endif
3373cda55fadSBarry Smith                                        0,
3374cda55fadSBarry Smith                                        0,
33754994cf47SJed Brown                                 /*29*/ MatSetUp_MPIAIJ,
3376519f805aSKarl Rupp #if defined(PETSC_HAVE_PBGL)
3377719d5645SBarry Smith                                        0,
3378103bf8bdSMatthew Knepley #else
3379cda55fadSBarry Smith                                        0,
3380103bf8bdSMatthew Knepley #endif
3381cda55fadSBarry Smith                                        0,
3382cda55fadSBarry Smith                                        0,
3383cda55fadSBarry Smith                                        0,
3384d519adbfSMatthew Knepley                                 /*34*/ MatDuplicate_MPIAIJ,
3385cda55fadSBarry Smith                                        0,
3386cda55fadSBarry Smith                                        0,
3387cda55fadSBarry Smith                                        0,
3388cda55fadSBarry Smith                                        0,
3389d519adbfSMatthew Knepley                                 /*39*/ MatAXPY_MPIAIJ,
3390cda55fadSBarry Smith                                        MatGetSubMatrices_MPIAIJ,
3391cda55fadSBarry Smith                                        MatIncreaseOverlap_MPIAIJ,
3392cda55fadSBarry Smith                                        MatGetValues_MPIAIJ,
3393cb5b572fSBarry Smith                                        MatCopy_MPIAIJ,
3394d519adbfSMatthew Knepley                                 /*44*/ MatGetRowMax_MPIAIJ,
3395cda55fadSBarry Smith                                        MatScale_MPIAIJ,
3396cda55fadSBarry Smith                                        0,
3397cda55fadSBarry Smith                                        0,
3398564f14d6SBarry Smith                                        MatZeroRowsColumns_MPIAIJ,
339973a71a0fSBarry Smith                                 /*49*/ MatSetRandom_MPIAIJ,
3400cda55fadSBarry Smith                                        0,
3401cda55fadSBarry Smith                                        0,
3402cda55fadSBarry Smith                                        0,
3403cda55fadSBarry Smith                                        0,
3404d519adbfSMatthew Knepley                                 /*54*/ MatFDColoringCreate_MPIAIJ,
3405cda55fadSBarry Smith                                        0,
3406cda55fadSBarry Smith                                        MatSetUnfactored_MPIAIJ,
340772e6a0cfSJed Brown                                        MatPermute_MPIAIJ,
3408cda55fadSBarry Smith                                        0,
3409d519adbfSMatthew Knepley                                 /*59*/ MatGetSubMatrix_MPIAIJ,
3410e03a110bSBarry Smith                                        MatDestroy_MPIAIJ,
3411e03a110bSBarry Smith                                        MatView_MPIAIJ,
3412357abbc8SBarry Smith                                        0,
3413f996eeb8SHong Zhang                                        MatMatMatMult_MPIAIJ_MPIAIJ_MPIAIJ,
3414f996eeb8SHong Zhang                                 /*64*/ MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ,
3415f996eeb8SHong Zhang                                        MatMatMatMultNumeric_MPIAIJ_MPIAIJ_MPIAIJ,
3416a2243be0SBarry Smith                                        0,
3417a2243be0SBarry Smith                                        0,
3418a2243be0SBarry Smith                                        0,
3419d519adbfSMatthew Knepley                                 /*69*/ MatGetRowMaxAbs_MPIAIJ,
3420c87e5d42SMatthew Knepley                                        MatGetRowMinAbs_MPIAIJ,
3421a2243be0SBarry Smith                                        0,
3422a2243be0SBarry Smith                                        MatSetColoring_MPIAIJ,
3423dcf5cc72SBarry Smith                                        0,
342497304618SKris Buschelman                                        MatSetValuesAdifor_MPIAIJ,
34253acb8795SBarry Smith                                 /*75*/ MatFDColoringApply_AIJ,
342697304618SKris Buschelman                                        0,
342797304618SKris Buschelman                                        0,
342897304618SKris Buschelman                                        0,
3429f1f41ecbSJed Brown                                        MatFindZeroDiagonals_MPIAIJ,
343097304618SKris Buschelman                                 /*80*/ 0,
343197304618SKris Buschelman                                        0,
343297304618SKris Buschelman                                        0,
34335bba2384SShri Abhyankar                                 /*83*/ MatLoad_MPIAIJ,
34346284ec50SHong Zhang                                        0,
34356284ec50SHong Zhang                                        0,
34366284ec50SHong Zhang                                        0,
34376284ec50SHong Zhang                                        0,
3438865e5f61SKris Buschelman                                        0,
3439d519adbfSMatthew Knepley                                 /*89*/ MatMatMult_MPIAIJ_MPIAIJ,
344026be0446SHong Zhang                                        MatMatMultSymbolic_MPIAIJ_MPIAIJ,
344126be0446SHong Zhang                                        MatMatMultNumeric_MPIAIJ_MPIAIJ,
3442cf3ca8ceSHong Zhang                                        MatPtAP_MPIAIJ_MPIAIJ,
3443cf3ca8ceSHong Zhang                                        MatPtAPSymbolic_MPIAIJ_MPIAIJ,
3444cf3ca8ceSHong Zhang                                 /*94*/ MatPtAPNumeric_MPIAIJ_MPIAIJ,
34457a7894deSKris Buschelman                                        0,
34467a7894deSKris Buschelman                                        0,
34477a7894deSKris Buschelman                                        0,
34487a7894deSKris Buschelman                                        0,
3449d519adbfSMatthew Knepley                                 /*99*/ 0,
3450d2b207f1SPeter Brune                                        0,
3451d2b207f1SPeter Brune                                        0,
34522fd7e33dSBarry Smith                                        MatConjugate_MPIAIJ,
34532fd7e33dSBarry Smith                                        0,
3454d519adbfSMatthew Knepley                                 /*104*/MatSetValuesRow_MPIAIJ,
345599cafbc1SBarry Smith                                        MatRealPart_MPIAIJ,
345669db28dcSHong Zhang                                        MatImaginaryPart_MPIAIJ,
345769db28dcSHong Zhang                                        0,
345869db28dcSHong Zhang                                        0,
3459d519adbfSMatthew Knepley                                 /*109*/0,
346003bc72f1SMatthew Knepley                                        MatGetRedundantMatrix_MPIAIJ,
34615494a064SHong Zhang                                        MatGetRowMin_MPIAIJ,
34625494a064SHong Zhang                                        0,
34635494a064SHong Zhang                                        0,
3464d1adec66SJed Brown                                 /*114*/MatGetSeqNonzeroStructure_MPIAIJ,
3465bd0c2dcbSBarry Smith                                        0,
3466bd0c2dcbSBarry Smith                                        0,
3467bd0c2dcbSBarry Smith                                        0,
3468bd0c2dcbSBarry Smith                                        0,
34698fb81238SShri Abhyankar                                 /*119*/0,
34708fb81238SShri Abhyankar                                        0,
34718fb81238SShri Abhyankar                                        0,
3472d6037b41SHong Zhang                                        0,
3473b9614d88SDmitry Karpeev                                        MatGetMultiProcBlock_MPIAIJ,
3474f2c98031SJed Brown                                 /*124*/MatFindNonzeroRows_MPIAIJ,
34750716a85fSBarry Smith                                        MatGetColumnNorms_MPIAIJ,
3476bbead8a2SBarry Smith                                        MatInvertBlockDiagonal_MPIAIJ,
3477b9614d88SDmitry Karpeev                                        0,
347837868618SMatthew G Knepley                                        MatGetSubMatricesParallel_MPIAIJ,
3479187b3c17SHong Zhang                                 /*129*/0,
3480187b3c17SHong Zhang                                        MatTransposeMatMult_MPIAIJ_MPIAIJ,
3481187b3c17SHong Zhang                                        MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ,
3482187b3c17SHong Zhang                                        MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
3483187b3c17SHong Zhang                                        0,
3484187b3c17SHong Zhang                                 /*134*/0,
3485187b3c17SHong Zhang                                        0,
3486187b3c17SHong Zhang                                        0,
3487187b3c17SHong Zhang                                        0,
34883964eb88SJed Brown                                        0,
34893964eb88SJed Brown                                 /*139*/0,
3490187b3c17SHong Zhang                                        0
3491bd0c2dcbSBarry Smith };
349236ce4990SBarry Smith 
34932e8a6d31SBarry Smith /* ----------------------------------------------------------------------------------------*/
34942e8a6d31SBarry Smith 
34954a2ae208SSatish Balay #undef __FUNCT__
34964a2ae208SSatish Balay #define __FUNCT__ "MatStoreValues_MPIAIJ"
34977087cfbeSBarry Smith PetscErrorCode  MatStoreValues_MPIAIJ(Mat mat)
34982e8a6d31SBarry Smith {
34992e8a6d31SBarry Smith   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
3500dfbe8321SBarry Smith   PetscErrorCode ierr;
35012e8a6d31SBarry Smith 
35022e8a6d31SBarry Smith   PetscFunctionBegin;
35032e8a6d31SBarry Smith   ierr = MatStoreValues(aij->A);CHKERRQ(ierr);
35042e8a6d31SBarry Smith   ierr = MatStoreValues(aij->B);CHKERRQ(ierr);
35052e8a6d31SBarry Smith   PetscFunctionReturn(0);
35062e8a6d31SBarry Smith }
35072e8a6d31SBarry Smith 
35084a2ae208SSatish Balay #undef __FUNCT__
35094a2ae208SSatish Balay #define __FUNCT__ "MatRetrieveValues_MPIAIJ"
35107087cfbeSBarry Smith PetscErrorCode  MatRetrieveValues_MPIAIJ(Mat mat)
35112e8a6d31SBarry Smith {
35122e8a6d31SBarry Smith   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
3513dfbe8321SBarry Smith   PetscErrorCode ierr;
35142e8a6d31SBarry Smith 
35152e8a6d31SBarry Smith   PetscFunctionBegin;
35162e8a6d31SBarry Smith   ierr = MatRetrieveValues(aij->A);CHKERRQ(ierr);
35172e8a6d31SBarry Smith   ierr = MatRetrieveValues(aij->B);CHKERRQ(ierr);
35182e8a6d31SBarry Smith   PetscFunctionReturn(0);
35192e8a6d31SBarry Smith }
35208a729477SBarry Smith 
35214a2ae208SSatish Balay #undef __FUNCT__
3522a23d5eceSKris Buschelman #define __FUNCT__ "MatMPIAIJSetPreallocation_MPIAIJ"
35237087cfbeSBarry Smith PetscErrorCode  MatMPIAIJSetPreallocation_MPIAIJ(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
3524a23d5eceSKris Buschelman {
3525a23d5eceSKris Buschelman   Mat_MPIAIJ     *b;
3526dfbe8321SBarry Smith   PetscErrorCode ierr;
3527a23d5eceSKris Buschelman 
3528a23d5eceSKris Buschelman   PetscFunctionBegin;
352926283091SBarry Smith   ierr = PetscLayoutSetUp(B->rmap);CHKERRQ(ierr);
353026283091SBarry Smith   ierr = PetscLayoutSetUp(B->cmap);CHKERRQ(ierr);
3531a23d5eceSKris Buschelman   b = (Mat_MPIAIJ*)B->data;
3532899cda47SBarry Smith 
3533526dfc15SBarry Smith   if (!B->preallocated) {
3534899cda47SBarry Smith     /* Explicitly create 2 MATSEQAIJ matrices. */
3535899cda47SBarry Smith     ierr = MatCreate(PETSC_COMM_SELF,&b->A);CHKERRQ(ierr);
3536d0f46423SBarry Smith     ierr = MatSetSizes(b->A,B->rmap->n,B->cmap->n,B->rmap->n,B->cmap->n);CHKERRQ(ierr);
3537f9e9af59SJed Brown     ierr = MatSetBlockSizes(b->A,B->rmap->bs,B->cmap->bs);CHKERRQ(ierr);
3538899cda47SBarry Smith     ierr = MatSetType(b->A,MATSEQAIJ);CHKERRQ(ierr);
3539899cda47SBarry Smith     ierr = PetscLogObjectParent(B,b->A);CHKERRQ(ierr);
3540899cda47SBarry Smith     ierr = MatCreate(PETSC_COMM_SELF,&b->B);CHKERRQ(ierr);
3541d0f46423SBarry Smith     ierr = MatSetSizes(b->B,B->rmap->n,B->cmap->N,B->rmap->n,B->cmap->N);CHKERRQ(ierr);
3542f9e9af59SJed Brown     ierr = MatSetBlockSizes(b->B,B->rmap->bs,B->cmap->bs);CHKERRQ(ierr);
3543899cda47SBarry Smith     ierr = MatSetType(b->B,MATSEQAIJ);CHKERRQ(ierr);
3544899cda47SBarry Smith     ierr = PetscLogObjectParent(B,b->B);CHKERRQ(ierr);
3545526dfc15SBarry Smith   }
3546899cda47SBarry Smith 
3547c60e587dSKris Buschelman   ierr = MatSeqAIJSetPreallocation(b->A,d_nz,d_nnz);CHKERRQ(ierr);
3548c60e587dSKris Buschelman   ierr = MatSeqAIJSetPreallocation(b->B,o_nz,o_nnz);CHKERRQ(ierr);
3549526dfc15SBarry Smith   B->preallocated = PETSC_TRUE;
3550a23d5eceSKris Buschelman   PetscFunctionReturn(0);
3551a23d5eceSKris Buschelman }
3552a23d5eceSKris Buschelman 
35534a2ae208SSatish Balay #undef __FUNCT__
35544a2ae208SSatish Balay #define __FUNCT__ "MatDuplicate_MPIAIJ"
3555dfbe8321SBarry Smith PetscErrorCode MatDuplicate_MPIAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
3556d6dfbf8fSBarry Smith {
3557d6dfbf8fSBarry Smith   Mat            mat;
3558416022c9SBarry Smith   Mat_MPIAIJ     *a,*oldmat = (Mat_MPIAIJ*)matin->data;
3559dfbe8321SBarry Smith   PetscErrorCode ierr;
3560d6dfbf8fSBarry Smith 
35613a40ed3dSBarry Smith   PetscFunctionBegin;
3562416022c9SBarry Smith   *newmat = 0;
3563ce94432eSBarry Smith   ierr    = MatCreate(PetscObjectComm((PetscObject)matin),&mat);CHKERRQ(ierr);
3564d0f46423SBarry Smith   ierr    = MatSetSizes(mat,matin->rmap->n,matin->cmap->n,matin->rmap->N,matin->cmap->N);CHKERRQ(ierr);
3565a2f3521dSMark F. Adams   ierr    = MatSetBlockSizes(mat,matin->rmap->bs,matin->cmap->bs);CHKERRQ(ierr);
35667adad957SLisandro Dalcin   ierr    = MatSetType(mat,((PetscObject)matin)->type_name);CHKERRQ(ierr);
35671d5dac46SHong Zhang   ierr    = PetscMemcpy(mat->ops,matin->ops,sizeof(struct _MatOps));CHKERRQ(ierr);
3568273d9f13SBarry Smith   a       = (Mat_MPIAIJ*)mat->data;
3569e1b6402fSHong Zhang 
3570d5f3da31SBarry Smith   mat->factortype   = matin->factortype;
3571d0f46423SBarry Smith   mat->rmap->bs     = matin->rmap->bs;
3572a2f3521dSMark F. Adams   mat->cmap->bs     = matin->cmap->bs;
3573c456f294SBarry Smith   mat->assembled    = PETSC_TRUE;
3574e7641de0SSatish Balay   mat->insertmode   = NOT_SET_VALUES;
3575273d9f13SBarry Smith   mat->preallocated = PETSC_TRUE;
3576d6dfbf8fSBarry Smith 
357717699dbbSLois Curfman McInnes   a->size         = oldmat->size;
357817699dbbSLois Curfman McInnes   a->rank         = oldmat->rank;
3579e7641de0SSatish Balay   a->donotstash   = oldmat->donotstash;
3580e7641de0SSatish Balay   a->roworiented  = oldmat->roworiented;
3581e7641de0SSatish Balay   a->rowindices   = 0;
3582bcd2baecSBarry Smith   a->rowvalues    = 0;
3583bcd2baecSBarry Smith   a->getrowactive = PETSC_FALSE;
3584d6dfbf8fSBarry Smith 
35851e1e43feSBarry Smith   ierr = PetscLayoutReference(matin->rmap,&mat->rmap);CHKERRQ(ierr);
35861e1e43feSBarry Smith   ierr = PetscLayoutReference(matin->cmap,&mat->cmap);CHKERRQ(ierr);
3587899cda47SBarry Smith 
35882ee70a88SLois Curfman McInnes   if (oldmat->colmap) {
3589aa482453SBarry Smith #if defined(PETSC_USE_CTABLE)
35900f5bd95cSBarry Smith     ierr = PetscTableCreateCopy(oldmat->colmap,&a->colmap);CHKERRQ(ierr);
3591b1fc9764SSatish Balay #else
3592d0f46423SBarry Smith     ierr = PetscMalloc((mat->cmap->N)*sizeof(PetscInt),&a->colmap);CHKERRQ(ierr);
3593d0f46423SBarry Smith     ierr = PetscLogObjectMemory(mat,(mat->cmap->N)*sizeof(PetscInt));CHKERRQ(ierr);
3594d0f46423SBarry Smith     ierr = PetscMemcpy(a->colmap,oldmat->colmap,(mat->cmap->N)*sizeof(PetscInt));CHKERRQ(ierr);
3595b1fc9764SSatish Balay #endif
3596416022c9SBarry Smith   } else a->colmap = 0;
35973f41c07dSBarry Smith   if (oldmat->garray) {
3598b1d57f15SBarry Smith     PetscInt len;
3599d0f46423SBarry Smith     len  = oldmat->B->cmap->n;
3600b1d57f15SBarry Smith     ierr = PetscMalloc((len+1)*sizeof(PetscInt),&a->garray);CHKERRQ(ierr);
360152e6d16bSBarry Smith     ierr = PetscLogObjectMemory(mat,len*sizeof(PetscInt));CHKERRQ(ierr);
3602b1d57f15SBarry Smith     if (len) { ierr = PetscMemcpy(a->garray,oldmat->garray,len*sizeof(PetscInt));CHKERRQ(ierr); }
3603416022c9SBarry Smith   } else a->garray = 0;
3604d6dfbf8fSBarry Smith 
3605416022c9SBarry Smith   ierr    = VecDuplicate(oldmat->lvec,&a->lvec);CHKERRQ(ierr);
360652e6d16bSBarry Smith   ierr    = PetscLogObjectParent(mat,a->lvec);CHKERRQ(ierr);
3607a56f8943SBarry Smith   ierr    = VecScatterCopy(oldmat->Mvctx,&a->Mvctx);CHKERRQ(ierr);
360852e6d16bSBarry Smith   ierr    = PetscLogObjectParent(mat,a->Mvctx);CHKERRQ(ierr);
36092e8a6d31SBarry Smith   ierr    = MatDuplicate(oldmat->A,cpvalues,&a->A);CHKERRQ(ierr);
361052e6d16bSBarry Smith   ierr    = PetscLogObjectParent(mat,a->A);CHKERRQ(ierr);
36112e8a6d31SBarry Smith   ierr    = MatDuplicate(oldmat->B,cpvalues,&a->B);CHKERRQ(ierr);
361252e6d16bSBarry Smith   ierr    = PetscLogObjectParent(mat,a->B);CHKERRQ(ierr);
3613140e18c1SBarry Smith   ierr    = PetscFunctionListDuplicate(((PetscObject)matin)->qlist,&((PetscObject)mat)->qlist);CHKERRQ(ierr);
36148a729477SBarry Smith   *newmat = mat;
36153a40ed3dSBarry Smith   PetscFunctionReturn(0);
36168a729477SBarry Smith }
3617416022c9SBarry Smith 
36181a4ee126SBarry Smith 
36191a4ee126SBarry Smith 
36204a2ae208SSatish Balay #undef __FUNCT__
36215bba2384SShri Abhyankar #define __FUNCT__ "MatLoad_MPIAIJ"
3622112444f4SShri Abhyankar PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
36238fb81238SShri Abhyankar {
36248fb81238SShri Abhyankar   PetscScalar    *vals,*svals;
3625ce94432eSBarry Smith   MPI_Comm       comm;
36268fb81238SShri Abhyankar   PetscErrorCode ierr;
36271a4ee126SBarry Smith   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
36288fb81238SShri Abhyankar   PetscInt       i,nz,j,rstart,rend,mmax,maxnz = 0,grows,gcols;
36298fb81238SShri Abhyankar   PetscInt       header[4],*rowlengths = 0,M,N,m,*cols;
36300298fd71SBarry Smith   PetscInt       *ourlens = NULL,*procsnz = NULL,*offlens = NULL,jj,*mycols,*smycols;
36318fb81238SShri Abhyankar   PetscInt       cend,cstart,n,*rowners,sizesset=1;
36328fb81238SShri Abhyankar   int            fd;
363308ea439dSMark F. Adams   PetscInt       bs = 1;
36348fb81238SShri Abhyankar 
36358fb81238SShri Abhyankar   PetscFunctionBegin;
3636ce94432eSBarry Smith   ierr = PetscObjectGetComm((PetscObject)viewer,&comm);CHKERRQ(ierr);
36378fb81238SShri Abhyankar   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
36388fb81238SShri Abhyankar   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
36398fb81238SShri Abhyankar   if (!rank) {
36408fb81238SShri Abhyankar     ierr = PetscViewerBinaryGetDescriptor(viewer,&fd);CHKERRQ(ierr);
36418fb81238SShri Abhyankar     ierr = PetscBinaryRead(fd,(char*)header,4,PETSC_INT);CHKERRQ(ierr);
36428fb81238SShri Abhyankar     if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
36438fb81238SShri Abhyankar   }
36448fb81238SShri Abhyankar 
36450298fd71SBarry Smith   ierr = PetscOptionsBegin(comm,NULL,"Options for loading SEQAIJ matrix","Mat");CHKERRQ(ierr);
36460298fd71SBarry Smith   ierr = PetscOptionsInt("-matload_block_size","Set the blocksize used to store the matrix","MatLoad",bs,&bs,NULL);CHKERRQ(ierr);
364708ea439dSMark F. Adams   ierr = PetscOptionsEnd();CHKERRQ(ierr);
364808ea439dSMark F. Adams 
36498fb81238SShri Abhyankar   if (newMat->rmap->n < 0 && newMat->rmap->N < 0 && newMat->cmap->n < 0 && newMat->cmap->N < 0) sizesset = 0;
36508fb81238SShri Abhyankar 
36518fb81238SShri Abhyankar   ierr = MPI_Bcast(header+1,3,MPIU_INT,0,comm);CHKERRQ(ierr);
36528fb81238SShri Abhyankar   M    = header[1]; N = header[2];
36538fb81238SShri Abhyankar   /* If global rows/cols are set to PETSC_DECIDE, set it to the sizes given in the file */
36548fb81238SShri Abhyankar   if (sizesset && newMat->rmap->N < 0) newMat->rmap->N = M;
36558fb81238SShri Abhyankar   if (sizesset && newMat->cmap->N < 0) newMat->cmap->N = N;
36568fb81238SShri Abhyankar 
36578fb81238SShri Abhyankar   /* If global sizes are set, check if they are consistent with that given in the file */
36588fb81238SShri Abhyankar   if (sizesset) {
36598fb81238SShri Abhyankar     ierr = MatGetSize(newMat,&grows,&gcols);CHKERRQ(ierr);
36608fb81238SShri Abhyankar   }
3661abd38a8fSBarry Smith   if (sizesset && newMat->rmap->N != grows) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of rows:Matrix in file has (%d) and input matrix has (%d)",M,grows);
3662abd38a8fSBarry Smith   if (sizesset && newMat->cmap->N != gcols) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of cols:Matrix in file has (%d) and input matrix has (%d)",N,gcols);
36638fb81238SShri Abhyankar 
366408ea439dSMark F. Adams   /* determine ownership of all (block) rows */
366508ea439dSMark F. Adams   if (M%bs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of rows (%d) and block size (%d)",M,bs);
366608ea439dSMark F. Adams   if (newMat->rmap->n < 0) m = bs*((M/bs)/size + (((M/bs) % size) > rank));    /* PETSC_DECIDE */
36674683f7a4SShri Abhyankar   else m = newMat->rmap->n; /* Set by user */
36688fb81238SShri Abhyankar 
36698fb81238SShri Abhyankar   ierr = PetscMalloc((size+1)*sizeof(PetscInt),&rowners);CHKERRQ(ierr);
36708fb81238SShri Abhyankar   ierr = MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);CHKERRQ(ierr);
36718fb81238SShri Abhyankar 
36728fb81238SShri Abhyankar   /* First process needs enough room for process with most rows */
36738fb81238SShri Abhyankar   if (!rank) {
36748fb81238SShri Abhyankar     mmax = rowners[1];
36755c4ea359SMatthew G Knepley     for (i=2; i<=size; i++) {
36768fb81238SShri Abhyankar       mmax = PetscMax(mmax, rowners[i]);
36778fb81238SShri Abhyankar     }
36783964eb88SJed Brown   } else mmax = -1;             /* unused, but compilers complain */
36798fb81238SShri Abhyankar 
36808fb81238SShri Abhyankar   rowners[0] = 0;
36818fb81238SShri Abhyankar   for (i=2; i<=size; i++) {
36828fb81238SShri Abhyankar     rowners[i] += rowners[i-1];
36838fb81238SShri Abhyankar   }
36848fb81238SShri Abhyankar   rstart = rowners[rank];
36858fb81238SShri Abhyankar   rend   = rowners[rank+1];
36868fb81238SShri Abhyankar 
36878fb81238SShri Abhyankar   /* distribute row lengths to all processors */
36885aa9a6beSBarry Smith   ierr = PetscMalloc2(m,PetscInt,&ourlens,m,PetscInt,&offlens);CHKERRQ(ierr);
36898fb81238SShri Abhyankar   if (!rank) {
36908fb81238SShri Abhyankar     ierr = PetscBinaryRead(fd,ourlens,m,PETSC_INT);CHKERRQ(ierr);
36915c4ea359SMatthew G Knepley     ierr = PetscMalloc(mmax*sizeof(PetscInt),&rowlengths);CHKERRQ(ierr);
36928fb81238SShri Abhyankar     ierr = PetscMalloc(size*sizeof(PetscInt),&procsnz);CHKERRQ(ierr);
36938fb81238SShri Abhyankar     ierr = PetscMemzero(procsnz,size*sizeof(PetscInt));CHKERRQ(ierr);
36948fb81238SShri Abhyankar     for (j=0; j<m; j++) {
36958fb81238SShri Abhyankar       procsnz[0] += ourlens[j];
36968fb81238SShri Abhyankar     }
36978fb81238SShri Abhyankar     for (i=1; i<size; i++) {
36988fb81238SShri Abhyankar       ierr = PetscBinaryRead(fd,rowlengths,rowners[i+1]-rowners[i],PETSC_INT);CHKERRQ(ierr);
36998fb81238SShri Abhyankar       /* calculate the number of nonzeros on each processor */
37008fb81238SShri Abhyankar       for (j=0; j<rowners[i+1]-rowners[i]; j++) {
37018fb81238SShri Abhyankar         procsnz[i] += rowlengths[j];
37028fb81238SShri Abhyankar       }
3703a25532f0SBarry Smith       ierr = MPIULong_Send(rowlengths,rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);CHKERRQ(ierr);
37048fb81238SShri Abhyankar     }
37058fb81238SShri Abhyankar     ierr = PetscFree(rowlengths);CHKERRQ(ierr);
37068fb81238SShri Abhyankar   } else {
3707a25532f0SBarry Smith     ierr = MPIULong_Recv(ourlens,m,MPIU_INT,0,tag,comm);CHKERRQ(ierr);
37088fb81238SShri Abhyankar   }
37098fb81238SShri Abhyankar 
37108fb81238SShri Abhyankar   if (!rank) {
37118fb81238SShri Abhyankar     /* determine max buffer needed and allocate it */
37128fb81238SShri Abhyankar     maxnz = 0;
37138fb81238SShri Abhyankar     for (i=0; i<size; i++) {
37148fb81238SShri Abhyankar       maxnz = PetscMax(maxnz,procsnz[i]);
37158fb81238SShri Abhyankar     }
37168fb81238SShri Abhyankar     ierr = PetscMalloc(maxnz*sizeof(PetscInt),&cols);CHKERRQ(ierr);
37178fb81238SShri Abhyankar 
37188fb81238SShri Abhyankar     /* read in my part of the matrix column indices  */
37198fb81238SShri Abhyankar     nz   = procsnz[0];
37208fb81238SShri Abhyankar     ierr = PetscMalloc(nz*sizeof(PetscInt),&mycols);CHKERRQ(ierr);
37218fb81238SShri Abhyankar     ierr = PetscBinaryRead(fd,mycols,nz,PETSC_INT);CHKERRQ(ierr);
37228fb81238SShri Abhyankar 
37238fb81238SShri Abhyankar     /* read in every one elses and ship off */
37248fb81238SShri Abhyankar     for (i=1; i<size; i++) {
37258fb81238SShri Abhyankar       nz   = procsnz[i];
37268fb81238SShri Abhyankar       ierr = PetscBinaryRead(fd,cols,nz,PETSC_INT);CHKERRQ(ierr);
3727a25532f0SBarry Smith       ierr = MPIULong_Send(cols,nz,MPIU_INT,i,tag,comm);CHKERRQ(ierr);
37288fb81238SShri Abhyankar     }
37298fb81238SShri Abhyankar     ierr = PetscFree(cols);CHKERRQ(ierr);
37308fb81238SShri Abhyankar   } else {
37318fb81238SShri Abhyankar     /* determine buffer space needed for message */
37328fb81238SShri Abhyankar     nz = 0;
37338fb81238SShri Abhyankar     for (i=0; i<m; i++) {
37348fb81238SShri Abhyankar       nz += ourlens[i];
37358fb81238SShri Abhyankar     }
37368fb81238SShri Abhyankar     ierr = PetscMalloc(nz*sizeof(PetscInt),&mycols);CHKERRQ(ierr);
37378fb81238SShri Abhyankar 
37388fb81238SShri Abhyankar     /* receive message of column indices*/
3739a25532f0SBarry Smith     ierr = MPIULong_Recv(mycols,nz,MPIU_INT,0,tag,comm);CHKERRQ(ierr);
37408fb81238SShri Abhyankar   }
37418fb81238SShri Abhyankar 
37428fb81238SShri Abhyankar   /* determine column ownership if matrix is not square */
37438fb81238SShri Abhyankar   if (N != M) {
37448fb81238SShri Abhyankar     if (newMat->cmap->n < 0) n = N/size + ((N % size) > rank);
37458fb81238SShri Abhyankar     else n = newMat->cmap->n;
37468fb81238SShri Abhyankar     ierr   = MPI_Scan(&n,&cend,1,MPIU_INT,MPI_SUM,comm);CHKERRQ(ierr);
37478fb81238SShri Abhyankar     cstart = cend - n;
37488fb81238SShri Abhyankar   } else {
37498fb81238SShri Abhyankar     cstart = rstart;
37508fb81238SShri Abhyankar     cend   = rend;
37518fb81238SShri Abhyankar     n      = cend - cstart;
37528fb81238SShri Abhyankar   }
37538fb81238SShri Abhyankar 
37548fb81238SShri Abhyankar   /* loop over local rows, determining number of off diagonal entries */
37558fb81238SShri Abhyankar   ierr = PetscMemzero(offlens,m*sizeof(PetscInt));CHKERRQ(ierr);
37568fb81238SShri Abhyankar   jj   = 0;
37578fb81238SShri Abhyankar   for (i=0; i<m; i++) {
37588fb81238SShri Abhyankar     for (j=0; j<ourlens[i]; j++) {
37598fb81238SShri Abhyankar       if (mycols[jj] < cstart || mycols[jj] >= cend) offlens[i]++;
37608fb81238SShri Abhyankar       jj++;
37618fb81238SShri Abhyankar     }
37628fb81238SShri Abhyankar   }
37638fb81238SShri Abhyankar 
37648fb81238SShri Abhyankar   for (i=0; i<m; i++) {
37658fb81238SShri Abhyankar     ourlens[i] -= offlens[i];
37668fb81238SShri Abhyankar   }
37678fb81238SShri Abhyankar   if (!sizesset) {
37688fb81238SShri Abhyankar     ierr = MatSetSizes(newMat,m,n,M,N);CHKERRQ(ierr);
37698fb81238SShri Abhyankar   }
377008ea439dSMark F. Adams 
377108ea439dSMark F. Adams   if (bs > 1) {ierr = MatSetBlockSize(newMat,bs);CHKERRQ(ierr);}
377208ea439dSMark F. Adams 
37738fb81238SShri Abhyankar   ierr = MatMPIAIJSetPreallocation(newMat,0,ourlens,0,offlens);CHKERRQ(ierr);
37748fb81238SShri Abhyankar 
37758fb81238SShri Abhyankar   for (i=0; i<m; i++) {
37768fb81238SShri Abhyankar     ourlens[i] += offlens[i];
37778fb81238SShri Abhyankar   }
37788fb81238SShri Abhyankar 
37798fb81238SShri Abhyankar   if (!rank) {
37808fb81238SShri Abhyankar     ierr = PetscMalloc((maxnz+1)*sizeof(PetscScalar),&vals);CHKERRQ(ierr);
37818fb81238SShri Abhyankar 
37828fb81238SShri Abhyankar     /* read in my part of the matrix numerical values  */
37838fb81238SShri Abhyankar     nz   = procsnz[0];
37848fb81238SShri Abhyankar     ierr = PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);CHKERRQ(ierr);
37858fb81238SShri Abhyankar 
37868fb81238SShri Abhyankar     /* insert into matrix */
37878fb81238SShri Abhyankar     jj      = rstart;
37888fb81238SShri Abhyankar     smycols = mycols;
37898fb81238SShri Abhyankar     svals   = vals;
37908fb81238SShri Abhyankar     for (i=0; i<m; i++) {
37918fb81238SShri Abhyankar       ierr     = MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);CHKERRQ(ierr);
37928fb81238SShri Abhyankar       smycols += ourlens[i];
37938fb81238SShri Abhyankar       svals   += ourlens[i];
37948fb81238SShri Abhyankar       jj++;
37958fb81238SShri Abhyankar     }
37968fb81238SShri Abhyankar 
37978fb81238SShri Abhyankar     /* read in other processors and ship out */
37988fb81238SShri Abhyankar     for (i=1; i<size; i++) {
37998fb81238SShri Abhyankar       nz   = procsnz[i];
38008fb81238SShri Abhyankar       ierr = PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);CHKERRQ(ierr);
3801a25532f0SBarry Smith       ierr = MPIULong_Send(vals,nz,MPIU_SCALAR,i,((PetscObject)newMat)->tag,comm);CHKERRQ(ierr);
38028fb81238SShri Abhyankar     }
38038fb81238SShri Abhyankar     ierr = PetscFree(procsnz);CHKERRQ(ierr);
38048fb81238SShri Abhyankar   } else {
38058fb81238SShri Abhyankar     /* receive numeric values */
38068fb81238SShri Abhyankar     ierr = PetscMalloc((nz+1)*sizeof(PetscScalar),&vals);CHKERRQ(ierr);
38078fb81238SShri Abhyankar 
38088fb81238SShri Abhyankar     /* receive message of values*/
3809a25532f0SBarry Smith     ierr = MPIULong_Recv(vals,nz,MPIU_SCALAR,0,((PetscObject)newMat)->tag,comm);CHKERRQ(ierr);
38108fb81238SShri Abhyankar 
38118fb81238SShri Abhyankar     /* insert into matrix */
38128fb81238SShri Abhyankar     jj      = rstart;
38138fb81238SShri Abhyankar     smycols = mycols;
38148fb81238SShri Abhyankar     svals   = vals;
38158fb81238SShri Abhyankar     for (i=0; i<m; i++) {
38168fb81238SShri Abhyankar       ierr     = MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);CHKERRQ(ierr);
38178fb81238SShri Abhyankar       smycols += ourlens[i];
38188fb81238SShri Abhyankar       svals   += ourlens[i];
38198fb81238SShri Abhyankar       jj++;
38208fb81238SShri Abhyankar     }
38218fb81238SShri Abhyankar   }
38228fb81238SShri Abhyankar   ierr = PetscFree2(ourlens,offlens);CHKERRQ(ierr);
38238fb81238SShri Abhyankar   ierr = PetscFree(vals);CHKERRQ(ierr);
38248fb81238SShri Abhyankar   ierr = PetscFree(mycols);CHKERRQ(ierr);
38258fb81238SShri Abhyankar   ierr = PetscFree(rowners);CHKERRQ(ierr);
38268fb81238SShri Abhyankar   ierr = MatAssemblyBegin(newMat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
38278fb81238SShri Abhyankar   ierr = MatAssemblyEnd(newMat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
38288fb81238SShri Abhyankar   PetscFunctionReturn(0);
38298fb81238SShri Abhyankar }
38308fb81238SShri Abhyankar 
38318fb81238SShri Abhyankar #undef __FUNCT__
38324a2ae208SSatish Balay #define __FUNCT__ "MatGetSubMatrix_MPIAIJ"
38334aa3045dSJed Brown PetscErrorCode MatGetSubMatrix_MPIAIJ(Mat mat,IS isrow,IS iscol,MatReuse call,Mat *newmat)
38344aa3045dSJed Brown {
38354aa3045dSJed Brown   PetscErrorCode ierr;
38364aa3045dSJed Brown   IS             iscol_local;
38374aa3045dSJed Brown   PetscInt       csize;
38384aa3045dSJed Brown 
38394aa3045dSJed Brown   PetscFunctionBegin;
38404aa3045dSJed Brown   ierr = ISGetLocalSize(iscol,&csize);CHKERRQ(ierr);
3841b79d0421SJed Brown   if (call == MAT_REUSE_MATRIX) {
3842b79d0421SJed Brown     ierr = PetscObjectQuery((PetscObject)*newmat,"ISAllGather",(PetscObject*)&iscol_local);CHKERRQ(ierr);
3843e32f2f54SBarry Smith     if (!iscol_local) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
3844b79d0421SJed Brown   } else {
3845c5bfad50SMark F. Adams     PetscInt cbs;
3846c5bfad50SMark F. Adams     ierr = ISGetBlockSize(iscol,&cbs);CHKERRQ(ierr);
38474aa3045dSJed Brown     ierr = ISAllGather(iscol,&iscol_local);CHKERRQ(ierr);
3848c5bfad50SMark F. Adams     ierr = ISSetBlockSize(iscol_local,cbs);CHKERRQ(ierr);
3849b79d0421SJed Brown   }
38504aa3045dSJed Brown   ierr = MatGetSubMatrix_MPIAIJ_Private(mat,isrow,iscol_local,csize,call,newmat);CHKERRQ(ierr);
3851b79d0421SJed Brown   if (call == MAT_INITIAL_MATRIX) {
3852b79d0421SJed Brown     ierr = PetscObjectCompose((PetscObject)*newmat,"ISAllGather",(PetscObject)iscol_local);CHKERRQ(ierr);
38536bf464f9SBarry Smith     ierr = ISDestroy(&iscol_local);CHKERRQ(ierr);
3854b79d0421SJed Brown   }
38554aa3045dSJed Brown   PetscFunctionReturn(0);
38564aa3045dSJed Brown }
38574aa3045dSJed Brown 
385829dcf524SDmitry Karpeev extern PetscErrorCode MatGetSubMatrices_MPIAIJ_Local(Mat,PetscInt,const IS[],const IS[],MatReuse,PetscBool*,Mat*);
38594aa3045dSJed Brown #undef __FUNCT__
38604aa3045dSJed Brown #define __FUNCT__ "MatGetSubMatrix_MPIAIJ_Private"
3861a0ff6018SBarry Smith /*
386229da9460SBarry Smith     Not great since it makes two copies of the submatrix, first an SeqAIJ
386329da9460SBarry Smith   in local and then by concatenating the local matrices the end result.
386429da9460SBarry Smith   Writing it directly would be much like MatGetSubMatrices_MPIAIJ()
38654aa3045dSJed Brown 
38664aa3045dSJed Brown   Note: This requires a sequential iscol with all indices.
3867a0ff6018SBarry Smith */
38684aa3045dSJed Brown PetscErrorCode MatGetSubMatrix_MPIAIJ_Private(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse call,Mat *newmat)
3869a0ff6018SBarry Smith {
3870dfbe8321SBarry Smith   PetscErrorCode ierr;
387132dcc486SBarry Smith   PetscMPIInt    rank,size;
3872a2f3521dSMark F. Adams   PetscInt       i,m,n,rstart,row,rend,nz,*cwork,j,bs,cbs;
387329dcf524SDmitry Karpeev   PetscInt       *ii,*jj,nlocal,*dlens,*olens,dlen,olen,jend,mglobal,ncol;
387429dcf524SDmitry Karpeev   PetscBool      allcolumns, colflag;
387529dcf524SDmitry Karpeev   Mat            M,Mreuse;
3876a77337e4SBarry Smith   MatScalar      *vwork,*aa;
3877ce94432eSBarry Smith   MPI_Comm       comm;
387800e6dbe6SBarry Smith   Mat_SeqAIJ     *aij;
38797e2c5f70SBarry Smith 
3880a0ff6018SBarry Smith   PetscFunctionBegin;
3881ce94432eSBarry Smith   ierr = PetscObjectGetComm((PetscObject)mat,&comm);CHKERRQ(ierr);
38821dab6e02SBarry Smith   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
38831dab6e02SBarry Smith   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
388400e6dbe6SBarry Smith 
388529dcf524SDmitry Karpeev   ierr = ISIdentity(iscol,&colflag);CHKERRQ(ierr);
388629dcf524SDmitry Karpeev   ierr = ISGetLocalSize(iscol,&ncol);CHKERRQ(ierr);
388729dcf524SDmitry Karpeev   if (colflag && ncol == mat->cmap->N) {
388829dcf524SDmitry Karpeev     allcolumns = PETSC_TRUE;
388929dcf524SDmitry Karpeev   } else {
389029dcf524SDmitry Karpeev     allcolumns = PETSC_FALSE;
389129dcf524SDmitry Karpeev   }
3892fee21e36SBarry Smith   if (call ==  MAT_REUSE_MATRIX) {
3893fee21e36SBarry Smith     ierr = PetscObjectQuery((PetscObject)*newmat,"SubMatrix",(PetscObject*)&Mreuse);CHKERRQ(ierr);
3894e32f2f54SBarry Smith     if (!Mreuse) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
389529dcf524SDmitry Karpeev     ierr = MatGetSubMatrices_MPIAIJ_Local(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,&allcolumns,&Mreuse);CHKERRQ(ierr);
3896fee21e36SBarry Smith   } else {
389729dcf524SDmitry Karpeev     ierr = MatGetSubMatrices_MPIAIJ_Local(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&allcolumns,&Mreuse);CHKERRQ(ierr);
3898fee21e36SBarry Smith   }
3899a0ff6018SBarry Smith 
3900a0ff6018SBarry Smith   /*
3901a0ff6018SBarry Smith       m - number of local rows
3902a0ff6018SBarry Smith       n - number of columns (same on all processors)
3903a0ff6018SBarry Smith       rstart - first row in new global matrix generated
3904a0ff6018SBarry Smith   */
3905fee21e36SBarry Smith   ierr = MatGetSize(Mreuse,&m,&n);CHKERRQ(ierr);
3906a2f3521dSMark F. Adams   ierr = MatGetBlockSizes(Mreuse,&bs,&cbs);CHKERRQ(ierr);
3907a0ff6018SBarry Smith   if (call == MAT_INITIAL_MATRIX) {
3908fee21e36SBarry Smith     aij = (Mat_SeqAIJ*)(Mreuse)->data;
390900e6dbe6SBarry Smith     ii  = aij->i;
391000e6dbe6SBarry Smith     jj  = aij->j;
391100e6dbe6SBarry Smith 
3912a0ff6018SBarry Smith     /*
391300e6dbe6SBarry Smith         Determine the number of non-zeros in the diagonal and off-diagonal
391400e6dbe6SBarry Smith         portions of the matrix in order to do correct preallocation
3915a0ff6018SBarry Smith     */
391600e6dbe6SBarry Smith 
391700e6dbe6SBarry Smith     /* first get start and end of "diagonal" columns */
39186a6a5d1dSBarry Smith     if (csize == PETSC_DECIDE) {
3919ab50ec6bSBarry Smith       ierr = ISGetSize(isrow,&mglobal);CHKERRQ(ierr);
3920ab50ec6bSBarry Smith       if (mglobal == n) { /* square matrix */
3921e2c4fddaSBarry Smith         nlocal = m;
39226a6a5d1dSBarry Smith       } else {
3923ab50ec6bSBarry Smith         nlocal = n/size + ((n % size) > rank);
3924ab50ec6bSBarry Smith       }
3925ab50ec6bSBarry Smith     } else {
39266a6a5d1dSBarry Smith       nlocal = csize;
39276a6a5d1dSBarry Smith     }
3928b1d57f15SBarry Smith     ierr   = MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);CHKERRQ(ierr);
392900e6dbe6SBarry Smith     rstart = rend - nlocal;
393065e19b50SBarry Smith     if (rank == size - 1 && rend != n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Local column sizes %D do not add up to total number of columns %D",rend,n);
393100e6dbe6SBarry Smith 
393200e6dbe6SBarry Smith     /* next, compute all the lengths */
3933b1d57f15SBarry Smith     ierr  = PetscMalloc((2*m+1)*sizeof(PetscInt),&dlens);CHKERRQ(ierr);
393400e6dbe6SBarry Smith     olens = dlens + m;
393500e6dbe6SBarry Smith     for (i=0; i<m; i++) {
393600e6dbe6SBarry Smith       jend = ii[i+1] - ii[i];
393700e6dbe6SBarry Smith       olen = 0;
393800e6dbe6SBarry Smith       dlen = 0;
393900e6dbe6SBarry Smith       for (j=0; j<jend; j++) {
394000e6dbe6SBarry Smith         if (*jj < rstart || *jj >= rend) olen++;
394100e6dbe6SBarry Smith         else dlen++;
394200e6dbe6SBarry Smith         jj++;
394300e6dbe6SBarry Smith       }
394400e6dbe6SBarry Smith       olens[i] = olen;
394500e6dbe6SBarry Smith       dlens[i] = dlen;
394600e6dbe6SBarry Smith     }
3947f69a0ea3SMatthew Knepley     ierr = MatCreate(comm,&M);CHKERRQ(ierr);
3948f69a0ea3SMatthew Knepley     ierr = MatSetSizes(M,m,nlocal,PETSC_DECIDE,n);CHKERRQ(ierr);
3949a2f3521dSMark F. Adams     ierr = MatSetBlockSizes(M,bs,cbs);CHKERRQ(ierr);
39507adad957SLisandro Dalcin     ierr = MatSetType(M,((PetscObject)mat)->type_name);CHKERRQ(ierr);
3951e2d9671bSKris Buschelman     ierr = MatMPIAIJSetPreallocation(M,0,dlens,0,olens);CHKERRQ(ierr);
3952606d414cSSatish Balay     ierr = PetscFree(dlens);CHKERRQ(ierr);
3953a0ff6018SBarry Smith   } else {
3954b1d57f15SBarry Smith     PetscInt ml,nl;
3955a0ff6018SBarry Smith 
3956a0ff6018SBarry Smith     M    = *newmat;
3957a0ff6018SBarry Smith     ierr = MatGetLocalSize(M,&ml,&nl);CHKERRQ(ierr);
3958e32f2f54SBarry Smith     if (ml != m) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Previous matrix must be same size/layout as request");
3959a0ff6018SBarry Smith     ierr = MatZeroEntries(M);CHKERRQ(ierr);
3960c48de900SBarry Smith     /*
3961c48de900SBarry Smith          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3962c48de900SBarry Smith        rather than the slower MatSetValues().
3963c48de900SBarry Smith     */
3964c48de900SBarry Smith     M->was_assembled = PETSC_TRUE;
3965c48de900SBarry Smith     M->assembled     = PETSC_FALSE;
3966a0ff6018SBarry Smith   }
3967a0ff6018SBarry Smith   ierr = MatGetOwnershipRange(M,&rstart,&rend);CHKERRQ(ierr);
3968fee21e36SBarry Smith   aij  = (Mat_SeqAIJ*)(Mreuse)->data;
396900e6dbe6SBarry Smith   ii   = aij->i;
397000e6dbe6SBarry Smith   jj   = aij->j;
397100e6dbe6SBarry Smith   aa   = aij->a;
3972a0ff6018SBarry Smith   for (i=0; i<m; i++) {
3973a0ff6018SBarry Smith     row   = rstart + i;
397400e6dbe6SBarry Smith     nz    = ii[i+1] - ii[i];
397500e6dbe6SBarry Smith     cwork = jj;     jj += nz;
397600e6dbe6SBarry Smith     vwork = aa;     aa += nz;
39778c638d02SBarry Smith     ierr  = MatSetValues_MPIAIJ(M,1,&row,nz,cwork,vwork,INSERT_VALUES);CHKERRQ(ierr);
3978a0ff6018SBarry Smith   }
3979a0ff6018SBarry Smith 
3980a0ff6018SBarry Smith   ierr    = MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
3981a0ff6018SBarry Smith   ierr    = MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
3982a0ff6018SBarry Smith   *newmat = M;
3983fee21e36SBarry Smith 
3984fee21e36SBarry Smith   /* save submatrix used in processor for next request */
3985fee21e36SBarry Smith   if (call ==  MAT_INITIAL_MATRIX) {
3986fee21e36SBarry Smith     ierr = PetscObjectCompose((PetscObject)M,"SubMatrix",(PetscObject)Mreuse);CHKERRQ(ierr);
3987bf0cc555SLisandro Dalcin     ierr = MatDestroy(&Mreuse);CHKERRQ(ierr);
3988fee21e36SBarry Smith   }
3989a0ff6018SBarry Smith   PetscFunctionReturn(0);
3990a0ff6018SBarry Smith }
3991273d9f13SBarry Smith 
39924a2ae208SSatish Balay #undef __FUNCT__
3993ccd8e176SBarry Smith #define __FUNCT__ "MatMPIAIJSetPreallocationCSR_MPIAIJ"
39947087cfbeSBarry Smith PetscErrorCode  MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
3995ccd8e176SBarry Smith {
3996899cda47SBarry Smith   PetscInt       m,cstart, cend,j,nnz,i,d;
3997899cda47SBarry Smith   PetscInt       *d_nnz,*o_nnz,nnz_max = 0,rstart,ii;
3998ccd8e176SBarry Smith   const PetscInt *JJ;
3999ccd8e176SBarry Smith   PetscScalar    *values;
4000ccd8e176SBarry Smith   PetscErrorCode ierr;
4001ccd8e176SBarry Smith 
4002ccd8e176SBarry Smith   PetscFunctionBegin;
4003e32f2f54SBarry Smith   if (Ii[0]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Ii[0] must be 0 it is %D",Ii[0]);
4004899cda47SBarry Smith 
400526283091SBarry Smith   ierr   = PetscLayoutSetUp(B->rmap);CHKERRQ(ierr);
400626283091SBarry Smith   ierr   = PetscLayoutSetUp(B->cmap);CHKERRQ(ierr);
4007d0f46423SBarry Smith   m      = B->rmap->n;
4008d0f46423SBarry Smith   cstart = B->cmap->rstart;
4009d0f46423SBarry Smith   cend   = B->cmap->rend;
4010d0f46423SBarry Smith   rstart = B->rmap->rstart;
4011899cda47SBarry Smith 
40121d79065fSBarry Smith   ierr = PetscMalloc2(m,PetscInt,&d_nnz,m,PetscInt,&o_nnz);CHKERRQ(ierr);
4013ccd8e176SBarry Smith 
4014ecc77c7aSBarry Smith #if defined(PETSC_USE_DEBUGGING)
4015ecc77c7aSBarry Smith   for (i=0; i<m; i++) {
4016ecc77c7aSBarry Smith     nnz = Ii[i+1]- Ii[i];
4017ecc77c7aSBarry Smith     JJ  = J + Ii[i];
4018e32f2f54SBarry Smith     if (nnz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative %D number of columns",i,nnz);
4019ecc77c7aSBarry Smith     if (nnz && (JJ[0] < 0)) SETERRRQ1(PETSC_ERR_ARG_WRONGSTATE,"Row %D starts with negative column index",i,j);
4020d0f46423SBarry Smith     if (nnz && (JJ[nnz-1] >= B->cmap->N) SETERRRQ3(PETSC_ERR_ARG_WRONGSTATE,"Row %D ends with too large a column index %D (max allowed %D)",i,JJ[nnz-1],B->cmap->N);
4021ecc77c7aSBarry Smith   }
4022ecc77c7aSBarry Smith #endif
4023ecc77c7aSBarry Smith 
4024ccd8e176SBarry Smith   for (i=0; i<m; i++) {
4025b7940d39SSatish Balay     nnz     = Ii[i+1]- Ii[i];
4026b7940d39SSatish Balay     JJ      = J + Ii[i];
4027ccd8e176SBarry Smith     nnz_max = PetscMax(nnz_max,nnz);
4028ccd8e176SBarry Smith     d       = 0;
40290daa03b5SJed Brown     for (j=0; j<nnz; j++) {
40300daa03b5SJed Brown       if (cstart <= JJ[j] && JJ[j] < cend) d++;
4031ccd8e176SBarry Smith     }
4032ccd8e176SBarry Smith     d_nnz[i] = d;
4033ccd8e176SBarry Smith     o_nnz[i] = nnz - d;
4034ccd8e176SBarry Smith   }
4035ccd8e176SBarry Smith   ierr = MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);CHKERRQ(ierr);
40361d79065fSBarry Smith   ierr = PetscFree2(d_nnz,o_nnz);CHKERRQ(ierr);
4037ccd8e176SBarry Smith 
4038ccd8e176SBarry Smith   if (v) values = (PetscScalar*)v;
4039ccd8e176SBarry Smith   else {
4040ccd8e176SBarry Smith     ierr = PetscMalloc((nnz_max+1)*sizeof(PetscScalar),&values);CHKERRQ(ierr);
4041ccd8e176SBarry Smith     ierr = PetscMemzero(values,nnz_max*sizeof(PetscScalar));CHKERRQ(ierr);
4042ccd8e176SBarry Smith   }
4043ccd8e176SBarry Smith 
4044ccd8e176SBarry Smith   for (i=0; i<m; i++) {
4045ccd8e176SBarry Smith     ii   = i + rstart;
4046b7940d39SSatish Balay     nnz  = Ii[i+1]- Ii[i];
4047b7940d39SSatish Balay     ierr = MatSetValues_MPIAIJ(B,1,&ii,nnz,J+Ii[i],values+(v ? Ii[i] : 0),INSERT_VALUES);CHKERRQ(ierr);
4048ccd8e176SBarry Smith   }
4049ccd8e176SBarry Smith   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4050ccd8e176SBarry Smith   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4051ccd8e176SBarry Smith 
4052ccd8e176SBarry Smith   if (!v) {
4053ccd8e176SBarry Smith     ierr = PetscFree(values);CHKERRQ(ierr);
4054ccd8e176SBarry Smith   }
40557827cd58SJed Brown   ierr = MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);CHKERRQ(ierr);
4056ccd8e176SBarry Smith   PetscFunctionReturn(0);
4057ccd8e176SBarry Smith }
4058ccd8e176SBarry Smith 
4059ccd8e176SBarry Smith #undef __FUNCT__
4060ccd8e176SBarry Smith #define __FUNCT__ "MatMPIAIJSetPreallocationCSR"
40611eea217eSSatish Balay /*@
4062ccd8e176SBarry Smith    MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in AIJ format
4063ccd8e176SBarry Smith    (the default parallel PETSc format).
4064ccd8e176SBarry Smith 
4065ccd8e176SBarry Smith    Collective on MPI_Comm
4066ccd8e176SBarry Smith 
4067ccd8e176SBarry Smith    Input Parameters:
4068a1661176SMatthew Knepley +  B - the matrix
4069ccd8e176SBarry Smith .  i - the indices into j for the start of each local row (starts with zero)
40700daa03b5SJed Brown .  j - the column indices for each local row (starts with zero)
4071ccd8e176SBarry Smith -  v - optional values in the matrix
4072ccd8e176SBarry Smith 
4073ccd8e176SBarry Smith    Level: developer
4074ccd8e176SBarry Smith 
407512251496SSatish Balay    Notes:
407612251496SSatish Balay        The i, j, and a arrays ARE copied by this routine into the internal format used by PETSc;
407712251496SSatish Balay      thus you CANNOT change the matrix entries by changing the values of a[] after you have
407812251496SSatish Balay      called this routine. Use MatCreateMPIAIJWithSplitArrays() to avoid needing to copy the arrays.
407912251496SSatish Balay 
408012251496SSatish Balay        The i and j indices are 0 based, and i indices are indices corresponding to the local j array.
408112251496SSatish Balay 
408212251496SSatish Balay        The format which is used for the sparse matrix input, is equivalent to a
408312251496SSatish Balay     row-major ordering.. i.e for the following matrix, the input data expected is
408412251496SSatish Balay     as shown:
408512251496SSatish Balay 
408612251496SSatish Balay         1 0 0
408712251496SSatish Balay         2 0 3     P0
408812251496SSatish Balay        -------
408912251496SSatish Balay         4 5 6     P1
409012251496SSatish Balay 
409112251496SSatish Balay      Process0 [P0]: rows_owned=[0,1]
409212251496SSatish Balay         i =  {0,1,3}  [size = nrow+1  = 2+1]
409312251496SSatish Balay         j =  {0,0,2}  [size = nz = 6]
409412251496SSatish Balay         v =  {1,2,3}  [size = nz = 6]
409512251496SSatish Balay 
409612251496SSatish Balay      Process1 [P1]: rows_owned=[2]
409712251496SSatish Balay         i =  {0,3}    [size = nrow+1  = 1+1]
409812251496SSatish Balay         j =  {0,1,2}  [size = nz = 6]
409912251496SSatish Balay         v =  {4,5,6}  [size = nz = 6]
410012251496SSatish Balay 
4101ccd8e176SBarry Smith .keywords: matrix, aij, compressed row, sparse, parallel
4102ccd8e176SBarry Smith 
410369b1f4b7SBarry Smith .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatCreateAIJ(), MPIAIJ,
41048d7a6e47SBarry Smith           MatCreateSeqAIJWithArrays(), MatCreateMPIAIJWithSplitArrays()
4105ccd8e176SBarry Smith @*/
41067087cfbeSBarry Smith PetscErrorCode  MatMPIAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
4107ccd8e176SBarry Smith {
41084ac538c5SBarry Smith   PetscErrorCode ierr;
4109ccd8e176SBarry Smith 
4110ccd8e176SBarry Smith   PetscFunctionBegin;
41114ac538c5SBarry Smith   ierr = PetscTryMethod(B,"MatMPIAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));CHKERRQ(ierr);
4112ccd8e176SBarry Smith   PetscFunctionReturn(0);
4113ccd8e176SBarry Smith }
4114ccd8e176SBarry Smith 
4115ccd8e176SBarry Smith #undef __FUNCT__
41164a2ae208SSatish Balay #define __FUNCT__ "MatMPIAIJSetPreallocation"
4117273d9f13SBarry Smith /*@C
4118ccd8e176SBarry Smith    MatMPIAIJSetPreallocation - Preallocates memory for a sparse parallel matrix in AIJ format
4119273d9f13SBarry Smith    (the default parallel PETSc format).  For good matrix assembly performance
4120273d9f13SBarry Smith    the user should preallocate the matrix storage by setting the parameters
4121273d9f13SBarry Smith    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
4122273d9f13SBarry Smith    performance can be increased by more than a factor of 50.
4123273d9f13SBarry Smith 
4124273d9f13SBarry Smith    Collective on MPI_Comm
4125273d9f13SBarry Smith 
4126273d9f13SBarry Smith    Input Parameters:
4127273d9f13SBarry Smith +  A - the matrix
4128273d9f13SBarry Smith .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4129273d9f13SBarry Smith            (same value is used for all local rows)
4130273d9f13SBarry Smith .  d_nnz - array containing the number of nonzeros in the various rows of the
4131273d9f13SBarry Smith            DIAGONAL portion of the local submatrix (possibly different for each row)
41320298fd71SBarry Smith            or NULL, if d_nz is used to specify the nonzero structure.
4133273d9f13SBarry Smith            The size of this array is equal to the number of local rows, i.e 'm'.
41343287b5eaSJed Brown            For matrices that will be factored, you must leave room for (and set)
41353287b5eaSJed Brown            the diagonal entry even if it is zero.
4136273d9f13SBarry Smith .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4137273d9f13SBarry Smith            submatrix (same value is used for all local rows).
4138273d9f13SBarry Smith -  o_nnz - array containing the number of nonzeros in the various rows of the
4139273d9f13SBarry Smith            OFF-DIAGONAL portion of the local submatrix (possibly different for
41400298fd71SBarry Smith            each row) or NULL, if o_nz is used to specify the nonzero
4141273d9f13SBarry Smith            structure. The size of this array is equal to the number
4142273d9f13SBarry Smith            of local rows, i.e 'm'.
4143273d9f13SBarry Smith 
414449a6f317SBarry Smith    If the *_nnz parameter is given then the *_nz parameter is ignored
414549a6f317SBarry Smith 
4146273d9f13SBarry Smith    The AIJ format (also called the Yale sparse matrix format or
4147ccd8e176SBarry Smith    compressed row storage (CSR)), is fully compatible with standard Fortran 77
41480598bfebSBarry Smith    storage.  The stored row and column indices begin with zero.
41490598bfebSBarry Smith    See the <A href="../../docs/manual.pdf#nameddest=ch_mat">Mat chapter of the users manual</A> for details.
4150273d9f13SBarry Smith 
4151273d9f13SBarry Smith    The parallel matrix is partitioned such that the first m0 rows belong to
4152273d9f13SBarry Smith    process 0, the next m1 rows belong to process 1, the next m2 rows belong
4153273d9f13SBarry Smith    to process 2 etc.. where m0,m1,m2... are the input parameter 'm'.
4154273d9f13SBarry Smith 
4155273d9f13SBarry Smith    The DIAGONAL portion of the local submatrix of a processor can be defined
4156a05b864aSJed Brown    as the submatrix which is obtained by extraction the part corresponding to
4157a05b864aSJed Brown    the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
4158a05b864aSJed Brown    first row that belongs to the processor, r2 is the last row belonging to
4159a05b864aSJed Brown    the this processor, and c1-c2 is range of indices of the local part of a
4160a05b864aSJed Brown    vector suitable for applying the matrix to.  This is an mxn matrix.  In the
4161a05b864aSJed Brown    common case of a square matrix, the row and column ranges are the same and
4162a05b864aSJed Brown    the DIAGONAL part is also square. The remaining portion of the local
4163a05b864aSJed Brown    submatrix (mxN) constitute the OFF-DIAGONAL portion.
4164273d9f13SBarry Smith 
4165273d9f13SBarry Smith    If o_nnz, d_nnz are specified, then o_nz, and d_nz are ignored.
4166273d9f13SBarry Smith 
4167aa95bbe8SBarry Smith    You can call MatGetInfo() to get information on how effective the preallocation was;
4168aa95bbe8SBarry Smith    for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
4169aa95bbe8SBarry Smith    You can also run with the option -info and look for messages with the string
4170aa95bbe8SBarry Smith    malloc in them to see if additional memory allocation was needed.
4171aa95bbe8SBarry Smith 
4172273d9f13SBarry Smith    Example usage:
4173273d9f13SBarry Smith 
4174273d9f13SBarry Smith    Consider the following 8x8 matrix with 34 non-zero values, that is
4175273d9f13SBarry Smith    assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4176273d9f13SBarry Smith    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4177273d9f13SBarry Smith    as follows:
4178273d9f13SBarry Smith 
4179273d9f13SBarry Smith .vb
4180273d9f13SBarry Smith             1  2  0  |  0  3  0  |  0  4
4181273d9f13SBarry Smith     Proc0   0  5  6  |  7  0  0  |  8  0
4182273d9f13SBarry Smith             9  0 10  | 11  0  0  | 12  0
4183273d9f13SBarry Smith     -------------------------------------
4184273d9f13SBarry Smith            13  0 14  | 15 16 17  |  0  0
4185273d9f13SBarry Smith     Proc1   0 18  0  | 19 20 21  |  0  0
4186273d9f13SBarry Smith             0  0  0  | 22 23  0  | 24  0
4187273d9f13SBarry Smith     -------------------------------------
4188273d9f13SBarry Smith     Proc2  25 26 27  |  0  0 28  | 29  0
4189273d9f13SBarry Smith            30  0  0  | 31 32 33  |  0 34
4190273d9f13SBarry Smith .ve
4191273d9f13SBarry Smith 
4192273d9f13SBarry Smith    This can be represented as a collection of submatrices as:
4193273d9f13SBarry Smith 
4194273d9f13SBarry Smith .vb
4195273d9f13SBarry Smith       A B C
4196273d9f13SBarry Smith       D E F
4197273d9f13SBarry Smith       G H I
4198273d9f13SBarry Smith .ve
4199273d9f13SBarry Smith 
4200273d9f13SBarry Smith    Where the submatrices A,B,C are owned by proc0, D,E,F are
4201273d9f13SBarry Smith    owned by proc1, G,H,I are owned by proc2.
4202273d9f13SBarry Smith 
4203273d9f13SBarry Smith    The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4204273d9f13SBarry Smith    The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4205273d9f13SBarry Smith    The 'M','N' parameters are 8,8, and have the same values on all procs.
4206273d9f13SBarry Smith 
4207273d9f13SBarry Smith    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4208273d9f13SBarry Smith    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4209273d9f13SBarry Smith    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4210273d9f13SBarry Smith    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4211273d9f13SBarry Smith    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
4212273d9f13SBarry Smith    matrix, ans [DF] as another SeqAIJ matrix.
4213273d9f13SBarry Smith 
4214273d9f13SBarry Smith    When d_nz, o_nz parameters are specified, d_nz storage elements are
4215273d9f13SBarry Smith    allocated for every row of the local diagonal submatrix, and o_nz
4216273d9f13SBarry Smith    storage locations are allocated for every row of the OFF-DIAGONAL submat.
4217273d9f13SBarry Smith    One way to choose d_nz and o_nz is to use the max nonzerors per local
4218273d9f13SBarry Smith    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4219273d9f13SBarry Smith    In this case, the values of d_nz,o_nz are:
4220273d9f13SBarry Smith .vb
4221273d9f13SBarry Smith      proc0 : dnz = 2, o_nz = 2
4222273d9f13SBarry Smith      proc1 : dnz = 3, o_nz = 2
4223273d9f13SBarry Smith      proc2 : dnz = 1, o_nz = 4
4224273d9f13SBarry Smith .ve
4225273d9f13SBarry Smith    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
4226273d9f13SBarry Smith    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4227273d9f13SBarry Smith    for proc3. i.e we are using 12+15+10=37 storage locations to store
4228273d9f13SBarry Smith    34 values.
4229273d9f13SBarry Smith 
4230273d9f13SBarry Smith    When d_nnz, o_nnz parameters are specified, the storage is specified
4231273d9f13SBarry Smith    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4232273d9f13SBarry Smith    In the above case the values for d_nnz,o_nnz are:
4233273d9f13SBarry Smith .vb
4234273d9f13SBarry Smith      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
4235273d9f13SBarry Smith      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
4236273d9f13SBarry Smith      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
4237273d9f13SBarry Smith .ve
4238273d9f13SBarry Smith    Here the space allocated is sum of all the above values i.e 34, and
4239273d9f13SBarry Smith    hence pre-allocation is perfect.
4240273d9f13SBarry Smith 
4241273d9f13SBarry Smith    Level: intermediate
4242273d9f13SBarry Smith 
4243273d9f13SBarry Smith .keywords: matrix, aij, compressed row, sparse, parallel
4244273d9f13SBarry Smith 
424569b1f4b7SBarry Smith .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatCreateAIJ(), MatMPIAIJSetPreallocationCSR(),
4246ab978733SBarry Smith           MPIAIJ, MatGetInfo(), PetscSplitOwnership()
4247273d9f13SBarry Smith @*/
42487087cfbeSBarry Smith PetscErrorCode  MatMPIAIJSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
4249273d9f13SBarry Smith {
42504ac538c5SBarry Smith   PetscErrorCode ierr;
4251273d9f13SBarry Smith 
4252273d9f13SBarry Smith   PetscFunctionBegin;
42536ba663aaSJed Brown   PetscValidHeaderSpecific(B,MAT_CLASSID,1);
42546ba663aaSJed Brown   PetscValidType(B,1);
42554ac538c5SBarry Smith   ierr = PetscTryMethod(B,"MatMPIAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,d_nz,d_nnz,o_nz,o_nnz));CHKERRQ(ierr);
4256273d9f13SBarry Smith   PetscFunctionReturn(0);
4257273d9f13SBarry Smith }
4258273d9f13SBarry Smith 
42594a2ae208SSatish Balay #undef __FUNCT__
42602fb0ec9aSBarry Smith #define __FUNCT__ "MatCreateMPIAIJWithArrays"
426158d36128SBarry Smith /*@
42622fb0ec9aSBarry Smith      MatCreateMPIAIJWithArrays - creates a MPI AIJ matrix using arrays that contain in standard
42632fb0ec9aSBarry Smith          CSR format the local rows.
42642fb0ec9aSBarry Smith 
42652fb0ec9aSBarry Smith    Collective on MPI_Comm
42662fb0ec9aSBarry Smith 
42672fb0ec9aSBarry Smith    Input Parameters:
42682fb0ec9aSBarry Smith +  comm - MPI communicator
42692fb0ec9aSBarry Smith .  m - number of local rows (Cannot be PETSC_DECIDE)
42702fb0ec9aSBarry Smith .  n - This value should be the same as the local size used in creating the
42712fb0ec9aSBarry Smith        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
42722fb0ec9aSBarry Smith        calculated if N is given) For square matrices n is almost always m.
42732fb0ec9aSBarry Smith .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
42742fb0ec9aSBarry Smith .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
42752fb0ec9aSBarry Smith .   i - row indices
42762fb0ec9aSBarry Smith .   j - column indices
42772fb0ec9aSBarry Smith -   a - matrix values
42782fb0ec9aSBarry Smith 
42792fb0ec9aSBarry Smith    Output Parameter:
42802fb0ec9aSBarry Smith .   mat - the matrix
428103bfb495SBarry Smith 
42822fb0ec9aSBarry Smith    Level: intermediate
42832fb0ec9aSBarry Smith 
42842fb0ec9aSBarry Smith    Notes:
42852fb0ec9aSBarry Smith        The i, j, and a arrays ARE copied by this routine into the internal format used by PETSc;
42862fb0ec9aSBarry Smith      thus you CANNOT change the matrix entries by changing the values of a[] after you have
42878d7a6e47SBarry Smith      called this routine. Use MatCreateMPIAIJWithSplitArrays() to avoid needing to copy the arrays.
42882fb0ec9aSBarry Smith 
428912251496SSatish Balay        The i and j indices are 0 based, and i indices are indices corresponding to the local j array.
429012251496SSatish Balay 
429112251496SSatish Balay        The format which is used for the sparse matrix input, is equivalent to a
429212251496SSatish Balay     row-major ordering.. i.e for the following matrix, the input data expected is
429312251496SSatish Balay     as shown:
429412251496SSatish Balay 
429512251496SSatish Balay         1 0 0
429612251496SSatish Balay         2 0 3     P0
429712251496SSatish Balay        -------
429812251496SSatish Balay         4 5 6     P1
429912251496SSatish Balay 
430012251496SSatish Balay      Process0 [P0]: rows_owned=[0,1]
430112251496SSatish Balay         i =  {0,1,3}  [size = nrow+1  = 2+1]
430212251496SSatish Balay         j =  {0,0,2}  [size = nz = 6]
430312251496SSatish Balay         v =  {1,2,3}  [size = nz = 6]
430412251496SSatish Balay 
430512251496SSatish Balay      Process1 [P1]: rows_owned=[2]
430612251496SSatish Balay         i =  {0,3}    [size = nrow+1  = 1+1]
430712251496SSatish Balay         j =  {0,1,2}  [size = nz = 6]
430812251496SSatish Balay         v =  {4,5,6}  [size = nz = 6]
43092fb0ec9aSBarry Smith 
43102fb0ec9aSBarry Smith .keywords: matrix, aij, compressed row, sparse, parallel
43112fb0ec9aSBarry Smith 
43122fb0ec9aSBarry Smith .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
431369b1f4b7SBarry Smith           MPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays()
43142fb0ec9aSBarry Smith @*/
43157087cfbeSBarry Smith PetscErrorCode  MatCreateMPIAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
43162fb0ec9aSBarry Smith {
43172fb0ec9aSBarry Smith   PetscErrorCode ierr;
43182fb0ec9aSBarry Smith 
43192fb0ec9aSBarry Smith   PetscFunctionBegin;
432069b1f4b7SBarry Smith   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4321e32f2f54SBarry Smith   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
43222fb0ec9aSBarry Smith   ierr = MatCreate(comm,mat);CHKERRQ(ierr);
4323d4146a68SBarry Smith   ierr = MatSetSizes(*mat,m,n,M,N);CHKERRQ(ierr);
4324a2f3521dSMark F. Adams   /* ierr = MatSetBlockSizes(M,bs,cbs);CHKERRQ(ierr); */
43252fb0ec9aSBarry Smith   ierr = MatSetType(*mat,MATMPIAIJ);CHKERRQ(ierr);
43262fb0ec9aSBarry Smith   ierr = MatMPIAIJSetPreallocationCSR(*mat,i,j,a);CHKERRQ(ierr);
43272fb0ec9aSBarry Smith   PetscFunctionReturn(0);
43282fb0ec9aSBarry Smith }
43292fb0ec9aSBarry Smith 
43302fb0ec9aSBarry Smith #undef __FUNCT__
433169b1f4b7SBarry Smith #define __FUNCT__ "MatCreateAIJ"
4332273d9f13SBarry Smith /*@C
433369b1f4b7SBarry Smith    MatCreateAIJ - Creates a sparse parallel matrix in AIJ format
4334273d9f13SBarry Smith    (the default parallel PETSc format).  For good matrix assembly performance
4335273d9f13SBarry Smith    the user should preallocate the matrix storage by setting the parameters
4336273d9f13SBarry Smith    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
4337273d9f13SBarry Smith    performance can be increased by more than a factor of 50.
4338273d9f13SBarry Smith 
4339273d9f13SBarry Smith    Collective on MPI_Comm
4340273d9f13SBarry Smith 
4341273d9f13SBarry Smith    Input Parameters:
4342273d9f13SBarry Smith +  comm - MPI communicator
4343273d9f13SBarry Smith .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
4344273d9f13SBarry Smith            This value should be the same as the local size used in creating the
4345273d9f13SBarry Smith            y vector for the matrix-vector product y = Ax.
4346273d9f13SBarry Smith .  n - This value should be the same as the local size used in creating the
4347273d9f13SBarry Smith        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4348273d9f13SBarry Smith        calculated if N is given) For square matrices n is almost always m.
4349273d9f13SBarry Smith .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4350273d9f13SBarry Smith .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4351273d9f13SBarry Smith .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4352273d9f13SBarry Smith            (same value is used for all local rows)
4353273d9f13SBarry Smith .  d_nnz - array containing the number of nonzeros in the various rows of the
4354273d9f13SBarry Smith            DIAGONAL portion of the local submatrix (possibly different for each row)
43550298fd71SBarry Smith            or NULL, if d_nz is used to specify the nonzero structure.
4356273d9f13SBarry Smith            The size of this array is equal to the number of local rows, i.e 'm'.
4357273d9f13SBarry Smith .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4358273d9f13SBarry Smith            submatrix (same value is used for all local rows).
4359273d9f13SBarry Smith -  o_nnz - array containing the number of nonzeros in the various rows of the
4360273d9f13SBarry Smith            OFF-DIAGONAL portion of the local submatrix (possibly different for
43610298fd71SBarry Smith            each row) or NULL, if o_nz is used to specify the nonzero
4362273d9f13SBarry Smith            structure. The size of this array is equal to the number
4363273d9f13SBarry Smith            of local rows, i.e 'm'.
4364273d9f13SBarry Smith 
4365273d9f13SBarry Smith    Output Parameter:
4366273d9f13SBarry Smith .  A - the matrix
4367273d9f13SBarry Smith 
4368175b88e8SBarry Smith    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
4369ae1d86c5SBarry Smith    MatXXXXSetPreallocation() paradgm instead of this routine directly.
4370175b88e8SBarry Smith    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]
4371175b88e8SBarry Smith 
4372273d9f13SBarry Smith    Notes:
437349a6f317SBarry Smith    If the *_nnz parameter is given then the *_nz parameter is ignored
437449a6f317SBarry Smith 
4375273d9f13SBarry Smith    m,n,M,N parameters specify the size of the matrix, and its partitioning across
4376273d9f13SBarry Smith    processors, while d_nz,d_nnz,o_nz,o_nnz parameters specify the approximate
4377273d9f13SBarry Smith    storage requirements for this matrix.
4378273d9f13SBarry Smith 
4379273d9f13SBarry Smith    If PETSC_DECIDE or  PETSC_DETERMINE is used for a particular argument on one
4380273d9f13SBarry Smith    processor than it must be used on all processors that share the object for
4381273d9f13SBarry Smith    that argument.
4382273d9f13SBarry Smith 
4383273d9f13SBarry Smith    The user MUST specify either the local or global matrix dimensions
4384273d9f13SBarry Smith    (possibly both).
4385273d9f13SBarry Smith 
438633a7c187SSatish Balay    The parallel matrix is partitioned across processors such that the
438733a7c187SSatish Balay    first m0 rows belong to process 0, the next m1 rows belong to
438833a7c187SSatish Balay    process 1, the next m2 rows belong to process 2 etc.. where
438933a7c187SSatish Balay    m0,m1,m2,.. are the input parameter 'm'. i.e each processor stores
439033a7c187SSatish Balay    values corresponding to [m x N] submatrix.
4391273d9f13SBarry Smith 
439233a7c187SSatish Balay    The columns are logically partitioned with the n0 columns belonging
439333a7c187SSatish Balay    to 0th partition, the next n1 columns belonging to the next
439433a7c187SSatish Balay    partition etc.. where n0,n1,n2... are the the input parameter 'n'.
439533a7c187SSatish Balay 
439633a7c187SSatish Balay    The DIAGONAL portion of the local submatrix on any given processor
439733a7c187SSatish Balay    is the submatrix corresponding to the rows and columns m,n
439833a7c187SSatish Balay    corresponding to the given processor. i.e diagonal matrix on
439933a7c187SSatish Balay    process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
440033a7c187SSatish Balay    etc. The remaining portion of the local submatrix [m x (N-n)]
440133a7c187SSatish Balay    constitute the OFF-DIAGONAL portion. The example below better
440233a7c187SSatish Balay    illustrates this concept.
440333a7c187SSatish Balay 
440433a7c187SSatish Balay    For a square global matrix we define each processor's diagonal portion
440533a7c187SSatish Balay    to be its local rows and the corresponding columns (a square submatrix);
440633a7c187SSatish Balay    each processor's off-diagonal portion encompasses the remainder of the
440733a7c187SSatish Balay    local matrix (a rectangular submatrix).
4408273d9f13SBarry Smith 
4409273d9f13SBarry Smith    If o_nnz, d_nnz are specified, then o_nz, and d_nz are ignored.
4410273d9f13SBarry Smith 
441197d05335SKris Buschelman    When calling this routine with a single process communicator, a matrix of
441297d05335SKris Buschelman    type SEQAIJ is returned.  If a matrix of type MPIAIJ is desired for this
441397d05335SKris Buschelman    type of communicator, use the construction mechanism:
441478102f6cSMatthew Knepley      MatCreate(...,&A); MatSetType(A,MATMPIAIJ); MatSetSizes(A, m,n,M,N); MatMPIAIJSetPreallocation(A,...);
441597d05335SKris Buschelman 
4416273d9f13SBarry Smith    By default, this format uses inodes (identical nodes) when possible.
4417273d9f13SBarry Smith    We search for consecutive rows with the same nonzero structure, thereby
4418273d9f13SBarry Smith    reusing matrix information to achieve increased efficiency.
4419273d9f13SBarry Smith 
4420273d9f13SBarry Smith    Options Database Keys:
4421923f20ffSKris Buschelman +  -mat_no_inode  - Do not use inodes
4422923f20ffSKris Buschelman .  -mat_inode_limit <limit> - Sets inode limit (max limit=5)
4423273d9f13SBarry Smith -  -mat_aij_oneindex - Internally use indexing starting at 1
4424273d9f13SBarry Smith         rather than 0.  Note that when calling MatSetValues(),
4425273d9f13SBarry Smith         the user still MUST index entries starting at 0!
4426273d9f13SBarry Smith 
4427273d9f13SBarry Smith 
4428273d9f13SBarry Smith    Example usage:
4429273d9f13SBarry Smith 
4430273d9f13SBarry Smith    Consider the following 8x8 matrix with 34 non-zero values, that is
4431273d9f13SBarry Smith    assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4432273d9f13SBarry Smith    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4433273d9f13SBarry Smith    as follows:
4434273d9f13SBarry Smith 
4435273d9f13SBarry Smith .vb
4436273d9f13SBarry Smith             1  2  0  |  0  3  0  |  0  4
4437273d9f13SBarry Smith     Proc0   0  5  6  |  7  0  0  |  8  0
4438273d9f13SBarry Smith             9  0 10  | 11  0  0  | 12  0
4439273d9f13SBarry Smith     -------------------------------------
4440273d9f13SBarry Smith            13  0 14  | 15 16 17  |  0  0
4441273d9f13SBarry Smith     Proc1   0 18  0  | 19 20 21  |  0  0
4442273d9f13SBarry Smith             0  0  0  | 22 23  0  | 24  0
4443273d9f13SBarry Smith     -------------------------------------
4444273d9f13SBarry Smith     Proc2  25 26 27  |  0  0 28  | 29  0
4445273d9f13SBarry Smith            30  0  0  | 31 32 33  |  0 34
4446273d9f13SBarry Smith .ve
4447273d9f13SBarry Smith 
4448273d9f13SBarry Smith    This can be represented as a collection of submatrices as:
4449273d9f13SBarry Smith 
4450273d9f13SBarry Smith .vb
4451273d9f13SBarry Smith       A B C
4452273d9f13SBarry Smith       D E F
4453273d9f13SBarry Smith       G H I
4454273d9f13SBarry Smith .ve
4455273d9f13SBarry Smith 
4456273d9f13SBarry Smith    Where the submatrices A,B,C are owned by proc0, D,E,F are
4457273d9f13SBarry Smith    owned by proc1, G,H,I are owned by proc2.
4458273d9f13SBarry Smith 
4459273d9f13SBarry Smith    The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4460273d9f13SBarry Smith    The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4461273d9f13SBarry Smith    The 'M','N' parameters are 8,8, and have the same values on all procs.
4462273d9f13SBarry Smith 
4463273d9f13SBarry Smith    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4464273d9f13SBarry Smith    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4465273d9f13SBarry Smith    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4466273d9f13SBarry Smith    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4467273d9f13SBarry Smith    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
4468273d9f13SBarry Smith    matrix, ans [DF] as another SeqAIJ matrix.
4469273d9f13SBarry Smith 
4470273d9f13SBarry Smith    When d_nz, o_nz parameters are specified, d_nz storage elements are
4471273d9f13SBarry Smith    allocated for every row of the local diagonal submatrix, and o_nz
4472273d9f13SBarry Smith    storage locations are allocated for every row of the OFF-DIAGONAL submat.
4473273d9f13SBarry Smith    One way to choose d_nz and o_nz is to use the max nonzerors per local
4474273d9f13SBarry Smith    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4475273d9f13SBarry Smith    In this case, the values of d_nz,o_nz are:
4476273d9f13SBarry Smith .vb
4477273d9f13SBarry Smith      proc0 : dnz = 2, o_nz = 2
4478273d9f13SBarry Smith      proc1 : dnz = 3, o_nz = 2
4479273d9f13SBarry Smith      proc2 : dnz = 1, o_nz = 4
4480273d9f13SBarry Smith .ve
4481273d9f13SBarry Smith    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
4482273d9f13SBarry Smith    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4483273d9f13SBarry Smith    for proc3. i.e we are using 12+15+10=37 storage locations to store
4484273d9f13SBarry Smith    34 values.
4485273d9f13SBarry Smith 
4486273d9f13SBarry Smith    When d_nnz, o_nnz parameters are specified, the storage is specified
4487273d9f13SBarry Smith    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4488273d9f13SBarry Smith    In the above case the values for d_nnz,o_nnz are:
4489273d9f13SBarry Smith .vb
4490273d9f13SBarry Smith      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
4491273d9f13SBarry Smith      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
4492273d9f13SBarry Smith      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
4493273d9f13SBarry Smith .ve
4494273d9f13SBarry Smith    Here the space allocated is sum of all the above values i.e 34, and
4495273d9f13SBarry Smith    hence pre-allocation is perfect.
4496273d9f13SBarry Smith 
4497273d9f13SBarry Smith    Level: intermediate
4498273d9f13SBarry Smith 
4499273d9f13SBarry Smith .keywords: matrix, aij, compressed row, sparse, parallel
4500273d9f13SBarry Smith 
4501ccd8e176SBarry Smith .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
45022fb0ec9aSBarry Smith           MPIAIJ, MatCreateMPIAIJWithArrays()
4503273d9f13SBarry Smith @*/
450469b1f4b7SBarry Smith PetscErrorCode  MatCreateAIJ(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[],Mat *A)
4505273d9f13SBarry Smith {
45066849ba73SBarry Smith   PetscErrorCode ierr;
4507b1d57f15SBarry Smith   PetscMPIInt    size;
4508273d9f13SBarry Smith 
4509273d9f13SBarry Smith   PetscFunctionBegin;
4510f69a0ea3SMatthew Knepley   ierr = MatCreate(comm,A);CHKERRQ(ierr);
4511f69a0ea3SMatthew Knepley   ierr = MatSetSizes(*A,m,n,M,N);CHKERRQ(ierr);
4512273d9f13SBarry Smith   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
4513273d9f13SBarry Smith   if (size > 1) {
4514273d9f13SBarry Smith     ierr = MatSetType(*A,MATMPIAIJ);CHKERRQ(ierr);
4515273d9f13SBarry Smith     ierr = MatMPIAIJSetPreallocation(*A,d_nz,d_nnz,o_nz,o_nnz);CHKERRQ(ierr);
4516273d9f13SBarry Smith   } else {
4517273d9f13SBarry Smith     ierr = MatSetType(*A,MATSEQAIJ);CHKERRQ(ierr);
4518273d9f13SBarry Smith     ierr = MatSeqAIJSetPreallocation(*A,d_nz,d_nnz);CHKERRQ(ierr);
4519273d9f13SBarry Smith   }
4520273d9f13SBarry Smith   PetscFunctionReturn(0);
4521273d9f13SBarry Smith }
4522195d93cdSBarry Smith 
45234a2ae208SSatish Balay #undef __FUNCT__
45244a2ae208SSatish Balay #define __FUNCT__ "MatMPIAIJGetSeqAIJ"
45259230625dSJed Brown PetscErrorCode  MatMPIAIJGetSeqAIJ(Mat A,Mat *Ad,Mat *Ao,const PetscInt *colmap[])
4526195d93cdSBarry Smith {
4527195d93cdSBarry Smith   Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
4528b1d57f15SBarry Smith 
4529195d93cdSBarry Smith   PetscFunctionBegin;
4530195d93cdSBarry Smith   *Ad     = a->A;
4531195d93cdSBarry Smith   *Ao     = a->B;
4532195d93cdSBarry Smith   *colmap = a->garray;
4533195d93cdSBarry Smith   PetscFunctionReturn(0);
4534195d93cdSBarry Smith }
4535a2243be0SBarry Smith 
4536a2243be0SBarry Smith #undef __FUNCT__
4537a2243be0SBarry Smith #define __FUNCT__ "MatSetColoring_MPIAIJ"
4538dfbe8321SBarry Smith PetscErrorCode MatSetColoring_MPIAIJ(Mat A,ISColoring coloring)
4539a2243be0SBarry Smith {
4540dfbe8321SBarry Smith   PetscErrorCode ierr;
4541b1d57f15SBarry Smith   PetscInt       i;
4542a2243be0SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
4543a2243be0SBarry Smith 
4544a2243be0SBarry Smith   PetscFunctionBegin;
45458ee2e534SBarry Smith   if (coloring->ctype == IS_COLORING_GLOBAL) {
454608b6dcc0SBarry Smith     ISColoringValue *allcolors,*colors;
4547a2243be0SBarry Smith     ISColoring      ocoloring;
4548a2243be0SBarry Smith 
4549a2243be0SBarry Smith     /* set coloring for diagonal portion */
4550a2243be0SBarry Smith     ierr = MatSetColoring_SeqAIJ(a->A,coloring);CHKERRQ(ierr);
4551a2243be0SBarry Smith 
4552a2243be0SBarry Smith     /* set coloring for off-diagonal portion */
4553ce94432eSBarry Smith     ierr = ISAllGatherColors(PetscObjectComm((PetscObject)A),coloring->n,coloring->colors,NULL,&allcolors);CHKERRQ(ierr);
4554d0f46423SBarry Smith     ierr = PetscMalloc((a->B->cmap->n+1)*sizeof(ISColoringValue),&colors);CHKERRQ(ierr);
4555d0f46423SBarry Smith     for (i=0; i<a->B->cmap->n; i++) {
4556a2243be0SBarry Smith       colors[i] = allcolors[a->garray[i]];
4557a2243be0SBarry Smith     }
4558a2243be0SBarry Smith     ierr = PetscFree(allcolors);CHKERRQ(ierr);
4559d0f46423SBarry Smith     ierr = ISColoringCreate(MPI_COMM_SELF,coloring->n,a->B->cmap->n,colors,&ocoloring);CHKERRQ(ierr);
4560a2243be0SBarry Smith     ierr = MatSetColoring_SeqAIJ(a->B,ocoloring);CHKERRQ(ierr);
45616bf464f9SBarry Smith     ierr = ISColoringDestroy(&ocoloring);CHKERRQ(ierr);
4562a2243be0SBarry Smith   } else if (coloring->ctype == IS_COLORING_GHOSTED) {
456308b6dcc0SBarry Smith     ISColoringValue *colors;
4564b1d57f15SBarry Smith     PetscInt        *larray;
4565a2243be0SBarry Smith     ISColoring      ocoloring;
4566a2243be0SBarry Smith 
4567a2243be0SBarry Smith     /* set coloring for diagonal portion */
4568d0f46423SBarry Smith     ierr = PetscMalloc((a->A->cmap->n+1)*sizeof(PetscInt),&larray);CHKERRQ(ierr);
4569d0f46423SBarry Smith     for (i=0; i<a->A->cmap->n; i++) {
4570d0f46423SBarry Smith       larray[i] = i + A->cmap->rstart;
4571a2243be0SBarry Smith     }
45720298fd71SBarry Smith     ierr = ISGlobalToLocalMappingApply(A->cmap->mapping,IS_GTOLM_MASK,a->A->cmap->n,larray,NULL,larray);CHKERRQ(ierr);
4573d0f46423SBarry Smith     ierr = PetscMalloc((a->A->cmap->n+1)*sizeof(ISColoringValue),&colors);CHKERRQ(ierr);
4574d0f46423SBarry Smith     for (i=0; i<a->A->cmap->n; i++) {
4575a2243be0SBarry Smith       colors[i] = coloring->colors[larray[i]];
4576a2243be0SBarry Smith     }
4577a2243be0SBarry Smith     ierr = PetscFree(larray);CHKERRQ(ierr);
4578d0f46423SBarry Smith     ierr = ISColoringCreate(PETSC_COMM_SELF,coloring->n,a->A->cmap->n,colors,&ocoloring);CHKERRQ(ierr);
4579a2243be0SBarry Smith     ierr = MatSetColoring_SeqAIJ(a->A,ocoloring);CHKERRQ(ierr);
45806bf464f9SBarry Smith     ierr = ISColoringDestroy(&ocoloring);CHKERRQ(ierr);
4581a2243be0SBarry Smith 
4582a2243be0SBarry Smith     /* set coloring for off-diagonal portion */
4583d0f46423SBarry Smith     ierr = PetscMalloc((a->B->cmap->n+1)*sizeof(PetscInt),&larray);CHKERRQ(ierr);
45840298fd71SBarry Smith     ierr = ISGlobalToLocalMappingApply(A->cmap->mapping,IS_GTOLM_MASK,a->B->cmap->n,a->garray,NULL,larray);CHKERRQ(ierr);
4585d0f46423SBarry Smith     ierr = PetscMalloc((a->B->cmap->n+1)*sizeof(ISColoringValue),&colors);CHKERRQ(ierr);
4586d0f46423SBarry Smith     for (i=0; i<a->B->cmap->n; i++) {
4587a2243be0SBarry Smith       colors[i] = coloring->colors[larray[i]];
4588a2243be0SBarry Smith     }
4589a2243be0SBarry Smith     ierr = PetscFree(larray);CHKERRQ(ierr);
4590d0f46423SBarry Smith     ierr = ISColoringCreate(MPI_COMM_SELF,coloring->n,a->B->cmap->n,colors,&ocoloring);CHKERRQ(ierr);
4591a2243be0SBarry Smith     ierr = MatSetColoring_SeqAIJ(a->B,ocoloring);CHKERRQ(ierr);
45926bf464f9SBarry Smith     ierr = ISColoringDestroy(&ocoloring);CHKERRQ(ierr);
45936bf464f9SBarry Smith   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support ISColoringType %d",(int)coloring->ctype);
4594a2243be0SBarry Smith   PetscFunctionReturn(0);
4595a2243be0SBarry Smith }
4596a2243be0SBarry Smith 
4597779c1a83SBarry Smith #undef __FUNCT__
4598779c1a83SBarry Smith #define __FUNCT__ "MatSetValuesAdifor_MPIAIJ"
4599b1d57f15SBarry Smith PetscErrorCode MatSetValuesAdifor_MPIAIJ(Mat A,PetscInt nl,void *advalues)
4600779c1a83SBarry Smith {
4601779c1a83SBarry Smith   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
4602dfbe8321SBarry Smith   PetscErrorCode ierr;
4603779c1a83SBarry Smith 
4604779c1a83SBarry Smith   PetscFunctionBegin;
4605779c1a83SBarry Smith   ierr = MatSetValuesAdifor_SeqAIJ(a->A,nl,advalues);CHKERRQ(ierr);
4606779c1a83SBarry Smith   ierr = MatSetValuesAdifor_SeqAIJ(a->B,nl,advalues);CHKERRQ(ierr);
4607a2243be0SBarry Smith   PetscFunctionReturn(0);
4608a2243be0SBarry Smith }
4609c5d6d63eSBarry Smith 
4610c5d6d63eSBarry Smith #undef __FUNCT__
461190431a8fSHong Zhang #define __FUNCT__ "MatCreateMPIAIJConcatenateSeqAIJSymbolic"
461290431a8fSHong Zhang PetscErrorCode  MatCreateMPIAIJConcatenateSeqAIJSymbolic(MPI_Comm comm,Mat inmat,PetscInt n,Mat *outmat)
46139b8102ccSHong Zhang {
46149b8102ccSHong Zhang   PetscErrorCode ierr;
4615a2f3521dSMark F. Adams   PetscInt       m,N,i,rstart,nnz,*dnz,*onz,sum,bs,cbs;
46169b8102ccSHong Zhang   PetscInt       *indx;
46179b8102ccSHong Zhang 
46189b8102ccSHong Zhang   PetscFunctionBegin;
46199b8102ccSHong Zhang   /* This routine will ONLY return MPIAIJ type matrix */
46209b8102ccSHong Zhang   ierr = MatGetSize(inmat,&m,&N);CHKERRQ(ierr);
4621a2f3521dSMark F. Adams   ierr = MatGetBlockSizes(inmat,&bs,&cbs);CHKERRQ(ierr);
46229b8102ccSHong Zhang   if (n == PETSC_DECIDE) {
46239b8102ccSHong Zhang     ierr = PetscSplitOwnership(comm,&n,&N);CHKERRQ(ierr);
46249b8102ccSHong Zhang   }
4625a22543b6SHong Zhang   /* Check sum(n) = N */
4626a95133b1SBarry Smith   ierr = MPI_Allreduce(&n,&sum,1,MPIU_INT,MPI_SUM,comm);CHKERRQ(ierr);
4627a22543b6SHong Zhang   if (sum != N) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Sum of local columns != global columns %d",N);
4628a22543b6SHong Zhang 
46299b8102ccSHong Zhang   ierr    = MPI_Scan(&m, &rstart,1,MPIU_INT,MPI_SUM,comm);CHKERRQ(ierr);
46309b8102ccSHong Zhang   rstart -= m;
46319b8102ccSHong Zhang 
46329b8102ccSHong Zhang   ierr = MatPreallocateInitialize(comm,m,n,dnz,onz);CHKERRQ(ierr);
46339b8102ccSHong Zhang   for (i=0; i<m; i++) {
46340298fd71SBarry Smith     ierr = MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);CHKERRQ(ierr);
46359b8102ccSHong Zhang     ierr = MatPreallocateSet(i+rstart,nnz,indx,dnz,onz);CHKERRQ(ierr);
46360298fd71SBarry Smith     ierr = MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);CHKERRQ(ierr);
46379b8102ccSHong Zhang   }
46389b8102ccSHong Zhang 
46399b8102ccSHong Zhang   ierr = MatCreate(comm,outmat);CHKERRQ(ierr);
46409b8102ccSHong Zhang   ierr = MatSetSizes(*outmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);CHKERRQ(ierr);
4641a2f3521dSMark F. Adams   ierr = MatSetBlockSizes(*outmat,bs,cbs);CHKERRQ(ierr);
46429b8102ccSHong Zhang   ierr = MatSetType(*outmat,MATMPIAIJ);CHKERRQ(ierr);
46439b8102ccSHong Zhang   ierr = MatMPIAIJSetPreallocation(*outmat,0,dnz,0,onz);CHKERRQ(ierr);
46449b8102ccSHong Zhang   ierr = MatPreallocateFinalize(dnz,onz);CHKERRQ(ierr);
46459b8102ccSHong Zhang   PetscFunctionReturn(0);
46469b8102ccSHong Zhang }
46479b8102ccSHong Zhang 
46489b8102ccSHong Zhang #undef __FUNCT__
464990431a8fSHong Zhang #define __FUNCT__ "MatCreateMPIAIJConcatenateSeqAIJNumeric"
465090431a8fSHong Zhang PetscErrorCode  MatCreateMPIAIJConcatenateSeqAIJNumeric(MPI_Comm comm,Mat inmat,PetscInt n,Mat outmat)
46519b8102ccSHong Zhang {
46529b8102ccSHong Zhang   PetscErrorCode ierr;
46539b8102ccSHong Zhang   PetscInt       m,N,i,rstart,nnz,Ii;
46549b8102ccSHong Zhang   PetscInt       *indx;
46559b8102ccSHong Zhang   PetscScalar    *values;
46569b8102ccSHong Zhang 
46579b8102ccSHong Zhang   PetscFunctionBegin;
46589b8102ccSHong Zhang   ierr = MatGetSize(inmat,&m,&N);CHKERRQ(ierr);
46590298fd71SBarry Smith   ierr = MatGetOwnershipRange(outmat,&rstart,NULL);CHKERRQ(ierr);
46609b8102ccSHong Zhang   for (i=0; i<m; i++) {
46619b8102ccSHong Zhang     ierr = MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,&values);CHKERRQ(ierr);
46629b8102ccSHong Zhang     Ii   = i + rstart;
46633c79b8e7SHong Zhang     ierr = MatSetValues(outmat,1,&Ii,nnz,indx,values,INSERT_VALUES);CHKERRQ(ierr);
46649b8102ccSHong Zhang     ierr = MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,&values);CHKERRQ(ierr);
46659b8102ccSHong Zhang   }
46669b8102ccSHong Zhang   ierr = MatAssemblyBegin(outmat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
46679b8102ccSHong Zhang   ierr = MatAssemblyEnd(outmat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
46689b8102ccSHong Zhang   PetscFunctionReturn(0);
46699b8102ccSHong Zhang }
46709b8102ccSHong Zhang 
46719b8102ccSHong Zhang #undef __FUNCT__
467290431a8fSHong Zhang #define __FUNCT__ "MatCreateMPIAIJConcatenateSeqAIJ"
4673bc08b0f1SBarry Smith /*@
467490431a8fSHong Zhang       MatCreateMPIAIJConcatenateSeqAIJ - Creates a single large PETSc matrix by concatenating sequential
467551dd7536SBarry Smith                  matrices from each processor
4676c5d6d63eSBarry Smith 
4677c5d6d63eSBarry Smith     Collective on MPI_Comm
4678c5d6d63eSBarry Smith 
4679c5d6d63eSBarry Smith    Input Parameters:
468051dd7536SBarry Smith +    comm - the communicators the parallel matrix will live on
4681d6bb3c2dSHong Zhang .    inmat - the input sequential matrices
46820e36024fSHong Zhang .    n - number of local columns (or PETSC_DECIDE)
4683d6bb3c2dSHong Zhang -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
468451dd7536SBarry Smith 
468551dd7536SBarry Smith    Output Parameter:
468651dd7536SBarry Smith .    outmat - the parallel matrix generated
4687c5d6d63eSBarry Smith 
46887e25d530SSatish Balay     Level: advanced
46897e25d530SSatish Balay 
4690f08fae4eSHong Zhang    Notes: The number of columns of the matrix in EACH processor MUST be the same.
4691c5d6d63eSBarry Smith 
4692c5d6d63eSBarry Smith @*/
469390431a8fSHong Zhang PetscErrorCode  MatCreateMPIAIJConcatenateSeqAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
4694c5d6d63eSBarry Smith {
4695dfbe8321SBarry Smith   PetscErrorCode ierr;
4696c5d6d63eSBarry Smith 
4697c5d6d63eSBarry Smith   PetscFunctionBegin;
46989b8102ccSHong Zhang   ierr = PetscLogEventBegin(MAT_Merge,inmat,0,0,0);CHKERRQ(ierr);
4699d6bb3c2dSHong Zhang   if (scall == MAT_INITIAL_MATRIX) {
470090431a8fSHong Zhang     ierr = MatCreateMPIAIJConcatenateSeqAIJSymbolic(comm,inmat,n,outmat);CHKERRQ(ierr);
47010e36024fSHong Zhang   }
470290431a8fSHong Zhang   ierr = MatCreateMPIAIJConcatenateSeqAIJNumeric(comm,inmat,n,*outmat);CHKERRQ(ierr);
47039b8102ccSHong Zhang   ierr = PetscLogEventEnd(MAT_Merge,inmat,0,0,0);CHKERRQ(ierr);
4704c5d6d63eSBarry Smith   PetscFunctionReturn(0);
4705c5d6d63eSBarry Smith }
4706c5d6d63eSBarry Smith 
4707c5d6d63eSBarry Smith #undef __FUNCT__
4708c5d6d63eSBarry Smith #define __FUNCT__ "MatFileSplit"
4709dfbe8321SBarry Smith PetscErrorCode MatFileSplit(Mat A,char *outfile)
4710c5d6d63eSBarry Smith {
4711dfbe8321SBarry Smith   PetscErrorCode    ierr;
471232dcc486SBarry Smith   PetscMPIInt       rank;
4713b1d57f15SBarry Smith   PetscInt          m,N,i,rstart,nnz;
4714de4209c5SBarry Smith   size_t            len;
4715b1d57f15SBarry Smith   const PetscInt    *indx;
4716c5d6d63eSBarry Smith   PetscViewer       out;
4717c5d6d63eSBarry Smith   char              *name;
4718c5d6d63eSBarry Smith   Mat               B;
4719b3cc6726SBarry Smith   const PetscScalar *values;
4720c5d6d63eSBarry Smith 
4721c5d6d63eSBarry Smith   PetscFunctionBegin;
4722c5d6d63eSBarry Smith   ierr = MatGetLocalSize(A,&m,0);CHKERRQ(ierr);
4723c5d6d63eSBarry Smith   ierr = MatGetSize(A,0,&N);CHKERRQ(ierr);
4724f204ca49SKris Buschelman   /* Should this be the type of the diagonal block of A? */
4725f69a0ea3SMatthew Knepley   ierr = MatCreate(PETSC_COMM_SELF,&B);CHKERRQ(ierr);
4726f69a0ea3SMatthew Knepley   ierr = MatSetSizes(B,m,N,m,N);CHKERRQ(ierr);
4727a2f3521dSMark F. Adams   ierr = MatSetBlockSizes(B,A->rmap->bs,A->cmap->bs);CHKERRQ(ierr);
4728f204ca49SKris Buschelman   ierr = MatSetType(B,MATSEQAIJ);CHKERRQ(ierr);
47290298fd71SBarry Smith   ierr = MatSeqAIJSetPreallocation(B,0,NULL);CHKERRQ(ierr);
4730c5d6d63eSBarry Smith   ierr = MatGetOwnershipRange(A,&rstart,0);CHKERRQ(ierr);
4731c5d6d63eSBarry Smith   for (i=0; i<m; i++) {
4732c5d6d63eSBarry Smith     ierr = MatGetRow(A,i+rstart,&nnz,&indx,&values);CHKERRQ(ierr);
4733c5d6d63eSBarry Smith     ierr = MatSetValues(B,1,&i,nnz,indx,values,INSERT_VALUES);CHKERRQ(ierr);
4734c5d6d63eSBarry Smith     ierr = MatRestoreRow(A,i+rstart,&nnz,&indx,&values);CHKERRQ(ierr);
4735c5d6d63eSBarry Smith   }
4736c5d6d63eSBarry Smith   ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4737c5d6d63eSBarry Smith   ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
4738c5d6d63eSBarry Smith 
4739ce94432eSBarry Smith   ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);CHKERRQ(ierr);
4740c5d6d63eSBarry Smith   ierr = PetscStrlen(outfile,&len);CHKERRQ(ierr);
4741c5d6d63eSBarry Smith   ierr = PetscMalloc((len+5)*sizeof(char),&name);CHKERRQ(ierr);
4742c5d6d63eSBarry Smith   sprintf(name,"%s.%d",outfile,rank);
4743852598b0SBarry Smith   ierr = PetscViewerBinaryOpen(PETSC_COMM_SELF,name,FILE_MODE_APPEND,&out);CHKERRQ(ierr);
4744a2ea699eSBarry Smith   ierr = PetscFree(name);CHKERRQ(ierr);
4745c5d6d63eSBarry Smith   ierr = MatView(B,out);CHKERRQ(ierr);
47466bf464f9SBarry Smith   ierr = PetscViewerDestroy(&out);CHKERRQ(ierr);
47476bf464f9SBarry Smith   ierr = MatDestroy(&B);CHKERRQ(ierr);
4748c5d6d63eSBarry Smith   PetscFunctionReturn(0);
4749c5d6d63eSBarry Smith }
4750e5f2cdd8SHong Zhang 
475109573ac7SBarry Smith extern PetscErrorCode MatDestroy_MPIAIJ(Mat);
475251a7d1a8SHong Zhang #undef __FUNCT__
475351a7d1a8SHong Zhang #define __FUNCT__ "MatDestroy_MPIAIJ_SeqsToMPI"
47547087cfbeSBarry Smith PetscErrorCode  MatDestroy_MPIAIJ_SeqsToMPI(Mat A)
475551a7d1a8SHong Zhang {
475651a7d1a8SHong Zhang   PetscErrorCode      ierr;
4757671beff6SHong Zhang   Mat_Merge_SeqsToMPI *merge;
4758776b82aeSLisandro Dalcin   PetscContainer      container;
475951a7d1a8SHong Zhang 
476051a7d1a8SHong Zhang   PetscFunctionBegin;
4761671beff6SHong Zhang   ierr = PetscObjectQuery((PetscObject)A,"MatMergeSeqsToMPI",(PetscObject*)&container);CHKERRQ(ierr);
4762671beff6SHong Zhang   if (container) {
4763776b82aeSLisandro Dalcin     ierr = PetscContainerGetPointer(container,(void**)&merge);CHKERRQ(ierr);
476451a7d1a8SHong Zhang     ierr = PetscFree(merge->id_r);CHKERRQ(ierr);
47653e06a4e6SHong Zhang     ierr = PetscFree(merge->len_s);CHKERRQ(ierr);
47663e06a4e6SHong Zhang     ierr = PetscFree(merge->len_r);CHKERRQ(ierr);
476751a7d1a8SHong Zhang     ierr = PetscFree(merge->bi);CHKERRQ(ierr);
476851a7d1a8SHong Zhang     ierr = PetscFree(merge->bj);CHKERRQ(ierr);
4769533163c2SBarry Smith     ierr = PetscFree(merge->buf_ri[0]);CHKERRQ(ierr);
477002c68681SHong Zhang     ierr = PetscFree(merge->buf_ri);CHKERRQ(ierr);
4771533163c2SBarry Smith     ierr = PetscFree(merge->buf_rj[0]);CHKERRQ(ierr);
477202c68681SHong Zhang     ierr = PetscFree(merge->buf_rj);CHKERRQ(ierr);
477305b42c5fSBarry Smith     ierr = PetscFree(merge->coi);CHKERRQ(ierr);
477405b42c5fSBarry Smith     ierr = PetscFree(merge->coj);CHKERRQ(ierr);
477505b42c5fSBarry Smith     ierr = PetscFree(merge->owners_co);CHKERRQ(ierr);
47766bf464f9SBarry Smith     ierr = PetscLayoutDestroy(&merge->rowmap);CHKERRQ(ierr);
4777bf0cc555SLisandro Dalcin     ierr = PetscFree(merge);CHKERRQ(ierr);
4778671beff6SHong Zhang     ierr = PetscObjectCompose((PetscObject)A,"MatMergeSeqsToMPI",0);CHKERRQ(ierr);
4779671beff6SHong Zhang   }
478051a7d1a8SHong Zhang   ierr = MatDestroy_MPIAIJ(A);CHKERRQ(ierr);
478151a7d1a8SHong Zhang   PetscFunctionReturn(0);
478251a7d1a8SHong Zhang }
478351a7d1a8SHong Zhang 
4784c6db04a5SJed Brown #include <../src/mat/utils/freespace.h>
4785c6db04a5SJed Brown #include <petscbt.h>
47864ebed01fSBarry Smith 
4787e5f2cdd8SHong Zhang #undef __FUNCT__
478890431a8fSHong Zhang #define __FUNCT__ "MatCreateMPIAIJSumSeqAIJNumeric"
478990431a8fSHong Zhang PetscErrorCode  MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat,Mat mpimat)
479055d1abb9SHong Zhang {
479155d1abb9SHong Zhang   PetscErrorCode      ierr;
4792ce94432eSBarry Smith   MPI_Comm            comm;
479355d1abb9SHong Zhang   Mat_SeqAIJ          *a  =(Mat_SeqAIJ*)seqmat->data;
4794b1d57f15SBarry Smith   PetscMPIInt         size,rank,taga,*len_s;
4795a2ea699eSBarry Smith   PetscInt            N=mpimat->cmap->N,i,j,*owners,*ai=a->i,*aj;
4796b1d57f15SBarry Smith   PetscInt            proc,m;
4797b1d57f15SBarry Smith   PetscInt            **buf_ri,**buf_rj;
4798b1d57f15SBarry Smith   PetscInt            k,anzi,*bj_i,*bi,*bj,arow,bnzi,nextaj;
4799b1d57f15SBarry Smith   PetscInt            nrows,**buf_ri_k,**nextrow,**nextai;
480055d1abb9SHong Zhang   MPI_Request         *s_waits,*r_waits;
480155d1abb9SHong Zhang   MPI_Status          *status;
4802a77337e4SBarry Smith   MatScalar           *aa=a->a;
4803dd6ea824SBarry Smith   MatScalar           **abuf_r,*ba_i;
480455d1abb9SHong Zhang   Mat_Merge_SeqsToMPI *merge;
4805776b82aeSLisandro Dalcin   PetscContainer      container;
480655d1abb9SHong Zhang 
480755d1abb9SHong Zhang   PetscFunctionBegin;
4808bedda5b1SHong Zhang   ierr = PetscObjectGetComm((PetscObject)mpimat,&comm);CHKERRQ(ierr);
48094ebed01fSBarry Smith   ierr = PetscLogEventBegin(MAT_Seqstompinum,seqmat,0,0,0);CHKERRQ(ierr);
48103c2c1871SHong Zhang 
481155d1abb9SHong Zhang   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
481255d1abb9SHong Zhang   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
481355d1abb9SHong Zhang 
481455d1abb9SHong Zhang   ierr = PetscObjectQuery((PetscObject)mpimat,"MatMergeSeqsToMPI",(PetscObject*)&container);CHKERRQ(ierr);
4815776b82aeSLisandro Dalcin   ierr = PetscContainerGetPointer(container,(void**)&merge);CHKERRQ(ierr);
4816bf0cc555SLisandro Dalcin 
481755d1abb9SHong Zhang   bi     = merge->bi;
481855d1abb9SHong Zhang   bj     = merge->bj;
481955d1abb9SHong Zhang   buf_ri = merge->buf_ri;
482055d1abb9SHong Zhang   buf_rj = merge->buf_rj;
482155d1abb9SHong Zhang 
482255d1abb9SHong Zhang   ierr   = PetscMalloc(size*sizeof(MPI_Status),&status);CHKERRQ(ierr);
48237a2fc3feSBarry Smith   owners = merge->rowmap->range;
482455d1abb9SHong Zhang   len_s  = merge->len_s;
482555d1abb9SHong Zhang 
482655d1abb9SHong Zhang   /* send and recv matrix values */
482755d1abb9SHong Zhang   /*-----------------------------*/
4828357abbc8SBarry Smith   ierr = PetscObjectGetNewTag((PetscObject)mpimat,&taga);CHKERRQ(ierr);
482955d1abb9SHong Zhang   ierr = PetscPostIrecvScalar(comm,taga,merge->nrecv,merge->id_r,merge->len_r,&abuf_r,&r_waits);CHKERRQ(ierr);
483055d1abb9SHong Zhang 
483155d1abb9SHong Zhang   ierr = PetscMalloc((merge->nsend+1)*sizeof(MPI_Request),&s_waits);CHKERRQ(ierr);
483255d1abb9SHong Zhang   for (proc=0,k=0; proc<size; proc++) {
483355d1abb9SHong Zhang     if (!len_s[proc]) continue;
483455d1abb9SHong Zhang     i    = owners[proc];
483555d1abb9SHong Zhang     ierr = MPI_Isend(aa+ai[i],len_s[proc],MPIU_MATSCALAR,proc,taga,comm,s_waits+k);CHKERRQ(ierr);
483655d1abb9SHong Zhang     k++;
483755d1abb9SHong Zhang   }
483855d1abb9SHong Zhang 
48390c468ba9SBarry Smith   if (merge->nrecv) {ierr = MPI_Waitall(merge->nrecv,r_waits,status);CHKERRQ(ierr);}
48400c468ba9SBarry Smith   if (merge->nsend) {ierr = MPI_Waitall(merge->nsend,s_waits,status);CHKERRQ(ierr);}
484155d1abb9SHong Zhang   ierr = PetscFree(status);CHKERRQ(ierr);
484255d1abb9SHong Zhang 
484355d1abb9SHong Zhang   ierr = PetscFree(s_waits);CHKERRQ(ierr);
484455d1abb9SHong Zhang   ierr = PetscFree(r_waits);CHKERRQ(ierr);
484555d1abb9SHong Zhang 
484655d1abb9SHong Zhang   /* insert mat values of mpimat */
484755d1abb9SHong Zhang   /*----------------------------*/
4848a77337e4SBarry Smith   ierr = PetscMalloc(N*sizeof(PetscScalar),&ba_i);CHKERRQ(ierr);
48490572522cSBarry Smith   ierr = PetscMalloc3(merge->nrecv,PetscInt*,&buf_ri_k,merge->nrecv,PetscInt*,&nextrow,merge->nrecv,PetscInt*,&nextai);CHKERRQ(ierr);
485055d1abb9SHong Zhang 
485155d1abb9SHong Zhang   for (k=0; k<merge->nrecv; k++) {
485255d1abb9SHong Zhang     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
485355d1abb9SHong Zhang     nrows       = *(buf_ri_k[k]);
485455d1abb9SHong Zhang     nextrow[k]  = buf_ri_k[k]+1;  /* next row number of k-th recved i-structure */
485555d1abb9SHong Zhang     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
485655d1abb9SHong Zhang   }
485755d1abb9SHong Zhang 
485855d1abb9SHong Zhang   /* set values of ba */
48597a2fc3feSBarry Smith   m = merge->rowmap->n;
486055d1abb9SHong Zhang   for (i=0; i<m; i++) {
486155d1abb9SHong Zhang     arow = owners[rank] + i;
486255d1abb9SHong Zhang     bj_i = bj+bi[i];  /* col indices of the i-th row of mpimat */
486355d1abb9SHong Zhang     bnzi = bi[i+1] - bi[i];
4864a77337e4SBarry Smith     ierr = PetscMemzero(ba_i,bnzi*sizeof(PetscScalar));CHKERRQ(ierr);
486555d1abb9SHong Zhang 
486655d1abb9SHong Zhang     /* add local non-zero vals of this proc's seqmat into ba */
486755d1abb9SHong Zhang     anzi   = ai[arow+1] - ai[arow];
486855d1abb9SHong Zhang     aj     = a->j + ai[arow];
486955d1abb9SHong Zhang     aa     = a->a + ai[arow];
487055d1abb9SHong Zhang     nextaj = 0;
487155d1abb9SHong Zhang     for (j=0; nextaj<anzi; j++) {
487255d1abb9SHong Zhang       if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
487355d1abb9SHong Zhang         ba_i[j] += aa[nextaj++];
487455d1abb9SHong Zhang       }
487555d1abb9SHong Zhang     }
487655d1abb9SHong Zhang 
487755d1abb9SHong Zhang     /* add received vals into ba */
487855d1abb9SHong Zhang     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
487955d1abb9SHong Zhang       /* i-th row */
488055d1abb9SHong Zhang       if (i == *nextrow[k]) {
488155d1abb9SHong Zhang         anzi   = *(nextai[k]+1) - *nextai[k];
488255d1abb9SHong Zhang         aj     = buf_rj[k] + *(nextai[k]);
488355d1abb9SHong Zhang         aa     = abuf_r[k] + *(nextai[k]);
488455d1abb9SHong Zhang         nextaj = 0;
488555d1abb9SHong Zhang         for (j=0; nextaj<anzi; j++) {
488655d1abb9SHong Zhang           if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
488755d1abb9SHong Zhang             ba_i[j] += aa[nextaj++];
488855d1abb9SHong Zhang           }
488955d1abb9SHong Zhang         }
489055d1abb9SHong Zhang         nextrow[k]++; nextai[k]++;
489155d1abb9SHong Zhang       }
489255d1abb9SHong Zhang     }
489355d1abb9SHong Zhang     ierr = MatSetValues(mpimat,1,&arow,bnzi,bj_i,ba_i,INSERT_VALUES);CHKERRQ(ierr);
489455d1abb9SHong Zhang   }
489555d1abb9SHong Zhang   ierr = MatAssemblyBegin(mpimat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
489655d1abb9SHong Zhang   ierr = MatAssemblyEnd(mpimat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
489755d1abb9SHong Zhang 
4898533163c2SBarry Smith   ierr = PetscFree(abuf_r[0]);CHKERRQ(ierr);
489955d1abb9SHong Zhang   ierr = PetscFree(abuf_r);CHKERRQ(ierr);
490055d1abb9SHong Zhang   ierr = PetscFree(ba_i);CHKERRQ(ierr);
49011d79065fSBarry Smith   ierr = PetscFree3(buf_ri_k,nextrow,nextai);CHKERRQ(ierr);
49024ebed01fSBarry Smith   ierr = PetscLogEventEnd(MAT_Seqstompinum,seqmat,0,0,0);CHKERRQ(ierr);
490355d1abb9SHong Zhang   PetscFunctionReturn(0);
490455d1abb9SHong Zhang }
490538f152feSBarry Smith 
49066bc0bbbfSBarry Smith extern PetscErrorCode  MatDestroy_MPIAIJ_SeqsToMPI(Mat);
49076bc0bbbfSBarry Smith 
490838f152feSBarry Smith #undef __FUNCT__
490990431a8fSHong Zhang #define __FUNCT__ "MatCreateMPIAIJSumSeqAIJSymbolic"
491090431a8fSHong Zhang PetscErrorCode  MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,Mat *mpimat)
4911e5f2cdd8SHong Zhang {
4912f08fae4eSHong Zhang   PetscErrorCode      ierr;
491355a3bba9SHong Zhang   Mat                 B_mpi;
4914c2234fe3SHong Zhang   Mat_SeqAIJ          *a=(Mat_SeqAIJ*)seqmat->data;
4915b1d57f15SBarry Smith   PetscMPIInt         size,rank,tagi,tagj,*len_s,*len_si,*len_ri;
4916b1d57f15SBarry Smith   PetscInt            **buf_rj,**buf_ri,**buf_ri_k;
4917d0f46423SBarry Smith   PetscInt            M=seqmat->rmap->n,N=seqmat->cmap->n,i,*owners,*ai=a->i,*aj=a->j;
4918a2f3521dSMark F. Adams   PetscInt            len,proc,*dnz,*onz,bs,cbs;
4919b1d57f15SBarry Smith   PetscInt            k,anzi,*bi,*bj,*lnk,nlnk,arow,bnzi,nspacedouble=0;
4920b1d57f15SBarry Smith   PetscInt            nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextai;
492155d1abb9SHong Zhang   MPI_Request         *si_waits,*sj_waits,*ri_waits,*rj_waits;
492258cb9c82SHong Zhang   MPI_Status          *status;
49230298fd71SBarry Smith   PetscFreeSpaceList  free_space=NULL,current_space=NULL;
4924be0fcf8dSHong Zhang   PetscBT             lnkbt;
492551a7d1a8SHong Zhang   Mat_Merge_SeqsToMPI *merge;
4926776b82aeSLisandro Dalcin   PetscContainer      container;
492702c68681SHong Zhang 
4928e5f2cdd8SHong Zhang   PetscFunctionBegin;
49294ebed01fSBarry Smith   ierr = PetscLogEventBegin(MAT_Seqstompisym,seqmat,0,0,0);CHKERRQ(ierr);
49303c2c1871SHong Zhang 
493138f152feSBarry Smith   /* make sure it is a PETSc comm */
49320298fd71SBarry Smith   ierr = PetscCommDuplicate(comm,&comm,NULL);CHKERRQ(ierr);
4933e5f2cdd8SHong Zhang   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
4934e5f2cdd8SHong Zhang   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
493555d1abb9SHong Zhang 
493651a7d1a8SHong Zhang   ierr = PetscNew(Mat_Merge_SeqsToMPI,&merge);CHKERRQ(ierr);
4937c2234fe3SHong Zhang   ierr = PetscMalloc(size*sizeof(MPI_Status),&status);CHKERRQ(ierr);
4938e5f2cdd8SHong Zhang 
49396abd8857SHong Zhang   /* determine row ownership */
4940f08fae4eSHong Zhang   /*---------------------------------------------------------*/
494126283091SBarry Smith   ierr = PetscLayoutCreate(comm,&merge->rowmap);CHKERRQ(ierr);
494226283091SBarry Smith   ierr = PetscLayoutSetLocalSize(merge->rowmap,m);CHKERRQ(ierr);
494326283091SBarry Smith   ierr = PetscLayoutSetSize(merge->rowmap,M);CHKERRQ(ierr);
494426283091SBarry Smith   ierr = PetscLayoutSetBlockSize(merge->rowmap,1);CHKERRQ(ierr);
494526283091SBarry Smith   ierr = PetscLayoutSetUp(merge->rowmap);CHKERRQ(ierr);
4946b1d57f15SBarry Smith   ierr = PetscMalloc(size*sizeof(PetscMPIInt),&len_si);CHKERRQ(ierr);
4947b1d57f15SBarry Smith   ierr = PetscMalloc(size*sizeof(PetscMPIInt),&merge->len_s);CHKERRQ(ierr);
494855d1abb9SHong Zhang 
49497a2fc3feSBarry Smith   m      = merge->rowmap->n;
49507a2fc3feSBarry Smith   owners = merge->rowmap->range;
49516abd8857SHong Zhang 
49526abd8857SHong Zhang   /* determine the number of messages to send, their lengths */
49536abd8857SHong Zhang   /*---------------------------------------------------------*/
49543e06a4e6SHong Zhang   len_s = merge->len_s;
495551a7d1a8SHong Zhang 
49562257cef7SHong Zhang   len          = 0; /* length of buf_si[] */
4957c2234fe3SHong Zhang   merge->nsend = 0;
4958409913e3SHong Zhang   for (proc=0; proc<size; proc++) {
49592257cef7SHong Zhang     len_si[proc] = 0;
49603e06a4e6SHong Zhang     if (proc == rank) {
49616abd8857SHong Zhang       len_s[proc] = 0;
49623e06a4e6SHong Zhang     } else {
496302c68681SHong Zhang       len_si[proc] = owners[proc+1] - owners[proc] + 1;
49643e06a4e6SHong Zhang       len_s[proc]  = ai[owners[proc+1]] - ai[owners[proc]]; /* num of rows to be sent to [proc] */
49653e06a4e6SHong Zhang     }
49663e06a4e6SHong Zhang     if (len_s[proc]) {
4967c2234fe3SHong Zhang       merge->nsend++;
49682257cef7SHong Zhang       nrows = 0;
49692257cef7SHong Zhang       for (i=owners[proc]; i<owners[proc+1]; i++) {
49702257cef7SHong Zhang         if (ai[i+1] > ai[i]) nrows++;
49712257cef7SHong Zhang       }
49722257cef7SHong Zhang       len_si[proc] = 2*(nrows+1);
49732257cef7SHong Zhang       len         += len_si[proc];
4974409913e3SHong Zhang     }
497558cb9c82SHong Zhang   }
4976409913e3SHong Zhang 
49772257cef7SHong Zhang   /* determine the number and length of messages to receive for ij-structure */
49782257cef7SHong Zhang   /*-------------------------------------------------------------------------*/
49790298fd71SBarry Smith   ierr = PetscGatherNumberOfMessages(comm,NULL,len_s,&merge->nrecv);CHKERRQ(ierr);
498055d1abb9SHong Zhang   ierr = PetscGatherMessageLengths2(comm,merge->nsend,merge->nrecv,len_s,len_si,&merge->id_r,&merge->len_r,&len_ri);CHKERRQ(ierr);
4981671beff6SHong Zhang 
49823e06a4e6SHong Zhang   /* post the Irecv of j-structure */
49833e06a4e6SHong Zhang   /*-------------------------------*/
49842c72b5baSSatish Balay   ierr = PetscCommGetNewTag(comm,&tagj);CHKERRQ(ierr);
49853e06a4e6SHong Zhang   ierr = PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rj_waits);CHKERRQ(ierr);
498602c68681SHong Zhang 
49873e06a4e6SHong Zhang   /* post the Isend of j-structure */
4988affca5deSHong Zhang   /*--------------------------------*/
49891d79065fSBarry Smith   ierr = PetscMalloc2(merge->nsend,MPI_Request,&si_waits,merge->nsend,MPI_Request,&sj_waits);CHKERRQ(ierr);
49903e06a4e6SHong Zhang 
49912257cef7SHong Zhang   for (proc=0, k=0; proc<size; proc++) {
4992409913e3SHong Zhang     if (!len_s[proc]) continue;
499302c68681SHong Zhang     i    = owners[proc];
4994b1d57f15SBarry Smith     ierr = MPI_Isend(aj+ai[i],len_s[proc],MPIU_INT,proc,tagj,comm,sj_waits+k);CHKERRQ(ierr);
499551a7d1a8SHong Zhang     k++;
499651a7d1a8SHong Zhang   }
499751a7d1a8SHong Zhang 
49983e06a4e6SHong Zhang   /* receives and sends of j-structure are complete */
49993e06a4e6SHong Zhang   /*------------------------------------------------*/
50000c468ba9SBarry Smith   if (merge->nrecv) {ierr = MPI_Waitall(merge->nrecv,rj_waits,status);CHKERRQ(ierr);}
50010c468ba9SBarry Smith   if (merge->nsend) {ierr = MPI_Waitall(merge->nsend,sj_waits,status);CHKERRQ(ierr);}
500202c68681SHong Zhang 
500302c68681SHong Zhang   /* send and recv i-structure */
500402c68681SHong Zhang   /*---------------------------*/
50052c72b5baSSatish Balay   ierr = PetscCommGetNewTag(comm,&tagi);CHKERRQ(ierr);
500602c68681SHong Zhang   ierr = PetscPostIrecvInt(comm,tagi,merge->nrecv,merge->id_r,len_ri,&buf_ri,&ri_waits);CHKERRQ(ierr);
500702c68681SHong Zhang 
5008b1d57f15SBarry Smith   ierr   = PetscMalloc((len+1)*sizeof(PetscInt),&buf_s);CHKERRQ(ierr);
50093e06a4e6SHong Zhang   buf_si = buf_s;  /* points to the beginning of k-th msg to be sent */
50102257cef7SHong Zhang   for (proc=0,k=0; proc<size; proc++) {
501102c68681SHong Zhang     if (!len_s[proc]) continue;
50123e06a4e6SHong Zhang     /* form outgoing message for i-structure:
50133e06a4e6SHong Zhang          buf_si[0]:                 nrows to be sent
50143e06a4e6SHong Zhang                [1:nrows]:           row index (global)
50153e06a4e6SHong Zhang                [nrows+1:2*nrows+1]: i-structure index
50163e06a4e6SHong Zhang     */
50173e06a4e6SHong Zhang     /*-------------------------------------------*/
50182257cef7SHong Zhang     nrows       = len_si[proc]/2 - 1;
50193e06a4e6SHong Zhang     buf_si_i    = buf_si + nrows+1;
50203e06a4e6SHong Zhang     buf_si[0]   = nrows;
50213e06a4e6SHong Zhang     buf_si_i[0] = 0;
50223e06a4e6SHong Zhang     nrows       = 0;
50233e06a4e6SHong Zhang     for (i=owners[proc]; i<owners[proc+1]; i++) {
50243e06a4e6SHong Zhang       anzi = ai[i+1] - ai[i];
50253e06a4e6SHong Zhang       if (anzi) {
50263e06a4e6SHong Zhang         buf_si_i[nrows+1] = buf_si_i[nrows] + anzi; /* i-structure */
50273e06a4e6SHong Zhang         buf_si[nrows+1]   = i-owners[proc]; /* local row index */
50283e06a4e6SHong Zhang         nrows++;
50293e06a4e6SHong Zhang       }
50303e06a4e6SHong Zhang     }
5031b1d57f15SBarry Smith     ierr = MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,si_waits+k);CHKERRQ(ierr);
503202c68681SHong Zhang     k++;
50332257cef7SHong Zhang     buf_si += len_si[proc];
503402c68681SHong Zhang   }
50352257cef7SHong Zhang 
50360c468ba9SBarry Smith   if (merge->nrecv) {ierr = MPI_Waitall(merge->nrecv,ri_waits,status);CHKERRQ(ierr);}
50370c468ba9SBarry Smith   if (merge->nsend) {ierr = MPI_Waitall(merge->nsend,si_waits,status);CHKERRQ(ierr);}
503802c68681SHong Zhang 
5039ae15b995SBarry Smith   ierr = PetscInfo2(seqmat,"nsend: %D, nrecv: %D\n",merge->nsend,merge->nrecv);CHKERRQ(ierr);
50403e06a4e6SHong Zhang   for (i=0; i<merge->nrecv; i++) {
5041ae15b995SBarry Smith     ierr = PetscInfo3(seqmat,"recv len_ri=%D, len_rj=%D from [%D]\n",len_ri[i],merge->len_r[i],merge->id_r[i]);CHKERRQ(ierr);
50423e06a4e6SHong Zhang   }
50433e06a4e6SHong Zhang 
50443e06a4e6SHong Zhang   ierr = PetscFree(len_si);CHKERRQ(ierr);
504502c68681SHong Zhang   ierr = PetscFree(len_ri);CHKERRQ(ierr);
504602c68681SHong Zhang   ierr = PetscFree(rj_waits);CHKERRQ(ierr);
50471d79065fSBarry Smith   ierr = PetscFree2(si_waits,sj_waits);CHKERRQ(ierr);
50482257cef7SHong Zhang   ierr = PetscFree(ri_waits);CHKERRQ(ierr);
50493e06a4e6SHong Zhang   ierr = PetscFree(buf_s);CHKERRQ(ierr);
5050bcc1bcd5SHong Zhang   ierr = PetscFree(status);CHKERRQ(ierr);
505158cb9c82SHong Zhang 
5052bcc1bcd5SHong Zhang   /* compute a local seq matrix in each processor */
5053bcc1bcd5SHong Zhang   /*----------------------------------------------*/
505458cb9c82SHong Zhang   /* allocate bi array and free space for accumulating nonzero column info */
5055b1d57f15SBarry Smith   ierr  = PetscMalloc((m+1)*sizeof(PetscInt),&bi);CHKERRQ(ierr);
505658cb9c82SHong Zhang   bi[0] = 0;
505758cb9c82SHong Zhang 
5058be0fcf8dSHong Zhang   /* create and initialize a linked list */
5059be0fcf8dSHong Zhang   nlnk = N+1;
5060be0fcf8dSHong Zhang   ierr = PetscLLCreate(N,N,nlnk,lnk,lnkbt);CHKERRQ(ierr);
506158cb9c82SHong Zhang 
5062bcc1bcd5SHong Zhang   /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
5063bcc1bcd5SHong Zhang   len  = ai[owners[rank+1]] - ai[owners[rank]];
5064a1a86e44SBarry Smith   ierr = PetscFreeSpaceGet((PetscInt)(2*len+1),&free_space);CHKERRQ(ierr);
50652205254eSKarl Rupp 
506658cb9c82SHong Zhang   current_space = free_space;
506758cb9c82SHong Zhang 
5068bcc1bcd5SHong Zhang   /* determine symbolic info for each local row */
50690572522cSBarry Smith   ierr = PetscMalloc3(merge->nrecv,PetscInt*,&buf_ri_k,merge->nrecv,PetscInt*,&nextrow,merge->nrecv,PetscInt*,&nextai);CHKERRQ(ierr);
50701d79065fSBarry Smith 
50713e06a4e6SHong Zhang   for (k=0; k<merge->nrecv; k++) {
50722257cef7SHong Zhang     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
50733e06a4e6SHong Zhang     nrows       = *buf_ri_k[k];
50743e06a4e6SHong Zhang     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
50752257cef7SHong Zhang     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
50763e06a4e6SHong Zhang   }
50772257cef7SHong Zhang 
5078bcc1bcd5SHong Zhang   ierr = MatPreallocateInitialize(comm,m,n,dnz,onz);CHKERRQ(ierr);
5079bcc1bcd5SHong Zhang   len  = 0;
508058cb9c82SHong Zhang   for (i=0; i<m; i++) {
508158cb9c82SHong Zhang     bnzi = 0;
508258cb9c82SHong Zhang     /* add local non-zero cols of this proc's seqmat into lnk */
508358cb9c82SHong Zhang     arow  = owners[rank] + i;
508458cb9c82SHong Zhang     anzi  = ai[arow+1] - ai[arow];
508558cb9c82SHong Zhang     aj    = a->j + ai[arow];
5086dadf0e6bSHong Zhang     ierr  = PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);CHKERRQ(ierr);
508758cb9c82SHong Zhang     bnzi += nlnk;
508858cb9c82SHong Zhang     /* add received col data into lnk */
508951a7d1a8SHong Zhang     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
509055d1abb9SHong Zhang       if (i == *nextrow[k]) { /* i-th row */
50913e06a4e6SHong Zhang         anzi  = *(nextai[k]+1) - *nextai[k];
50923e06a4e6SHong Zhang         aj    = buf_rj[k] + *nextai[k];
5093dadf0e6bSHong Zhang         ierr  = PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);CHKERRQ(ierr);
50943e06a4e6SHong Zhang         bnzi += nlnk;
50953e06a4e6SHong Zhang         nextrow[k]++; nextai[k]++;
50963e06a4e6SHong Zhang       }
509758cb9c82SHong Zhang     }
5098bcc1bcd5SHong Zhang     if (len < bnzi) len = bnzi;  /* =max(bnzi) */
509958cb9c82SHong Zhang 
510058cb9c82SHong Zhang     /* if free space is not available, make more free space */
510158cb9c82SHong Zhang     if (current_space->local_remaining<bnzi) {
51024238b7adSHong Zhang       ierr = PetscFreeSpaceGet(bnzi+current_space->total_array_size,&current_space);CHKERRQ(ierr);
510358cb9c82SHong Zhang       nspacedouble++;
510458cb9c82SHong Zhang     }
510558cb9c82SHong Zhang     /* copy data into free space, then initialize lnk */
5106be0fcf8dSHong Zhang     ierr = PetscLLClean(N,N,bnzi,lnk,current_space->array,lnkbt);CHKERRQ(ierr);
5107bcc1bcd5SHong Zhang     ierr = MatPreallocateSet(i+owners[rank],bnzi,current_space->array,dnz,onz);CHKERRQ(ierr);
5108bcc1bcd5SHong Zhang 
510958cb9c82SHong Zhang     current_space->array           += bnzi;
511058cb9c82SHong Zhang     current_space->local_used      += bnzi;
511158cb9c82SHong Zhang     current_space->local_remaining -= bnzi;
511258cb9c82SHong Zhang 
511358cb9c82SHong Zhang     bi[i+1] = bi[i] + bnzi;
511458cb9c82SHong Zhang   }
5115bcc1bcd5SHong Zhang 
51161d79065fSBarry Smith   ierr = PetscFree3(buf_ri_k,nextrow,nextai);CHKERRQ(ierr);
5117bcc1bcd5SHong Zhang 
5118b1d57f15SBarry Smith   ierr = PetscMalloc((bi[m]+1)*sizeof(PetscInt),&bj);CHKERRQ(ierr);
5119a1a86e44SBarry Smith   ierr = PetscFreeSpaceContiguous(&free_space,bj);CHKERRQ(ierr);
5120be0fcf8dSHong Zhang   ierr = PetscLLDestroy(lnk,lnkbt);CHKERRQ(ierr);
5121409913e3SHong Zhang 
5122bcc1bcd5SHong Zhang   /* create symbolic parallel matrix B_mpi */
5123bcc1bcd5SHong Zhang   /*---------------------------------------*/
5124a2f3521dSMark F. Adams   ierr = MatGetBlockSizes(seqmat,&bs,&cbs);CHKERRQ(ierr);
5125f69a0ea3SMatthew Knepley   ierr = MatCreate(comm,&B_mpi);CHKERRQ(ierr);
512654b84b50SHong Zhang   if (n==PETSC_DECIDE) {
5127f69a0ea3SMatthew Knepley     ierr = MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,N);CHKERRQ(ierr);
512854b84b50SHong Zhang   } else {
5129f69a0ea3SMatthew Knepley     ierr = MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,PETSC_DETERMINE);CHKERRQ(ierr);
513054b84b50SHong Zhang   }
5131a2f3521dSMark F. Adams   ierr = MatSetBlockSizes(B_mpi,bs,cbs);CHKERRQ(ierr);
5132bcc1bcd5SHong Zhang   ierr = MatSetType(B_mpi,MATMPIAIJ);CHKERRQ(ierr);
5133bcc1bcd5SHong Zhang   ierr = MatMPIAIJSetPreallocation(B_mpi,0,dnz,0,onz);CHKERRQ(ierr);
5134bcc1bcd5SHong Zhang   ierr = MatPreallocateFinalize(dnz,onz);CHKERRQ(ierr);
51357e63b356SHong Zhang   ierr = MatSetOption(B_mpi,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);CHKERRQ(ierr);
513658cb9c82SHong Zhang 
513790431a8fSHong Zhang   /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
51386abd8857SHong Zhang   B_mpi->assembled    = PETSC_FALSE;
5139affca5deSHong Zhang   B_mpi->ops->destroy = MatDestroy_MPIAIJ_SeqsToMPI;
5140affca5deSHong Zhang   merge->bi           = bi;
5141affca5deSHong Zhang   merge->bj           = bj;
514202c68681SHong Zhang   merge->buf_ri       = buf_ri;
514302c68681SHong Zhang   merge->buf_rj       = buf_rj;
51440298fd71SBarry Smith   merge->coi          = NULL;
51450298fd71SBarry Smith   merge->coj          = NULL;
51460298fd71SBarry Smith   merge->owners_co    = NULL;
5147affca5deSHong Zhang 
5148bf0cc555SLisandro Dalcin   ierr = PetscCommDestroy(&comm);CHKERRQ(ierr);
5149bf0cc555SLisandro Dalcin 
5150affca5deSHong Zhang   /* attach the supporting struct to B_mpi for reuse */
5151776b82aeSLisandro Dalcin   ierr    = PetscContainerCreate(PETSC_COMM_SELF,&container);CHKERRQ(ierr);
5152776b82aeSLisandro Dalcin   ierr    = PetscContainerSetPointer(container,merge);CHKERRQ(ierr);
5153affca5deSHong Zhang   ierr    = PetscObjectCompose((PetscObject)B_mpi,"MatMergeSeqsToMPI",(PetscObject)container);CHKERRQ(ierr);
5154bf0cc555SLisandro Dalcin   ierr    = PetscContainerDestroy(&container);CHKERRQ(ierr);
5155affca5deSHong Zhang   *mpimat = B_mpi;
515638f152feSBarry Smith 
51574ebed01fSBarry Smith   ierr = PetscLogEventEnd(MAT_Seqstompisym,seqmat,0,0,0);CHKERRQ(ierr);
5158e5f2cdd8SHong Zhang   PetscFunctionReturn(0);
5159e5f2cdd8SHong Zhang }
516025616d81SHong Zhang 
516138f152feSBarry Smith #undef __FUNCT__
516290431a8fSHong Zhang #define __FUNCT__ "MatCreateMPIAIJSumSeqAIJ"
5163d4036a1aSHong Zhang /*@C
516490431a8fSHong Zhang       MatCreateMPIAIJSumSeqAIJ - Creates a MPIAIJ matrix by adding sequential
5165d4036a1aSHong Zhang                  matrices from each processor
5166d4036a1aSHong Zhang 
5167d4036a1aSHong Zhang     Collective on MPI_Comm
5168d4036a1aSHong Zhang 
5169d4036a1aSHong Zhang    Input Parameters:
5170d4036a1aSHong Zhang +    comm - the communicators the parallel matrix will live on
5171d4036a1aSHong Zhang .    seqmat - the input sequential matrices
5172d4036a1aSHong Zhang .    m - number of local rows (or PETSC_DECIDE)
5173d4036a1aSHong Zhang .    n - number of local columns (or PETSC_DECIDE)
5174d4036a1aSHong Zhang -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
5175d4036a1aSHong Zhang 
5176d4036a1aSHong Zhang    Output Parameter:
5177d4036a1aSHong Zhang .    mpimat - the parallel matrix generated
5178d4036a1aSHong Zhang 
5179d4036a1aSHong Zhang     Level: advanced
5180d4036a1aSHong Zhang 
5181d4036a1aSHong Zhang    Notes:
5182d4036a1aSHong Zhang      The dimensions of the sequential matrix in each processor MUST be the same.
5183d4036a1aSHong Zhang      The input seqmat is included into the container "Mat_Merge_SeqsToMPI", and will be
5184d4036a1aSHong Zhang      destroyed when mpimat is destroyed. Call PetscObjectQuery() to access seqmat.
5185d4036a1aSHong Zhang @*/
518690431a8fSHong Zhang PetscErrorCode  MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,MatReuse scall,Mat *mpimat)
518755d1abb9SHong Zhang {
518855d1abb9SHong Zhang   PetscErrorCode ierr;
51897e63b356SHong Zhang   PetscMPIInt    size;
519055d1abb9SHong Zhang 
519155d1abb9SHong Zhang   PetscFunctionBegin;
51927e63b356SHong Zhang   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
51937e63b356SHong Zhang   if (size == 1) {
51947e63b356SHong Zhang     ierr = PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);CHKERRQ(ierr);
51957e63b356SHong Zhang     if (scall == MAT_INITIAL_MATRIX) {
51967e63b356SHong Zhang       ierr = MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);CHKERRQ(ierr);
51977e63b356SHong Zhang     } else {
51987e63b356SHong Zhang       ierr = MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
51997e63b356SHong Zhang     }
52007e63b356SHong Zhang     ierr = PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);CHKERRQ(ierr);
52017e63b356SHong Zhang     PetscFunctionReturn(0);
52027e63b356SHong Zhang   }
52034ebed01fSBarry Smith   ierr = PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);CHKERRQ(ierr);
520455d1abb9SHong Zhang   if (scall == MAT_INITIAL_MATRIX) {
520590431a8fSHong Zhang     ierr = MatCreateMPIAIJSumSeqAIJSymbolic(comm,seqmat,m,n,mpimat);CHKERRQ(ierr);
520655d1abb9SHong Zhang   }
520790431a8fSHong Zhang   ierr = MatCreateMPIAIJSumSeqAIJNumeric(seqmat,*mpimat);CHKERRQ(ierr);
52084ebed01fSBarry Smith   ierr = PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);CHKERRQ(ierr);
520955d1abb9SHong Zhang   PetscFunctionReturn(0);
521055d1abb9SHong Zhang }
52114ebed01fSBarry Smith 
521225616d81SHong Zhang #undef __FUNCT__
52134a2b5492SBarry Smith #define __FUNCT__ "MatMPIAIJGetLocalMat"
5214bc08b0f1SBarry Smith /*@
52154a2b5492SBarry Smith      MatMPIAIJGetLocalMat - Creates a SeqAIJ from a MPIAIJ matrix by taking all its local rows and putting them into a sequential vector with
52168661ff28SBarry Smith           mlocal rows and n columns. Where mlocal is the row count obtained with MatGetLocalSize() and n is the global column count obtained
52178661ff28SBarry Smith           with MatGetSize()
521825616d81SHong Zhang 
521932fba14fSHong Zhang     Not Collective
522025616d81SHong Zhang 
522125616d81SHong Zhang    Input Parameters:
522225616d81SHong Zhang +    A - the matrix
522325616d81SHong Zhang .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
522425616d81SHong Zhang 
522525616d81SHong Zhang    Output Parameter:
522625616d81SHong Zhang .    A_loc - the local sequential matrix generated
522725616d81SHong Zhang 
522825616d81SHong Zhang     Level: developer
522925616d81SHong Zhang 
5230ba264940SBarry Smith .seealso: MatGetOwnerShipRange(), MatMPIAIJGetLocalMatCondensed()
52318661ff28SBarry Smith 
523225616d81SHong Zhang @*/
52334a2b5492SBarry Smith PetscErrorCode  MatMPIAIJGetLocalMat(Mat A,MatReuse scall,Mat *A_loc)
523425616d81SHong Zhang {
523525616d81SHong Zhang   PetscErrorCode ierr;
523601b7ae99SHong Zhang   Mat_MPIAIJ     *mpimat=(Mat_MPIAIJ*)A->data;
523701b7ae99SHong Zhang   Mat_SeqAIJ     *mat,*a=(Mat_SeqAIJ*)(mpimat->A)->data,*b=(Mat_SeqAIJ*)(mpimat->B)->data;
523801b7ae99SHong Zhang   PetscInt       *ai=a->i,*aj=a->j,*bi=b->i,*bj=b->j,*cmap=mpimat->garray;
5239a77337e4SBarry Smith   MatScalar      *aa=a->a,*ba=b->a,*cam;
5240a77337e4SBarry Smith   PetscScalar    *ca;
5241d0f46423SBarry Smith   PetscInt       am=A->rmap->n,i,j,k,cstart=A->cmap->rstart;
52425a7d977cSHong Zhang   PetscInt       *ci,*cj,col,ncols_d,ncols_o,jo;
52438661ff28SBarry Smith   PetscBool      match;
524425616d81SHong Zhang 
524525616d81SHong Zhang   PetscFunctionBegin;
5246251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);CHKERRQ(ierr);
5247ce94432eSBarry Smith   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MPIAIJ matrix as input");
52484ebed01fSBarry Smith   ierr = PetscLogEventBegin(MAT_Getlocalmat,A,0,0,0);CHKERRQ(ierr);
524901b7ae99SHong Zhang   if (scall == MAT_INITIAL_MATRIX) {
5250dea91ad1SHong Zhang     ierr  = PetscMalloc((1+am)*sizeof(PetscInt),&ci);CHKERRQ(ierr);
5251dea91ad1SHong Zhang     ci[0] = 0;
525201b7ae99SHong Zhang     for (i=0; i<am; i++) {
5253dea91ad1SHong Zhang       ci[i+1] = ci[i] + (ai[i+1] - ai[i]) + (bi[i+1] - bi[i]);
525401b7ae99SHong Zhang     }
5255dea91ad1SHong Zhang     ierr = PetscMalloc((1+ci[am])*sizeof(PetscInt),&cj);CHKERRQ(ierr);
5256dea91ad1SHong Zhang     ierr = PetscMalloc((1+ci[am])*sizeof(PetscScalar),&ca);CHKERRQ(ierr);
5257dea91ad1SHong Zhang     k    = 0;
525801b7ae99SHong Zhang     for (i=0; i<am; i++) {
52595a7d977cSHong Zhang       ncols_o = bi[i+1] - bi[i];
52605a7d977cSHong Zhang       ncols_d = ai[i+1] - ai[i];
526101b7ae99SHong Zhang       /* off-diagonal portion of A */
52625a7d977cSHong Zhang       for (jo=0; jo<ncols_o; jo++) {
52635a7d977cSHong Zhang         col = cmap[*bj];
52645a7d977cSHong Zhang         if (col >= cstart) break;
52655a7d977cSHong Zhang         cj[k]   = col; bj++;
52665a7d977cSHong Zhang         ca[k++] = *ba++;
52675a7d977cSHong Zhang       }
52685a7d977cSHong Zhang       /* diagonal portion of A */
52695a7d977cSHong Zhang       for (j=0; j<ncols_d; j++) {
52705a7d977cSHong Zhang         cj[k]   = cstart + *aj++;
52715a7d977cSHong Zhang         ca[k++] = *aa++;
52725a7d977cSHong Zhang       }
52735a7d977cSHong Zhang       /* off-diagonal portion of A */
52745a7d977cSHong Zhang       for (j=jo; j<ncols_o; j++) {
52755a7d977cSHong Zhang         cj[k]   = cmap[*bj++];
52765a7d977cSHong Zhang         ca[k++] = *ba++;
52775a7d977cSHong Zhang       }
527825616d81SHong Zhang     }
5279dea91ad1SHong Zhang     /* put together the new matrix */
5280d0f46423SBarry Smith     ierr = MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ci,cj,ca,A_loc);CHKERRQ(ierr);
5281dea91ad1SHong Zhang     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5282dea91ad1SHong Zhang     /* Since these are PETSc arrays, change flags to free them as necessary. */
5283dea91ad1SHong Zhang     mat          = (Mat_SeqAIJ*)(*A_loc)->data;
5284e6b907acSBarry Smith     mat->free_a  = PETSC_TRUE;
5285e6b907acSBarry Smith     mat->free_ij = PETSC_TRUE;
5286dea91ad1SHong Zhang     mat->nonew   = 0;
52875a7d977cSHong Zhang   } else if (scall == MAT_REUSE_MATRIX) {
52885a7d977cSHong Zhang     mat=(Mat_SeqAIJ*)(*A_loc)->data;
5289a77337e4SBarry Smith     ci = mat->i; cj = mat->j; cam = mat->a;
52905a7d977cSHong Zhang     for (i=0; i<am; i++) {
52915a7d977cSHong Zhang       /* off-diagonal portion of A */
52925a7d977cSHong Zhang       ncols_o = bi[i+1] - bi[i];
52935a7d977cSHong Zhang       for (jo=0; jo<ncols_o; jo++) {
52945a7d977cSHong Zhang         col = cmap[*bj];
52955a7d977cSHong Zhang         if (col >= cstart) break;
5296a77337e4SBarry Smith         *cam++ = *ba++; bj++;
52975a7d977cSHong Zhang       }
52985a7d977cSHong Zhang       /* diagonal portion of A */
5299ecc9b87dSHong Zhang       ncols_d = ai[i+1] - ai[i];
5300a77337e4SBarry Smith       for (j=0; j<ncols_d; j++) *cam++ = *aa++;
53015a7d977cSHong Zhang       /* off-diagonal portion of A */
5302f33d1a9aSHong Zhang       for (j=jo; j<ncols_o; j++) {
5303a77337e4SBarry Smith         *cam++ = *ba++; bj++;
5304f33d1a9aSHong Zhang       }
53055a7d977cSHong Zhang     }
53068661ff28SBarry Smith   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid MatReuse %d",(int)scall);
53074ebed01fSBarry Smith   ierr = PetscLogEventEnd(MAT_Getlocalmat,A,0,0,0);CHKERRQ(ierr);
530825616d81SHong Zhang   PetscFunctionReturn(0);
530925616d81SHong Zhang }
531025616d81SHong Zhang 
531132fba14fSHong Zhang #undef __FUNCT__
53124a2b5492SBarry Smith #define __FUNCT__ "MatMPIAIJGetLocalMatCondensed"
531332fba14fSHong Zhang /*@C
5314ba264940SBarry Smith      MatMPIAIJGetLocalMatCondensed - Creates a SeqAIJ matrix from an MPIAIJ matrix by taking all its local rows and NON-ZERO columns
531532fba14fSHong Zhang 
531632fba14fSHong Zhang     Not Collective
531732fba14fSHong Zhang 
531832fba14fSHong Zhang    Input Parameters:
531932fba14fSHong Zhang +    A - the matrix
532032fba14fSHong Zhang .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
53210298fd71SBarry Smith -    row, col - index sets of rows and columns to extract (or NULL)
532232fba14fSHong Zhang 
532332fba14fSHong Zhang    Output Parameter:
532432fba14fSHong Zhang .    A_loc - the local sequential matrix generated
532532fba14fSHong Zhang 
532632fba14fSHong Zhang     Level: developer
532732fba14fSHong Zhang 
5328ba264940SBarry Smith .seealso: MatGetOwnershipRange(), MatMPIAIJGetLocalMat()
5329ba264940SBarry Smith 
533032fba14fSHong Zhang @*/
53314a2b5492SBarry Smith PetscErrorCode  MatMPIAIJGetLocalMatCondensed(Mat A,MatReuse scall,IS *row,IS *col,Mat *A_loc)
533232fba14fSHong Zhang {
533332fba14fSHong Zhang   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
533432fba14fSHong Zhang   PetscErrorCode ierr;
533532fba14fSHong Zhang   PetscInt       i,start,end,ncols,nzA,nzB,*cmap,imark,*idx;
533632fba14fSHong Zhang   IS             isrowa,iscola;
533732fba14fSHong Zhang   Mat            *aloc;
53384a2b5492SBarry Smith   PetscBool      match;
533932fba14fSHong Zhang 
534032fba14fSHong Zhang   PetscFunctionBegin;
5341251f4c67SDmitry Karpeev   ierr = PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);CHKERRQ(ierr);
5342ce94432eSBarry Smith   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MPIAIJ matrix as input");
53434ebed01fSBarry Smith   ierr = PetscLogEventBegin(MAT_Getlocalmatcondensed,A,0,0,0);CHKERRQ(ierr);
534432fba14fSHong Zhang   if (!row) {
5345d0f46423SBarry Smith     start = A->rmap->rstart; end = A->rmap->rend;
534632fba14fSHong Zhang     ierr  = ISCreateStride(PETSC_COMM_SELF,end-start,start,1,&isrowa);CHKERRQ(ierr);
534732fba14fSHong Zhang   } else {
534832fba14fSHong Zhang     isrowa = *row;
534932fba14fSHong Zhang   }
535032fba14fSHong Zhang   if (!col) {
5351d0f46423SBarry Smith     start = A->cmap->rstart;
535232fba14fSHong Zhang     cmap  = a->garray;
5353d0f46423SBarry Smith     nzA   = a->A->cmap->n;
5354d0f46423SBarry Smith     nzB   = a->B->cmap->n;
535532fba14fSHong Zhang     ierr  = PetscMalloc((nzA+nzB)*sizeof(PetscInt), &idx);CHKERRQ(ierr);
535632fba14fSHong Zhang     ncols = 0;
535732fba14fSHong Zhang     for (i=0; i<nzB; i++) {
535832fba14fSHong Zhang       if (cmap[i] < start) idx[ncols++] = cmap[i];
535932fba14fSHong Zhang       else break;
536032fba14fSHong Zhang     }
536132fba14fSHong Zhang     imark = i;
536232fba14fSHong Zhang     for (i=0; i<nzA; i++) idx[ncols++] = start + i;
536332fba14fSHong Zhang     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i];
5364d67e408aSBarry Smith     ierr = ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&iscola);CHKERRQ(ierr);
536532fba14fSHong Zhang   } else {
536632fba14fSHong Zhang     iscola = *col;
536732fba14fSHong Zhang   }
536832fba14fSHong Zhang   if (scall != MAT_INITIAL_MATRIX) {
536932fba14fSHong Zhang     ierr    = PetscMalloc(sizeof(Mat),&aloc);CHKERRQ(ierr);
537032fba14fSHong Zhang     aloc[0] = *A_loc;
537132fba14fSHong Zhang   }
537232fba14fSHong Zhang   ierr   = MatGetSubMatrices(A,1,&isrowa,&iscola,scall,&aloc);CHKERRQ(ierr);
537332fba14fSHong Zhang   *A_loc = aloc[0];
537432fba14fSHong Zhang   ierr   = PetscFree(aloc);CHKERRQ(ierr);
537532fba14fSHong Zhang   if (!row) {
53766bf464f9SBarry Smith     ierr = ISDestroy(&isrowa);CHKERRQ(ierr);
537732fba14fSHong Zhang   }
537832fba14fSHong Zhang   if (!col) {
53796bf464f9SBarry Smith     ierr = ISDestroy(&iscola);CHKERRQ(ierr);
538032fba14fSHong Zhang   }
53814ebed01fSBarry Smith   ierr = PetscLogEventEnd(MAT_Getlocalmatcondensed,A,0,0,0);CHKERRQ(ierr);
538232fba14fSHong Zhang   PetscFunctionReturn(0);
538332fba14fSHong Zhang }
538432fba14fSHong Zhang 
538525616d81SHong Zhang #undef __FUNCT__
538625616d81SHong Zhang #define __FUNCT__ "MatGetBrowsOfAcols"
538725616d81SHong Zhang /*@C
538832fba14fSHong Zhang     MatGetBrowsOfAcols - Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A
538925616d81SHong Zhang 
539025616d81SHong Zhang     Collective on Mat
539125616d81SHong Zhang 
539225616d81SHong Zhang    Input Parameters:
5393e240928fSHong Zhang +    A,B - the matrices in mpiaij format
539425616d81SHong Zhang .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
53950298fd71SBarry Smith -    rowb, colb - index sets of rows and columns of B to extract (or NULL)
539625616d81SHong Zhang 
539725616d81SHong Zhang    Output Parameter:
539825616d81SHong Zhang +    rowb, colb - index sets of rows and columns of B to extract
539925616d81SHong Zhang -    B_seq - the sequential matrix generated
540025616d81SHong Zhang 
540125616d81SHong Zhang     Level: developer
540225616d81SHong Zhang 
540325616d81SHong Zhang @*/
540466bfb163SHong Zhang PetscErrorCode  MatGetBrowsOfAcols(Mat A,Mat B,MatReuse scall,IS *rowb,IS *colb,Mat *B_seq)
540525616d81SHong Zhang {
5406899cda47SBarry Smith   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
540725616d81SHong Zhang   PetscErrorCode ierr;
5408b1d57f15SBarry Smith   PetscInt       *idx,i,start,ncols,nzA,nzB,*cmap,imark;
540925616d81SHong Zhang   IS             isrowb,iscolb;
54100298fd71SBarry Smith   Mat            *bseq=NULL;
541125616d81SHong Zhang 
541225616d81SHong Zhang   PetscFunctionBegin;
5413d0f46423SBarry Smith   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5414e32f2f54SBarry Smith     SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, (%D, %D) != (%D,%D)",A->cmap->rstart,A->cmap->rend,B->rmap->rstart,B->rmap->rend);
541525616d81SHong Zhang   }
54164ebed01fSBarry Smith   ierr = PetscLogEventBegin(MAT_GetBrowsOfAcols,A,B,0,0);CHKERRQ(ierr);
541725616d81SHong Zhang 
541825616d81SHong Zhang   if (scall == MAT_INITIAL_MATRIX) {
5419d0f46423SBarry Smith     start = A->cmap->rstart;
542025616d81SHong Zhang     cmap  = a->garray;
5421d0f46423SBarry Smith     nzA   = a->A->cmap->n;
5422d0f46423SBarry Smith     nzB   = a->B->cmap->n;
5423b1d57f15SBarry Smith     ierr  = PetscMalloc((nzA+nzB)*sizeof(PetscInt), &idx);CHKERRQ(ierr);
542425616d81SHong Zhang     ncols = 0;
54250390132cSHong Zhang     for (i=0; i<nzB; i++) {  /* row < local row index */
542625616d81SHong Zhang       if (cmap[i] < start) idx[ncols++] = cmap[i];
542725616d81SHong Zhang       else break;
542825616d81SHong Zhang     }
542925616d81SHong Zhang     imark = i;
54300390132cSHong Zhang     for (i=0; i<nzA; i++) idx[ncols++] = start + i;  /* local rows */
54310390132cSHong Zhang     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5432d67e408aSBarry Smith     ierr = ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&isrowb);CHKERRQ(ierr);
5433d0f46423SBarry Smith     ierr = ISCreateStride(PETSC_COMM_SELF,B->cmap->N,0,1,&iscolb);CHKERRQ(ierr);
543425616d81SHong Zhang   } else {
5435e32f2f54SBarry Smith     if (!rowb || !colb) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"IS rowb and colb must be provided for MAT_REUSE_MATRIX");
543625616d81SHong Zhang     isrowb  = *rowb; iscolb = *colb;
543725616d81SHong Zhang     ierr    = PetscMalloc(sizeof(Mat),&bseq);CHKERRQ(ierr);
543825616d81SHong Zhang     bseq[0] = *B_seq;
543925616d81SHong Zhang   }
544025616d81SHong Zhang   ierr   = MatGetSubMatrices(B,1,&isrowb,&iscolb,scall,&bseq);CHKERRQ(ierr);
544125616d81SHong Zhang   *B_seq = bseq[0];
544225616d81SHong Zhang   ierr   = PetscFree(bseq);CHKERRQ(ierr);
544325616d81SHong Zhang   if (!rowb) {
54446bf464f9SBarry Smith     ierr = ISDestroy(&isrowb);CHKERRQ(ierr);
544525616d81SHong Zhang   } else {
544625616d81SHong Zhang     *rowb = isrowb;
544725616d81SHong Zhang   }
544825616d81SHong Zhang   if (!colb) {
54496bf464f9SBarry Smith     ierr = ISDestroy(&iscolb);CHKERRQ(ierr);
545025616d81SHong Zhang   } else {
545125616d81SHong Zhang     *colb = iscolb;
545225616d81SHong Zhang   }
54534ebed01fSBarry Smith   ierr = PetscLogEventEnd(MAT_GetBrowsOfAcols,A,B,0,0);CHKERRQ(ierr);
545425616d81SHong Zhang   PetscFunctionReturn(0);
545525616d81SHong Zhang }
5456429d309bSHong Zhang 
5457a61c8c0fSHong Zhang #undef __FUNCT__
5458f8487c73SHong Zhang #define __FUNCT__ "MatGetBrowsOfAoCols_MPIAIJ"
5459f8487c73SHong Zhang /*
5460f8487c73SHong Zhang     MatGetBrowsOfAoCols_MPIAIJ - Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns
546101b7ae99SHong Zhang     of the OFF-DIAGONAL portion of local A
5462429d309bSHong Zhang 
5463429d309bSHong Zhang     Collective on Mat
5464429d309bSHong Zhang 
5465429d309bSHong Zhang    Input Parameters:
5466429d309bSHong Zhang +    A,B - the matrices in mpiaij format
5467598bc09dSHong Zhang -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
5468429d309bSHong Zhang 
5469429d309bSHong Zhang    Output Parameter:
54700298fd71SBarry Smith +    startsj_s - starting point in B's sending j-arrays, saved for MAT_REUSE (or NULL)
54710298fd71SBarry Smith .    startsj_r - starting point in B's receiving j-arrays, saved for MAT_REUSE (or NULL)
54720298fd71SBarry Smith .    bufa_ptr - array for sending matrix values, saved for MAT_REUSE (or NULL)
5473598bc09dSHong Zhang -    B_oth - the sequential matrix generated with size aBn=a->B->cmap->n by B->cmap->N
5474429d309bSHong Zhang 
5475429d309bSHong Zhang     Level: developer
5476429d309bSHong Zhang 
5477f8487c73SHong Zhang */
5478b7f45c76SHong Zhang PetscErrorCode  MatGetBrowsOfAoCols_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscInt **startsj_s,PetscInt **startsj_r,MatScalar **bufa_ptr,Mat *B_oth)
5479429d309bSHong Zhang {
5480a6b2eed2SHong Zhang   VecScatter_MPI_General *gen_to,*gen_from;
5481429d309bSHong Zhang   PetscErrorCode         ierr;
5482899cda47SBarry Smith   Mat_MPIAIJ             *a=(Mat_MPIAIJ*)A->data;
548387025532SHong Zhang   Mat_SeqAIJ             *b_oth;
5484a6b2eed2SHong Zhang   VecScatter             ctx =a->Mvctx;
5485ce94432eSBarry Smith   MPI_Comm               comm;
54867adad957SLisandro Dalcin   PetscMPIInt            *rprocs,*sprocs,tag=((PetscObject)ctx)->tag,rank;
5487d0f46423SBarry Smith   PetscInt               *rowlen,*bufj,*bufJ,ncols,aBn=a->B->cmap->n,row,*b_othi,*b_othj;
5488dd6ea824SBarry Smith   PetscScalar            *rvalues,*svalues;
5489dd6ea824SBarry Smith   MatScalar              *b_otha,*bufa,*bufA;
5490e42f35eeSHong Zhang   PetscInt               i,j,k,l,ll,nrecvs,nsends,nrows,*srow,*rstarts,*rstartsj = 0,*sstarts,*sstartsj,len;
54910298fd71SBarry Smith   MPI_Request            *rwaits = NULL,*swaits = NULL;
549287025532SHong Zhang   MPI_Status             *sstatus,rstatus;
5493aa5bb8c0SSatish Balay   PetscMPIInt            jj;
5494e42f35eeSHong Zhang   PetscInt               *cols,sbs,rbs;
5495ba8c8a56SBarry Smith   PetscScalar            *vals;
5496429d309bSHong Zhang 
5497429d309bSHong Zhang   PetscFunctionBegin;
5498ce94432eSBarry Smith   ierr = PetscObjectGetComm((PetscObject)A,&comm);CHKERRQ(ierr);
5499d0f46423SBarry Smith   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5500e32f2f54SBarry Smith     SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, (%d, %d) != (%d,%d)",A->cmap->rstart,A->cmap->rend,B->rmap->rstart,B->rmap->rend);
5501429d309bSHong Zhang   }
55024ebed01fSBarry Smith   ierr = PetscLogEventBegin(MAT_GetBrowsOfAocols,A,B,0,0);CHKERRQ(ierr);
5503a6b2eed2SHong Zhang   ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
5504a6b2eed2SHong Zhang 
5505a6b2eed2SHong Zhang   gen_to   = (VecScatter_MPI_General*)ctx->todata;
5506a6b2eed2SHong Zhang   gen_from = (VecScatter_MPI_General*)ctx->fromdata;
5507e42f35eeSHong Zhang   rvalues  = gen_from->values; /* holds the length of receiving row */
5508e42f35eeSHong Zhang   svalues  = gen_to->values;   /* holds the length of sending row */
5509a6b2eed2SHong Zhang   nrecvs   = gen_from->n;
5510a6b2eed2SHong Zhang   nsends   = gen_to->n;
5511d7ee0231SBarry Smith 
5512d7ee0231SBarry Smith   ierr    = PetscMalloc2(nrecvs,MPI_Request,&rwaits,nsends,MPI_Request,&swaits);CHKERRQ(ierr);
5513a6b2eed2SHong Zhang   srow    = gen_to->indices;    /* local row index to be sent */
5514a6b2eed2SHong Zhang   sstarts = gen_to->starts;
5515a6b2eed2SHong Zhang   sprocs  = gen_to->procs;
5516a6b2eed2SHong Zhang   sstatus = gen_to->sstatus;
5517e42f35eeSHong Zhang   sbs     = gen_to->bs;
5518e42f35eeSHong Zhang   rstarts = gen_from->starts;
5519e42f35eeSHong Zhang   rprocs  = gen_from->procs;
5520e42f35eeSHong Zhang   rbs     = gen_from->bs;
5521429d309bSHong Zhang 
5522b7f45c76SHong Zhang   if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5523429d309bSHong Zhang   if (scall == MAT_INITIAL_MATRIX) {
5524a6b2eed2SHong Zhang     /* i-array */
5525a6b2eed2SHong Zhang     /*---------*/
5526a6b2eed2SHong Zhang     /*  post receives */
5527a6b2eed2SHong Zhang     for (i=0; i<nrecvs; i++) {
5528e42f35eeSHong Zhang       rowlen = (PetscInt*)rvalues + rstarts[i]*rbs;
5529e42f35eeSHong Zhang       nrows  = (rstarts[i+1]-rstarts[i])*rbs; /* num of indices to be received */
553087025532SHong Zhang       ierr   = MPI_Irecv(rowlen,nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);CHKERRQ(ierr);
5531429d309bSHong Zhang     }
5532a6b2eed2SHong Zhang 
5533a6b2eed2SHong Zhang     /* pack the outgoing message */
55341d79065fSBarry Smith     ierr = PetscMalloc2(nsends+1,PetscInt,&sstartsj,nrecvs+1,PetscInt,&rstartsj);CHKERRQ(ierr);
55352205254eSKarl Rupp 
55362205254eSKarl Rupp     sstartsj[0] = 0;
55372205254eSKarl Rupp     rstartsj[0] = 0;
5538a6b2eed2SHong Zhang     len         = 0; /* total length of j or a array to be sent */
5539a6b2eed2SHong Zhang     k           = 0;
5540a6b2eed2SHong Zhang     for (i=0; i<nsends; i++) {
5541e42f35eeSHong Zhang       rowlen = (PetscInt*)svalues + sstarts[i]*sbs;
5542e42f35eeSHong Zhang       nrows  = sstarts[i+1]-sstarts[i]; /* num of block rows */
554387025532SHong Zhang       for (j=0; j<nrows; j++) {
5544d0f46423SBarry Smith         row = srow[k] + B->rmap->range[rank]; /* global row idx */
5545e42f35eeSHong Zhang         for (l=0; l<sbs; l++) {
55460298fd71SBarry Smith           ierr = MatGetRow_MPIAIJ(B,row+l,&ncols,NULL,NULL);CHKERRQ(ierr); /* rowlength */
55472205254eSKarl Rupp 
5548e42f35eeSHong Zhang           rowlen[j*sbs+l] = ncols;
55492205254eSKarl Rupp 
5550e42f35eeSHong Zhang           len += ncols;
55510298fd71SBarry Smith           ierr = MatRestoreRow_MPIAIJ(B,row+l,&ncols,NULL,NULL);CHKERRQ(ierr);
5552e42f35eeSHong Zhang         }
5553a6b2eed2SHong Zhang         k++;
5554429d309bSHong Zhang       }
5555e42f35eeSHong Zhang       ierr = MPI_Isend(rowlen,nrows*sbs,MPIU_INT,sprocs[i],tag,comm,swaits+i);CHKERRQ(ierr);
55562205254eSKarl Rupp 
5557dea91ad1SHong Zhang       sstartsj[i+1] = len;  /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5558429d309bSHong Zhang     }
555987025532SHong Zhang     /* recvs and sends of i-array are completed */
556087025532SHong Zhang     i = nrecvs;
556187025532SHong Zhang     while (i--) {
5562aa5bb8c0SSatish Balay       ierr = MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);CHKERRQ(ierr);
556387025532SHong Zhang     }
55640c468ba9SBarry Smith     if (nsends) {ierr = MPI_Waitall(nsends,swaits,sstatus);CHKERRQ(ierr);}
5565e42f35eeSHong Zhang 
5566a6b2eed2SHong Zhang     /* allocate buffers for sending j and a arrays */
5567a6b2eed2SHong Zhang     ierr = PetscMalloc((len+1)*sizeof(PetscInt),&bufj);CHKERRQ(ierr);
5568a6b2eed2SHong Zhang     ierr = PetscMalloc((len+1)*sizeof(PetscScalar),&bufa);CHKERRQ(ierr);
5569a6b2eed2SHong Zhang 
557087025532SHong Zhang     /* create i-array of B_oth */
557187025532SHong Zhang     ierr = PetscMalloc((aBn+2)*sizeof(PetscInt),&b_othi);CHKERRQ(ierr);
55722205254eSKarl Rupp 
557387025532SHong Zhang     b_othi[0] = 0;
5574a6b2eed2SHong Zhang     len       = 0; /* total length of j or a array to be received */
5575a6b2eed2SHong Zhang     k         = 0;
5576a6b2eed2SHong Zhang     for (i=0; i<nrecvs; i++) {
5577fd0ff01cSHong Zhang       rowlen = (PetscInt*)rvalues + rstarts[i]*rbs;
5578e42f35eeSHong Zhang       nrows  = rbs*(rstarts[i+1]-rstarts[i]); /* num of rows to be recieved */
557987025532SHong Zhang       for (j=0; j<nrows; j++) {
558087025532SHong Zhang         b_othi[k+1] = b_othi[k] + rowlen[j];
5581a6b2eed2SHong Zhang         len        += rowlen[j]; k++;
5582a6b2eed2SHong Zhang       }
5583dea91ad1SHong Zhang       rstartsj[i+1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5584a6b2eed2SHong Zhang     }
5585a6b2eed2SHong Zhang 
558687025532SHong Zhang     /* allocate space for j and a arrrays of B_oth */
558787025532SHong Zhang     ierr = PetscMalloc((b_othi[aBn]+1)*sizeof(PetscInt),&b_othj);CHKERRQ(ierr);
5588dd6ea824SBarry Smith     ierr = PetscMalloc((b_othi[aBn]+1)*sizeof(MatScalar),&b_otha);CHKERRQ(ierr);
5589a6b2eed2SHong Zhang 
559087025532SHong Zhang     /* j-array */
559187025532SHong Zhang     /*---------*/
5592a6b2eed2SHong Zhang     /*  post receives of j-array */
5593a6b2eed2SHong Zhang     for (i=0; i<nrecvs; i++) {
559487025532SHong Zhang       nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
559587025532SHong Zhang       ierr  = MPI_Irecv(b_othj+rstartsj[i],nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);CHKERRQ(ierr);
5596a6b2eed2SHong Zhang     }
5597e42f35eeSHong Zhang 
5598e42f35eeSHong Zhang     /* pack the outgoing message j-array */
5599a6b2eed2SHong Zhang     k = 0;
5600a6b2eed2SHong Zhang     for (i=0; i<nsends; i++) {
5601e42f35eeSHong Zhang       nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
5602a6b2eed2SHong Zhang       bufJ  = bufj+sstartsj[i];
560387025532SHong Zhang       for (j=0; j<nrows; j++) {
5604d0f46423SBarry Smith         row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5605e42f35eeSHong Zhang         for (ll=0; ll<sbs; ll++) {
56060298fd71SBarry Smith           ierr = MatGetRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);CHKERRQ(ierr);
5607a6b2eed2SHong Zhang           for (l=0; l<ncols; l++) {
5608a6b2eed2SHong Zhang             *bufJ++ = cols[l];
560987025532SHong Zhang           }
56100298fd71SBarry Smith           ierr = MatRestoreRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);CHKERRQ(ierr);
5611e42f35eeSHong Zhang         }
561287025532SHong Zhang       }
561387025532SHong Zhang       ierr = MPI_Isend(bufj+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_INT,sprocs[i],tag,comm,swaits+i);CHKERRQ(ierr);
561487025532SHong Zhang     }
561587025532SHong Zhang 
561687025532SHong Zhang     /* recvs and sends of j-array are completed */
561787025532SHong Zhang     i = nrecvs;
561887025532SHong Zhang     while (i--) {
5619aa5bb8c0SSatish Balay       ierr = MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);CHKERRQ(ierr);
562087025532SHong Zhang     }
56210c468ba9SBarry Smith     if (nsends) {ierr = MPI_Waitall(nsends,swaits,sstatus);CHKERRQ(ierr);}
562287025532SHong Zhang   } else if (scall == MAT_REUSE_MATRIX) {
5623b7f45c76SHong Zhang     sstartsj = *startsj_s;
56241d79065fSBarry Smith     rstartsj = *startsj_r;
562587025532SHong Zhang     bufa     = *bufa_ptr;
562687025532SHong Zhang     b_oth    = (Mat_SeqAIJ*)(*B_oth)->data;
562787025532SHong Zhang     b_otha   = b_oth->a;
5628f23aa3ddSBarry Smith   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not posses an object container");
562987025532SHong Zhang 
563087025532SHong Zhang   /* a-array */
563187025532SHong Zhang   /*---------*/
563287025532SHong Zhang   /*  post receives of a-array */
563387025532SHong Zhang   for (i=0; i<nrecvs; i++) {
563487025532SHong Zhang     nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
563587025532SHong Zhang     ierr  = MPI_Irecv(b_otha+rstartsj[i],nrows,MPIU_SCALAR,rprocs[i],tag,comm,rwaits+i);CHKERRQ(ierr);
563687025532SHong Zhang   }
5637e42f35eeSHong Zhang 
5638e42f35eeSHong Zhang   /* pack the outgoing message a-array */
563987025532SHong Zhang   k = 0;
564087025532SHong Zhang   for (i=0; i<nsends; i++) {
5641e42f35eeSHong Zhang     nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
564287025532SHong Zhang     bufA  = bufa+sstartsj[i];
564387025532SHong Zhang     for (j=0; j<nrows; j++) {
5644d0f46423SBarry Smith       row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5645e42f35eeSHong Zhang       for (ll=0; ll<sbs; ll++) {
56460298fd71SBarry Smith         ierr = MatGetRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);CHKERRQ(ierr);
564787025532SHong Zhang         for (l=0; l<ncols; l++) {
5648a6b2eed2SHong Zhang           *bufA++ = vals[l];
5649a6b2eed2SHong Zhang         }
56500298fd71SBarry Smith         ierr = MatRestoreRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);CHKERRQ(ierr);
5651e42f35eeSHong Zhang       }
5652a6b2eed2SHong Zhang     }
565387025532SHong Zhang     ierr = MPI_Isend(bufa+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_SCALAR,sprocs[i],tag,comm,swaits+i);CHKERRQ(ierr);
5654a6b2eed2SHong Zhang   }
565587025532SHong Zhang   /* recvs and sends of a-array are completed */
565687025532SHong Zhang   i = nrecvs;
565787025532SHong Zhang   while (i--) {
5658aa5bb8c0SSatish Balay     ierr = MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);CHKERRQ(ierr);
565987025532SHong Zhang   }
56600c468ba9SBarry Smith   if (nsends) {ierr = MPI_Waitall(nsends,swaits,sstatus);CHKERRQ(ierr);}
5661d7ee0231SBarry Smith   ierr = PetscFree2(rwaits,swaits);CHKERRQ(ierr);
5662a6b2eed2SHong Zhang 
566387025532SHong Zhang   if (scall == MAT_INITIAL_MATRIX) {
5664a6b2eed2SHong Zhang     /* put together the new matrix */
5665d0f46423SBarry Smith     ierr = MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,aBn,B->cmap->N,b_othi,b_othj,b_otha,B_oth);CHKERRQ(ierr);
5666a6b2eed2SHong Zhang 
5667a6b2eed2SHong Zhang     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5668a6b2eed2SHong Zhang     /* Since these are PETSc arrays, change flags to free them as necessary. */
566987025532SHong Zhang     b_oth          = (Mat_SeqAIJ*)(*B_oth)->data;
5670e6b907acSBarry Smith     b_oth->free_a  = PETSC_TRUE;
5671e6b907acSBarry Smith     b_oth->free_ij = PETSC_TRUE;
567287025532SHong Zhang     b_oth->nonew   = 0;
5673a6b2eed2SHong Zhang 
5674a6b2eed2SHong Zhang     ierr = PetscFree(bufj);CHKERRQ(ierr);
5675b7f45c76SHong Zhang     if (!startsj_s || !bufa_ptr) {
56761d79065fSBarry Smith       ierr = PetscFree2(sstartsj,rstartsj);CHKERRQ(ierr);
5677dea91ad1SHong Zhang       ierr = PetscFree(bufa_ptr);CHKERRQ(ierr);
5678dea91ad1SHong Zhang     } else {
5679b7f45c76SHong Zhang       *startsj_s = sstartsj;
56801d79065fSBarry Smith       *startsj_r = rstartsj;
568187025532SHong Zhang       *bufa_ptr  = bufa;
568287025532SHong Zhang     }
5683dea91ad1SHong Zhang   }
56844ebed01fSBarry Smith   ierr = PetscLogEventEnd(MAT_GetBrowsOfAocols,A,B,0,0);CHKERRQ(ierr);
5685429d309bSHong Zhang   PetscFunctionReturn(0);
5686429d309bSHong Zhang }
5687ccd8e176SBarry Smith 
568843eb5e2fSMatthew Knepley #undef __FUNCT__
568943eb5e2fSMatthew Knepley #define __FUNCT__ "MatGetCommunicationStructs"
569043eb5e2fSMatthew Knepley /*@C
569143eb5e2fSMatthew Knepley   MatGetCommunicationStructs - Provides access to the communication structures used in matrix-vector multiplication.
569243eb5e2fSMatthew Knepley 
569343eb5e2fSMatthew Knepley   Not Collective
569443eb5e2fSMatthew Knepley 
569543eb5e2fSMatthew Knepley   Input Parameters:
569643eb5e2fSMatthew Knepley . A - The matrix in mpiaij format
569743eb5e2fSMatthew Knepley 
569843eb5e2fSMatthew Knepley   Output Parameter:
569943eb5e2fSMatthew Knepley + lvec - The local vector holding off-process values from the argument to a matrix-vector product
570043eb5e2fSMatthew Knepley . colmap - A map from global column index to local index into lvec
570143eb5e2fSMatthew Knepley - multScatter - A scatter from the argument of a matrix-vector product to lvec
570243eb5e2fSMatthew Knepley 
570343eb5e2fSMatthew Knepley   Level: developer
570443eb5e2fSMatthew Knepley 
570543eb5e2fSMatthew Knepley @*/
570643eb5e2fSMatthew Knepley #if defined(PETSC_USE_CTABLE)
57077087cfbeSBarry Smith PetscErrorCode  MatGetCommunicationStructs(Mat A, Vec *lvec, PetscTable *colmap, VecScatter *multScatter)
570843eb5e2fSMatthew Knepley #else
57097087cfbeSBarry Smith PetscErrorCode  MatGetCommunicationStructs(Mat A, Vec *lvec, PetscInt *colmap[], VecScatter *multScatter)
571043eb5e2fSMatthew Knepley #endif
571143eb5e2fSMatthew Knepley {
571243eb5e2fSMatthew Knepley   Mat_MPIAIJ *a;
571343eb5e2fSMatthew Knepley 
571443eb5e2fSMatthew Knepley   PetscFunctionBegin;
57150700a824SBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5716e414b56bSJed Brown   PetscValidPointer(lvec, 2);
5717e414b56bSJed Brown   PetscValidPointer(colmap, 3);
5718e414b56bSJed Brown   PetscValidPointer(multScatter, 4);
571943eb5e2fSMatthew Knepley   a = (Mat_MPIAIJ*) A->data;
572043eb5e2fSMatthew Knepley   if (lvec) *lvec = a->lvec;
572143eb5e2fSMatthew Knepley   if (colmap) *colmap = a->colmap;
572243eb5e2fSMatthew Knepley   if (multScatter) *multScatter = a->Mvctx;
572343eb5e2fSMatthew Knepley   PetscFunctionReturn(0);
572443eb5e2fSMatthew Knepley }
572543eb5e2fSMatthew Knepley 
57268cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat,MatType,MatReuse,Mat*);
57278cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat,MatType,MatReuse,Mat*);
57288cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat,MatType,MatReuse,Mat*);
572917667f90SBarry Smith 
5730fc4dec0aSBarry Smith #undef __FUNCT__
5731fc4dec0aSBarry Smith #define __FUNCT__ "MatMatMultNumeric_MPIDense_MPIAIJ"
5732fc4dec0aSBarry Smith /*
5733fc4dec0aSBarry Smith     Computes (B'*A')' since computing B*A directly is untenable
5734fc4dec0aSBarry Smith 
5735fc4dec0aSBarry Smith                n                       p                          p
5736fc4dec0aSBarry Smith         (              )       (              )         (                  )
5737fc4dec0aSBarry Smith       m (      A       )  *  n (       B      )   =   m (         C        )
5738fc4dec0aSBarry Smith         (              )       (              )         (                  )
5739fc4dec0aSBarry Smith 
5740fc4dec0aSBarry Smith */
5741fc4dec0aSBarry Smith PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A,Mat B,Mat C)
5742fc4dec0aSBarry Smith {
5743fc4dec0aSBarry Smith   PetscErrorCode ierr;
5744fc4dec0aSBarry Smith   Mat            At,Bt,Ct;
5745fc4dec0aSBarry Smith 
5746fc4dec0aSBarry Smith   PetscFunctionBegin;
5747fc4dec0aSBarry Smith   ierr = MatTranspose(A,MAT_INITIAL_MATRIX,&At);CHKERRQ(ierr);
5748fc4dec0aSBarry Smith   ierr = MatTranspose(B,MAT_INITIAL_MATRIX,&Bt);CHKERRQ(ierr);
5749fc4dec0aSBarry Smith   ierr = MatMatMult(Bt,At,MAT_INITIAL_MATRIX,1.0,&Ct);CHKERRQ(ierr);
57506bf464f9SBarry Smith   ierr = MatDestroy(&At);CHKERRQ(ierr);
57516bf464f9SBarry Smith   ierr = MatDestroy(&Bt);CHKERRQ(ierr);
5752fc4dec0aSBarry Smith   ierr = MatTranspose(Ct,MAT_REUSE_MATRIX,&C);CHKERRQ(ierr);
57536bf464f9SBarry Smith   ierr = MatDestroy(&Ct);CHKERRQ(ierr);
5754fc4dec0aSBarry Smith   PetscFunctionReturn(0);
5755fc4dec0aSBarry Smith }
5756fc4dec0aSBarry Smith 
5757fc4dec0aSBarry Smith #undef __FUNCT__
5758fc4dec0aSBarry Smith #define __FUNCT__ "MatMatMultSymbolic_MPIDense_MPIAIJ"
5759fc4dec0aSBarry Smith PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
5760fc4dec0aSBarry Smith {
5761fc4dec0aSBarry Smith   PetscErrorCode ierr;
5762d0f46423SBarry Smith   PetscInt       m=A->rmap->n,n=B->cmap->n;
5763fc4dec0aSBarry Smith   Mat            Cmat;
5764fc4dec0aSBarry Smith 
5765fc4dec0aSBarry Smith   PetscFunctionBegin;
5766e32f2f54SBarry Smith   if (A->cmap->n != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"A->cmap->n %d != B->rmap->n %d\n",A->cmap->n,B->rmap->n);
5767ce94432eSBarry Smith   ierr = MatCreate(PetscObjectComm((PetscObject)A),&Cmat);CHKERRQ(ierr);
5768fc4dec0aSBarry Smith   ierr = MatSetSizes(Cmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);CHKERRQ(ierr);
5769a2f3521dSMark F. Adams   ierr = MatSetBlockSizes(Cmat,A->rmap->bs,B->cmap->bs);CHKERRQ(ierr);
5770fc4dec0aSBarry Smith   ierr = MatSetType(Cmat,MATMPIDENSE);CHKERRQ(ierr);
57710298fd71SBarry Smith   ierr = MatMPIDenseSetPreallocation(Cmat,NULL);CHKERRQ(ierr);
577238556019SBarry Smith   ierr = MatAssemblyBegin(Cmat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
577338556019SBarry Smith   ierr = MatAssemblyEnd(Cmat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
5774f75ecaa4SHong Zhang 
5775f75ecaa4SHong Zhang   Cmat->ops->matmultnumeric = MatMatMultNumeric_MPIDense_MPIAIJ;
57762205254eSKarl Rupp 
5777fc4dec0aSBarry Smith   *C = Cmat;
5778fc4dec0aSBarry Smith   PetscFunctionReturn(0);
5779fc4dec0aSBarry Smith }
5780fc4dec0aSBarry Smith 
5781fc4dec0aSBarry Smith /* ----------------------------------------------------------------*/
5782fc4dec0aSBarry Smith #undef __FUNCT__
5783fc4dec0aSBarry Smith #define __FUNCT__ "MatMatMult_MPIDense_MPIAIJ"
5784fc4dec0aSBarry Smith PetscErrorCode MatMatMult_MPIDense_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
5785fc4dec0aSBarry Smith {
5786fc4dec0aSBarry Smith   PetscErrorCode ierr;
5787fc4dec0aSBarry Smith 
5788fc4dec0aSBarry Smith   PetscFunctionBegin;
5789fc4dec0aSBarry Smith   if (scall == MAT_INITIAL_MATRIX) {
57903ff4c91cSHong Zhang     ierr = PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
5791fc4dec0aSBarry Smith     ierr = MatMatMultSymbolic_MPIDense_MPIAIJ(A,B,fill,C);CHKERRQ(ierr);
57923ff4c91cSHong Zhang     ierr = PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);CHKERRQ(ierr);
5793fc4dec0aSBarry Smith   }
57943ff4c91cSHong Zhang   ierr = PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
5795fc4dec0aSBarry Smith   ierr = MatMatMultNumeric_MPIDense_MPIAIJ(A,B,*C);CHKERRQ(ierr);
57963ff4c91cSHong Zhang   ierr = PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);CHKERRQ(ierr);
5797fc4dec0aSBarry Smith   PetscFunctionReturn(0);
5798fc4dec0aSBarry Smith }
5799fc4dec0aSBarry Smith 
5800611f576cSBarry Smith #if defined(PETSC_HAVE_MUMPS)
58018cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatGetFactor_aij_mumps(Mat,MatFactorType,Mat*);
5802611f576cSBarry Smith #endif
58033bf14a46SMatthew Knepley #if defined(PETSC_HAVE_PASTIX)
58048cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatGetFactor_mpiaij_pastix(Mat,MatFactorType,Mat*);
58053bf14a46SMatthew Knepley #endif
5806611f576cSBarry Smith #if defined(PETSC_HAVE_SUPERLU_DIST)
58078cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatGetFactor_mpiaij_superlu_dist(Mat,MatFactorType,Mat*);
5808611f576cSBarry Smith #endif
580917f1a0eaSHong Zhang #if defined(PETSC_HAVE_CLIQUE)
58108cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatGetFactor_aij_clique(Mat,MatFactorType,Mat*);
581117f1a0eaSHong Zhang #endif
58125c9eb25fSBarry Smith 
5813ccd8e176SBarry Smith /*MC
5814ccd8e176SBarry Smith    MATMPIAIJ - MATMPIAIJ = "mpiaij" - A matrix type to be used for parallel sparse matrices.
5815ccd8e176SBarry Smith 
5816ccd8e176SBarry Smith    Options Database Keys:
5817ccd8e176SBarry Smith . -mat_type mpiaij - sets the matrix type to "mpiaij" during a call to MatSetFromOptions()
5818ccd8e176SBarry Smith 
5819ccd8e176SBarry Smith   Level: beginner
5820ccd8e176SBarry Smith 
582169b1f4b7SBarry Smith .seealso: MatCreateAIJ()
5822ccd8e176SBarry Smith M*/
5823ccd8e176SBarry Smith 
5824ccd8e176SBarry Smith #undef __FUNCT__
5825ccd8e176SBarry Smith #define __FUNCT__ "MatCreate_MPIAIJ"
58268cc058d9SJed Brown PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
5827ccd8e176SBarry Smith {
5828ccd8e176SBarry Smith   Mat_MPIAIJ     *b;
5829ccd8e176SBarry Smith   PetscErrorCode ierr;
5830ccd8e176SBarry Smith   PetscMPIInt    size;
5831ccd8e176SBarry Smith 
5832ccd8e176SBarry Smith   PetscFunctionBegin;
5833ce94432eSBarry Smith   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)B),&size);CHKERRQ(ierr);
58342205254eSKarl Rupp 
583538f2d2fdSLisandro Dalcin   ierr          = PetscNewLog(B,Mat_MPIAIJ,&b);CHKERRQ(ierr);
5836ccd8e176SBarry Smith   B->data       = (void*)b;
5837ccd8e176SBarry Smith   ierr          = PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));CHKERRQ(ierr);
5838ccd8e176SBarry Smith   B->assembled  = PETSC_FALSE;
5839ccd8e176SBarry Smith   B->insertmode = NOT_SET_VALUES;
5840ccd8e176SBarry Smith   b->size       = size;
58412205254eSKarl Rupp 
5842ce94432eSBarry Smith   ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)B),&b->rank);CHKERRQ(ierr);
5843ccd8e176SBarry Smith 
5844ccd8e176SBarry Smith   /* build cache for off array entries formed */
5845ce94432eSBarry Smith   ierr = MatStashCreate_Private(PetscObjectComm((PetscObject)B),1,&B->stash);CHKERRQ(ierr);
58462205254eSKarl Rupp 
5847ccd8e176SBarry Smith   b->donotstash  = PETSC_FALSE;
5848ccd8e176SBarry Smith   b->colmap      = 0;
5849ccd8e176SBarry Smith   b->garray      = 0;
5850ccd8e176SBarry Smith   b->roworiented = PETSC_TRUE;
5851ccd8e176SBarry Smith 
5852ccd8e176SBarry Smith   /* stuff used for matrix vector multiply */
58530298fd71SBarry Smith   b->lvec  = NULL;
58540298fd71SBarry Smith   b->Mvctx = NULL;
5855ccd8e176SBarry Smith 
5856ccd8e176SBarry Smith   /* stuff for MatGetRow() */
5857ccd8e176SBarry Smith   b->rowindices   = 0;
5858ccd8e176SBarry Smith   b->rowvalues    = 0;
5859ccd8e176SBarry Smith   b->getrowactive = PETSC_FALSE;
5860ccd8e176SBarry Smith 
5861bbf3fe20SPaul Mullowney   /* flexible pointer used in CUSP/CUSPARSE classes */
58620298fd71SBarry Smith   b->spptr = NULL;
5863f60c3dc2SHong Zhang 
5864611f576cSBarry Smith #if defined(PETSC_HAVE_MUMPS)
5865bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_mumps_C",MatGetFactor_aij_mumps);CHKERRQ(ierr);
5866611f576cSBarry Smith #endif
58673bf14a46SMatthew Knepley #if defined(PETSC_HAVE_PASTIX)
5868bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_pastix_C",MatGetFactor_mpiaij_pastix);CHKERRQ(ierr);
58693bf14a46SMatthew Knepley #endif
5870611f576cSBarry Smith #if defined(PETSC_HAVE_SUPERLU_DIST)
5871bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_superlu_dist_C",MatGetFactor_mpiaij_superlu_dist);CHKERRQ(ierr);
5872611f576cSBarry Smith #endif
587317f1a0eaSHong Zhang #if defined(PETSC_HAVE_CLIQUE)
5874bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_clique_C",MatGetFactor_aij_clique);CHKERRQ(ierr);
587517f1a0eaSHong Zhang #endif
5876bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_MPIAIJ);CHKERRQ(ierr);
5877bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_MPIAIJ);CHKERRQ(ierr);
5878bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatGetDiagonalBlock_C",MatGetDiagonalBlock_MPIAIJ);CHKERRQ(ierr);
5879bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_MPIAIJ);CHKERRQ(ierr);
5880bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocation_C",MatMPIAIJSetPreallocation_MPIAIJ);CHKERRQ(ierr);
5881bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocationCSR_C",MatMPIAIJSetPreallocationCSR_MPIAIJ);CHKERRQ(ierr);
5882bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatDiagonalScaleLocal_C",MatDiagonalScaleLocal_MPIAIJ);CHKERRQ(ierr);
5883bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijperm_C",MatConvert_MPIAIJ_MPIAIJPERM);CHKERRQ(ierr);
5884bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijcrl_C",MatConvert_MPIAIJ_MPIAIJCRL);CHKERRQ(ierr);
5885bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpisbaij_C",MatConvert_MPIAIJ_MPISBAIJ);CHKERRQ(ierr);
5886bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatMatMult_mpidense_mpiaij_C",MatMatMult_MPIDense_MPIAIJ);CHKERRQ(ierr);
5887bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatMatMultSymbolic_mpidense_mpiaij_C",MatMatMultSymbolic_MPIDense_MPIAIJ);CHKERRQ(ierr);
5888bdf89e91SBarry Smith   ierr = PetscObjectComposeFunction((PetscObject)B,"MatMatMultNumeric_mpidense_mpiaij_C",MatMatMultNumeric_MPIDense_MPIAIJ);CHKERRQ(ierr);
588917667f90SBarry Smith   ierr = PetscObjectChangeTypeName((PetscObject)B,MATMPIAIJ);CHKERRQ(ierr);
5890ccd8e176SBarry Smith   PetscFunctionReturn(0);
5891ccd8e176SBarry Smith }
589281824310SBarry Smith 
589303bfb495SBarry Smith #undef __FUNCT__
589403bfb495SBarry Smith #define __FUNCT__ "MatCreateMPIAIJWithSplitArrays"
589558d36128SBarry Smith /*@
589603bfb495SBarry Smith      MatCreateMPIAIJWithSplitArrays - creates a MPI AIJ matrix using arrays that contain the "diagonal"
589703bfb495SBarry Smith          and "off-diagonal" part of the matrix in CSR format.
589803bfb495SBarry Smith 
589903bfb495SBarry Smith    Collective on MPI_Comm
590003bfb495SBarry Smith 
590103bfb495SBarry Smith    Input Parameters:
590203bfb495SBarry Smith +  comm - MPI communicator
590303bfb495SBarry Smith .  m - number of local rows (Cannot be PETSC_DECIDE)
590403bfb495SBarry Smith .  n - This value should be the same as the local size used in creating the
590503bfb495SBarry Smith        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
590603bfb495SBarry Smith        calculated if N is given) For square matrices n is almost always m.
590703bfb495SBarry Smith .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
590803bfb495SBarry Smith .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
590903bfb495SBarry Smith .   i - row indices for "diagonal" portion of matrix
591003bfb495SBarry Smith .   j - column indices
591103bfb495SBarry Smith .   a - matrix values
591203bfb495SBarry Smith .   oi - row indices for "off-diagonal" portion of matrix
591303bfb495SBarry Smith .   oj - column indices
591403bfb495SBarry Smith -   oa - matrix values
591503bfb495SBarry Smith 
591603bfb495SBarry Smith    Output Parameter:
591703bfb495SBarry Smith .   mat - the matrix
591803bfb495SBarry Smith 
591903bfb495SBarry Smith    Level: advanced
592003bfb495SBarry Smith 
592103bfb495SBarry Smith    Notes:
5922292fb18eSBarry Smith        The i, j, and a arrays ARE NOT copied by this routine into the internal format used by PETSc. The user
5923292fb18eSBarry Smith        must free the arrays once the matrix has been destroyed and not before.
592403bfb495SBarry Smith 
592503bfb495SBarry Smith        The i and j indices are 0 based
592603bfb495SBarry Smith 
592769b1f4b7SBarry Smith        See MatCreateAIJ() for the definition of "diagonal" and "off-diagonal" portion of the matrix
592803bfb495SBarry Smith 
59297b55108eSBarry Smith        This sets local rows and cannot be used to set off-processor values.
59307b55108eSBarry Smith 
5931dca341c0SJed Brown        Use of this routine is discouraged because it is inflexible and cumbersome to use. It is extremely rare that a
5932dca341c0SJed Brown        legacy application natively assembles into exactly this split format. The code to do so is nontrivial and does
5933dca341c0SJed Brown        not easily support in-place reassembly. It is recommended to use MatSetValues() (or a variant thereof) because
5934dca341c0SJed Brown        the resulting assembly is easier to implement, will work with any matrix format, and the user does not have to
5935dca341c0SJed Brown        keep track of the underlying array. Use MatSetOption(A,MAT_IGNORE_OFF_PROC_ENTRIES,PETSC_TRUE) to disable all
5936dca341c0SJed Brown        communication if it is known that only local entries will be set.
593703bfb495SBarry Smith 
593803bfb495SBarry Smith .keywords: matrix, aij, compressed row, sparse, parallel
593903bfb495SBarry Smith 
594003bfb495SBarry Smith .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
594169b1f4b7SBarry Smith           MPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithArrays()
594203bfb495SBarry Smith @*/
59432205254eSKarl Rupp PetscErrorCode  MatCreateMPIAIJWithSplitArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscInt i[],PetscInt j[],PetscScalar a[],PetscInt oi[], PetscInt oj[],PetscScalar oa[],Mat *mat)
594403bfb495SBarry Smith {
594503bfb495SBarry Smith   PetscErrorCode ierr;
594603bfb495SBarry Smith   Mat_MPIAIJ     *maij;
594703bfb495SBarry Smith 
594803bfb495SBarry Smith   PetscFunctionBegin;
5949e32f2f54SBarry Smith   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
5950ea345e14SBarry Smith   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
5951ea345e14SBarry Smith   if (oi[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"oi (row indices) must start with 0");
595203bfb495SBarry Smith   ierr = MatCreate(comm,mat);CHKERRQ(ierr);
595303bfb495SBarry Smith   ierr = MatSetSizes(*mat,m,n,M,N);CHKERRQ(ierr);
595403bfb495SBarry Smith   ierr = MatSetType(*mat,MATMPIAIJ);CHKERRQ(ierr);
595503bfb495SBarry Smith   maij = (Mat_MPIAIJ*) (*mat)->data;
59562205254eSKarl Rupp 
59578d7a6e47SBarry Smith   (*mat)->preallocated = PETSC_TRUE;
595803bfb495SBarry Smith 
595926283091SBarry Smith   ierr = PetscLayoutSetUp((*mat)->rmap);CHKERRQ(ierr);
596026283091SBarry Smith   ierr = PetscLayoutSetUp((*mat)->cmap);CHKERRQ(ierr);
596103bfb495SBarry Smith 
596203bfb495SBarry Smith   ierr = MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,m,n,i,j,a,&maij->A);CHKERRQ(ierr);
5963d0f46423SBarry Smith   ierr = MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,m,(*mat)->cmap->N,oi,oj,oa,&maij->B);CHKERRQ(ierr);
596403bfb495SBarry Smith 
59658d7a6e47SBarry Smith   ierr = MatAssemblyBegin(maij->A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
59668d7a6e47SBarry Smith   ierr = MatAssemblyEnd(maij->A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
59678d7a6e47SBarry Smith   ierr = MatAssemblyBegin(maij->B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
59688d7a6e47SBarry Smith   ierr = MatAssemblyEnd(maij->B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
59698d7a6e47SBarry Smith 
597003bfb495SBarry Smith   ierr = MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
597103bfb495SBarry Smith   ierr = MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
5972dca341c0SJed Brown   ierr = MatSetOption(*mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);CHKERRQ(ierr);
597303bfb495SBarry Smith   PetscFunctionReturn(0);
597403bfb495SBarry Smith }
597503bfb495SBarry Smith 
597681824310SBarry Smith /*
597781824310SBarry Smith     Special version for direct calls from Fortran
597881824310SBarry Smith */
5979b45d2f2cSJed Brown #include <petsc-private/fortranimpl.h>
59807087cfbeSBarry Smith 
598181824310SBarry Smith #if defined(PETSC_HAVE_FORTRAN_CAPS)
598281824310SBarry Smith #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
598381824310SBarry Smith #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
598481824310SBarry Smith #define matsetvaluesmpiaij_ matsetvaluesmpiaij
598581824310SBarry Smith #endif
598681824310SBarry Smith 
598781824310SBarry Smith /* Change these macros so can be used in void function */
598881824310SBarry Smith #undef CHKERRQ
5989e32f2f54SBarry Smith #define CHKERRQ(ierr) CHKERRABORT(PETSC_COMM_WORLD,ierr)
599081824310SBarry Smith #undef SETERRQ2
5991e32f2f54SBarry Smith #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
59924994cf47SJed Brown #undef SETERRQ3
59934994cf47SJed Brown #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)
599481824310SBarry Smith #undef SETERRQ
5995e32f2f54SBarry Smith #define SETERRQ(c,ierr,b) CHKERRABORT(c,ierr)
599681824310SBarry Smith 
599781824310SBarry Smith #undef __FUNCT__
599881824310SBarry Smith #define __FUNCT__ "matsetvaluesmpiaij_"
59998cc058d9SJed Brown PETSC_EXTERN void PETSC_STDCALL matsetvaluesmpiaij_(Mat *mmat,PetscInt *mm,const PetscInt im[],PetscInt *mn,const PetscInt in[],const PetscScalar v[],InsertMode *maddv,PetscErrorCode *_ierr)
600081824310SBarry Smith {
600181824310SBarry Smith   Mat            mat  = *mmat;
600281824310SBarry Smith   PetscInt       m    = *mm, n = *mn;
600381824310SBarry Smith   InsertMode     addv = *maddv;
600481824310SBarry Smith   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
600581824310SBarry Smith   PetscScalar    value;
600681824310SBarry Smith   PetscErrorCode ierr;
6007899cda47SBarry Smith 
60084994cf47SJed Brown   MatCheckPreallocated(mat,1);
60092205254eSKarl Rupp   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
60102205254eSKarl Rupp 
601181824310SBarry Smith #if defined(PETSC_USE_DEBUG)
6012f23aa3ddSBarry Smith   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
601381824310SBarry Smith #endif
601481824310SBarry Smith   {
6015d0f46423SBarry Smith     PetscInt  i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
6016d0f46423SBarry Smith     PetscInt  cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
6017ace3abfcSBarry Smith     PetscBool roworiented = aij->roworiented;
601881824310SBarry Smith 
601981824310SBarry Smith     /* Some Variables required in the macro */
602081824310SBarry Smith     Mat        A                 = aij->A;
602181824310SBarry Smith     Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
602281824310SBarry Smith     PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
6023dd6ea824SBarry Smith     MatScalar  *aa               = a->a;
6024ace3abfcSBarry Smith     PetscBool  ignorezeroentries = (((a->ignorezeroentries)&&(addv==ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
602581824310SBarry Smith     Mat        B                 = aij->B;
602681824310SBarry Smith     Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
6027d0f46423SBarry Smith     PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
6028dd6ea824SBarry Smith     MatScalar  *ba               = b->a;
602981824310SBarry Smith 
603081824310SBarry Smith     PetscInt  *rp1,*rp2,ii,nrow1,nrow2,_i,rmax1,rmax2,N,low1,high1,low2,high2,t,lastcol1,lastcol2;
603181824310SBarry Smith     PetscInt  nonew = a->nonew;
6032dd6ea824SBarry Smith     MatScalar *ap1,*ap2;
603381824310SBarry Smith 
603481824310SBarry Smith     PetscFunctionBegin;
603581824310SBarry Smith     for (i=0; i<m; i++) {
603681824310SBarry Smith       if (im[i] < 0) continue;
603781824310SBarry Smith #if defined(PETSC_USE_DEBUG)
6038e32f2f54SBarry Smith       if (im[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",im[i],mat->rmap->N-1);
603981824310SBarry Smith #endif
604081824310SBarry Smith       if (im[i] >= rstart && im[i] < rend) {
604181824310SBarry Smith         row      = im[i] - rstart;
604281824310SBarry Smith         lastcol1 = -1;
604381824310SBarry Smith         rp1      = aj + ai[row];
604481824310SBarry Smith         ap1      = aa + ai[row];
604581824310SBarry Smith         rmax1    = aimax[row];
604681824310SBarry Smith         nrow1    = ailen[row];
604781824310SBarry Smith         low1     = 0;
604881824310SBarry Smith         high1    = nrow1;
604981824310SBarry Smith         lastcol2 = -1;
605081824310SBarry Smith         rp2      = bj + bi[row];
605181824310SBarry Smith         ap2      = ba + bi[row];
605281824310SBarry Smith         rmax2    = bimax[row];
605381824310SBarry Smith         nrow2    = bilen[row];
605481824310SBarry Smith         low2     = 0;
605581824310SBarry Smith         high2    = nrow2;
605681824310SBarry Smith 
605781824310SBarry Smith         for (j=0; j<n; j++) {
60582205254eSKarl Rupp           if (roworiented) value = v[i*n+j];
60592205254eSKarl Rupp           else value = v[i+j*m];
606081824310SBarry Smith           if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES)) continue;
606181824310SBarry Smith           if (in[j] >= cstart && in[j] < cend) {
606281824310SBarry Smith             col = in[j] - cstart;
606381824310SBarry Smith             MatSetValues_SeqAIJ_A_Private(row,col,value,addv);
606481824310SBarry Smith           } else if (in[j] < 0) continue;
606581824310SBarry Smith #if defined(PETSC_USE_DEBUG)
6066cb9801acSJed Brown           else if (in[j] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[j],mat->cmap->N-1);
606781824310SBarry Smith #endif
606881824310SBarry Smith           else {
606981824310SBarry Smith             if (mat->was_assembled) {
607081824310SBarry Smith               if (!aij->colmap) {
6071ab9863d7SBarry Smith                 ierr = MatCreateColmap_MPIAIJ_Private(mat);CHKERRQ(ierr);
607281824310SBarry Smith               }
607381824310SBarry Smith #if defined(PETSC_USE_CTABLE)
607481824310SBarry Smith               ierr = PetscTableFind(aij->colmap,in[j]+1,&col);CHKERRQ(ierr);
607581824310SBarry Smith               col--;
607681824310SBarry Smith #else
607781824310SBarry Smith               col = aij->colmap[in[j]] - 1;
607881824310SBarry Smith #endif
607981824310SBarry Smith               if (col < 0 && !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
6080ab9863d7SBarry Smith                 ierr = MatDisAssemble_MPIAIJ(mat);CHKERRQ(ierr);
608181824310SBarry Smith                 col  =  in[j];
608281824310SBarry Smith                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
608381824310SBarry Smith                 B     = aij->B;
608481824310SBarry Smith                 b     = (Mat_SeqAIJ*)B->data;
608581824310SBarry Smith                 bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j;
608681824310SBarry Smith                 rp2   = bj + bi[row];
608781824310SBarry Smith                 ap2   = ba + bi[row];
608881824310SBarry Smith                 rmax2 = bimax[row];
608981824310SBarry Smith                 nrow2 = bilen[row];
609081824310SBarry Smith                 low2  = 0;
609181824310SBarry Smith                 high2 = nrow2;
6092d0f46423SBarry Smith                 bm    = aij->B->rmap->n;
609381824310SBarry Smith                 ba    = b->a;
609481824310SBarry Smith               }
609581824310SBarry Smith             } else col = in[j];
609681824310SBarry Smith             MatSetValues_SeqAIJ_B_Private(row,col,value,addv);
609781824310SBarry Smith           }
609881824310SBarry Smith         }
60992205254eSKarl Rupp       } else if (!aij->donotstash) {
610081824310SBarry Smith         if (roworiented) {
6101ace3abfcSBarry Smith           ierr = MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));CHKERRQ(ierr);
610281824310SBarry Smith         } else {
6103ace3abfcSBarry Smith           ierr = MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));CHKERRQ(ierr);
610481824310SBarry Smith         }
610581824310SBarry Smith       }
610681824310SBarry Smith     }
61072205254eSKarl Rupp   }
610881824310SBarry Smith   PetscFunctionReturnVoid();
610981824310SBarry Smith }
611003bfb495SBarry Smith 
6111