Actual source code: mpiaij.c
1: #define PETSCMAT_DLL
3: #include ../src/mat/impls/aij/mpi/mpiaij.h
4: #include ../src/inline/spops.h
8: /*
9: Distributes a SeqAIJ matrix across a set of processes. Code stolen from
10: MatLoad_MPIAIJ(). Horrible lack of reuse. Should be a routine for each matrix type.
12: Only for square matrices
13: */
14: PetscErrorCode MatDistribute_MPIAIJ(MPI_Comm comm,Mat gmat,PetscInt m,MatReuse reuse,Mat *inmat)
15: {
16: PetscMPIInt rank,size;
17: PetscInt *rowners,*dlens,*olens,i,rstart,rend,j,jj,nz,*gmataj,cnt,row,*ld;
19: Mat mat;
20: Mat_SeqAIJ *gmata;
21: PetscMPIInt tag;
22: MPI_Status status;
23: PetscTruth aij;
24: MatScalar *gmataa,*ao,*ad,*gmataarestore=0;
27: CHKMEMQ;
28: MPI_Comm_rank(comm,&rank);
29: MPI_Comm_size(comm,&size);
30: if (!rank) {
31: PetscTypeCompare((PetscObject)gmat,MATSEQAIJ,&aij);
32: if (!aij) SETERRQ1(PETSC_ERR_SUP,"Currently no support for input matrix of type %s\n",((PetscObject)gmat)->type_name);
33: }
34: if (reuse == MAT_INITIAL_MATRIX) {
35: MatCreate(comm,&mat);
36: MatSetSizes(mat,m,m,PETSC_DETERMINE,PETSC_DETERMINE);
37: MatSetType(mat,MATAIJ);
38: PetscMalloc((size+1)*sizeof(PetscInt),&rowners);
39: PetscMalloc2(m,PetscInt,&dlens,m,PetscInt,&olens);
40: MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);
41: rowners[0] = 0;
42: for (i=2; i<=size; i++) {
43: rowners[i] += rowners[i-1];
44: }
45: rstart = rowners[rank];
46: rend = rowners[rank+1];
47: PetscObjectGetNewTag((PetscObject)mat,&tag);
48: if (!rank) {
49: gmata = (Mat_SeqAIJ*) gmat->data;
50: /* send row lengths to all processors */
51: for (i=0; i<m; i++) dlens[i] = gmata->ilen[i];
52: for (i=1; i<size; i++) {
53: MPI_Send(gmata->ilen + rowners[i],rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);
54: }
55: /* determine number diagonal and off-diagonal counts */
56: PetscMemzero(olens,m*sizeof(PetscInt));
57: PetscMalloc(m*sizeof(PetscInt),&ld);
58: PetscMemzero(ld,m*sizeof(PetscInt));
59: jj = 0;
60: for (i=0; i<m; i++) {
61: for (j=0; j<dlens[i]; j++) {
62: if (gmata->j[jj] < rstart) ld[i]++;
63: if (gmata->j[jj] < rstart || gmata->j[jj] >= rend) olens[i]++;
64: jj++;
65: }
66: }
67: /* send column indices to other processes */
68: for (i=1; i<size; i++) {
69: nz = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
70: MPI_Send(&nz,1,MPIU_INT,i,tag,comm);
71: MPI_Send(gmata->j + gmata->i[rowners[i]],nz,MPIU_INT,i,tag,comm);
72: }
74: /* send numerical values to other processes */
75: for (i=1; i<size; i++) {
76: nz = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
77: MPI_Send(gmata->a + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);
78: }
79: gmataa = gmata->a;
80: gmataj = gmata->j;
82: } else {
83: /* receive row lengths */
84: MPI_Recv(dlens,m,MPIU_INT,0,tag,comm,&status);
85: /* receive column indices */
86: MPI_Recv(&nz,1,MPIU_INT,0,tag,comm,&status);
87: PetscMalloc2(nz,PetscScalar,&gmataa,nz,PetscInt,&gmataj);
88: MPI_Recv(gmataj,nz,MPIU_INT,0,tag,comm,&status);
89: /* determine number diagonal and off-diagonal counts */
90: PetscMemzero(olens,m*sizeof(PetscInt));
91: PetscMalloc(m*sizeof(PetscInt),&ld);
92: PetscMemzero(ld,m*sizeof(PetscInt));
93: jj = 0;
94: for (i=0; i<m; i++) {
95: for (j=0; j<dlens[i]; j++) {
96: if (gmataj[jj] < rstart) ld[i]++;
97: if (gmataj[jj] < rstart || gmataj[jj] >= rend) olens[i]++;
98: jj++;
99: }
100: }
101: /* receive numerical values */
102: PetscMemzero(gmataa,nz*sizeof(PetscScalar));
103: MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);
104: }
105: /* set preallocation */
106: for (i=0; i<m; i++) {
107: dlens[i] -= olens[i];
108: }
109: MatSeqAIJSetPreallocation(mat,0,dlens);
110: MatMPIAIJSetPreallocation(mat,0,dlens,0,olens);
111:
112: for (i=0; i<m; i++) {
113: dlens[i] += olens[i];
114: }
115: cnt = 0;
116: for (i=0; i<m; i++) {
117: row = rstart + i;
118: MatSetValues(mat,1,&row,dlens[i],gmataj+cnt,gmataa+cnt,INSERT_VALUES);
119: cnt += dlens[i];
120: }
121: if (rank) {
122: PetscFree2(gmataa,gmataj);
123: }
124: PetscFree2(dlens,olens);
125: PetscFree(rowners);
126: ((Mat_MPIAIJ*)(mat->data))->ld = ld;
127: *inmat = mat;
128: } else { /* column indices are already set; only need to move over numerical values from process 0 */
129: Mat_SeqAIJ *Ad = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->A->data;
130: Mat_SeqAIJ *Ao = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->B->data;
131: mat = *inmat;
132: PetscObjectGetNewTag((PetscObject)mat,&tag);
133: if (!rank) {
134: /* send numerical values to other processes */
135: gmata = (Mat_SeqAIJ*) gmat->data;
136: MatGetOwnershipRanges(mat,(const PetscInt**)&rowners);
137: gmataa = gmata->a;
138: for (i=1; i<size; i++) {
139: nz = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
140: MPI_Send(gmataa + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);
141: }
142: nz = gmata->i[rowners[1]]-gmata->i[rowners[0]];
143: } else {
144: /* receive numerical values from process 0*/
145: nz = Ad->nz + Ao->nz;
146: PetscMalloc(nz*sizeof(PetscScalar),&gmataa); gmataarestore = gmataa;
147: MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);
148: }
149: /* transfer numerical values into the diagonal A and off diagonal B parts of mat */
150: ld = ((Mat_MPIAIJ*)(mat->data))->ld;
151: ad = Ad->a;
152: ao = Ao->a;
153: if (mat->rmap->n) {
154: i = 0;
155: nz = ld[i]; PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar)); ao += nz; gmataa += nz;
156: nz = Ad->i[i+1] - Ad->i[i]; PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar)); ad += nz; gmataa += nz;
157: }
158: for (i=1; i<mat->rmap->n; i++) {
159: nz = Ao->i[i] - Ao->i[i-1] - ld[i-1] + ld[i]; PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar)); ao += nz; gmataa += nz;
160: nz = Ad->i[i+1] - Ad->i[i]; PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar)); ad += nz; gmataa += nz;
161: }
162: i--;
163: if (mat->rmap->n) {
164: nz = Ao->i[i+1] - Ao->i[i] - ld[i]; PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar)); ao += nz; gmataa += nz;
165: }
166: if (rank) {
167: PetscFree(gmataarestore);
168: }
169: }
170: MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
171: MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
172: CHKMEMQ;
173: return(0);
174: }
176: /*
177: Local utility routine that creates a mapping from the global column
178: number to the local number in the off-diagonal part of the local
179: storage of the matrix. When PETSC_USE_CTABLE is used this is scalable at
180: a slightly higher hash table cost; without it it is not scalable (each processor
181: has an order N integer array but is fast to acess.
182: */
185: PetscErrorCode CreateColmap_MPIAIJ_Private(Mat mat)
186: {
187: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
189: PetscInt n = aij->B->cmap->n,i;
192: #if defined (PETSC_USE_CTABLE)
193: PetscTableCreate(n,&aij->colmap);
194: for (i=0; i<n; i++){
195: PetscTableAdd(aij->colmap,aij->garray[i]+1,i+1);
196: }
197: #else
198: PetscMalloc((mat->cmap->N+1)*sizeof(PetscInt),&aij->colmap);
199: PetscLogObjectMemory(mat,mat->cmap->N*sizeof(PetscInt));
200: PetscMemzero(aij->colmap,mat->cmap->N*sizeof(PetscInt));
201: for (i=0; i<n; i++) aij->colmap[aij->garray[i]] = i+1;
202: #endif
203: return(0);
204: }
207: #define CHUNKSIZE 15
208: #define MatSetValues_SeqAIJ_A_Private(row,col,value,addv) \
209: { \
210: if (col <= lastcol1) low1 = 0; else high1 = nrow1; \
211: lastcol1 = col;\
212: while (high1-low1 > 5) { \
213: t = (low1+high1)/2; \
214: if (rp1[t] > col) high1 = t; \
215: else low1 = t; \
216: } \
217: for (_i=low1; _i<high1; _i++) { \
218: if (rp1[_i] > col) break; \
219: if (rp1[_i] == col) { \
220: if (addv == ADD_VALUES) ap1[_i] += value; \
221: else ap1[_i] = value; \
222: goto a_noinsert; \
223: } \
224: } \
225: if (value == 0.0 && ignorezeroentries) {low1 = 0; high1 = nrow1;goto a_noinsert;} \
226: if (nonew == 1) {low1 = 0; high1 = nrow1; goto a_noinsert;} \
227: if (nonew == -1) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
228: MatSeqXAIJReallocateAIJ(A,am,1,nrow1,row,col,rmax1,aa,ai,aj,rp1,ap1,aimax,nonew,MatScalar); \
229: N = nrow1++ - 1; a->nz++; high1++; \
230: /* shift up all the later entries in this row */ \
231: for (ii=N; ii>=_i; ii--) { \
232: rp1[ii+1] = rp1[ii]; \
233: ap1[ii+1] = ap1[ii]; \
234: } \
235: rp1[_i] = col; \
236: ap1[_i] = value; \
237: a_noinsert: ; \
238: ailen[row] = nrow1; \
239: }
242: #define MatSetValues_SeqAIJ_B_Private(row,col,value,addv) \
243: { \
244: if (col <= lastcol2) low2 = 0; else high2 = nrow2; \
245: lastcol2 = col;\
246: while (high2-low2 > 5) { \
247: t = (low2+high2)/2; \
248: if (rp2[t] > col) high2 = t; \
249: else low2 = t; \
250: } \
251: for (_i=low2; _i<high2; _i++) { \
252: if (rp2[_i] > col) break; \
253: if (rp2[_i] == col) { \
254: if (addv == ADD_VALUES) ap2[_i] += value; \
255: else ap2[_i] = value; \
256: goto b_noinsert; \
257: } \
258: } \
259: if (value == 0.0 && ignorezeroentries) {low2 = 0; high2 = nrow2; goto b_noinsert;} \
260: if (nonew == 1) {low2 = 0; high2 = nrow2; goto b_noinsert;} \
261: if (nonew == -1) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
262: MatSeqXAIJReallocateAIJ(B,bm,1,nrow2,row,col,rmax2,ba,bi,bj,rp2,ap2,bimax,nonew,MatScalar); \
263: N = nrow2++ - 1; b->nz++; high2++; \
264: /* shift up all the later entries in this row */ \
265: for (ii=N; ii>=_i; ii--) { \
266: rp2[ii+1] = rp2[ii]; \
267: ap2[ii+1] = ap2[ii]; \
268: } \
269: rp2[_i] = col; \
270: ap2[_i] = value; \
271: b_noinsert: ; \
272: bilen[row] = nrow2; \
273: }
277: PetscErrorCode MatSetValuesRow_MPIAIJ(Mat A,PetscInt row,const PetscScalar v[])
278: {
279: Mat_MPIAIJ *mat = (Mat_MPIAIJ*)A->data;
280: Mat_SeqAIJ *a = (Mat_SeqAIJ*)mat->A->data,*b = (Mat_SeqAIJ*)mat->B->data;
282: PetscInt l,*garray = mat->garray,diag;
285: /* code only works for square matrices A */
287: /* find size of row to the left of the diagonal part */
288: MatGetOwnershipRange(A,&diag,0);
289: row = row - diag;
290: for (l=0; l<b->i[row+1]-b->i[row]; l++) {
291: if (garray[b->j[b->i[row]+l]] > diag) break;
292: }
293: PetscMemcpy(b->a+b->i[row],v,l*sizeof(PetscScalar));
295: /* diagonal part */
296: PetscMemcpy(a->a+a->i[row],v+l,(a->i[row+1]-a->i[row])*sizeof(PetscScalar));
298: /* right of diagonal part */
299: 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));
300: return(0);
301: }
305: PetscErrorCode MatSetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
306: {
307: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
308: PetscScalar value;
310: PetscInt i,j,rstart = mat->rmap->rstart,rend = mat->rmap->rend;
311: PetscInt cstart = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
312: PetscTruth roworiented = aij->roworiented;
314: /* Some Variables required in the macro */
315: Mat A = aij->A;
316: Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
317: PetscInt *aimax = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
318: MatScalar *aa = a->a;
319: PetscTruth ignorezeroentries = a->ignorezeroentries;
320: Mat B = aij->B;
321: Mat_SeqAIJ *b = (Mat_SeqAIJ*)B->data;
322: PetscInt *bimax = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
323: MatScalar *ba = b->a;
325: PetscInt *rp1,*rp2,ii,nrow1,nrow2,_i,rmax1,rmax2,N,low1,high1,low2,high2,t,lastcol1,lastcol2;
326: PetscInt nonew = a->nonew;
327: MatScalar *ap1,*ap2;
330: for (i=0; i<m; i++) {
331: if (im[i] < 0) continue;
332: #if defined(PETSC_USE_DEBUG)
333: if (im[i] >= mat->rmap->N) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",im[i],mat->rmap->N-1);
334: #endif
335: if (im[i] >= rstart && im[i] < rend) {
336: row = im[i] - rstart;
337: lastcol1 = -1;
338: rp1 = aj + ai[row];
339: ap1 = aa + ai[row];
340: rmax1 = aimax[row];
341: nrow1 = ailen[row];
342: low1 = 0;
343: high1 = nrow1;
344: lastcol2 = -1;
345: rp2 = bj + bi[row];
346: ap2 = ba + bi[row];
347: rmax2 = bimax[row];
348: nrow2 = bilen[row];
349: low2 = 0;
350: high2 = nrow2;
352: for (j=0; j<n; j++) {
353: if (v) {if (roworiented) value = v[i*n+j]; else value = v[i+j*m];} else value = 0.0;
354: if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES)) continue;
355: if (in[j] >= cstart && in[j] < cend){
356: col = in[j] - cstart;
357: MatSetValues_SeqAIJ_A_Private(row,col,value,addv);
358: } else if (in[j] < 0) continue;
359: #if defined(PETSC_USE_DEBUG)
360: else if (in[j] >= mat->cmap->N) {SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[j],mat->cmap->N-1);}
361: #endif
362: else {
363: if (mat->was_assembled) {
364: if (!aij->colmap) {
365: CreateColmap_MPIAIJ_Private(mat);
366: }
367: #if defined (PETSC_USE_CTABLE)
368: PetscTableFind(aij->colmap,in[j]+1,&col);
369: col--;
370: #else
371: col = aij->colmap[in[j]] - 1;
372: #endif
373: if (col < 0 && !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
374: DisAssemble_MPIAIJ(mat);
375: col = in[j];
376: /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
377: B = aij->B;
378: b = (Mat_SeqAIJ*)B->data;
379: bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j; ba = b->a;
380: rp2 = bj + bi[row];
381: ap2 = ba + bi[row];
382: rmax2 = bimax[row];
383: nrow2 = bilen[row];
384: low2 = 0;
385: high2 = nrow2;
386: bm = aij->B->rmap->n;
387: ba = b->a;
388: }
389: } else col = in[j];
390: MatSetValues_SeqAIJ_B_Private(row,col,value,addv);
391: }
392: }
393: } else {
394: if (!aij->donotstash) {
395: if (roworiented) {
396: if (ignorezeroentries && v[i*n] == 0.0) continue;
397: MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n);
398: } else {
399: if (ignorezeroentries && v[i] == 0.0) continue;
400: MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m);
401: }
402: }
403: }
404: }
405: return(0);
406: }
410: PetscErrorCode MatGetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
411: {
412: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
414: PetscInt i,j,rstart = mat->rmap->rstart,rend = mat->rmap->rend;
415: PetscInt cstart = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
418: for (i=0; i<m; i++) {
419: if (idxm[i] < 0) continue; /* SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",idxm[i]);*/
420: if (idxm[i] >= mat->rmap->N) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",idxm[i],mat->rmap->N-1);
421: if (idxm[i] >= rstart && idxm[i] < rend) {
422: row = idxm[i] - rstart;
423: for (j=0; j<n; j++) {
424: if (idxn[j] < 0) continue; /* SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",idxn[j]); */
425: if (idxn[j] >= mat->cmap->N) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",idxn[j],mat->cmap->N-1);
426: if (idxn[j] >= cstart && idxn[j] < cend){
427: col = idxn[j] - cstart;
428: MatGetValues(aij->A,1,&row,1,&col,v+i*n+j);
429: } else {
430: if (!aij->colmap) {
431: CreateColmap_MPIAIJ_Private(mat);
432: }
433: #if defined (PETSC_USE_CTABLE)
434: PetscTableFind(aij->colmap,idxn[j]+1,&col);
435: col --;
436: #else
437: col = aij->colmap[idxn[j]] - 1;
438: #endif
439: if ((col < 0) || (aij->garray[col] != idxn[j])) *(v+i*n+j) = 0.0;
440: else {
441: MatGetValues(aij->B,1,&row,1,&col,v+i*n+j);
442: }
443: }
444: }
445: } else {
446: SETERRQ(PETSC_ERR_SUP,"Only local values currently supported");
447: }
448: }
449: return(0);
450: }
454: PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat,MatAssemblyType mode)
455: {
456: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
458: PetscInt nstash,reallocs;
459: InsertMode addv;
462: if (aij->donotstash) {
463: return(0);
464: }
466: /* make sure all processors are either in INSERTMODE or ADDMODE */
467: MPI_Allreduce(&mat->insertmode,&addv,1,MPI_INT,MPI_BOR,((PetscObject)mat)->comm);
468: if (addv == (ADD_VALUES|INSERT_VALUES)) {
469: SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Some processors inserted others added");
470: }
471: mat->insertmode = addv; /* in case this processor had no cache */
473: MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);
474: MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
475: PetscInfo2(aij->A,"Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
476: return(0);
477: }
481: PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat,MatAssemblyType mode)
482: {
483: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
484: Mat_SeqAIJ *a=(Mat_SeqAIJ *)aij->A->data;
486: PetscMPIInt n;
487: PetscInt i,j,rstart,ncols,flg;
488: PetscInt *row,*col;
489: PetscTruth other_disassembled;
490: PetscScalar *val;
491: InsertMode addv = mat->insertmode;
493: /* do not use 'b = (Mat_SeqAIJ *)aij->B->data' as B can be reset in disassembly */
495: if (!aij->donotstash) {
496: while (1) {
497: MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);
498: if (!flg) break;
500: for (i=0; i<n;) {
501: /* Now identify the consecutive vals belonging to the same row */
502: for (j=i,rstart=row[j]; j<n; j++) { if (row[j] != rstart) break; }
503: if (j < n) ncols = j-i;
504: else ncols = n-i;
505: /* Now assemble all these values with a single function call */
506: MatSetValues_MPIAIJ(mat,1,row+i,ncols,col+i,val+i,addv);
507: i = j;
508: }
509: }
510: MatStashScatterEnd_Private(&mat->stash);
511: }
512: a->compressedrow.use = PETSC_FALSE;
513: MatAssemblyBegin(aij->A,mode);
514: MatAssemblyEnd(aij->A,mode);
516: /* determine if any processor has disassembled, if so we must
517: also disassemble ourselfs, in order that we may reassemble. */
518: /*
519: if nonzero structure of submatrix B cannot change then we know that
520: no processor disassembled thus we can skip this stuff
521: */
522: if (!((Mat_SeqAIJ*)aij->B->data)->nonew) {
523: MPI_Allreduce(&mat->was_assembled,&other_disassembled,1,MPI_INT,MPI_PROD,((PetscObject)mat)->comm);
524: if (mat->was_assembled && !other_disassembled) {
525: DisAssemble_MPIAIJ(mat);
526: }
527: }
528: if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
529: MatSetUpMultiply_MPIAIJ(mat);
530: }
531: MatSetOption(aij->B,MAT_USE_INODES,PETSC_FALSE);
532: ((Mat_SeqAIJ *)aij->B->data)->compressedrow.use = PETSC_TRUE; /* b->compressedrow.use */
533: MatAssemblyBegin(aij->B,mode);
534: MatAssemblyEnd(aij->B,mode);
536: PetscFree(aij->rowvalues);
537: aij->rowvalues = 0;
539: /* used by MatAXPY() */
540: a->xtoy = 0; ((Mat_SeqAIJ *)aij->B->data)->xtoy = 0; /* b->xtoy = 0 */
541: a->XtoY = 0; ((Mat_SeqAIJ *)aij->B->data)->XtoY = 0; /* b->XtoY = 0 */
543: return(0);
544: }
548: PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
549: {
550: Mat_MPIAIJ *l = (Mat_MPIAIJ*)A->data;
554: MatZeroEntries(l->A);
555: MatZeroEntries(l->B);
556: return(0);
557: }
561: PetscErrorCode MatZeroRows_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag)
562: {
563: Mat_MPIAIJ *l = (Mat_MPIAIJ*)A->data;
565: PetscMPIInt size = l->size,imdex,n,rank = l->rank,tag = ((PetscObject)A)->tag,lastidx = -1;
566: PetscInt i,*owners = A->rmap->range;
567: PetscInt *nprocs,j,idx,nsends,row;
568: PetscInt nmax,*svalues,*starts,*owner,nrecvs;
569: PetscInt *rvalues,count,base,slen,*source;
570: PetscInt *lens,*lrows,*values,rstart=A->rmap->rstart;
571: MPI_Comm comm = ((PetscObject)A)->comm;
572: MPI_Request *send_waits,*recv_waits;
573: MPI_Status recv_status,*send_status;
574: #if defined(PETSC_DEBUG)
575: PetscTruth found = PETSC_FALSE;
576: #endif
579: /* first count number of contributors to each processor */
580: PetscMalloc(2*size*sizeof(PetscInt),&nprocs);
581: PetscMemzero(nprocs,2*size*sizeof(PetscInt));
582: PetscMalloc((N+1)*sizeof(PetscInt),&owner); /* see note*/
583: j = 0;
584: for (i=0; i<N; i++) {
585: if (lastidx > (idx = rows[i])) j = 0;
586: lastidx = idx;
587: for (; j<size; j++) {
588: if (idx >= owners[j] && idx < owners[j+1]) {
589: nprocs[2*j]++;
590: nprocs[2*j+1] = 1;
591: owner[i] = j;
592: #if defined(PETSC_DEBUG)
593: found = PETSC_TRUE;
594: #endif
595: break;
596: }
597: }
598: #if defined(PETSC_DEBUG)
599: if (!found) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Index out of range");
600: found = PETSC_FALSE;
601: #endif
602: }
603: nsends = 0; for (i=0; i<size; i++) { nsends += nprocs[2*i+1];}
605: /* inform other processors of number of messages and max length*/
606: PetscMaxSum(comm,nprocs,&nmax,&nrecvs);
608: /* post receives: */
609: PetscMalloc((nrecvs+1)*(nmax+1)*sizeof(PetscInt),&rvalues);
610: PetscMalloc((nrecvs+1)*sizeof(MPI_Request),&recv_waits);
611: for (i=0; i<nrecvs; i++) {
612: MPI_Irecv(rvalues+nmax*i,nmax,MPIU_INT,MPI_ANY_SOURCE,tag,comm,recv_waits+i);
613: }
615: /* do sends:
616: 1) starts[i] gives the starting index in svalues for stuff going to
617: the ith processor
618: */
619: PetscMalloc((N+1)*sizeof(PetscInt),&svalues);
620: PetscMalloc((nsends+1)*sizeof(MPI_Request),&send_waits);
621: PetscMalloc((size+1)*sizeof(PetscInt),&starts);
622: starts[0] = 0;
623: for (i=1; i<size; i++) { starts[i] = starts[i-1] + nprocs[2*i-2];}
624: for (i=0; i<N; i++) {
625: svalues[starts[owner[i]]++] = rows[i];
626: }
628: starts[0] = 0;
629: for (i=1; i<size+1; i++) { starts[i] = starts[i-1] + nprocs[2*i-2];}
630: count = 0;
631: for (i=0; i<size; i++) {
632: if (nprocs[2*i+1]) {
633: MPI_Isend(svalues+starts[i],nprocs[2*i],MPIU_INT,i,tag,comm,send_waits+count++);
634: }
635: }
636: PetscFree(starts);
638: base = owners[rank];
640: /* wait on receives */
641: PetscMalloc(2*(nrecvs+1)*sizeof(PetscInt),&lens);
642: source = lens + nrecvs;
643: count = nrecvs; slen = 0;
644: while (count) {
645: MPI_Waitany(nrecvs,recv_waits,&imdex,&recv_status);
646: /* unpack receives into our local space */
647: MPI_Get_count(&recv_status,MPIU_INT,&n);
648: source[imdex] = recv_status.MPI_SOURCE;
649: lens[imdex] = n;
650: slen += n;
651: count--;
652: }
653: PetscFree(recv_waits);
654:
655: /* move the data into the send scatter */
656: PetscMalloc((slen+1)*sizeof(PetscInt),&lrows);
657: count = 0;
658: for (i=0; i<nrecvs; i++) {
659: values = rvalues + i*nmax;
660: for (j=0; j<lens[i]; j++) {
661: lrows[count++] = values[j] - base;
662: }
663: }
664: PetscFree(rvalues);
665: PetscFree(lens);
666: PetscFree(owner);
667: PetscFree(nprocs);
668:
669: /* actually zap the local rows */
670: /*
671: Zero the required rows. If the "diagonal block" of the matrix
672: is square and the user wishes to set the diagonal we use separate
673: code so that MatSetValues() is not called for each diagonal allocating
674: new memory, thus calling lots of mallocs and slowing things down.
676: Contributed by: Matthew Knepley
677: */
678: /* must zero l->B before l->A because the (diag) case below may put values into l->B*/
679: MatZeroRows(l->B,slen,lrows,0.0);
680: if ((diag != 0.0) && (l->A->rmap->N == l->A->cmap->N)) {
681: MatZeroRows(l->A,slen,lrows,diag);
682: } else if (diag != 0.0) {
683: MatZeroRows(l->A,slen,lrows,0.0);
684: if (((Mat_SeqAIJ*)l->A->data)->nonew) {
685: SETERRQ(PETSC_ERR_SUP,"MatZeroRows() on rectangular matrices cannot be used with the Mat options\n\
686: MAT_NEW_NONZERO_LOCATIONS,MAT_NEW_NONZERO_LOCATION_ERR,MAT_NEW_NONZERO_ALLOCATION_ERR");
687: }
688: for (i = 0; i < slen; i++) {
689: row = lrows[i] + rstart;
690: MatSetValues(A,1,&row,1,&row,&diag,INSERT_VALUES);
691: }
692: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
693: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
694: } else {
695: MatZeroRows(l->A,slen,lrows,0.0);
696: }
697: PetscFree(lrows);
699: /* wait on sends */
700: if (nsends) {
701: PetscMalloc(nsends*sizeof(MPI_Status),&send_status);
702: MPI_Waitall(nsends,send_waits,send_status);
703: PetscFree(send_status);
704: }
705: PetscFree(send_waits);
706: PetscFree(svalues);
708: return(0);
709: }
713: PetscErrorCode MatMult_MPIAIJ(Mat A,Vec xx,Vec yy)
714: {
715: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
717: PetscInt nt;
720: VecGetLocalSize(xx,&nt);
721: if (nt != A->cmap->n) {
722: SETERRQ2(PETSC_ERR_ARG_SIZ,"Incompatible partition of A (%D) and xx (%D)",A->cmap->n,nt);
723: }
724: VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
725: (*a->A->ops->mult)(a->A,xx,yy);
726: VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
727: (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
728: return(0);
729: }
733: PetscErrorCode MatMultAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
734: {
735: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
739: VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
740: (*a->A->ops->multadd)(a->A,xx,yy,zz);
741: VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
742: (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);
743: return(0);
744: }
748: PetscErrorCode MatMultTranspose_MPIAIJ(Mat A,Vec xx,Vec yy)
749: {
750: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
752: PetscTruth merged;
755: VecScatterGetMerged(a->Mvctx,&merged);
756: /* do nondiagonal part */
757: (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
758: if (!merged) {
759: /* send it on its way */
760: VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
761: /* do local part */
762: (*a->A->ops->multtranspose)(a->A,xx,yy);
763: /* receive remote parts: note this assumes the values are not actually */
764: /* added in yy until the next line, */
765: VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
766: } else {
767: /* do local part */
768: (*a->A->ops->multtranspose)(a->A,xx,yy);
769: /* send it on its way */
770: VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
771: /* values actually were received in the Begin() but we need to call this nop */
772: VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
773: }
774: return(0);
775: }
780: PetscErrorCode MatIsTranspose_MPIAIJ(Mat Amat,Mat Bmat,PetscReal tol,PetscTruth *f)
781: {
782: MPI_Comm comm;
783: Mat_MPIAIJ *Aij = (Mat_MPIAIJ *) Amat->data, *Bij;
784: Mat Adia = Aij->A, Bdia, Aoff,Boff,*Aoffs,*Boffs;
785: IS Me,Notme;
787: PetscInt M,N,first,last,*notme,i;
788: PetscMPIInt size;
792: /* Easy test: symmetric diagonal block */
793: Bij = (Mat_MPIAIJ *) Bmat->data; Bdia = Bij->A;
794: MatIsTranspose(Adia,Bdia,tol,f);
795: if (!*f) return(0);
796: PetscObjectGetComm((PetscObject)Amat,&comm);
797: MPI_Comm_size(comm,&size);
798: if (size == 1) return(0);
800: /* Hard test: off-diagonal block. This takes a MatGetSubMatrix. */
801: MatGetSize(Amat,&M,&N);
802: MatGetOwnershipRange(Amat,&first,&last);
803: PetscMalloc((N-last+first)*sizeof(PetscInt),¬me);
804: for (i=0; i<first; i++) notme[i] = i;
805: for (i=last; i<M; i++) notme[i-last+first] = i;
806: ISCreateGeneral(MPI_COMM_SELF,N-last+first,notme,&Notme);
807: ISCreateStride(MPI_COMM_SELF,last-first,first,1,&Me);
808: MatGetSubMatrices(Amat,1,&Me,&Notme,MAT_INITIAL_MATRIX,&Aoffs);
809: Aoff = Aoffs[0];
810: MatGetSubMatrices(Bmat,1,&Notme,&Me,MAT_INITIAL_MATRIX,&Boffs);
811: Boff = Boffs[0];
812: MatIsTranspose(Aoff,Boff,tol,f);
813: MatDestroyMatrices(1,&Aoffs);
814: MatDestroyMatrices(1,&Boffs);
815: ISDestroy(Me);
816: ISDestroy(Notme);
818: return(0);
819: }
824: PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
825: {
826: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
830: /* do nondiagonal part */
831: (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
832: /* send it on its way */
833: VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
834: /* do local part */
835: (*a->A->ops->multtransposeadd)(a->A,xx,yy,zz);
836: /* receive remote parts */
837: VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
838: return(0);
839: }
841: /*
842: This only works correctly for square matrices where the subblock A->A is the
843: diagonal block
844: */
847: PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A,Vec v)
848: {
850: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
853: if (A->rmap->N != A->cmap->N) SETERRQ(PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block");
854: if (A->rmap->rstart != A->cmap->rstart || A->rmap->rend != A->cmap->rend) {
855: SETERRQ(PETSC_ERR_ARG_SIZ,"row partition must equal col partition");
856: }
857: MatGetDiagonal(a->A,v);
858: return(0);
859: }
863: PetscErrorCode MatScale_MPIAIJ(Mat A,PetscScalar aa)
864: {
865: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
869: MatScale(a->A,aa);
870: MatScale(a->B,aa);
871: return(0);
872: }
876: PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
877: {
878: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
882: #if defined(PETSC_USE_LOG)
883: PetscLogObjectState((PetscObject)mat,"Rows=%D, Cols=%D",mat->rmap->N,mat->cmap->N);
884: #endif
885: MatStashDestroy_Private(&mat->stash);
886: MatDestroy(aij->A);
887: MatDestroy(aij->B);
888: #if defined (PETSC_USE_CTABLE)
889: if (aij->colmap) {PetscTableDestroy(aij->colmap);}
890: #else
891: PetscFree(aij->colmap);
892: #endif
893: PetscFree(aij->garray);
894: if (aij->lvec) {VecDestroy(aij->lvec);}
895: if (aij->Mvctx) {VecScatterDestroy(aij->Mvctx);}
896: PetscFree(aij->rowvalues);
897: PetscFree(aij->ld);
898: PetscFree(aij);
900: PetscObjectChangeTypeName((PetscObject)mat,0);
901: PetscObjectComposeFunction((PetscObject)mat,"MatStoreValues_C","",PETSC_NULL);
902: PetscObjectComposeFunction((PetscObject)mat,"MatRetrieveValues_C","",PETSC_NULL);
903: PetscObjectComposeFunction((PetscObject)mat,"MatGetDiagonalBlock_C","",PETSC_NULL);
904: PetscObjectComposeFunction((PetscObject)mat,"MatIsTranspose_C","",PETSC_NULL);
905: PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocation_C","",PETSC_NULL);
906: PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocationCSR_C","",PETSC_NULL);
907: PetscObjectComposeFunction((PetscObject)mat,"MatDiagonalScaleLocal_C","",PETSC_NULL);
908: return(0);
909: }
913: PetscErrorCode MatView_MPIAIJ_Binary(Mat mat,PetscViewer viewer)
914: {
915: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
916: Mat_SeqAIJ* A = (Mat_SeqAIJ*)aij->A->data;
917: Mat_SeqAIJ* B = (Mat_SeqAIJ*)aij->B->data;
918: PetscErrorCode ierr;
919: PetscMPIInt rank,size,tag = ((PetscObject)viewer)->tag;
920: int fd;
921: PetscInt nz,header[4],*row_lengths,*range=0,rlen,i;
922: PetscInt nzmax,*column_indices,j,k,col,*garray = aij->garray,cnt,cstart = mat->cmap->rstart,rnz;
923: PetscScalar *column_values;
926: MPI_Comm_rank(((PetscObject)mat)->comm,&rank);
927: MPI_Comm_size(((PetscObject)mat)->comm,&size);
928: nz = A->nz + B->nz;
929: if (!rank) {
930: header[0] = MAT_FILE_COOKIE;
931: header[1] = mat->rmap->N;
932: header[2] = mat->cmap->N;
933: MPI_Reduce(&nz,&header[3],1,MPIU_INT,MPI_SUM,0,((PetscObject)mat)->comm);
934: PetscViewerBinaryGetDescriptor(viewer,&fd);
935: PetscBinaryWrite(fd,header,4,PETSC_INT,PETSC_TRUE);
936: /* get largest number of rows any processor has */
937: rlen = mat->rmap->n;
938: range = mat->rmap->range;
939: for (i=1; i<size; i++) {
940: rlen = PetscMax(rlen,range[i+1] - range[i]);
941: }
942: } else {
943: MPI_Reduce(&nz,0,1,MPIU_INT,MPI_SUM,0,((PetscObject)mat)->comm);
944: rlen = mat->rmap->n;
945: }
947: /* load up the local row counts */
948: PetscMalloc((rlen+1)*sizeof(PetscInt),&row_lengths);
949: for (i=0; i<mat->rmap->n; i++) {
950: row_lengths[i] = A->i[i+1] - A->i[i] + B->i[i+1] - B->i[i];
951: }
953: /* store the row lengths to the file */
954: if (!rank) {
955: MPI_Status status;
956: PetscBinaryWrite(fd,row_lengths,mat->rmap->n,PETSC_INT,PETSC_TRUE);
957: for (i=1; i<size; i++) {
958: rlen = range[i+1] - range[i];
959: MPI_Recv(row_lengths,rlen,MPIU_INT,i,tag,((PetscObject)mat)->comm,&status);
960: PetscBinaryWrite(fd,row_lengths,rlen,PETSC_INT,PETSC_TRUE);
961: }
962: } else {
963: MPI_Send(row_lengths,mat->rmap->n,MPIU_INT,0,tag,((PetscObject)mat)->comm);
964: }
965: PetscFree(row_lengths);
967: /* load up the local column indices */
968: nzmax = nz; /* )th processor needs space a largest processor needs */
969: MPI_Reduce(&nz,&nzmax,1,MPIU_INT,MPI_MAX,0,((PetscObject)mat)->comm);
970: PetscMalloc((nzmax+1)*sizeof(PetscInt),&column_indices);
971: cnt = 0;
972: for (i=0; i<mat->rmap->n; i++) {
973: for (j=B->i[i]; j<B->i[i+1]; j++) {
974: if ( (col = garray[B->j[j]]) > cstart) break;
975: column_indices[cnt++] = col;
976: }
977: for (k=A->i[i]; k<A->i[i+1]; k++) {
978: column_indices[cnt++] = A->j[k] + cstart;
979: }
980: for (; j<B->i[i+1]; j++) {
981: column_indices[cnt++] = garray[B->j[j]];
982: }
983: }
984: if (cnt != A->nz + B->nz) SETERRQ2(PETSC_ERR_LIB,"Internal PETSc error: cnt = %D nz = %D",cnt,A->nz+B->nz);
986: /* store the column indices to the file */
987: if (!rank) {
988: MPI_Status status;
989: PetscBinaryWrite(fd,column_indices,nz,PETSC_INT,PETSC_TRUE);
990: for (i=1; i<size; i++) {
991: MPI_Recv(&rnz,1,MPIU_INT,i,tag,((PetscObject)mat)->comm,&status);
992: if (rnz > nzmax) SETERRQ2(PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
993: MPI_Recv(column_indices,rnz,MPIU_INT,i,tag,((PetscObject)mat)->comm,&status);
994: PetscBinaryWrite(fd,column_indices,rnz,PETSC_INT,PETSC_TRUE);
995: }
996: } else {
997: MPI_Send(&nz,1,MPIU_INT,0,tag,((PetscObject)mat)->comm);
998: MPI_Send(column_indices,nz,MPIU_INT,0,tag,((PetscObject)mat)->comm);
999: }
1000: PetscFree(column_indices);
1002: /* load up the local column values */
1003: PetscMalloc((nzmax+1)*sizeof(PetscScalar),&column_values);
1004: cnt = 0;
1005: for (i=0; i<mat->rmap->n; i++) {
1006: for (j=B->i[i]; j<B->i[i+1]; j++) {
1007: if ( garray[B->j[j]] > cstart) break;
1008: column_values[cnt++] = B->a[j];
1009: }
1010: for (k=A->i[i]; k<A->i[i+1]; k++) {
1011: column_values[cnt++] = A->a[k];
1012: }
1013: for (; j<B->i[i+1]; j++) {
1014: column_values[cnt++] = B->a[j];
1015: }
1016: }
1017: if (cnt != A->nz + B->nz) SETERRQ2(PETSC_ERR_PLIB,"Internal PETSc error: cnt = %D nz = %D",cnt,A->nz+B->nz);
1019: /* store the column values to the file */
1020: if (!rank) {
1021: MPI_Status status;
1022: PetscBinaryWrite(fd,column_values,nz,PETSC_SCALAR,PETSC_TRUE);
1023: for (i=1; i<size; i++) {
1024: MPI_Recv(&rnz,1,MPIU_INT,i,tag,((PetscObject)mat)->comm,&status);
1025: if (rnz > nzmax) SETERRQ2(PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1026: MPI_Recv(column_values,rnz,MPIU_SCALAR,i,tag,((PetscObject)mat)->comm,&status);
1027: PetscBinaryWrite(fd,column_values,rnz,PETSC_SCALAR,PETSC_TRUE);
1028: }
1029: } else {
1030: MPI_Send(&nz,1,MPIU_INT,0,tag,((PetscObject)mat)->comm);
1031: MPI_Send(column_values,nz,MPIU_SCALAR,0,tag,((PetscObject)mat)->comm);
1032: }
1033: PetscFree(column_values);
1034: return(0);
1035: }
1039: PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
1040: {
1041: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
1042: PetscErrorCode ierr;
1043: PetscMPIInt rank = aij->rank,size = aij->size;
1044: PetscTruth isdraw,iascii,isbinary;
1045: PetscViewer sviewer;
1046: PetscViewerFormat format;
1049: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_DRAW,&isdraw);
1050: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&iascii);
1051: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_BINARY,&isbinary);
1052: if (iascii) {
1053: PetscViewerGetFormat(viewer,&format);
1054: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1055: MatInfo info;
1056: PetscTruth inodes;
1058: MPI_Comm_rank(((PetscObject)mat)->comm,&rank);
1059: MatGetInfo(mat,MAT_LOCAL,&info);
1060: MatInodeGetInodeSizes(aij->A,PETSC_NULL,(PetscInt **)&inodes,PETSC_NULL);
1061: if (!inodes) {
1062: PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, not using I-node routines\n",
1063: rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);
1064: } else {
1065: PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, using I-node routines\n",
1066: rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);
1067: }
1068: MatGetInfo(aij->A,MAT_LOCAL,&info);
1069: PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1070: MatGetInfo(aij->B,MAT_LOCAL,&info);
1071: PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1072: PetscViewerFlush(viewer);
1073: PetscViewerASCIIPrintf(viewer,"Information on VecScatter used in matrix-vector product: \n");
1074: VecScatterView(aij->Mvctx,viewer);
1075: return(0);
1076: } else if (format == PETSC_VIEWER_ASCII_INFO) {
1077: PetscInt inodecount,inodelimit,*inodes;
1078: MatInodeGetInodeSizes(aij->A,&inodecount,&inodes,&inodelimit);
1079: if (inodes) {
1080: PetscViewerASCIIPrintf(viewer,"using I-node (on process 0) routines: found %D nodes, limit used is %D\n",inodecount,inodelimit);
1081: } else {
1082: PetscViewerASCIIPrintf(viewer,"not using I-node (on process 0) routines\n");
1083: }
1084: return(0);
1085: } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1086: return(0);
1087: }
1088: } else if (isbinary) {
1089: if (size == 1) {
1090: PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);
1091: MatView(aij->A,viewer);
1092: } else {
1093: MatView_MPIAIJ_Binary(mat,viewer);
1094: }
1095: return(0);
1096: } else if (isdraw) {
1097: PetscDraw draw;
1098: PetscTruth isnull;
1099: PetscViewerDrawGetDraw(viewer,0,&draw);
1100: PetscDrawIsNull(draw,&isnull); if (isnull) return(0);
1101: }
1103: if (size == 1) {
1104: PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);
1105: MatView(aij->A,viewer);
1106: } else {
1107: /* assemble the entire matrix onto first processor. */
1108: Mat A;
1109: Mat_SeqAIJ *Aloc;
1110: PetscInt M = mat->rmap->N,N = mat->cmap->N,m,*ai,*aj,row,*cols,i,*ct;
1111: MatScalar *a;
1113: if (mat->rmap->N > 1024) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"ASCII matrix output not allowed for matrices with more than 512 rows, use binary format instead");
1115: MatCreate(((PetscObject)mat)->comm,&A);
1116: if (!rank) {
1117: MatSetSizes(A,M,N,M,N);
1118: } else {
1119: MatSetSizes(A,0,0,M,N);
1120: }
1121: /* This is just a temporary matrix, so explicitly using MATMPIAIJ is probably best */
1122: MatSetType(A,MATMPIAIJ);
1123: MatMPIAIJSetPreallocation(A,0,PETSC_NULL,0,PETSC_NULL);
1124: PetscLogObjectParent(mat,A);
1126: /* copy over the A part */
1127: Aloc = (Mat_SeqAIJ*)aij->A->data;
1128: m = aij->A->rmap->n; ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1129: row = mat->rmap->rstart;
1130: for (i=0; i<ai[m]; i++) {aj[i] += mat->cmap->rstart ;}
1131: for (i=0; i<m; i++) {
1132: MatSetValues(A,1,&row,ai[i+1]-ai[i],aj,a,INSERT_VALUES);
1133: row++; a += ai[i+1]-ai[i]; aj += ai[i+1]-ai[i];
1134: }
1135: aj = Aloc->j;
1136: for (i=0; i<ai[m]; i++) {aj[i] -= mat->cmap->rstart;}
1138: /* copy over the B part */
1139: Aloc = (Mat_SeqAIJ*)aij->B->data;
1140: m = aij->B->rmap->n; ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1141: row = mat->rmap->rstart;
1142: PetscMalloc((ai[m]+1)*sizeof(PetscInt),&cols);
1143: ct = cols;
1144: for (i=0; i<ai[m]; i++) {cols[i] = aij->garray[aj[i]];}
1145: for (i=0; i<m; i++) {
1146: MatSetValues(A,1,&row,ai[i+1]-ai[i],cols,a,INSERT_VALUES);
1147: row++; a += ai[i+1]-ai[i]; cols += ai[i+1]-ai[i];
1148: }
1149: PetscFree(ct);
1150: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1151: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1152: /*
1153: Everyone has to call to draw the matrix since the graphics waits are
1154: synchronized across all processors that share the PetscDraw object
1155: */
1156: PetscViewerGetSingleton(viewer,&sviewer);
1157: if (!rank) {
1158: PetscObjectSetName((PetscObject)((Mat_MPIAIJ*)(A->data))->A,((PetscObject)mat)->name);
1159: MatView(((Mat_MPIAIJ*)(A->data))->A,sviewer);
1160: }
1161: PetscViewerRestoreSingleton(viewer,&sviewer);
1162: MatDestroy(A);
1163: }
1164: return(0);
1165: }
1169: PetscErrorCode MatView_MPIAIJ(Mat mat,PetscViewer viewer)
1170: {
1172: PetscTruth iascii,isdraw,issocket,isbinary;
1173:
1175: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&iascii);
1176: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_DRAW,&isdraw);
1177: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_BINARY,&isbinary);
1178: PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_SOCKET,&issocket);
1179: if (iascii || isdraw || isbinary || issocket) {
1180: MatView_MPIAIJ_ASCIIorDraworSocket(mat,viewer);
1181: } else {
1182: SETERRQ1(PETSC_ERR_SUP,"Viewer type %s not supported by MPIAIJ matrices",((PetscObject)viewer)->type_name);
1183: }
1184: return(0);
1185: }
1189: PetscErrorCode MatRelax_MPIAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
1190: {
1191: Mat_MPIAIJ *mat = (Mat_MPIAIJ*)matin->data;
1193: Vec bb1;
1196: VecDuplicate(bb,&bb1);
1198: if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP){
1199: if (flag & SOR_ZERO_INITIAL_GUESS) {
1200: (*mat->A->ops->relax)(mat->A,bb,omega,flag,fshift,lits,lits,xx);
1201: its--;
1202: }
1203:
1204: while (its--) {
1205: VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1206: VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1208: /* update rhs: bb1 = bb - B*x */
1209: VecScale(mat->lvec,-1.0);
1210: (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);
1212: /* local sweep */
1213: (*mat->A->ops->relax)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,lits,xx);
1214: }
1215: } else if (flag & SOR_LOCAL_FORWARD_SWEEP){
1216: if (flag & SOR_ZERO_INITIAL_GUESS) {
1217: (*mat->A->ops->relax)(mat->A,bb,omega,flag,fshift,lits,PETSC_NULL,xx);
1218: its--;
1219: }
1220: while (its--) {
1221: VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1222: VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1224: /* update rhs: bb1 = bb - B*x */
1225: VecScale(mat->lvec,-1.0);
1226: (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);
1228: /* local sweep */
1229: (*mat->A->ops->relax)(mat->A,bb1,omega,SOR_FORWARD_SWEEP,fshift,lits,PETSC_NULL,xx);
1230: }
1231: } else if (flag & SOR_LOCAL_BACKWARD_SWEEP){
1232: if (flag & SOR_ZERO_INITIAL_GUESS) {
1233: (*mat->A->ops->relax)(mat->A,bb,omega,flag,fshift,lits,PETSC_NULL,xx);
1234: its--;
1235: }
1236: while (its--) {
1237: VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1238: VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1240: /* update rhs: bb1 = bb - B*x */
1241: VecScale(mat->lvec,-1.0);
1242: (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);
1244: /* local sweep */
1245: (*mat->A->ops->relax)(mat->A,bb1,omega,SOR_BACKWARD_SWEEP,fshift,lits,PETSC_NULL,xx);
1246: }
1247: } else {
1248: SETERRQ(PETSC_ERR_SUP,"Parallel SOR not supported");
1249: }
1251: VecDestroy(bb1);
1252: return(0);
1253: }
1257: PetscErrorCode MatPermute_MPIAIJ(Mat A,IS rowp,IS colp,Mat *B)
1258: {
1259: MPI_Comm comm,pcomm;
1260: PetscInt first,local_size,nrows;
1261: const PetscInt *rows;
1262: int ntids;
1263: IS crowp,growp,irowp,lrowp,lcolp,icolp;
1267: PetscObjectGetComm((PetscObject)A,&comm);
1268: /* make a collective version of 'rowp' */
1269: PetscObjectGetComm((PetscObject)rowp,&pcomm);
1270: if (pcomm==comm) {
1271: crowp = rowp;
1272: } else {
1273: ISGetSize(rowp,&nrows);
1274: ISGetIndices(rowp,&rows);
1275: ISCreateGeneral(comm,nrows,rows,&crowp);
1276: ISRestoreIndices(rowp,&rows);
1277: }
1278: /* collect the global row permutation and invert it */
1279: ISAllGather(crowp,&growp);
1280: ISSetPermutation(growp);
1281: if (pcomm!=comm) {
1282: ISDestroy(crowp);
1283: }
1284: ISInvertPermutation(growp,PETSC_DECIDE,&irowp);
1285: /* get the local target indices */
1286: MatGetOwnershipRange(A,&first,PETSC_NULL);
1287: MatGetLocalSize(A,&local_size,PETSC_NULL);
1288: ISGetIndices(irowp,&rows);
1289: ISCreateGeneral(MPI_COMM_SELF,local_size,rows+first,&lrowp);
1290: ISRestoreIndices(irowp,&rows);
1291: ISDestroy(irowp);
1292: /* the column permutation is so much easier;
1293: make a local version of 'colp' and invert it */
1294: PetscObjectGetComm((PetscObject)colp,&pcomm);
1295: MPI_Comm_size(pcomm,&ntids);
1296: if (ntids==1) {
1297: lcolp = colp;
1298: } else {
1299: ISGetSize(colp,&nrows);
1300: ISGetIndices(colp,&rows);
1301: ISCreateGeneral(MPI_COMM_SELF,nrows,rows,&lcolp);
1302: }
1303: ISInvertPermutation(lcolp,PETSC_DECIDE,&icolp);
1304: ISSetPermutation(lcolp);
1305: if (ntids>1) {
1306: ISRestoreIndices(colp,&rows);
1307: ISDestroy(lcolp);
1308: }
1309: /* now we just get the submatrix */
1310: MatGetSubMatrix(A,lrowp,icolp,local_size,MAT_INITIAL_MATRIX,B);
1311: /* clean up */
1312: ISDestroy(lrowp);
1313: ISDestroy(icolp);
1314: return(0);
1315: }
1319: PetscErrorCode MatGetInfo_MPIAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1320: {
1321: Mat_MPIAIJ *mat = (Mat_MPIAIJ*)matin->data;
1322: Mat A = mat->A,B = mat->B;
1324: PetscReal isend[5],irecv[5];
1327: info->block_size = 1.0;
1328: MatGetInfo(A,MAT_LOCAL,info);
1329: isend[0] = info->nz_used; isend[1] = info->nz_allocated; isend[2] = info->nz_unneeded;
1330: isend[3] = info->memory; isend[4] = info->mallocs;
1331: MatGetInfo(B,MAT_LOCAL,info);
1332: isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
1333: isend[3] += info->memory; isend[4] += info->mallocs;
1334: if (flag == MAT_LOCAL) {
1335: info->nz_used = isend[0];
1336: info->nz_allocated = isend[1];
1337: info->nz_unneeded = isend[2];
1338: info->memory = isend[3];
1339: info->mallocs = isend[4];
1340: } else if (flag == MAT_GLOBAL_MAX) {
1341: MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPI_MAX,((PetscObject)matin)->comm);
1342: info->nz_used = irecv[0];
1343: info->nz_allocated = irecv[1];
1344: info->nz_unneeded = irecv[2];
1345: info->memory = irecv[3];
1346: info->mallocs = irecv[4];
1347: } else if (flag == MAT_GLOBAL_SUM) {
1348: MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPI_SUM,((PetscObject)matin)->comm);
1349: info->nz_used = irecv[0];
1350: info->nz_allocated = irecv[1];
1351: info->nz_unneeded = irecv[2];
1352: info->memory = irecv[3];
1353: info->mallocs = irecv[4];
1354: }
1355: info->fill_ratio_given = 0; /* no parallel LU/ILU/Cholesky */
1356: info->fill_ratio_needed = 0;
1357: info->factor_mallocs = 0;
1359: return(0);
1360: }
1364: PetscErrorCode MatSetOption_MPIAIJ(Mat A,MatOption op,PetscTruth flg)
1365: {
1366: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
1370: switch (op) {
1371: case MAT_NEW_NONZERO_LOCATIONS:
1372: case MAT_NEW_NONZERO_ALLOCATION_ERR:
1373: case MAT_UNUSED_NONZERO_LOCATION_ERR:
1374: case MAT_KEEP_ZEROED_ROWS:
1375: case MAT_NEW_NONZERO_LOCATION_ERR:
1376: case MAT_USE_INODES:
1377: case MAT_IGNORE_ZERO_ENTRIES:
1378: MatSetOption(a->A,op,flg);
1379: MatSetOption(a->B,op,flg);
1380: break;
1381: case MAT_ROW_ORIENTED:
1382: a->roworiented = flg;
1383: MatSetOption(a->A,op,flg);
1384: MatSetOption(a->B,op,flg);
1385: break;
1386: case MAT_NEW_DIAGONALS:
1387: PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1388: break;
1389: case MAT_IGNORE_OFF_PROC_ENTRIES:
1390: a->donotstash = PETSC_TRUE;
1391: break;
1392: case MAT_SYMMETRIC:
1393: MatSetOption(a->A,op,flg);
1394: break;
1395: case MAT_STRUCTURALLY_SYMMETRIC:
1396: case MAT_HERMITIAN:
1397: case MAT_SYMMETRY_ETERNAL:
1398: MatSetOption(a->A,op,flg);
1399: break;
1400: default:
1401: SETERRQ1(PETSC_ERR_SUP,"unknown option %d",op);
1402: }
1403: return(0);
1404: }
1408: PetscErrorCode MatGetRow_MPIAIJ(Mat matin,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1409: {
1410: Mat_MPIAIJ *mat = (Mat_MPIAIJ*)matin->data;
1411: PetscScalar *vworkA,*vworkB,**pvA,**pvB,*v_p;
1413: PetscInt i,*cworkA,*cworkB,**pcA,**pcB,cstart = matin->cmap->rstart;
1414: PetscInt nztot,nzA,nzB,lrow,rstart = matin->rmap->rstart,rend = matin->rmap->rend;
1415: PetscInt *cmap,*idx_p;
1418: if (mat->getrowactive) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Already active");
1419: mat->getrowactive = PETSC_TRUE;
1421: if (!mat->rowvalues && (idx || v)) {
1422: /*
1423: allocate enough space to hold information from the longest row.
1424: */
1425: Mat_SeqAIJ *Aa = (Mat_SeqAIJ*)mat->A->data,*Ba = (Mat_SeqAIJ*)mat->B->data;
1426: PetscInt max = 1,tmp;
1427: for (i=0; i<matin->rmap->n; i++) {
1428: tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i];
1429: if (max < tmp) { max = tmp; }
1430: }
1431: PetscMalloc(max*(sizeof(PetscInt)+sizeof(PetscScalar)),&mat->rowvalues);
1432: mat->rowindices = (PetscInt*)(mat->rowvalues + max);
1433: }
1435: if (row < rstart || row >= rend) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Only local rows")
1436: lrow = row - rstart;
1438: pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1439: if (!v) {pvA = 0; pvB = 0;}
1440: if (!idx) {pcA = 0; if (!v) pcB = 0;}
1441: (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
1442: (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
1443: nztot = nzA + nzB;
1445: cmap = mat->garray;
1446: if (v || idx) {
1447: if (nztot) {
1448: /* Sort by increasing column numbers, assuming A and B already sorted */
1449: PetscInt imark = -1;
1450: if (v) {
1451: *v = v_p = mat->rowvalues;
1452: for (i=0; i<nzB; i++) {
1453: if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1454: else break;
1455: }
1456: imark = i;
1457: for (i=0; i<nzA; i++) v_p[imark+i] = vworkA[i];
1458: for (i=imark; i<nzB; i++) v_p[nzA+i] = vworkB[i];
1459: }
1460: if (idx) {
1461: *idx = idx_p = mat->rowindices;
1462: if (imark > -1) {
1463: for (i=0; i<imark; i++) {
1464: idx_p[i] = cmap[cworkB[i]];
1465: }
1466: } else {
1467: for (i=0; i<nzB; i++) {
1468: if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1469: else break;
1470: }
1471: imark = i;
1472: }
1473: for (i=0; i<nzA; i++) idx_p[imark+i] = cstart + cworkA[i];
1474: for (i=imark; i<nzB; i++) idx_p[nzA+i] = cmap[cworkB[i]];
1475: }
1476: } else {
1477: if (idx) *idx = 0;
1478: if (v) *v = 0;
1479: }
1480: }
1481: *nz = nztot;
1482: (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
1483: (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
1484: return(0);
1485: }
1489: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1490: {
1491: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
1494: if (!aij->getrowactive) {
1495: SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"MatGetRow() must be called first");
1496: }
1497: aij->getrowactive = PETSC_FALSE;
1498: return(0);
1499: }
1503: PetscErrorCode MatNorm_MPIAIJ(Mat mat,NormType type,PetscReal *norm)
1504: {
1505: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
1506: Mat_SeqAIJ *amat = (Mat_SeqAIJ*)aij->A->data,*bmat = (Mat_SeqAIJ*)aij->B->data;
1508: PetscInt i,j,cstart = mat->cmap->rstart;
1509: PetscReal sum = 0.0;
1510: MatScalar *v;
1513: if (aij->size == 1) {
1514: MatNorm(aij->A,type,norm);
1515: } else {
1516: if (type == NORM_FROBENIUS) {
1517: v = amat->a;
1518: for (i=0; i<amat->nz; i++) {
1519: #if defined(PETSC_USE_COMPLEX)
1520: sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1521: #else
1522: sum += (*v)*(*v); v++;
1523: #endif
1524: }
1525: v = bmat->a;
1526: for (i=0; i<bmat->nz; i++) {
1527: #if defined(PETSC_USE_COMPLEX)
1528: sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1529: #else
1530: sum += (*v)*(*v); v++;
1531: #endif
1532: }
1533: MPI_Allreduce(&sum,norm,1,MPIU_REAL,MPI_SUM,((PetscObject)mat)->comm);
1534: *norm = sqrt(*norm);
1535: } else if (type == NORM_1) { /* max column norm */
1536: PetscReal *tmp,*tmp2;
1537: PetscInt *jj,*garray = aij->garray;
1538: PetscMalloc((mat->cmap->N+1)*sizeof(PetscReal),&tmp);
1539: PetscMalloc((mat->cmap->N+1)*sizeof(PetscReal),&tmp2);
1540: PetscMemzero(tmp,mat->cmap->N*sizeof(PetscReal));
1541: *norm = 0.0;
1542: v = amat->a; jj = amat->j;
1543: for (j=0; j<amat->nz; j++) {
1544: tmp[cstart + *jj++ ] += PetscAbsScalar(*v); v++;
1545: }
1546: v = bmat->a; jj = bmat->j;
1547: for (j=0; j<bmat->nz; j++) {
1548: tmp[garray[*jj++]] += PetscAbsScalar(*v); v++;
1549: }
1550: MPI_Allreduce(tmp,tmp2,mat->cmap->N,MPIU_REAL,MPI_SUM,((PetscObject)mat)->comm);
1551: for (j=0; j<mat->cmap->N; j++) {
1552: if (tmp2[j] > *norm) *norm = tmp2[j];
1553: }
1554: PetscFree(tmp);
1555: PetscFree(tmp2);
1556: } else if (type == NORM_INFINITY) { /* max row norm */
1557: PetscReal ntemp = 0.0;
1558: for (j=0; j<aij->A->rmap->n; j++) {
1559: v = amat->a + amat->i[j];
1560: sum = 0.0;
1561: for (i=0; i<amat->i[j+1]-amat->i[j]; i++) {
1562: sum += PetscAbsScalar(*v); v++;
1563: }
1564: v = bmat->a + bmat->i[j];
1565: for (i=0; i<bmat->i[j+1]-bmat->i[j]; i++) {
1566: sum += PetscAbsScalar(*v); v++;
1567: }
1568: if (sum > ntemp) ntemp = sum;
1569: }
1570: MPI_Allreduce(&ntemp,norm,1,MPIU_REAL,MPI_MAX,((PetscObject)mat)->comm);
1571: } else {
1572: SETERRQ(PETSC_ERR_SUP,"No support for two norm");
1573: }
1574: }
1575: return(0);
1576: }
1580: PetscErrorCode MatTranspose_MPIAIJ(Mat A,MatReuse reuse,Mat *matout)
1581: {
1582: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
1583: Mat_SeqAIJ *Aloc=(Mat_SeqAIJ*)a->A->data,*Bloc=(Mat_SeqAIJ*)a->B->data;
1585: PetscInt M = A->rmap->N,N = A->cmap->N,ma,na,mb,*ai,*aj,*bi,*bj,row,*cols,*cols_tmp,i,*d_nnz;
1586: PetscInt cstart=A->cmap->rstart,ncol;
1587: Mat B;
1588: MatScalar *array;
1591: if (reuse == MAT_REUSE_MATRIX && A == *matout && M != N) SETERRQ(PETSC_ERR_ARG_SIZ,"Square matrix only for in-place");
1593: ma = A->rmap->n; na = A->cmap->n; mb = a->B->rmap->n;
1594: ai = Aloc->i; aj = Aloc->j;
1595: bi = Bloc->i; bj = Bloc->j;
1596: if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1597: /* compute d_nnz for preallocation; o_nnz is approximated by d_nnz to avoid communication */
1598: PetscMalloc((1+na)*sizeof(PetscInt),&d_nnz);
1599: PetscMemzero(d_nnz,(1+na)*sizeof(PetscInt));
1600: for (i=0; i<ai[ma]; i++){
1601: d_nnz[aj[i]] ++;
1602: aj[i] += cstart; /* global col index to be used by MatSetValues() */
1603: }
1605: MatCreate(((PetscObject)A)->comm,&B);
1606: MatSetSizes(B,A->cmap->n,A->rmap->n,N,M);
1607: MatSetType(B,((PetscObject)A)->type_name);
1608: MatMPIAIJSetPreallocation(B,0,d_nnz,0,d_nnz);
1609: PetscFree(d_nnz);
1610: } else {
1611: B = *matout;
1612: }
1614: /* copy over the A part */
1615: array = Aloc->a;
1616: row = A->rmap->rstart;
1617: for (i=0; i<ma; i++) {
1618: ncol = ai[i+1]-ai[i];
1619: MatSetValues(B,ncol,aj,1,&row,array,INSERT_VALUES);
1620: row++; array += ncol; aj += ncol;
1621: }
1622: aj = Aloc->j;
1623: for (i=0; i<ai[ma]; i++) aj[i] -= cstart; /* resume local col index */
1625: /* copy over the B part */
1626: PetscMalloc(bi[mb]*sizeof(PetscInt),&cols);
1627: PetscMemzero(cols,bi[mb]*sizeof(PetscInt));
1628: array = Bloc->a;
1629: row = A->rmap->rstart;
1630: for (i=0; i<bi[mb]; i++) {cols[i] = a->garray[bj[i]];}
1631: cols_tmp = cols;
1632: for (i=0; i<mb; i++) {
1633: ncol = bi[i+1]-bi[i];
1634: MatSetValues(B,ncol,cols_tmp,1,&row,array,INSERT_VALUES);
1635: row++; array += ncol; cols_tmp += ncol;
1636: }
1637: PetscFree(cols);
1638:
1639: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1640: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1641: if (reuse == MAT_INITIAL_MATRIX || *matout != A) {
1642: *matout = B;
1643: } else {
1644: MatHeaderCopy(A,B);
1645: }
1646: return(0);
1647: }
1651: PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat,Vec ll,Vec rr)
1652: {
1653: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
1654: Mat a = aij->A,b = aij->B;
1656: PetscInt s1,s2,s3;
1659: MatGetLocalSize(mat,&s2,&s3);
1660: if (rr) {
1661: VecGetLocalSize(rr,&s1);
1662: if (s1!=s3) SETERRQ(PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
1663: /* Overlap communication with computation. */
1664: VecScatterBegin(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
1665: }
1666: if (ll) {
1667: VecGetLocalSize(ll,&s1);
1668: if (s1!=s2) SETERRQ(PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
1669: (*b->ops->diagonalscale)(b,ll,0);
1670: }
1671: /* scale the diagonal block */
1672: (*a->ops->diagonalscale)(a,ll,rr);
1674: if (rr) {
1675: /* Do a scatter end and then right scale the off-diagonal block */
1676: VecScatterEnd(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
1677: (*b->ops->diagonalscale)(b,0,aij->lvec);
1678: }
1679:
1680: return(0);
1681: }
1685: PetscErrorCode MatSetBlockSize_MPIAIJ(Mat A,PetscInt bs)
1686: {
1687: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
1691: MatSetBlockSize(a->A,bs);
1692: MatSetBlockSize(a->B,bs);
1693: return(0);
1694: }
1697: PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
1698: {
1699: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
1703: MatSetUnfactored(a->A);
1704: return(0);
1705: }
1709: PetscErrorCode MatEqual_MPIAIJ(Mat A,Mat B,PetscTruth *flag)
1710: {
1711: Mat_MPIAIJ *matB = (Mat_MPIAIJ*)B->data,*matA = (Mat_MPIAIJ*)A->data;
1712: Mat a,b,c,d;
1713: PetscTruth flg;
1717: a = matA->A; b = matA->B;
1718: c = matB->A; d = matB->B;
1720: MatEqual(a,c,&flg);
1721: if (flg) {
1722: MatEqual(b,d,&flg);
1723: }
1724: MPI_Allreduce(&flg,flag,1,MPI_INT,MPI_LAND,((PetscObject)A)->comm);
1725: return(0);
1726: }
1730: PetscErrorCode MatCopy_MPIAIJ(Mat A,Mat B,MatStructure str)
1731: {
1733: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
1734: Mat_MPIAIJ *b = (Mat_MPIAIJ *)B->data;
1737: /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
1738: if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
1739: /* because of the column compression in the off-processor part of the matrix a->B,
1740: the number of columns in a->B and b->B may be different, hence we cannot call
1741: the MatCopy() directly on the two parts. If need be, we can provide a more
1742: efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
1743: then copying the submatrices */
1744: MatCopy_Basic(A,B,str);
1745: } else {
1746: MatCopy(a->A,b->A,str);
1747: MatCopy(a->B,b->B,str);
1748: }
1749: return(0);
1750: }
1754: PetscErrorCode MatSetUpPreallocation_MPIAIJ(Mat A)
1755: {
1759: MatMPIAIJSetPreallocation(A,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
1760: return(0);
1761: }
1763: #include petscblaslapack.h
1766: PetscErrorCode MatAXPY_MPIAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
1767: {
1769: PetscInt i;
1770: Mat_MPIAIJ *xx = (Mat_MPIAIJ *)X->data,*yy = (Mat_MPIAIJ *)Y->data;
1771: PetscBLASInt bnz,one=1;
1772: Mat_SeqAIJ *x,*y;
1775: if (str == SAME_NONZERO_PATTERN) {
1776: PetscScalar alpha = a;
1777: x = (Mat_SeqAIJ *)xx->A->data;
1778: y = (Mat_SeqAIJ *)yy->A->data;
1779: bnz = PetscBLASIntCast(x->nz);
1780: BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one);
1781: x = (Mat_SeqAIJ *)xx->B->data;
1782: y = (Mat_SeqAIJ *)yy->B->data;
1783: bnz = PetscBLASIntCast(x->nz);
1784: BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one);
1785: } else if (str == SUBSET_NONZERO_PATTERN) {
1786: MatAXPY_SeqAIJ(yy->A,a,xx->A,str);
1788: x = (Mat_SeqAIJ *)xx->B->data;
1789: y = (Mat_SeqAIJ *)yy->B->data;
1790: if (y->xtoy && y->XtoY != xx->B) {
1791: PetscFree(y->xtoy);
1792: MatDestroy(y->XtoY);
1793: }
1794: if (!y->xtoy) { /* get xtoy */
1795: MatAXPYGetxtoy_Private(xx->B->rmap->n,x->i,x->j,xx->garray,y->i,y->j,yy->garray,&y->xtoy);
1796: y->XtoY = xx->B;
1797: PetscObjectReference((PetscObject)xx->B);
1798: }
1799: for (i=0; i<x->nz; i++) y->a[y->xtoy[i]] += a*(x->a[i]);
1800: } else {
1801: MatAXPY_Basic(Y,a,X,str);
1802: }
1803: return(0);
1804: }
1806: EXTERN PetscErrorCode MatConjugate_SeqAIJ(Mat);
1810: PetscErrorCode MatConjugate_MPIAIJ(Mat mat)
1811: {
1812: #if defined(PETSC_USE_COMPLEX)
1814: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
1817: MatConjugate_SeqAIJ(aij->A);
1818: MatConjugate_SeqAIJ(aij->B);
1819: #else
1821: #endif
1822: return(0);
1823: }
1827: PetscErrorCode MatRealPart_MPIAIJ(Mat A)
1828: {
1829: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
1833: MatRealPart(a->A);
1834: MatRealPart(a->B);
1835: return(0);
1836: }
1840: PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
1841: {
1842: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
1846: MatImaginaryPart(a->A);
1847: MatImaginaryPart(a->B);
1848: return(0);
1849: }
1851: #ifdef PETSC_HAVE_PBGL
1853: #include <boost/parallel/mpi/bsp_process_group.hpp>
1854: #include <boost/graph/distributed/ilu_default_graph.hpp>
1855: #include <boost/graph/distributed/ilu_0_block.hpp>
1856: #include <boost/graph/distributed/ilu_preconditioner.hpp>
1857: #include <boost/graph/distributed/petsc/interface.hpp>
1858: #include <boost/multi_array.hpp>
1859: #include <boost/parallel/distributed_property_map->hpp>
1863: /*
1864: This uses the parallel ILU factorization of Peter Gottschling <pgottsch@osl.iu.edu>
1865: */
1866: PetscErrorCode MatILUFactorSymbolic_MPIAIJ(Mat fact,Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
1867: {
1868: namespace petsc = boost::distributed::petsc;
1869:
1870: namespace graph_dist = boost::graph::distributed;
1871: using boost::graph::distributed::ilu_default::process_group_type;
1872: using boost::graph::ilu_permuted;
1874: PetscTruth row_identity, col_identity;
1875: PetscContainer c;
1876: PetscInt m, n, M, N;
1877: PetscErrorCode ierr;
1880: if (info->levels != 0) SETERRQ(PETSC_ERR_SUP,"Only levels = 0 supported for parallel ilu");
1881: ISIdentity(isrow, &row_identity);
1882: ISIdentity(iscol, &col_identity);
1883: if (!row_identity || !col_identity) {
1884: SETERRQ(PETSC_ERR_ARG_WRONG,"Row and column permutations must be identity for parallel ILU");
1885: }
1887: process_group_type pg;
1888: typedef graph_dist::ilu_default::ilu_level_graph_type lgraph_type;
1889: lgraph_type* lgraph_p = new lgraph_type(petsc::num_global_vertices(A), pg, petsc::matrix_distribution(A, pg));
1890: lgraph_type& level_graph = *lgraph_p;
1891: graph_dist::ilu_default::graph_type& graph(level_graph.graph);
1893: petsc::read_matrix(A, graph, get(boost::edge_weight, graph));
1894: ilu_permuted(level_graph);
1896: /* put together the new matrix */
1897: MatCreate(((PetscObject)A)->comm, fact);
1898: MatGetLocalSize(A, &m, &n);
1899: MatGetSize(A, &M, &N);
1900: MatSetSizes(fact, m, n, M, N);
1901: MatSetType(fact, ((PetscObject)A)->type_name);
1902: MatAssemblyBegin(fact, MAT_FINAL_ASSEMBLY);
1903: MatAssemblyEnd(fact, MAT_FINAL_ASSEMBLY);
1905: PetscContainerCreate(((PetscObject)A)->comm, &c);
1906: PetscContainerSetPointer(c, lgraph_p);
1907: PetscObjectCompose((PetscObject) (fact), "graph", (PetscObject) c);
1908: return(0);
1909: }
1913: PetscErrorCode MatLUFactorNumeric_MPIAIJ(Mat B,Mat A, const MatFactorInfo *info)
1914: {
1916: return(0);
1917: }
1921: /*
1922: This uses the parallel ILU factorization of Peter Gottschling <pgottsch@osl.iu.edu>
1923: */
1924: PetscErrorCode MatSolve_MPIAIJ(Mat A, Vec b, Vec x)
1925: {
1926: namespace graph_dist = boost::graph::distributed;
1928: typedef graph_dist::ilu_default::ilu_level_graph_type lgraph_type;
1929: lgraph_type* lgraph_p;
1930: PetscContainer c;
1934: PetscObjectQuery((PetscObject) A, "graph", (PetscObject *) &c);
1935: PetscContainerGetPointer(c, (void **) &lgraph_p);
1936: VecCopy(b, x);
1938: PetscScalar* array_x;
1939: VecGetArray(x, &array_x);
1940: PetscInt sx;
1941: VecGetSize(x, &sx);
1942:
1943: PetscScalar* array_b;
1944: VecGetArray(b, &array_b);
1945: PetscInt sb;
1946: VecGetSize(b, &sb);
1948: lgraph_type& level_graph = *lgraph_p;
1949: graph_dist::ilu_default::graph_type& graph(level_graph.graph);
1951: typedef boost::multi_array_ref<PetscScalar, 1> array_ref_type;
1952: array_ref_type ref_b(array_b, boost::extents[num_vertices(graph)]),
1953: ref_x(array_x, boost::extents[num_vertices(graph)]);
1955: typedef boost::iterator_property_map<array_ref_type::iterator,
1956: boost::property_map<graph_dist::ilu_default::graph_type, boost::vertex_index_t>::type> gvector_type;
1957: gvector_type vector_b(ref_b.begin(), get(boost::vertex_index, graph)),
1958: vector_x(ref_x.begin(), get(boost::vertex_index, graph));
1959:
1960: ilu_set_solve(*lgraph_p, vector_b, vector_x);
1962: return(0);
1963: }
1964: #endif
1966: typedef struct { /* used by MatGetRedundantMatrix() for reusing matredundant */
1967: PetscInt nzlocal,nsends,nrecvs;
1968: PetscMPIInt *send_rank;
1969: PetscInt *sbuf_nz,*sbuf_j,**rbuf_j;
1970: PetscScalar *sbuf_a,**rbuf_a;
1971: PetscErrorCode (*MatDestroy)(Mat);
1972: } Mat_Redundant;
1976: PetscErrorCode PetscContainerDestroy_MatRedundant(void *ptr)
1977: {
1978: PetscErrorCode ierr;
1979: Mat_Redundant *redund=(Mat_Redundant*)ptr;
1980: PetscInt i;
1983: PetscFree(redund->send_rank);
1984: PetscFree(redund->sbuf_j);
1985: PetscFree(redund->sbuf_a);
1986: for (i=0; i<redund->nrecvs; i++){
1987: PetscFree(redund->rbuf_j[i]);
1988: PetscFree(redund->rbuf_a[i]);
1989: }
1990: PetscFree3(redund->sbuf_nz,redund->rbuf_j,redund->rbuf_a);
1991: PetscFree(redund);
1992: return(0);
1993: }
1997: PetscErrorCode MatDestroy_MatRedundant(Mat A)
1998: {
1999: PetscErrorCode ierr;
2000: PetscContainer container;
2001: Mat_Redundant *redund=PETSC_NULL;
2004: PetscObjectQuery((PetscObject)A,"Mat_Redundant",(PetscObject *)&container);
2005: if (container) {
2006: PetscContainerGetPointer(container,(void **)&redund);
2007: } else {
2008: SETERRQ(PETSC_ERR_PLIB,"Container does not exit");
2009: }
2010: A->ops->destroy = redund->MatDestroy;
2011: PetscObjectCompose((PetscObject)A,"Mat_Redundant",0);
2012: (*A->ops->destroy)(A);
2013: PetscContainerDestroy(container);
2014: return(0);
2015: }
2019: PetscErrorCode MatGetRedundantMatrix_MPIAIJ(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,PetscInt mlocal_sub,MatReuse reuse,Mat *matredundant)
2020: {
2021: PetscMPIInt rank,size;
2022: MPI_Comm comm=((PetscObject)mat)->comm;
2024: PetscInt nsends=0,nrecvs=0,i,rownz_max=0;
2025: PetscMPIInt *send_rank=PETSC_NULL,*recv_rank=PETSC_NULL;
2026: PetscInt *rowrange=mat->rmap->range;
2027: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
2028: Mat A=aij->A,B=aij->B,C=*matredundant;
2029: Mat_SeqAIJ *a=(Mat_SeqAIJ*)A->data,*b=(Mat_SeqAIJ*)B->data;
2030: PetscScalar *sbuf_a;
2031: PetscInt nzlocal=a->nz+b->nz;
2032: PetscInt j,cstart=mat->cmap->rstart,cend=mat->cmap->rend,row,nzA,nzB,ncols,*cworkA,*cworkB;
2033: PetscInt rstart=mat->rmap->rstart,rend=mat->rmap->rend,*bmap=aij->garray,M,N;
2034: PetscInt *cols,ctmp,lwrite,*rptr,l,*sbuf_j;
2035: MatScalar *aworkA,*aworkB;
2036: PetscScalar *vals;
2037: PetscMPIInt tag1,tag2,tag3,imdex;
2038: MPI_Request *s_waits1=PETSC_NULL,*s_waits2=PETSC_NULL,*s_waits3=PETSC_NULL,
2039: *r_waits1=PETSC_NULL,*r_waits2=PETSC_NULL,*r_waits3=PETSC_NULL;
2040: MPI_Status recv_status,*send_status;
2041: PetscInt *sbuf_nz=PETSC_NULL,*rbuf_nz=PETSC_NULL,count;
2042: PetscInt **rbuf_j=PETSC_NULL;
2043: PetscScalar **rbuf_a=PETSC_NULL;
2044: Mat_Redundant *redund=PETSC_NULL;
2045: PetscContainer container;
2048: MPI_Comm_rank(comm,&rank);
2049: MPI_Comm_size(comm,&size);
2051: if (reuse == MAT_REUSE_MATRIX) {
2052: MatGetSize(C,&M,&N);
2053: if (M != N || M != mat->rmap->N) SETERRQ(PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. Wrong global size");
2054: MatGetLocalSize(C,&M,&N);
2055: if (M != N || M != mlocal_sub) SETERRQ(PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. Wrong local size");
2056: PetscObjectQuery((PetscObject)C,"Mat_Redundant",(PetscObject *)&container);
2057: if (container) {
2058: PetscContainerGetPointer(container,(void **)&redund);
2059: } else {
2060: SETERRQ(PETSC_ERR_PLIB,"Container does not exit");
2061: }
2062: if (nzlocal != redund->nzlocal) SETERRQ(PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. Wrong nzlocal");
2064: nsends = redund->nsends;
2065: nrecvs = redund->nrecvs;
2066: send_rank = redund->send_rank; recv_rank = send_rank + size;
2067: sbuf_nz = redund->sbuf_nz; rbuf_nz = sbuf_nz + nsends;
2068: sbuf_j = redund->sbuf_j;
2069: sbuf_a = redund->sbuf_a;
2070: rbuf_j = redund->rbuf_j;
2071: rbuf_a = redund->rbuf_a;
2072: }
2074: if (reuse == MAT_INITIAL_MATRIX){
2075: PetscMPIInt subrank,subsize;
2076: PetscInt nleftover,np_subcomm;
2077: /* get the destination processors' id send_rank, nsends and nrecvs */
2078: MPI_Comm_rank(subcomm,&subrank);
2079: MPI_Comm_size(subcomm,&subsize);
2080: PetscMalloc((2*size+1)*sizeof(PetscMPIInt),&send_rank);
2081: recv_rank = send_rank + size;
2082: np_subcomm = size/nsubcomm;
2083: nleftover = size - nsubcomm*np_subcomm;
2084: nsends = 0; nrecvs = 0;
2085: for (i=0; i<size; i++){ /* i=rank*/
2086: if (subrank == i/nsubcomm && rank != i){ /* my_subrank == other's subrank */
2087: send_rank[nsends] = i; nsends++;
2088: recv_rank[nrecvs++] = i;
2089: }
2090: }
2091: if (rank >= size - nleftover){/* this proc is a leftover processor */
2092: i = size-nleftover-1;
2093: j = 0;
2094: while (j < nsubcomm - nleftover){
2095: send_rank[nsends++] = i;
2096: i--; j++;
2097: }
2098: }
2100: if (nleftover && subsize == size/nsubcomm && subrank==subsize-1){ /* this proc recvs from leftover processors */
2101: for (i=0; i<nleftover; i++){
2102: recv_rank[nrecvs++] = size-nleftover+i;
2103: }
2104: }
2106: /* allocate sbuf_j, sbuf_a */
2107: i = nzlocal + rowrange[rank+1] - rowrange[rank] + 2;
2108: PetscMalloc(i*sizeof(PetscInt),&sbuf_j);
2109: PetscMalloc((nzlocal+1)*sizeof(PetscScalar),&sbuf_a);
2110: } /* endof if (reuse == MAT_INITIAL_MATRIX) */
2111:
2112: /* copy mat's local entries into the buffers */
2113: if (reuse == MAT_INITIAL_MATRIX){
2114: rownz_max = 0;
2115: rptr = sbuf_j;
2116: cols = sbuf_j + rend-rstart + 1;
2117: vals = sbuf_a;
2118: rptr[0] = 0;
2119: for (i=0; i<rend-rstart; i++){
2120: row = i + rstart;
2121: nzA = a->i[i+1] - a->i[i]; nzB = b->i[i+1] - b->i[i];
2122: ncols = nzA + nzB;
2123: cworkA = a->j + a->i[i]; cworkB = b->j + b->i[i];
2124: aworkA = a->a + a->i[i]; aworkB = b->a + b->i[i];
2125: /* load the column indices for this row into cols */
2126: lwrite = 0;
2127: for (l=0; l<nzB; l++) {
2128: if ((ctmp = bmap[cworkB[l]]) < cstart){
2129: vals[lwrite] = aworkB[l];
2130: cols[lwrite++] = ctmp;
2131: }
2132: }
2133: for (l=0; l<nzA; l++){
2134: vals[lwrite] = aworkA[l];
2135: cols[lwrite++] = cstart + cworkA[l];
2136: }
2137: for (l=0; l<nzB; l++) {
2138: if ((ctmp = bmap[cworkB[l]]) >= cend){
2139: vals[lwrite] = aworkB[l];
2140: cols[lwrite++] = ctmp;
2141: }
2142: }
2143: vals += ncols;
2144: cols += ncols;
2145: rptr[i+1] = rptr[i] + ncols;
2146: if (rownz_max < ncols) rownz_max = ncols;
2147: }
2148: if (rptr[rend-rstart] != a->nz + b->nz) SETERRQ4(1, "rptr[%d] %d != %d + %d",rend-rstart,rptr[rend-rstart+1],a->nz,b->nz);
2149: } else { /* only copy matrix values into sbuf_a */
2150: rptr = sbuf_j;
2151: vals = sbuf_a;
2152: rptr[0] = 0;
2153: for (i=0; i<rend-rstart; i++){
2154: row = i + rstart;
2155: nzA = a->i[i+1] - a->i[i]; nzB = b->i[i+1] - b->i[i];
2156: ncols = nzA + nzB;
2157: cworkA = a->j + a->i[i]; cworkB = b->j + b->i[i];
2158: aworkA = a->a + a->i[i]; aworkB = b->a + b->i[i];
2159: lwrite = 0;
2160: for (l=0; l<nzB; l++) {
2161: if ((ctmp = bmap[cworkB[l]]) < cstart) vals[lwrite++] = aworkB[l];
2162: }
2163: for (l=0; l<nzA; l++) vals[lwrite++] = aworkA[l];
2164: for (l=0; l<nzB; l++) {
2165: if ((ctmp = bmap[cworkB[l]]) >= cend) vals[lwrite++] = aworkB[l];
2166: }
2167: vals += ncols;
2168: rptr[i+1] = rptr[i] + ncols;
2169: }
2170: } /* endof if (reuse == MAT_INITIAL_MATRIX) */
2172: /* send nzlocal to others, and recv other's nzlocal */
2173: /*--------------------------------------------------*/
2174: if (reuse == MAT_INITIAL_MATRIX){
2175: PetscMalloc2(3*(nsends + nrecvs)+1,MPI_Request,&s_waits3,nsends+1,MPI_Status,&send_status);
2176: s_waits2 = s_waits3 + nsends;
2177: s_waits1 = s_waits2 + nsends;
2178: r_waits1 = s_waits1 + nsends;
2179: r_waits2 = r_waits1 + nrecvs;
2180: r_waits3 = r_waits2 + nrecvs;
2181: } else {
2182: PetscMalloc2(nsends + nrecvs +1,MPI_Request,&s_waits3,nsends+1,MPI_Status,&send_status);
2183: r_waits3 = s_waits3 + nsends;
2184: }
2186: PetscObjectGetNewTag((PetscObject)mat,&tag3);
2187: if (reuse == MAT_INITIAL_MATRIX){
2188: /* get new tags to keep the communication clean */
2189: PetscObjectGetNewTag((PetscObject)mat,&tag1);
2190: PetscObjectGetNewTag((PetscObject)mat,&tag2);
2191: PetscMalloc3(nsends+nrecvs+1,PetscInt,&sbuf_nz,nrecvs,PetscInt*,&rbuf_j,nrecvs,PetscScalar*,&rbuf_a);
2192: rbuf_nz = sbuf_nz + nsends;
2193:
2194: /* post receives of other's nzlocal */
2195: for (i=0; i<nrecvs; i++){
2196: MPI_Irecv(rbuf_nz+i,1,MPIU_INT,MPI_ANY_SOURCE,tag1,comm,r_waits1+i);
2197: }
2198: /* send nzlocal to others */
2199: for (i=0; i<nsends; i++){
2200: sbuf_nz[i] = nzlocal;
2201: MPI_Isend(sbuf_nz+i,1,MPIU_INT,send_rank[i],tag1,comm,s_waits1+i);
2202: }
2203: /* wait on receives of nzlocal; allocate space for rbuf_j, rbuf_a */
2204: count = nrecvs;
2205: while (count) {
2206: MPI_Waitany(nrecvs,r_waits1,&imdex,&recv_status);
2207: recv_rank[imdex] = recv_status.MPI_SOURCE;
2208: /* allocate rbuf_a and rbuf_j; then post receives of rbuf_j */
2209: PetscMalloc((rbuf_nz[imdex]+1)*sizeof(PetscScalar),&rbuf_a[imdex]);
2211: i = rowrange[recv_status.MPI_SOURCE+1] - rowrange[recv_status.MPI_SOURCE]; /* number of expected mat->i */
2212: rbuf_nz[imdex] += i + 2;
2213: PetscMalloc(rbuf_nz[imdex]*sizeof(PetscInt),&rbuf_j[imdex]);
2214: MPI_Irecv(rbuf_j[imdex],rbuf_nz[imdex],MPIU_INT,recv_status.MPI_SOURCE,tag2,comm,r_waits2+imdex);
2215: count--;
2216: }
2217: /* wait on sends of nzlocal */
2218: if (nsends) {MPI_Waitall(nsends,s_waits1,send_status);}
2219: /* send mat->i,j to others, and recv from other's */
2220: /*------------------------------------------------*/
2221: for (i=0; i<nsends; i++){
2222: j = nzlocal + rowrange[rank+1] - rowrange[rank] + 1;
2223: MPI_Isend(sbuf_j,j,MPIU_INT,send_rank[i],tag2,comm,s_waits2+i);
2224: }
2225: /* wait on receives of mat->i,j */
2226: /*------------------------------*/
2227: count = nrecvs;
2228: while (count) {
2229: MPI_Waitany(nrecvs,r_waits2,&imdex,&recv_status);
2230: if (recv_rank[imdex] != recv_status.MPI_SOURCE) SETERRQ2(1, "recv_rank %d != MPI_SOURCE %d",recv_rank[imdex],recv_status.MPI_SOURCE);
2231: count--;
2232: }
2233: /* wait on sends of mat->i,j */
2234: /*---------------------------*/
2235: if (nsends) {
2236: MPI_Waitall(nsends,s_waits2,send_status);
2237: }
2238: } /* endof if (reuse == MAT_INITIAL_MATRIX) */
2240: /* post receives, send and receive mat->a */
2241: /*----------------------------------------*/
2242: for (imdex=0; imdex<nrecvs; imdex++) {
2243: MPI_Irecv(rbuf_a[imdex],rbuf_nz[imdex],MPIU_SCALAR,recv_rank[imdex],tag3,comm,r_waits3+imdex);
2244: }
2245: for (i=0; i<nsends; i++){
2246: MPI_Isend(sbuf_a,nzlocal,MPIU_SCALAR,send_rank[i],tag3,comm,s_waits3+i);
2247: }
2248: count = nrecvs;
2249: while (count) {
2250: MPI_Waitany(nrecvs,r_waits3,&imdex,&recv_status);
2251: if (recv_rank[imdex] != recv_status.MPI_SOURCE) SETERRQ2(1, "recv_rank %d != MPI_SOURCE %d",recv_rank[imdex],recv_status.MPI_SOURCE);
2252: count--;
2253: }
2254: if (nsends) {
2255: MPI_Waitall(nsends,s_waits3,send_status);
2256: }
2258: PetscFree2(s_waits3,send_status);
2259:
2260: /* create redundant matrix */
2261: /*-------------------------*/
2262: if (reuse == MAT_INITIAL_MATRIX){
2263: /* compute rownz_max for preallocation */
2264: for (imdex=0; imdex<nrecvs; imdex++){
2265: j = rowrange[recv_rank[imdex]+1] - rowrange[recv_rank[imdex]];
2266: rptr = rbuf_j[imdex];
2267: for (i=0; i<j; i++){
2268: ncols = rptr[i+1] - rptr[i];
2269: if (rownz_max < ncols) rownz_max = ncols;
2270: }
2271: }
2272:
2273: MatCreate(subcomm,&C);
2274: MatSetSizes(C,mlocal_sub,mlocal_sub,PETSC_DECIDE,PETSC_DECIDE);
2275: MatSetFromOptions(C);
2276: MatSeqAIJSetPreallocation(C,rownz_max,PETSC_NULL);
2277: MatMPIAIJSetPreallocation(C,rownz_max,PETSC_NULL,rownz_max,PETSC_NULL);
2278: } else {
2279: C = *matredundant;
2280: }
2282: /* insert local matrix entries */
2283: rptr = sbuf_j;
2284: cols = sbuf_j + rend-rstart + 1;
2285: vals = sbuf_a;
2286: for (i=0; i<rend-rstart; i++){
2287: row = i + rstart;
2288: ncols = rptr[i+1] - rptr[i];
2289: MatSetValues(C,1,&row,ncols,cols,vals,INSERT_VALUES);
2290: vals += ncols;
2291: cols += ncols;
2292: }
2293: /* insert received matrix entries */
2294: for (imdex=0; imdex<nrecvs; imdex++){
2295: rstart = rowrange[recv_rank[imdex]];
2296: rend = rowrange[recv_rank[imdex]+1];
2297: rptr = rbuf_j[imdex];
2298: cols = rbuf_j[imdex] + rend-rstart + 1;
2299: vals = rbuf_a[imdex];
2300: for (i=0; i<rend-rstart; i++){
2301: row = i + rstart;
2302: ncols = rptr[i+1] - rptr[i];
2303: MatSetValues(C,1,&row,ncols,cols,vals,INSERT_VALUES);
2304: vals += ncols;
2305: cols += ncols;
2306: }
2307: }
2308: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2309: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2310: MatGetSize(C,&M,&N);
2311: if (M != mat->rmap->N || N != mat->cmap->N) SETERRQ2(PETSC_ERR_ARG_INCOMP,"redundant mat size %d != input mat size %d",M,mat->rmap->N);
2312: if (reuse == MAT_INITIAL_MATRIX){
2313: PetscContainer container;
2314: *matredundant = C;
2315: /* create a supporting struct and attach it to C for reuse */
2316: PetscNewLog(C,Mat_Redundant,&redund);
2317: PetscContainerCreate(PETSC_COMM_SELF,&container);
2318: PetscContainerSetPointer(container,redund);
2319: PetscObjectCompose((PetscObject)C,"Mat_Redundant",(PetscObject)container);
2320: PetscContainerSetUserDestroy(container,PetscContainerDestroy_MatRedundant);
2321:
2322: redund->nzlocal = nzlocal;
2323: redund->nsends = nsends;
2324: redund->nrecvs = nrecvs;
2325: redund->send_rank = send_rank;
2326: redund->sbuf_nz = sbuf_nz;
2327: redund->sbuf_j = sbuf_j;
2328: redund->sbuf_a = sbuf_a;
2329: redund->rbuf_j = rbuf_j;
2330: redund->rbuf_a = rbuf_a;
2332: redund->MatDestroy = C->ops->destroy;
2333: C->ops->destroy = MatDestroy_MatRedundant;
2334: }
2335: return(0);
2336: }
2340: PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2341: {
2342: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
2344: PetscInt i,*idxb = 0;
2345: PetscScalar *va,*vb;
2346: Vec vtmp;
2349: MatGetRowMaxAbs(a->A,v,idx);
2350: VecGetArray(v,&va);
2351: if (idx) {
2352: for (i=0; i<A->rmap->n; i++) {
2353: if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2354: }
2355: }
2357: VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2358: if (idx) {
2359: PetscMalloc(A->rmap->n*sizeof(PetscInt),&idxb);
2360: }
2361: MatGetRowMaxAbs(a->B,vtmp,idxb);
2362: VecGetArray(vtmp,&vb);
2364: for (i=0; i<A->rmap->n; i++){
2365: if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2366: va[i] = vb[i];
2367: if (idx) idx[i] = a->garray[idxb[i]];
2368: }
2369: }
2371: VecRestoreArray(v,&va);
2372: VecRestoreArray(vtmp,&vb);
2373: if (idxb) {
2374: PetscFree(idxb);
2375: }
2376: VecDestroy(vtmp);
2377: return(0);
2378: }
2382: PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2383: {
2384: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
2386: PetscInt i,*idxb = 0;
2387: PetscScalar *va,*vb;
2388: Vec vtmp;
2391: MatGetRowMinAbs(a->A,v,idx);
2392: VecGetArray(v,&va);
2393: if (idx) {
2394: for (i=0; i<A->cmap->n; i++) {
2395: if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2396: }
2397: }
2399: VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2400: if (idx) {
2401: PetscMalloc(A->rmap->n*sizeof(PetscInt),&idxb);
2402: }
2403: MatGetRowMinAbs(a->B,vtmp,idxb);
2404: VecGetArray(vtmp,&vb);
2406: for (i=0; i<A->rmap->n; i++){
2407: if (PetscAbsScalar(va[i]) > PetscAbsScalar(vb[i])) {
2408: va[i] = vb[i];
2409: if (idx) idx[i] = a->garray[idxb[i]];
2410: }
2411: }
2413: VecRestoreArray(v,&va);
2414: VecRestoreArray(vtmp,&vb);
2415: if (idxb) {
2416: PetscFree(idxb);
2417: }
2418: VecDestroy(vtmp);
2419: return(0);
2420: }
2424: PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2425: {
2426: Mat_MPIAIJ *mat = (Mat_MPIAIJ *) A->data;
2427: PetscInt n = A->rmap->n;
2428: PetscInt cstart = A->cmap->rstart;
2429: PetscInt *cmap = mat->garray;
2430: PetscInt *diagIdx, *offdiagIdx;
2431: Vec diagV, offdiagV;
2432: PetscScalar *a, *diagA, *offdiagA;
2433: PetscInt r;
2437: PetscMalloc2(n,PetscInt,&diagIdx,n,PetscInt,&offdiagIdx);
2438: VecCreateSeq(((PetscObject)A)->comm, n, &diagV);
2439: VecCreateSeq(((PetscObject)A)->comm, n, &offdiagV);
2440: MatGetRowMin(mat->A, diagV, diagIdx);
2441: MatGetRowMin(mat->B, offdiagV, offdiagIdx);
2442: VecGetArray(v, &a);
2443: VecGetArray(diagV, &diagA);
2444: VecGetArray(offdiagV, &offdiagA);
2445: for(r = 0; r < n; ++r) {
2446: if (PetscAbsScalar(diagA[r]) <= PetscAbsScalar(offdiagA[r])) {
2447: a[r] = diagA[r];
2448: idx[r] = cstart + diagIdx[r];
2449: } else {
2450: a[r] = offdiagA[r];
2451: idx[r] = cmap[offdiagIdx[r]];
2452: }
2453: }
2454: VecRestoreArray(v, &a);
2455: VecRestoreArray(diagV, &diagA);
2456: VecRestoreArray(offdiagV, &offdiagA);
2457: VecDestroy(diagV);
2458: VecDestroy(offdiagV);
2459: PetscFree2(diagIdx, offdiagIdx);
2460: return(0);
2461: }
2465: PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2466: {
2467: Mat_MPIAIJ *mat = (Mat_MPIAIJ *) A->data;
2468: PetscInt n = A->rmap->n;
2469: PetscInt cstart = A->cmap->rstart;
2470: PetscInt *cmap = mat->garray;
2471: PetscInt *diagIdx, *offdiagIdx;
2472: Vec diagV, offdiagV;
2473: PetscScalar *a, *diagA, *offdiagA;
2474: PetscInt r;
2478: PetscMalloc2(n,PetscInt,&diagIdx,n,PetscInt,&offdiagIdx);
2479: VecCreateSeq(((PetscObject)A)->comm, n, &diagV);
2480: VecCreateSeq(((PetscObject)A)->comm, n, &offdiagV);
2481: MatGetRowMax(mat->A, diagV, diagIdx);
2482: MatGetRowMax(mat->B, offdiagV, offdiagIdx);
2483: VecGetArray(v, &a);
2484: VecGetArray(diagV, &diagA);
2485: VecGetArray(offdiagV, &offdiagA);
2486: for(r = 0; r < n; ++r) {
2487: if (PetscAbsScalar(diagA[r]) >= PetscAbsScalar(offdiagA[r])) {
2488: a[r] = diagA[r];
2489: idx[r] = cstart + diagIdx[r];
2490: } else {
2491: a[r] = offdiagA[r];
2492: idx[r] = cmap[offdiagIdx[r]];
2493: }
2494: }
2495: VecRestoreArray(v, &a);
2496: VecRestoreArray(diagV, &diagA);
2497: VecRestoreArray(offdiagV, &offdiagA);
2498: VecDestroy(diagV);
2499: VecDestroy(offdiagV);
2500: PetscFree2(diagIdx, offdiagIdx);
2501: return(0);
2502: }
2506: PetscErrorCode MatGetSeqNonzerostructure_MPIAIJ(Mat mat,Mat *newmat[])
2507: {
2511: MatGetSubMatrix_MPIAIJ_All(mat,MAT_DO_NOT_GET_VALUES,MAT_INITIAL_MATRIX,newmat);
2512: return(0);
2513: }
2515: /* -------------------------------------------------------------------*/
2516: static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
2517: MatGetRow_MPIAIJ,
2518: MatRestoreRow_MPIAIJ,
2519: MatMult_MPIAIJ,
2520: /* 4*/ MatMultAdd_MPIAIJ,
2521: MatMultTranspose_MPIAIJ,
2522: MatMultTransposeAdd_MPIAIJ,
2523: #ifdef PETSC_HAVE_PBGL
2524: MatSolve_MPIAIJ,
2525: #else
2526: 0,
2527: #endif
2528: 0,
2529: 0,
2530: /*10*/ 0,
2531: 0,
2532: 0,
2533: MatRelax_MPIAIJ,
2534: MatTranspose_MPIAIJ,
2535: /*15*/ MatGetInfo_MPIAIJ,
2536: MatEqual_MPIAIJ,
2537: MatGetDiagonal_MPIAIJ,
2538: MatDiagonalScale_MPIAIJ,
2539: MatNorm_MPIAIJ,
2540: /*20*/ MatAssemblyBegin_MPIAIJ,
2541: MatAssemblyEnd_MPIAIJ,
2542: 0,
2543: MatSetOption_MPIAIJ,
2544: MatZeroEntries_MPIAIJ,
2545: /*25*/ MatZeroRows_MPIAIJ,
2546: 0,
2547: #ifdef PETSC_HAVE_PBGL
2548: 0,
2549: #else
2550: 0,
2551: #endif
2552: 0,
2553: 0,
2554: /*30*/ MatSetUpPreallocation_MPIAIJ,
2555: #ifdef PETSC_HAVE_PBGL
2556: 0,
2557: #else
2558: 0,
2559: #endif
2560: 0,
2561: 0,
2562: 0,
2563: /*35*/ MatDuplicate_MPIAIJ,
2564: 0,
2565: 0,
2566: 0,
2567: 0,
2568: /*40*/ MatAXPY_MPIAIJ,
2569: MatGetSubMatrices_MPIAIJ,
2570: MatIncreaseOverlap_MPIAIJ,
2571: MatGetValues_MPIAIJ,
2572: MatCopy_MPIAIJ,
2573: /*45*/ MatGetRowMax_MPIAIJ,
2574: MatScale_MPIAIJ,
2575: 0,
2576: 0,
2577: 0,
2578: /*50*/ MatSetBlockSize_MPIAIJ,
2579: 0,
2580: 0,
2581: 0,
2582: 0,
2583: /*55*/ MatFDColoringCreate_MPIAIJ,
2584: 0,
2585: MatSetUnfactored_MPIAIJ,
2586: MatPermute_MPIAIJ,
2587: 0,
2588: /*60*/ MatGetSubMatrix_MPIAIJ,
2589: MatDestroy_MPIAIJ,
2590: MatView_MPIAIJ,
2591: 0,
2592: 0,
2593: /*65*/ 0,
2594: 0,
2595: 0,
2596: 0,
2597: 0,
2598: /*70*/ MatGetRowMaxAbs_MPIAIJ,
2599: MatGetRowMinAbs_MPIAIJ,
2600: 0,
2601: MatSetColoring_MPIAIJ,
2602: #if defined(PETSC_HAVE_ADIC)
2603: MatSetValuesAdic_MPIAIJ,
2604: #else
2605: 0,
2606: #endif
2607: MatSetValuesAdifor_MPIAIJ,
2608: /*75*/ 0,
2609: 0,
2610: 0,
2611: 0,
2612: 0,
2613: /*80*/ 0,
2614: 0,
2615: 0,
2616: /*84*/ MatLoad_MPIAIJ,
2617: 0,
2618: 0,
2619: 0,
2620: 0,
2621: 0,
2622: /*90*/ MatMatMult_MPIAIJ_MPIAIJ,
2623: MatMatMultSymbolic_MPIAIJ_MPIAIJ,
2624: MatMatMultNumeric_MPIAIJ_MPIAIJ,
2625: MatPtAP_Basic,
2626: MatPtAPSymbolic_MPIAIJ,
2627: /*95*/ MatPtAPNumeric_MPIAIJ,
2628: 0,
2629: 0,
2630: 0,
2631: 0,
2632: /*100*/0,
2633: MatPtAPSymbolic_MPIAIJ_MPIAIJ,
2634: MatPtAPNumeric_MPIAIJ_MPIAIJ,
2635: MatConjugate_MPIAIJ,
2636: 0,
2637: /*105*/MatSetValuesRow_MPIAIJ,
2638: MatRealPart_MPIAIJ,
2639: MatImaginaryPart_MPIAIJ,
2640: 0,
2641: 0,
2642: /*110*/0,
2643: MatGetRedundantMatrix_MPIAIJ,
2644: MatGetRowMin_MPIAIJ,
2645: 0,
2646: 0,
2647: /*115*/MatGetSeqNonzerostructure_MPIAIJ};
2649: /* ----------------------------------------------------------------------------------------*/
2654: PetscErrorCode MatStoreValues_MPIAIJ(Mat mat)
2655: {
2656: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2660: MatStoreValues(aij->A);
2661: MatStoreValues(aij->B);
2662: return(0);
2663: }
2669: PetscErrorCode MatRetrieveValues_MPIAIJ(Mat mat)
2670: {
2671: Mat_MPIAIJ *aij = (Mat_MPIAIJ *)mat->data;
2675: MatRetrieveValues(aij->A);
2676: MatRetrieveValues(aij->B);
2677: return(0);
2678: }
2681: #include petscpc.h
2685: PetscErrorCode MatMPIAIJSetPreallocation_MPIAIJ(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
2686: {
2687: Mat_MPIAIJ *b;
2689: PetscInt i;
2692: B->preallocated = PETSC_TRUE;
2693: if (d_nz == PETSC_DEFAULT || d_nz == PETSC_DECIDE) d_nz = 5;
2694: if (o_nz == PETSC_DEFAULT || o_nz == PETSC_DECIDE) o_nz = 2;
2695: if (d_nz < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"d_nz cannot be less than 0: value %D",d_nz);
2696: if (o_nz < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"o_nz cannot be less than 0: value %D",o_nz);
2698: PetscMapSetBlockSize(B->rmap,1);
2699: PetscMapSetBlockSize(B->cmap,1);
2700: PetscMapSetUp(B->rmap);
2701: PetscMapSetUp(B->cmap);
2702: if (d_nnz) {
2703: for (i=0; i<B->rmap->n; i++) {
2704: if (d_nnz[i] < 0) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"d_nnz cannot be less than 0: local row %D value %D",i,d_nnz[i]);
2705: }
2706: }
2707: if (o_nnz) {
2708: for (i=0; i<B->rmap->n; i++) {
2709: if (o_nnz[i] < 0) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"o_nnz cannot be less than 0: local row %D value %D",i,o_nnz[i]);
2710: }
2711: }
2712: b = (Mat_MPIAIJ*)B->data;
2714: /* Explicitly create 2 MATSEQAIJ matrices. */
2715: MatCreate(PETSC_COMM_SELF,&b->A);
2716: MatSetSizes(b->A,B->rmap->n,B->cmap->n,B->rmap->n,B->cmap->n);
2717: MatSetType(b->A,MATSEQAIJ);
2718: PetscLogObjectParent(B,b->A);
2719: MatCreate(PETSC_COMM_SELF,&b->B);
2720: MatSetSizes(b->B,B->rmap->n,B->cmap->N,B->rmap->n,B->cmap->N);
2721: MatSetType(b->B,MATSEQAIJ);
2722: PetscLogObjectParent(B,b->B);
2724: MatSeqAIJSetPreallocation(b->A,d_nz,d_nnz);
2725: MatSeqAIJSetPreallocation(b->B,o_nz,o_nnz);
2727: return(0);
2728: }
2733: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
2734: {
2735: Mat mat;
2736: Mat_MPIAIJ *a,*oldmat = (Mat_MPIAIJ*)matin->data;
2740: *newmat = 0;
2741: MatCreate(((PetscObject)matin)->comm,&mat);
2742: MatSetSizes(mat,matin->rmap->n,matin->cmap->n,matin->rmap->N,matin->cmap->N);
2743: MatSetType(mat,((PetscObject)matin)->type_name);
2744: PetscMemcpy(mat->ops,matin->ops,sizeof(struct _MatOps));
2745: a = (Mat_MPIAIJ*)mat->data;
2746:
2747: mat->factor = matin->factor;
2748: mat->rmap->bs = matin->rmap->bs;
2749: mat->assembled = PETSC_TRUE;
2750: mat->insertmode = NOT_SET_VALUES;
2751: mat->preallocated = PETSC_TRUE;
2753: a->size = oldmat->size;
2754: a->rank = oldmat->rank;
2755: a->donotstash = oldmat->donotstash;
2756: a->roworiented = oldmat->roworiented;
2757: a->rowindices = 0;
2758: a->rowvalues = 0;
2759: a->getrowactive = PETSC_FALSE;
2761: PetscMapCopy(((PetscObject)mat)->comm,matin->rmap,mat->rmap);
2762: PetscMapCopy(((PetscObject)mat)->comm,matin->cmap,mat->cmap);
2764: MatStashCreate_Private(((PetscObject)matin)->comm,1,&mat->stash);
2765: if (oldmat->colmap) {
2766: #if defined (PETSC_USE_CTABLE)
2767: PetscTableCreateCopy(oldmat->colmap,&a->colmap);
2768: #else
2769: PetscMalloc((mat->cmap->N)*sizeof(PetscInt),&a->colmap);
2770: PetscLogObjectMemory(mat,(mat->cmap->N)*sizeof(PetscInt));
2771: PetscMemcpy(a->colmap,oldmat->colmap,(mat->cmap->N)*sizeof(PetscInt));
2772: #endif
2773: } else a->colmap = 0;
2774: if (oldmat->garray) {
2775: PetscInt len;
2776: len = oldmat->B->cmap->n;
2777: PetscMalloc((len+1)*sizeof(PetscInt),&a->garray);
2778: PetscLogObjectMemory(mat,len*sizeof(PetscInt));
2779: if (len) { PetscMemcpy(a->garray,oldmat->garray,len*sizeof(PetscInt)); }
2780: } else a->garray = 0;
2781:
2782: VecDuplicate(oldmat->lvec,&a->lvec);
2783: PetscLogObjectParent(mat,a->lvec);
2784: VecScatterCopy(oldmat->Mvctx,&a->Mvctx);
2785: PetscLogObjectParent(mat,a->Mvctx);
2786: MatDuplicate(oldmat->A,cpvalues,&a->A);
2787: PetscLogObjectParent(mat,a->A);
2788: MatDuplicate(oldmat->B,cpvalues,&a->B);
2789: PetscLogObjectParent(mat,a->B);
2790: PetscFListDuplicate(((PetscObject)matin)->qlist,&((PetscObject)mat)->qlist);
2791: *newmat = mat;
2792: return(0);
2793: }
2795: #include petscsys.h
2799: PetscErrorCode MatLoad_MPIAIJ(PetscViewer viewer, const MatType type,Mat *newmat)
2800: {
2801: Mat A;
2802: PetscScalar *vals,*svals;
2803: MPI_Comm comm = ((PetscObject)viewer)->comm;
2804: MPI_Status status;
2806: PetscMPIInt rank,size,tag = ((PetscObject)viewer)->tag,mpicnt,mpimaxnz;
2807: PetscInt i,nz,j,rstart,rend,mmax,maxnz;
2808: PetscInt header[4],*rowlengths = 0,M,N,m,*cols;
2809: PetscInt *ourlens = PETSC_NULL,*procsnz = PETSC_NULL,*offlens = PETSC_NULL,jj,*mycols,*smycols;
2810: PetscInt cend,cstart,n,*rowners;
2811: int fd;
2814: MPI_Comm_size(comm,&size);
2815: MPI_Comm_rank(comm,&rank);
2816: if (!rank) {
2817: PetscViewerBinaryGetDescriptor(viewer,&fd);
2818: PetscBinaryRead(fd,(char *)header,4,PETSC_INT);
2819: if (header[0] != MAT_FILE_COOKIE) SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
2820: }
2822: MPI_Bcast(header+1,3,MPIU_INT,0,comm);
2823: M = header[1]; N = header[2];
2824: /* determine ownership of all rows */
2825: m = M/size + ((M % size) > rank);
2826: PetscMalloc((size+1)*sizeof(PetscInt),&rowners);
2827: MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);
2829: /* First process needs enough room for process with most rows */
2830: if (!rank) {
2831: mmax = rowners[1];
2832: for (i=2; i<size; i++) {
2833: mmax = PetscMax(mmax,rowners[i]);
2834: }
2835: } else mmax = m;
2837: rowners[0] = 0;
2838: for (i=2; i<=size; i++) {
2839: rowners[i] += rowners[i-1];
2840: }
2841: rstart = rowners[rank];
2842: rend = rowners[rank+1];
2844: /* distribute row lengths to all processors */
2845: PetscMalloc2(mmax,PetscInt,&ourlens,mmax,PetscInt,&offlens);
2846: if (!rank) {
2847: PetscBinaryRead(fd,ourlens,m,PETSC_INT);
2848: PetscMalloc(m*sizeof(PetscInt),&rowlengths);
2849: PetscMalloc(size*sizeof(PetscInt),&procsnz);
2850: PetscMemzero(procsnz,size*sizeof(PetscInt));
2851: for (j=0; j<m; j++) {
2852: procsnz[0] += ourlens[j];
2853: }
2854: for (i=1; i<size; i++) {
2855: PetscBinaryRead(fd,rowlengths,rowners[i+1]-rowners[i],PETSC_INT);
2856: /* calculate the number of nonzeros on each processor */
2857: for (j=0; j<rowners[i+1]-rowners[i]; j++) {
2858: procsnz[i] += rowlengths[j];
2859: }
2860: mpicnt = PetscMPIIntCast(rowners[i+1]-rowners[i]);
2861: MPI_Send(rowlengths,mpicnt,MPIU_INT,i,tag,comm);
2862: }
2863: PetscFree(rowlengths);
2864: } else {
2865: mpicnt = PetscMPIIntCast(m);
2866: MPI_Recv(ourlens,mpicnt,MPIU_INT,0,tag,comm,&status);
2867: }
2869: if (!rank) {
2870: /* determine max buffer needed and allocate it */
2871: maxnz = 0;
2872: for (i=0; i<size; i++) {
2873: maxnz = PetscMax(maxnz,procsnz[i]);
2874: }
2875: PetscMalloc(maxnz*sizeof(PetscInt),&cols);
2877: /* read in my part of the matrix column indices */
2878: nz = procsnz[0];
2879: PetscMalloc(nz*sizeof(PetscInt),&mycols);
2880: PetscBinaryRead(fd,mycols,nz,PETSC_INT);
2882: /* read in every one elses and ship off */
2883: for (i=1; i<size; i++) {
2884: nz = procsnz[i];
2885: PetscBinaryRead(fd,cols,nz,PETSC_INT);
2886: mpicnt = PetscMPIIntCast(nz);
2887: MPI_Send(cols,mpicnt,MPIU_INT,i,tag,comm);
2888: }
2889: PetscFree(cols);
2890: } else {
2891: /* determine buffer space needed for message */
2892: nz = 0;
2893: for (i=0; i<m; i++) {
2894: nz += ourlens[i];
2895: }
2896: PetscMalloc(nz*sizeof(PetscInt),&mycols);
2898: /* receive message of column indices*/
2899: mpicnt = PetscMPIIntCast(nz);
2900: MPI_Recv(mycols,mpicnt,MPIU_INT,0,tag,comm,&status);
2901: MPI_Get_count(&status,MPIU_INT,&mpimaxnz);
2902: if (mpimaxnz == MPI_UNDEFINED) {SETERRQ1(PETSC_ERR_LIB,"MPI_Get_count() returned MPI_UNDEFINED, expected %d",mpicnt);}
2903: else if (mpimaxnz < 0) {SETERRQ2(PETSC_ERR_LIB,"MPI_Get_count() returned impossible negative value %d, expected %d",mpimaxnz,mpicnt);}
2904: else if (mpimaxnz != mpicnt) {SETERRQ2(PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file: expected %d received %d",mpicnt,mpimaxnz);}
2905: }
2907: /* determine column ownership if matrix is not square */
2908: if (N != M) {
2909: n = N/size + ((N % size) > rank);
2910: MPI_Scan(&n,&cend,1,MPIU_INT,MPI_SUM,comm);
2911: cstart = cend - n;
2912: } else {
2913: cstart = rstart;
2914: cend = rend;
2915: n = cend - cstart;
2916: }
2918: /* loop over local rows, determining number of off diagonal entries */
2919: PetscMemzero(offlens,m*sizeof(PetscInt));
2920: jj = 0;
2921: for (i=0; i<m; i++) {
2922: for (j=0; j<ourlens[i]; j++) {
2923: if (mycols[jj] < cstart || mycols[jj] >= cend) offlens[i]++;
2924: jj++;
2925: }
2926: }
2928: /* create our matrix */
2929: for (i=0; i<m; i++) {
2930: ourlens[i] -= offlens[i];
2931: }
2932: MatCreate(comm,&A);
2933: MatSetSizes(A,m,n,M,N);
2934: MatSetType(A,type);
2935: MatMPIAIJSetPreallocation(A,0,ourlens,0,offlens);
2937: for (i=0; i<m; i++) {
2938: ourlens[i] += offlens[i];
2939: }
2941: if (!rank) {
2942: PetscMalloc((maxnz+1)*sizeof(PetscScalar),&vals);
2944: /* read in my part of the matrix numerical values */
2945: nz = procsnz[0];
2946: PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2947:
2948: /* insert into matrix */
2949: jj = rstart;
2950: smycols = mycols;
2951: svals = vals;
2952: for (i=0; i<m; i++) {
2953: MatSetValues_MPIAIJ(A,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
2954: smycols += ourlens[i];
2955: svals += ourlens[i];
2956: jj++;
2957: }
2959: /* read in other processors and ship out */
2960: for (i=1; i<size; i++) {
2961: nz = procsnz[i];
2962: PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2963: mpicnt = PetscMPIIntCast(nz);
2964: MPI_Send(vals,mpicnt,MPIU_SCALAR,i,((PetscObject)A)->tag,comm);
2965: }
2966: PetscFree(procsnz);
2967: } else {
2968: /* receive numeric values */
2969: PetscMalloc((nz+1)*sizeof(PetscScalar),&vals);
2971: /* receive message of values*/
2972: mpicnt = PetscMPIIntCast(nz);
2973: MPI_Recv(vals,mpicnt,MPIU_SCALAR,0,((PetscObject)A)->tag,comm,&status);
2974: MPI_Get_count(&status,MPIU_SCALAR,&mpimaxnz);
2975: if (mpimaxnz == MPI_UNDEFINED) {SETERRQ1(PETSC_ERR_LIB,"MPI_Get_count() returned MPI_UNDEFINED, expected %d",mpicnt);}
2976: else if (mpimaxnz < 0) {SETERRQ2(PETSC_ERR_LIB,"MPI_Get_count() returned impossible negative value %d, expected %d",mpimaxnz,mpicnt);}
2977: else if (mpimaxnz != mpicnt) {SETERRQ2(PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file: expected %d received %d",mpicnt,mpimaxnz);}
2979: /* insert into matrix */
2980: jj = rstart;
2981: smycols = mycols;
2982: svals = vals;
2983: for (i=0; i<m; i++) {
2984: MatSetValues_MPIAIJ(A,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
2985: smycols += ourlens[i];
2986: svals += ourlens[i];
2987: jj++;
2988: }
2989: }
2990: PetscFree2(ourlens,offlens);
2991: PetscFree(vals);
2992: PetscFree(mycols);
2993: PetscFree(rowners);
2995: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2996: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2997: *newmat = A;
2998: return(0);
2999: }
3003: /*
3004: Not great since it makes two copies of the submatrix, first an SeqAIJ
3005: in local and then by concatenating the local matrices the end result.
3006: Writing it directly would be much like MatGetSubMatrices_MPIAIJ()
3007: */
3008: PetscErrorCode MatGetSubMatrix_MPIAIJ(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse call,Mat *newmat)
3009: {
3011: PetscMPIInt rank,size;
3012: PetscInt i,m,n,rstart,row,rend,nz,*cwork,j;
3013: PetscInt *ii,*jj,nlocal,*dlens,*olens,dlen,olen,jend,mglobal;
3014: Mat *local,M,Mreuse;
3015: MatScalar *vwork,*aa;
3016: MPI_Comm comm = ((PetscObject)mat)->comm;
3017: Mat_SeqAIJ *aij;
3021: MPI_Comm_rank(comm,&rank);
3022: MPI_Comm_size(comm,&size);
3024: if (call == MAT_REUSE_MATRIX) {
3025: PetscObjectQuery((PetscObject)*newmat,"SubMatrix",(PetscObject *)&Mreuse);
3026: if (!Mreuse) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
3027: local = &Mreuse;
3028: MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,&local);
3029: } else {
3030: MatGetSubMatrices(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&local);
3031: Mreuse = *local;
3032: PetscFree(local);
3033: }
3035: /*
3036: m - number of local rows
3037: n - number of columns (same on all processors)
3038: rstart - first row in new global matrix generated
3039: */
3040: MatGetSize(Mreuse,&m,&n);
3041: if (call == MAT_INITIAL_MATRIX) {
3042: aij = (Mat_SeqAIJ*)(Mreuse)->data;
3043: ii = aij->i;
3044: jj = aij->j;
3046: /*
3047: Determine the number of non-zeros in the diagonal and off-diagonal
3048: portions of the matrix in order to do correct preallocation
3049: */
3051: /* first get start and end of "diagonal" columns */
3052: if (csize == PETSC_DECIDE) {
3053: ISGetSize(isrow,&mglobal);
3054: if (mglobal == n) { /* square matrix */
3055: nlocal = m;
3056: } else {
3057: nlocal = n/size + ((n % size) > rank);
3058: }
3059: } else {
3060: nlocal = csize;
3061: }
3062: MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);
3063: rstart = rend - nlocal;
3064: if (rank == size - 1 && rend != n) {
3065: SETERRQ2(PETSC_ERR_ARG_SIZ,"Local column sizes %D do not add up to total number of columns %D",rend,n);
3066: }
3068: /* next, compute all the lengths */
3069: PetscMalloc((2*m+1)*sizeof(PetscInt),&dlens);
3070: olens = dlens + m;
3071: for (i=0; i<m; i++) {
3072: jend = ii[i+1] - ii[i];
3073: olen = 0;
3074: dlen = 0;
3075: for (j=0; j<jend; j++) {
3076: if (*jj < rstart || *jj >= rend) olen++;
3077: else dlen++;
3078: jj++;
3079: }
3080: olens[i] = olen;
3081: dlens[i] = dlen;
3082: }
3083: MatCreate(comm,&M);
3084: MatSetSizes(M,m,nlocal,PETSC_DECIDE,n);
3085: MatSetType(M,((PetscObject)mat)->type_name);
3086: MatMPIAIJSetPreallocation(M,0,dlens,0,olens);
3087: PetscFree(dlens);
3088: } else {
3089: PetscInt ml,nl;
3091: M = *newmat;
3092: MatGetLocalSize(M,&ml,&nl);
3093: if (ml != m) SETERRQ(PETSC_ERR_ARG_SIZ,"Previous matrix must be same size/layout as request");
3094: MatZeroEntries(M);
3095: /*
3096: The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3097: rather than the slower MatSetValues().
3098: */
3099: M->was_assembled = PETSC_TRUE;
3100: M->assembled = PETSC_FALSE;
3101: }
3102: MatGetOwnershipRange(M,&rstart,&rend);
3103: aij = (Mat_SeqAIJ*)(Mreuse)->data;
3104: ii = aij->i;
3105: jj = aij->j;
3106: aa = aij->a;
3107: for (i=0; i<m; i++) {
3108: row = rstart + i;
3109: nz = ii[i+1] - ii[i];
3110: cwork = jj; jj += nz;
3111: vwork = aa; aa += nz;
3112: MatSetValues_MPIAIJ(M,1,&row,nz,cwork,vwork,INSERT_VALUES);
3113: }
3115: MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
3116: MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);
3117: *newmat = M;
3119: /* save submatrix used in processor for next request */
3120: if (call == MAT_INITIAL_MATRIX) {
3121: PetscObjectCompose((PetscObject)M,"SubMatrix",(PetscObject)Mreuse);
3122: PetscObjectDereference((PetscObject)Mreuse);
3123: }
3125: return(0);
3126: }
3131: PetscErrorCode MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
3132: {
3133: PetscInt m,cstart, cend,j,nnz,i,d;
3134: PetscInt *d_nnz,*o_nnz,nnz_max = 0,rstart,ii;
3135: const PetscInt *JJ;
3136: PetscScalar *values;
3140: if (Ii[0]) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"Ii[0] must be 0 it is %D",Ii[0]);
3142: PetscMapSetBlockSize(B->rmap,1);
3143: PetscMapSetBlockSize(B->cmap,1);
3144: PetscMapSetUp(B->rmap);
3145: PetscMapSetUp(B->cmap);
3146: m = B->rmap->n;
3147: cstart = B->cmap->rstart;
3148: cend = B->cmap->rend;
3149: rstart = B->rmap->rstart;
3151: PetscMalloc((2*m+1)*sizeof(PetscInt),&d_nnz);
3152: o_nnz = d_nnz + m;
3154: #if defined(PETSC_USE_DEBUGGING)
3155: for (i=0; i<m; i++) {
3156: nnz = Ii[i+1]- Ii[i];
3157: JJ = J + Ii[i];
3158: if (nnz < 0) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative %D number of columns",i,nnz);
3159: if (nnz && (JJ[0] < 0)) SETERRRQ1(PETSC_ERR_ARG_WRONGSTATE,"Row %D starts with negative column index",i,j);
3160: 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);
3161: for (j=1; j<nnz; j++) {
3162: if (JJ[i] <= JJ[i-1]) SETERRRQ(PETSC_ERR_ARG_WRONGSTATE,"Row %D has unsorted column index at %D location in column indices",i,j);
3163: }
3164: }
3165: #endif
3167: for (i=0; i<m; i++) {
3168: nnz = Ii[i+1]- Ii[i];
3169: JJ = J + Ii[i];
3170: nnz_max = PetscMax(nnz_max,nnz);
3171: for (j=0; j<nnz; j++) {
3172: if (*JJ >= cstart) break;
3173: JJ++;
3174: }
3175: d = 0;
3176: for (; j<nnz; j++) {
3177: if (*JJ++ >= cend) break;
3178: d++;
3179: }
3180: d_nnz[i] = d;
3181: o_nnz[i] = nnz - d;
3182: }
3183: MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);
3184: PetscFree(d_nnz);
3186: if (v) values = (PetscScalar*)v;
3187: else {
3188: PetscMalloc((nnz_max+1)*sizeof(PetscScalar),&values);
3189: PetscMemzero(values,nnz_max*sizeof(PetscScalar));
3190: }
3192: for (i=0; i<m; i++) {
3193: ii = i + rstart;
3194: nnz = Ii[i+1]- Ii[i];
3195: MatSetValues_MPIAIJ(B,1,&ii,nnz,J+Ii[i],values+(v ? Ii[i] : 0),INSERT_VALUES);
3196: }
3197: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3198: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3200: if (!v) {
3201: PetscFree(values);
3202: }
3203: return(0);
3204: }
3209: /*@
3210: MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in AIJ format
3211: (the default parallel PETSc format).
3213: Collective on MPI_Comm
3215: Input Parameters:
3216: + B - the matrix
3217: . i - the indices into j for the start of each local row (starts with zero)
3218: . j - the column indices for each local row (starts with zero) these must be sorted for each row
3219: - v - optional values in the matrix
3221: Level: developer
3223: Notes:
3224: The i, j, and a arrays ARE copied by this routine into the internal format used by PETSc;
3225: thus you CANNOT change the matrix entries by changing the values of a[] after you have
3226: called this routine. Use MatCreateMPIAIJWithSplitArrays() to avoid needing to copy the arrays.
3228: The i and j indices are 0 based, and i indices are indices corresponding to the local j array.
3230: The format which is used for the sparse matrix input, is equivalent to a
3231: row-major ordering.. i.e for the following matrix, the input data expected is
3232: as shown:
3234: 1 0 0
3235: 2 0 3 P0
3236: -------
3237: 4 5 6 P1
3239: Process0 [P0]: rows_owned=[0,1]
3240: i = {0,1,3} [size = nrow+1 = 2+1]
3241: j = {0,0,2} [size = nz = 6]
3242: v = {1,2,3} [size = nz = 6]
3244: Process1 [P1]: rows_owned=[2]
3245: i = {0,3} [size = nrow+1 = 1+1]
3246: j = {0,1,2} [size = nz = 6]
3247: v = {4,5,6} [size = nz = 6]
3249: The column indices for each row MUST be sorted.
3251: .keywords: matrix, aij, compressed row, sparse, parallel
3253: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatCreateMPIAIJ(), MPIAIJ,
3254: MatCreateSeqAIJWithArrays(), MatCreateMPIAIJWithSplitArrays()
3255: @*/
3256: PetscErrorCode MatMPIAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
3257: {
3258: PetscErrorCode ierr,(*f)(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]);
3261: PetscObjectQueryFunction((PetscObject)B,"MatMPIAIJSetPreallocationCSR_C",(void (**)(void))&f);
3262: if (f) {
3263: (*f)(B,i,j,v);
3264: }
3265: return(0);
3266: }
3270: /*@C
3271: MatMPIAIJSetPreallocation - Preallocates memory for a sparse parallel matrix in AIJ format
3272: (the default parallel PETSc format). For good matrix assembly performance
3273: the user should preallocate the matrix storage by setting the parameters
3274: d_nz (or d_nnz) and o_nz (or o_nnz). By setting these parameters accurately,
3275: performance can be increased by more than a factor of 50.
3277: Collective on MPI_Comm
3279: Input Parameters:
3280: + A - the matrix
3281: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
3282: (same value is used for all local rows)
3283: . d_nnz - array containing the number of nonzeros in the various rows of the
3284: DIAGONAL portion of the local submatrix (possibly different for each row)
3285: or PETSC_NULL, if d_nz is used to specify the nonzero structure.
3286: The size of this array is equal to the number of local rows, i.e 'm'.
3287: You must leave room for the diagonal entry even if it is zero.
3288: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
3289: submatrix (same value is used for all local rows).
3290: - o_nnz - array containing the number of nonzeros in the various rows of the
3291: OFF-DIAGONAL portion of the local submatrix (possibly different for
3292: each row) or PETSC_NULL, if o_nz is used to specify the nonzero
3293: structure. The size of this array is equal to the number
3294: of local rows, i.e 'm'.
3296: If the *_nnz parameter is given then the *_nz parameter is ignored
3298: The AIJ format (also called the Yale sparse matrix format or
3299: compressed row storage (CSR)), is fully compatible with standard Fortran 77
3300: storage. The stored row and column indices begin with zero. See the users manual for details.
3302: The parallel matrix is partitioned such that the first m0 rows belong to
3303: process 0, the next m1 rows belong to process 1, the next m2 rows belong
3304: to process 2 etc.. where m0,m1,m2... are the input parameter 'm'.
3306: The DIAGONAL portion of the local submatrix of a processor can be defined
3307: as the submatrix which is obtained by extraction the part corresponding
3308: to the rows r1-r2 and columns r1-r2 of the global matrix, where r1 is the
3309: first row that belongs to the processor, and r2 is the last row belonging
3310: to the this processor. This is a square mxm matrix. The remaining portion
3311: of the local submatrix (mxN) constitute the OFF-DIAGONAL portion.
3313: If o_nnz, d_nnz are specified, then o_nz, and d_nz are ignored.
3315: You can call MatGetInfo() to get information on how effective the preallocation was;
3316: for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
3317: You can also run with the option -info and look for messages with the string
3318: malloc in them to see if additional memory allocation was needed.
3320: Example usage:
3321:
3322: Consider the following 8x8 matrix with 34 non-zero values, that is
3323: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
3324: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
3325: as follows:
3327: .vb
3328: 1 2 0 | 0 3 0 | 0 4
3329: Proc0 0 5 6 | 7 0 0 | 8 0
3330: 9 0 10 | 11 0 0 | 12 0
3331: -------------------------------------
3332: 13 0 14 | 15 16 17 | 0 0
3333: Proc1 0 18 0 | 19 20 21 | 0 0
3334: 0 0 0 | 22 23 0 | 24 0
3335: -------------------------------------
3336: Proc2 25 26 27 | 0 0 28 | 29 0
3337: 30 0 0 | 31 32 33 | 0 34
3338: .ve
3340: This can be represented as a collection of submatrices as:
3342: .vb
3343: A B C
3344: D E F
3345: G H I
3346: .ve
3348: Where the submatrices A,B,C are owned by proc0, D,E,F are
3349: owned by proc1, G,H,I are owned by proc2.
3351: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
3352: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
3353: The 'M','N' parameters are 8,8, and have the same values on all procs.
3355: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
3356: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
3357: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
3358: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
3359: part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
3360: matrix, ans [DF] as another SeqAIJ matrix.
3362: When d_nz, o_nz parameters are specified, d_nz storage elements are
3363: allocated for every row of the local diagonal submatrix, and o_nz
3364: storage locations are allocated for every row of the OFF-DIAGONAL submat.
3365: One way to choose d_nz and o_nz is to use the max nonzerors per local
3366: rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
3367: In this case, the values of d_nz,o_nz are:
3368: .vb
3369: proc0 : dnz = 2, o_nz = 2
3370: proc1 : dnz = 3, o_nz = 2
3371: proc2 : dnz = 1, o_nz = 4
3372: .ve
3373: We are allocating m*(d_nz+o_nz) storage locations for every proc. This
3374: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
3375: for proc3. i.e we are using 12+15+10=37 storage locations to store
3376: 34 values.
3378: When d_nnz, o_nnz parameters are specified, the storage is specified
3379: for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
3380: In the above case the values for d_nnz,o_nnz are:
3381: .vb
3382: proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
3383: proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
3384: proc2: d_nnz = [1,1] and o_nnz = [4,4]
3385: .ve
3386: Here the space allocated is sum of all the above values i.e 34, and
3387: hence pre-allocation is perfect.
3389: Level: intermediate
3391: .keywords: matrix, aij, compressed row, sparse, parallel
3393: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatCreateMPIAIJ(), MatMPIAIJSetPreallocationCSR(),
3394: MPIAIJ, MatGetInfo()
3395: @*/
3396: PetscErrorCode MatMPIAIJSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
3397: {
3398: PetscErrorCode ierr,(*f)(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]);
3401: PetscObjectQueryFunction((PetscObject)B,"MatMPIAIJSetPreallocation_C",(void (**)(void))&f);
3402: if (f) {
3403: (*f)(B,d_nz,d_nnz,o_nz,o_nnz);
3404: }
3405: return(0);
3406: }
3410: /*@
3411: MatCreateMPIAIJWithArrays - creates a MPI AIJ matrix using arrays that contain in standard
3412: CSR format the local rows.
3414: Collective on MPI_Comm
3416: Input Parameters:
3417: + comm - MPI communicator
3418: . m - number of local rows (Cannot be PETSC_DECIDE)
3419: . n - This value should be the same as the local size used in creating the
3420: x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
3421: calculated if N is given) For square matrices n is almost always m.
3422: . M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
3423: . N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
3424: . i - row indices
3425: . j - column indices
3426: - a - matrix values
3428: Output Parameter:
3429: . mat - the matrix
3431: Level: intermediate
3433: Notes:
3434: The i, j, and a arrays ARE copied by this routine into the internal format used by PETSc;
3435: thus you CANNOT change the matrix entries by changing the values of a[] after you have
3436: called this routine. Use MatCreateMPIAIJWithSplitArrays() to avoid needing to copy the arrays.
3438: The i and j indices are 0 based, and i indices are indices corresponding to the local j array.
3440: The format which is used for the sparse matrix input, is equivalent to a
3441: row-major ordering.. i.e for the following matrix, the input data expected is
3442: as shown:
3444: 1 0 0
3445: 2 0 3 P0
3446: -------
3447: 4 5 6 P1
3449: Process0 [P0]: rows_owned=[0,1]
3450: i = {0,1,3} [size = nrow+1 = 2+1]
3451: j = {0,0,2} [size = nz = 6]
3452: v = {1,2,3} [size = nz = 6]
3454: Process1 [P1]: rows_owned=[2]
3455: i = {0,3} [size = nrow+1 = 1+1]
3456: j = {0,1,2} [size = nz = 6]
3457: v = {4,5,6} [size = nz = 6]
3459: .keywords: matrix, aij, compressed row, sparse, parallel
3461: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
3462: MPIAIJ, MatCreateMPIAIJ(), MatCreateMPIAIJWithSplitArrays()
3463: @*/
3464: PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
3465: {
3469: if (i[0]) {
3470: SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
3471: }
3472: if (m < 0) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
3473: MatCreate(comm,mat);
3474: MatSetSizes(*mat,m,n,M,N);
3475: MatSetType(*mat,MATMPIAIJ);
3476: MatMPIAIJSetPreallocationCSR(*mat,i,j,a);
3477: return(0);
3478: }
3482: /*@C
3483: MatCreateMPIAIJ - Creates a sparse parallel matrix in AIJ format
3484: (the default parallel PETSc format). For good matrix assembly performance
3485: the user should preallocate the matrix storage by setting the parameters
3486: d_nz (or d_nnz) and o_nz (or o_nnz). By setting these parameters accurately,
3487: performance can be increased by more than a factor of 50.
3489: Collective on MPI_Comm
3491: Input Parameters:
3492: + comm - MPI communicator
3493: . m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
3494: This value should be the same as the local size used in creating the
3495: y vector for the matrix-vector product y = Ax.
3496: . n - This value should be the same as the local size used in creating the
3497: x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
3498: calculated if N is given) For square matrices n is almost always m.
3499: . M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
3500: . N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
3501: . d_nz - number of nonzeros per row in DIAGONAL portion of local submatrix
3502: (same value is used for all local rows)
3503: . d_nnz - array containing the number of nonzeros in the various rows of the
3504: DIAGONAL portion of the local submatrix (possibly different for each row)
3505: or PETSC_NULL, if d_nz is used to specify the nonzero structure.
3506: The size of this array is equal to the number of local rows, i.e 'm'.
3507: You must leave room for the diagonal entry even if it is zero.
3508: . o_nz - number of nonzeros per row in the OFF-DIAGONAL portion of local
3509: submatrix (same value is used for all local rows).
3510: - o_nnz - array containing the number of nonzeros in the various rows of the
3511: OFF-DIAGONAL portion of the local submatrix (possibly different for
3512: each row) or PETSC_NULL, if o_nz is used to specify the nonzero
3513: structure. The size of this array is equal to the number
3514: of local rows, i.e 'm'.
3516: Output Parameter:
3517: . A - the matrix
3519: It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
3520: MatXXXXSetPreallocation() paradgm instead of this routine directly.
3521: [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]
3523: Notes:
3524: If the *_nnz parameter is given then the *_nz parameter is ignored
3526: m,n,M,N parameters specify the size of the matrix, and its partitioning across
3527: processors, while d_nz,d_nnz,o_nz,o_nnz parameters specify the approximate
3528: storage requirements for this matrix.
3530: If PETSC_DECIDE or PETSC_DETERMINE is used for a particular argument on one
3531: processor than it must be used on all processors that share the object for
3532: that argument.
3534: The user MUST specify either the local or global matrix dimensions
3535: (possibly both).
3537: The parallel matrix is partitioned across processors such that the
3538: first m0 rows belong to process 0, the next m1 rows belong to
3539: process 1, the next m2 rows belong to process 2 etc.. where
3540: m0,m1,m2,.. are the input parameter 'm'. i.e each processor stores
3541: values corresponding to [m x N] submatrix.
3543: The columns are logically partitioned with the n0 columns belonging
3544: to 0th partition, the next n1 columns belonging to the next
3545: partition etc.. where n0,n1,n2... are the the input parameter 'n'.
3547: The DIAGONAL portion of the local submatrix on any given processor
3548: is the submatrix corresponding to the rows and columns m,n
3549: corresponding to the given processor. i.e diagonal matrix on
3550: process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
3551: etc. The remaining portion of the local submatrix [m x (N-n)]
3552: constitute the OFF-DIAGONAL portion. The example below better
3553: illustrates this concept.
3555: For a square global matrix we define each processor's diagonal portion
3556: to be its local rows and the corresponding columns (a square submatrix);
3557: each processor's off-diagonal portion encompasses the remainder of the
3558: local matrix (a rectangular submatrix).
3560: If o_nnz, d_nnz are specified, then o_nz, and d_nz are ignored.
3562: When calling this routine with a single process communicator, a matrix of
3563: type SEQAIJ is returned. If a matrix of type MPIAIJ is desired for this
3564: type of communicator, use the construction mechanism:
3565: MatCreate(...,&A); MatSetType(A,MPIAIJ); MatMPIAIJSetPreallocation(A,...);
3567: By default, this format uses inodes (identical nodes) when possible.
3568: We search for consecutive rows with the same nonzero structure, thereby
3569: reusing matrix information to achieve increased efficiency.
3571: Options Database Keys:
3572: + -mat_no_inode - Do not use inodes
3573: . -mat_inode_limit <limit> - Sets inode limit (max limit=5)
3574: - -mat_aij_oneindex - Internally use indexing starting at 1
3575: rather than 0. Note that when calling MatSetValues(),
3576: the user still MUST index entries starting at 0!
3579: Example usage:
3580:
3581: Consider the following 8x8 matrix with 34 non-zero values, that is
3582: assembled across 3 processors. Lets assume that proc0 owns 3 rows,
3583: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
3584: as follows:
3586: .vb
3587: 1 2 0 | 0 3 0 | 0 4
3588: Proc0 0 5 6 | 7 0 0 | 8 0
3589: 9 0 10 | 11 0 0 | 12 0
3590: -------------------------------------
3591: 13 0 14 | 15 16 17 | 0 0
3592: Proc1 0 18 0 | 19 20 21 | 0 0
3593: 0 0 0 | 22 23 0 | 24 0
3594: -------------------------------------
3595: Proc2 25 26 27 | 0 0 28 | 29 0
3596: 30 0 0 | 31 32 33 | 0 34
3597: .ve
3599: This can be represented as a collection of submatrices as:
3601: .vb
3602: A B C
3603: D E F
3604: G H I
3605: .ve
3607: Where the submatrices A,B,C are owned by proc0, D,E,F are
3608: owned by proc1, G,H,I are owned by proc2.
3610: The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
3611: The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
3612: The 'M','N' parameters are 8,8, and have the same values on all procs.
3614: The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
3615: submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
3616: corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
3617: Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
3618: part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
3619: matrix, ans [DF] as another SeqAIJ matrix.
3621: When d_nz, o_nz parameters are specified, d_nz storage elements are
3622: allocated for every row of the local diagonal submatrix, and o_nz
3623: storage locations are allocated for every row of the OFF-DIAGONAL submat.
3624: One way to choose d_nz and o_nz is to use the max nonzerors per local
3625: rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
3626: In this case, the values of d_nz,o_nz are:
3627: .vb
3628: proc0 : dnz = 2, o_nz = 2
3629: proc1 : dnz = 3, o_nz = 2
3630: proc2 : dnz = 1, o_nz = 4
3631: .ve
3632: We are allocating m*(d_nz+o_nz) storage locations for every proc. This
3633: translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
3634: for proc3. i.e we are using 12+15+10=37 storage locations to store
3635: 34 values.
3637: When d_nnz, o_nnz parameters are specified, the storage is specified
3638: for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
3639: In the above case the values for d_nnz,o_nnz are:
3640: .vb
3641: proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
3642: proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
3643: proc2: d_nnz = [1,1] and o_nnz = [4,4]
3644: .ve
3645: Here the space allocated is sum of all the above values i.e 34, and
3646: hence pre-allocation is perfect.
3648: Level: intermediate
3650: .keywords: matrix, aij, compressed row, sparse, parallel
3652: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
3653: MPIAIJ, MatCreateMPIAIJWithArrays()
3654: @*/
3655: PetscErrorCode MatCreateMPIAIJ(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)
3656: {
3658: PetscMPIInt size;
3661: MatCreate(comm,A);
3662: MatSetSizes(*A,m,n,M,N);
3663: MPI_Comm_size(comm,&size);
3664: if (size > 1) {
3665: MatSetType(*A,MATMPIAIJ);
3666: MatMPIAIJSetPreallocation(*A,d_nz,d_nnz,o_nz,o_nnz);
3667: } else {
3668: MatSetType(*A,MATSEQAIJ);
3669: MatSeqAIJSetPreallocation(*A,d_nz,d_nnz);
3670: }
3671: return(0);
3672: }
3676: PetscErrorCode MatMPIAIJGetSeqAIJ(Mat A,Mat *Ad,Mat *Ao,PetscInt *colmap[])
3677: {
3678: Mat_MPIAIJ *a = (Mat_MPIAIJ *)A->data;
3681: *Ad = a->A;
3682: *Ao = a->B;
3683: *colmap = a->garray;
3684: return(0);
3685: }
3689: PetscErrorCode MatSetColoring_MPIAIJ(Mat A,ISColoring coloring)
3690: {
3692: PetscInt i;
3693: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
3696: if (coloring->ctype == IS_COLORING_GLOBAL) {
3697: ISColoringValue *allcolors,*colors;
3698: ISColoring ocoloring;
3700: /* set coloring for diagonal portion */
3701: MatSetColoring_SeqAIJ(a->A,coloring);
3703: /* set coloring for off-diagonal portion */
3704: ISAllGatherColors(((PetscObject)A)->comm,coloring->n,coloring->colors,PETSC_NULL,&allcolors);
3705: PetscMalloc((a->B->cmap->n+1)*sizeof(ISColoringValue),&colors);
3706: for (i=0; i<a->B->cmap->n; i++) {
3707: colors[i] = allcolors[a->garray[i]];
3708: }
3709: PetscFree(allcolors);
3710: ISColoringCreate(MPI_COMM_SELF,coloring->n,a->B->cmap->n,colors,&ocoloring);
3711: MatSetColoring_SeqAIJ(a->B,ocoloring);
3712: ISColoringDestroy(ocoloring);
3713: } else if (coloring->ctype == IS_COLORING_GHOSTED) {
3714: ISColoringValue *colors;
3715: PetscInt *larray;
3716: ISColoring ocoloring;
3718: /* set coloring for diagonal portion */
3719: PetscMalloc((a->A->cmap->n+1)*sizeof(PetscInt),&larray);
3720: for (i=0; i<a->A->cmap->n; i++) {
3721: larray[i] = i + A->cmap->rstart;
3722: }
3723: ISGlobalToLocalMappingApply(A->mapping,IS_GTOLM_MASK,a->A->cmap->n,larray,PETSC_NULL,larray);
3724: PetscMalloc((a->A->cmap->n+1)*sizeof(ISColoringValue),&colors);
3725: for (i=0; i<a->A->cmap->n; i++) {
3726: colors[i] = coloring->colors[larray[i]];
3727: }
3728: PetscFree(larray);
3729: ISColoringCreate(PETSC_COMM_SELF,coloring->n,a->A->cmap->n,colors,&ocoloring);
3730: MatSetColoring_SeqAIJ(a->A,ocoloring);
3731: ISColoringDestroy(ocoloring);
3733: /* set coloring for off-diagonal portion */
3734: PetscMalloc((a->B->cmap->n+1)*sizeof(PetscInt),&larray);
3735: ISGlobalToLocalMappingApply(A->mapping,IS_GTOLM_MASK,a->B->cmap->n,a->garray,PETSC_NULL,larray);
3736: PetscMalloc((a->B->cmap->n+1)*sizeof(ISColoringValue),&colors);
3737: for (i=0; i<a->B->cmap->n; i++) {
3738: colors[i] = coloring->colors[larray[i]];
3739: }
3740: PetscFree(larray);
3741: ISColoringCreate(MPI_COMM_SELF,coloring->n,a->B->cmap->n,colors,&ocoloring);
3742: MatSetColoring_SeqAIJ(a->B,ocoloring);
3743: ISColoringDestroy(ocoloring);
3744: } else {
3745: SETERRQ1(PETSC_ERR_SUP,"No support ISColoringType %d",(int)coloring->ctype);
3746: }
3748: return(0);
3749: }
3751: #if defined(PETSC_HAVE_ADIC)
3754: PetscErrorCode MatSetValuesAdic_MPIAIJ(Mat A,void *advalues)
3755: {
3756: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
3760: MatSetValuesAdic_SeqAIJ(a->A,advalues);
3761: MatSetValuesAdic_SeqAIJ(a->B,advalues);
3762: return(0);
3763: }
3764: #endif
3768: PetscErrorCode MatSetValuesAdifor_MPIAIJ(Mat A,PetscInt nl,void *advalues)
3769: {
3770: Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;
3774: MatSetValuesAdifor_SeqAIJ(a->A,nl,advalues);
3775: MatSetValuesAdifor_SeqAIJ(a->B,nl,advalues);
3776: return(0);
3777: }
3781: /*@
3782: MatMerge - Creates a single large PETSc matrix by concatinating sequential
3783: matrices from each processor
3785: Collective on MPI_Comm
3787: Input Parameters:
3788: + comm - the communicators the parallel matrix will live on
3789: . inmat - the input sequential matrices
3790: . n - number of local columns (or PETSC_DECIDE)
3791: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
3793: Output Parameter:
3794: . outmat - the parallel matrix generated
3796: Level: advanced
3798: Notes: The number of columns of the matrix in EACH processor MUST be the same.
3800: @*/
3801: PetscErrorCode MatMerge(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
3802: {
3804: PetscInt m,N,i,rstart,nnz,Ii,*dnz,*onz;
3805: PetscInt *indx;
3806: PetscScalar *values;
3809: MatGetSize(inmat,&m,&N);
3810: if (scall == MAT_INITIAL_MATRIX){
3811: /* count nonzeros in each row, for diagonal and off diagonal portion of matrix */
3812: if (n == PETSC_DECIDE){
3813: PetscSplitOwnership(comm,&n,&N);
3814: }
3815: MPI_Scan(&m, &rstart,1,MPIU_INT,MPI_SUM,comm);
3816: rstart -= m;
3818: MatPreallocateInitialize(comm,m,n,dnz,onz);
3819: for (i=0;i<m;i++) {
3820: MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,PETSC_NULL);
3821: MatPreallocateSet(i+rstart,nnz,indx,dnz,onz);
3822: MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,PETSC_NULL);
3823: }
3824: /* This routine will ONLY return MPIAIJ type matrix */
3825: MatCreate(comm,outmat);
3826: MatSetSizes(*outmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
3827: MatSetType(*outmat,MATMPIAIJ);
3828: MatMPIAIJSetPreallocation(*outmat,0,dnz,0,onz);
3829: MatPreallocateFinalize(dnz,onz);
3830:
3831: } else if (scall == MAT_REUSE_MATRIX){
3832: MatGetOwnershipRange(*outmat,&rstart,PETSC_NULL);
3833: } else {
3834: SETERRQ1(PETSC_ERR_ARG_WRONG,"Invalid MatReuse %d",(int)scall);
3835: }
3837: for (i=0;i<m;i++) {
3838: MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
3839: Ii = i + rstart;
3840: MatSetValues(*outmat,1,&Ii,nnz,indx,values,INSERT_VALUES);
3841: MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
3842: }
3843: MatDestroy(inmat);
3844: MatAssemblyBegin(*outmat,MAT_FINAL_ASSEMBLY);
3845: MatAssemblyEnd(*outmat,MAT_FINAL_ASSEMBLY);
3847: return(0);
3848: }
3852: PetscErrorCode MatFileSplit(Mat A,char *outfile)
3853: {
3854: PetscErrorCode ierr;
3855: PetscMPIInt rank;
3856: PetscInt m,N,i,rstart,nnz;
3857: size_t len;
3858: const PetscInt *indx;
3859: PetscViewer out;
3860: char *name;
3861: Mat B;
3862: const PetscScalar *values;
3865: MatGetLocalSize(A,&m,0);
3866: MatGetSize(A,0,&N);
3867: /* Should this be the type of the diagonal block of A? */
3868: MatCreate(PETSC_COMM_SELF,&B);
3869: MatSetSizes(B,m,N,m,N);
3870: MatSetType(B,MATSEQAIJ);
3871: MatSeqAIJSetPreallocation(B,0,PETSC_NULL);
3872: MatGetOwnershipRange(A,&rstart,0);
3873: for (i=0;i<m;i++) {
3874: MatGetRow(A,i+rstart,&nnz,&indx,&values);
3875: MatSetValues(B,1,&i,nnz,indx,values,INSERT_VALUES);
3876: MatRestoreRow(A,i+rstart,&nnz,&indx,&values);
3877: }
3878: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3879: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3881: MPI_Comm_rank(((PetscObject)A)->comm,&rank);
3882: PetscStrlen(outfile,&len);
3883: PetscMalloc((len+5)*sizeof(char),&name);
3884: sprintf(name,"%s.%d",outfile,rank);
3885: PetscViewerBinaryOpen(PETSC_COMM_SELF,name,FILE_MODE_APPEND,&out);
3886: PetscFree(name);
3887: MatView(B,out);
3888: PetscViewerDestroy(out);
3889: MatDestroy(B);
3890: return(0);
3891: }
3893: EXTERN PetscErrorCode MatDestroy_MPIAIJ(Mat);
3896: PetscErrorCode MatDestroy_MPIAIJ_SeqsToMPI(Mat A)
3897: {
3898: PetscErrorCode ierr;
3899: Mat_Merge_SeqsToMPI *merge;
3900: PetscContainer container;
3903: PetscObjectQuery((PetscObject)A,"MatMergeSeqsToMPI",(PetscObject *)&container);
3904: if (container) {
3905: PetscContainerGetPointer(container,(void **)&merge);
3906: PetscFree(merge->id_r);
3907: PetscFree(merge->len_s);
3908: PetscFree(merge->len_r);
3909: PetscFree(merge->bi);
3910: PetscFree(merge->bj);
3911: PetscFree(merge->buf_ri);
3912: PetscFree(merge->buf_rj);
3913: PetscFree(merge->coi);
3914: PetscFree(merge->coj);
3915: PetscFree(merge->owners_co);
3916: PetscFree(merge->rowmap.range);
3917:
3918: PetscContainerDestroy(container);
3919: PetscObjectCompose((PetscObject)A,"MatMergeSeqsToMPI",0);
3920: }
3921: PetscFree(merge);
3923: MatDestroy_MPIAIJ(A);
3924: return(0);
3925: }
3927: #include ../src/mat/utils/freespace.h
3928: #include petscbt.h
3932: /*@C
3933: MatMerge_SeqsToMPI - Creates a MPIAIJ matrix by adding sequential
3934: matrices from each processor
3936: Collective on MPI_Comm
3938: Input Parameters:
3939: + comm - the communicators the parallel matrix will live on
3940: . seqmat - the input sequential matrices
3941: . m - number of local rows (or PETSC_DECIDE)
3942: . n - number of local columns (or PETSC_DECIDE)
3943: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
3945: Output Parameter:
3946: . mpimat - the parallel matrix generated
3948: Level: advanced
3950: Notes:
3951: The dimensions of the sequential matrix in each processor MUST be the same.
3952: The input seqmat is included into the container "Mat_Merge_SeqsToMPI", and will be
3953: destroyed when mpimat is destroyed. Call PetscObjectQuery() to access seqmat.
3954: @*/
3955: PetscErrorCode MatMerge_SeqsToMPINumeric(Mat seqmat,Mat mpimat)
3956: {
3957: PetscErrorCode ierr;
3958: MPI_Comm comm=((PetscObject)mpimat)->comm;
3959: Mat_SeqAIJ *a=(Mat_SeqAIJ*)seqmat->data;
3960: PetscMPIInt size,rank,taga,*len_s;
3961: PetscInt N=mpimat->cmap->N,i,j,*owners,*ai=a->i,*aj=a->j;
3962: PetscInt proc,m;
3963: PetscInt **buf_ri,**buf_rj;
3964: PetscInt k,anzi,*bj_i,*bi,*bj,arow,bnzi,nextaj;
3965: PetscInt nrows,**buf_ri_k,**nextrow,**nextai;
3966: MPI_Request *s_waits,*r_waits;
3967: MPI_Status *status;
3968: MatScalar *aa=a->a;
3969: MatScalar **abuf_r,*ba_i;
3970: Mat_Merge_SeqsToMPI *merge;
3971: PetscContainer container;
3972:
3974: PetscLogEventBegin(MAT_Seqstompinum,seqmat,0,0,0);
3976: MPI_Comm_size(comm,&size);
3977: MPI_Comm_rank(comm,&rank);
3979: PetscObjectQuery((PetscObject)mpimat,"MatMergeSeqsToMPI",(PetscObject *)&container);
3980: if (container) {
3981: PetscContainerGetPointer(container,(void **)&merge);
3982: }
3983: bi = merge->bi;
3984: bj = merge->bj;
3985: buf_ri = merge->buf_ri;
3986: buf_rj = merge->buf_rj;
3988: PetscMalloc(size*sizeof(MPI_Status),&status);
3989: owners = merge->rowmap.range;
3990: len_s = merge->len_s;
3992: /* send and recv matrix values */
3993: /*-----------------------------*/
3994: PetscObjectGetNewTag((PetscObject)mpimat,&taga);
3995: PetscPostIrecvScalar(comm,taga,merge->nrecv,merge->id_r,merge->len_r,&abuf_r,&r_waits);
3997: PetscMalloc((merge->nsend+1)*sizeof(MPI_Request),&s_waits);
3998: for (proc=0,k=0; proc<size; proc++){
3999: if (!len_s[proc]) continue;
4000: i = owners[proc];
4001: MPI_Isend(aa+ai[i],len_s[proc],MPIU_MATSCALAR,proc,taga,comm,s_waits+k);
4002: k++;
4003: }
4005: if (merge->nrecv) {MPI_Waitall(merge->nrecv,r_waits,status);}
4006: if (merge->nsend) {MPI_Waitall(merge->nsend,s_waits,status);}
4007: PetscFree(status);
4009: PetscFree(s_waits);
4010: PetscFree(r_waits);
4012: /* insert mat values of mpimat */
4013: /*----------------------------*/
4014: PetscMalloc(N*sizeof(PetscScalar),&ba_i);
4015: PetscMalloc((3*merge->nrecv+1)*sizeof(PetscInt**),&buf_ri_k);
4016: nextrow = buf_ri_k + merge->nrecv;
4017: nextai = nextrow + merge->nrecv;
4019: for (k=0; k<merge->nrecv; k++){
4020: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4021: nrows = *(buf_ri_k[k]);
4022: nextrow[k] = buf_ri_k[k]+1; /* next row number of k-th recved i-structure */
4023: nextai[k] = buf_ri_k[k] + (nrows + 1);/* poins to the next i-structure of k-th recved i-structure */
4024: }
4026: /* set values of ba */
4027: m = merge->rowmap.n;
4028: for (i=0; i<m; i++) {
4029: arow = owners[rank] + i;
4030: bj_i = bj+bi[i]; /* col indices of the i-th row of mpimat */
4031: bnzi = bi[i+1] - bi[i];
4032: PetscMemzero(ba_i,bnzi*sizeof(PetscScalar));
4034: /* add local non-zero vals of this proc's seqmat into ba */
4035: anzi = ai[arow+1] - ai[arow];
4036: aj = a->j + ai[arow];
4037: aa = a->a + ai[arow];
4038: nextaj = 0;
4039: for (j=0; nextaj<anzi; j++){
4040: if (*(bj_i + j) == aj[nextaj]){ /* bcol == acol */
4041: ba_i[j] += aa[nextaj++];
4042: }
4043: }
4045: /* add received vals into ba */
4046: for (k=0; k<merge->nrecv; k++){ /* k-th received message */
4047: /* i-th row */
4048: if (i == *nextrow[k]) {
4049: anzi = *(nextai[k]+1) - *nextai[k];
4050: aj = buf_rj[k] + *(nextai[k]);
4051: aa = abuf_r[k] + *(nextai[k]);
4052: nextaj = 0;
4053: for (j=0; nextaj<anzi; j++){
4054: if (*(bj_i + j) == aj[nextaj]){ /* bcol == acol */
4055: ba_i[j] += aa[nextaj++];
4056: }
4057: }
4058: nextrow[k]++; nextai[k]++;
4059: }
4060: }
4061: MatSetValues(mpimat,1,&arow,bnzi,bj_i,ba_i,INSERT_VALUES);
4062: }
4063: MatAssemblyBegin(mpimat,MAT_FINAL_ASSEMBLY);
4064: MatAssemblyEnd(mpimat,MAT_FINAL_ASSEMBLY);
4066: PetscFree(abuf_r);
4067: PetscFree(ba_i);
4068: PetscFree(buf_ri_k);
4069: PetscLogEventEnd(MAT_Seqstompinum,seqmat,0,0,0);
4070: return(0);
4071: }
4075: PetscErrorCode MatMerge_SeqsToMPISymbolic(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,Mat *mpimat)
4076: {
4077: PetscErrorCode ierr;
4078: Mat B_mpi;
4079: Mat_SeqAIJ *a=(Mat_SeqAIJ*)seqmat->data;
4080: PetscMPIInt size,rank,tagi,tagj,*len_s,*len_si,*len_ri;
4081: PetscInt **buf_rj,**buf_ri,**buf_ri_k;
4082: PetscInt M=seqmat->rmap->n,N=seqmat->cmap->n,i,*owners,*ai=a->i,*aj=a->j;
4083: PetscInt len,proc,*dnz,*onz;
4084: PetscInt k,anzi,*bi,*bj,*lnk,nlnk,arow,bnzi,nspacedouble=0;
4085: PetscInt nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextai;
4086: MPI_Request *si_waits,*sj_waits,*ri_waits,*rj_waits;
4087: MPI_Status *status;
4088: PetscFreeSpaceList free_space=PETSC_NULL,current_space=PETSC_NULL;
4089: PetscBT lnkbt;
4090: Mat_Merge_SeqsToMPI *merge;
4091: PetscContainer container;
4094: PetscLogEventBegin(MAT_Seqstompisym,seqmat,0,0,0);
4096: /* make sure it is a PETSc comm */
4097: PetscCommDuplicate(comm,&comm,PETSC_NULL);
4098: MPI_Comm_size(comm,&size);
4099: MPI_Comm_rank(comm,&rank);
4100:
4101: PetscNew(Mat_Merge_SeqsToMPI,&merge);
4102: PetscMalloc(size*sizeof(MPI_Status),&status);
4104: /* determine row ownership */
4105: /*---------------------------------------------------------*/
4106: PetscMapInitialize(comm,&merge->rowmap);
4107: merge->rowmap.n = m;
4108: merge->rowmap.N = M;
4109: merge->rowmap.bs = 1;
4110: PetscMapSetUp(&merge->rowmap);
4111: PetscMalloc(size*sizeof(PetscMPIInt),&len_si);
4112: PetscMalloc(size*sizeof(PetscMPIInt),&merge->len_s);
4113:
4114: m = merge->rowmap.n;
4115: M = merge->rowmap.N;
4116: owners = merge->rowmap.range;
4118: /* determine the number of messages to send, their lengths */
4119: /*---------------------------------------------------------*/
4120: len_s = merge->len_s;
4122: len = 0; /* length of buf_si[] */
4123: merge->nsend = 0;
4124: for (proc=0; proc<size; proc++){
4125: len_si[proc] = 0;
4126: if (proc == rank){
4127: len_s[proc] = 0;
4128: } else {
4129: len_si[proc] = owners[proc+1] - owners[proc] + 1;
4130: len_s[proc] = ai[owners[proc+1]] - ai[owners[proc]]; /* num of rows to be sent to [proc] */
4131: }
4132: if (len_s[proc]) {
4133: merge->nsend++;
4134: nrows = 0;
4135: for (i=owners[proc]; i<owners[proc+1]; i++){
4136: if (ai[i+1] > ai[i]) nrows++;
4137: }
4138: len_si[proc] = 2*(nrows+1);
4139: len += len_si[proc];
4140: }
4141: }
4143: /* determine the number and length of messages to receive for ij-structure */
4144: /*-------------------------------------------------------------------------*/
4145: PetscGatherNumberOfMessages(comm,PETSC_NULL,len_s,&merge->nrecv);
4146: PetscGatherMessageLengths2(comm,merge->nsend,merge->nrecv,len_s,len_si,&merge->id_r,&merge->len_r,&len_ri);
4148: /* post the Irecv of j-structure */
4149: /*-------------------------------*/
4150: PetscCommGetNewTag(comm,&tagj);
4151: PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rj_waits);
4153: /* post the Isend of j-structure */
4154: /*--------------------------------*/
4155: PetscMalloc((2*merge->nsend+1)*sizeof(MPI_Request),&si_waits);
4156: sj_waits = si_waits + merge->nsend;
4158: for (proc=0, k=0; proc<size; proc++){
4159: if (!len_s[proc]) continue;
4160: i = owners[proc];
4161: MPI_Isend(aj+ai[i],len_s[proc],MPIU_INT,proc,tagj,comm,sj_waits+k);
4162: k++;
4163: }
4165: /* receives and sends of j-structure are complete */
4166: /*------------------------------------------------*/
4167: if (merge->nrecv) {MPI_Waitall(merge->nrecv,rj_waits,status);}
4168: if (merge->nsend) {MPI_Waitall(merge->nsend,sj_waits,status);}
4169:
4170: /* send and recv i-structure */
4171: /*---------------------------*/
4172: PetscCommGetNewTag(comm,&tagi);
4173: PetscPostIrecvInt(comm,tagi,merge->nrecv,merge->id_r,len_ri,&buf_ri,&ri_waits);
4174:
4175: PetscMalloc((len+1)*sizeof(PetscInt),&buf_s);
4176: buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
4177: for (proc=0,k=0; proc<size; proc++){
4178: if (!len_s[proc]) continue;
4179: /* form outgoing message for i-structure:
4180: buf_si[0]: nrows to be sent
4181: [1:nrows]: row index (global)
4182: [nrows+1:2*nrows+1]: i-structure index
4183: */
4184: /*-------------------------------------------*/
4185: nrows = len_si[proc]/2 - 1;
4186: buf_si_i = buf_si + nrows+1;
4187: buf_si[0] = nrows;
4188: buf_si_i[0] = 0;
4189: nrows = 0;
4190: for (i=owners[proc]; i<owners[proc+1]; i++){
4191: anzi = ai[i+1] - ai[i];
4192: if (anzi) {
4193: buf_si_i[nrows+1] = buf_si_i[nrows] + anzi; /* i-structure */
4194: buf_si[nrows+1] = i-owners[proc]; /* local row index */
4195: nrows++;
4196: }
4197: }
4198: MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,si_waits+k);
4199: k++;
4200: buf_si += len_si[proc];
4201: }
4203: if (merge->nrecv) {MPI_Waitall(merge->nrecv,ri_waits,status);}
4204: if (merge->nsend) {MPI_Waitall(merge->nsend,si_waits,status);}
4206: PetscInfo2(seqmat,"nsend: %D, nrecv: %D\n",merge->nsend,merge->nrecv);
4207: for (i=0; i<merge->nrecv; i++){
4208: PetscInfo3(seqmat,"recv len_ri=%D, len_rj=%D from [%D]\n",len_ri[i],merge->len_r[i],merge->id_r[i]);
4209: }
4211: PetscFree(len_si);
4212: PetscFree(len_ri);
4213: PetscFree(rj_waits);
4214: PetscFree(si_waits);
4215: PetscFree(ri_waits);
4216: PetscFree(buf_s);
4217: PetscFree(status);
4219: /* compute a local seq matrix in each processor */
4220: /*----------------------------------------------*/
4221: /* allocate bi array and free space for accumulating nonzero column info */
4222: PetscMalloc((m+1)*sizeof(PetscInt),&bi);
4223: bi[0] = 0;
4225: /* create and initialize a linked list */
4226: nlnk = N+1;
4227: PetscLLCreate(N,N,nlnk,lnk,lnkbt);
4228:
4229: /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
4230: len = 0;
4231: len = ai[owners[rank+1]] - ai[owners[rank]];
4232: PetscFreeSpaceGet((PetscInt)(2*len+1),&free_space);
4233: current_space = free_space;
4235: /* determine symbolic info for each local row */
4236: PetscMalloc((3*merge->nrecv+1)*sizeof(PetscInt**),&buf_ri_k);
4237: nextrow = buf_ri_k + merge->nrecv;
4238: nextai = nextrow + merge->nrecv;
4239: for (k=0; k<merge->nrecv; k++){
4240: buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4241: nrows = *buf_ri_k[k];
4242: nextrow[k] = buf_ri_k[k] + 1; /* next row number of k-th recved i-structure */
4243: nextai[k] = buf_ri_k[k] + (nrows + 1);/* poins to the next i-structure of k-th recved i-structure */
4244: }
4246: MatPreallocateInitialize(comm,m,n,dnz,onz);
4247: len = 0;
4248: for (i=0;i<m;i++) {
4249: bnzi = 0;
4250: /* add local non-zero cols of this proc's seqmat into lnk */
4251: arow = owners[rank] + i;
4252: anzi = ai[arow+1] - ai[arow];
4253: aj = a->j + ai[arow];
4254: PetscLLAdd(anzi,aj,N,nlnk,lnk,lnkbt);
4255: bnzi += nlnk;
4256: /* add received col data into lnk */
4257: for (k=0; k<merge->nrecv; k++){ /* k-th received message */
4258: if (i == *nextrow[k]) { /* i-th row */
4259: anzi = *(nextai[k]+1) - *nextai[k];
4260: aj = buf_rj[k] + *nextai[k];
4261: PetscLLAdd(anzi,aj,N,nlnk,lnk,lnkbt);
4262: bnzi += nlnk;
4263: nextrow[k]++; nextai[k]++;
4264: }
4265: }
4266: if (len < bnzi) len = bnzi; /* =max(bnzi) */
4268: /* if free space is not available, make more free space */
4269: if (current_space->local_remaining<bnzi) {
4270: PetscFreeSpaceGet(bnzi+current_space->total_array_size,¤t_space);
4271: nspacedouble++;
4272: }
4273: /* copy data into free space, then initialize lnk */
4274: PetscLLClean(N,N,bnzi,lnk,current_space->array,lnkbt);
4275: MatPreallocateSet(i+owners[rank],bnzi,current_space->array,dnz,onz);
4277: current_space->array += bnzi;
4278: current_space->local_used += bnzi;
4279: current_space->local_remaining -= bnzi;
4280:
4281: bi[i+1] = bi[i] + bnzi;
4282: }
4283:
4284: PetscFree(buf_ri_k);
4286: PetscMalloc((bi[m]+1)*sizeof(PetscInt),&bj);
4287: PetscFreeSpaceContiguous(&free_space,bj);
4288: PetscLLDestroy(lnk,lnkbt);
4290: /* create symbolic parallel matrix B_mpi */
4291: /*---------------------------------------*/
4292: MatCreate(comm,&B_mpi);
4293: if (n==PETSC_DECIDE) {
4294: MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,N);
4295: } else {
4296: MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4297: }
4298: MatSetType(B_mpi,MATMPIAIJ);
4299: MatMPIAIJSetPreallocation(B_mpi,0,dnz,0,onz);
4300: MatPreallocateFinalize(dnz,onz);
4302: /* B_mpi is not ready for use - assembly will be done by MatMerge_SeqsToMPINumeric() */
4303: B_mpi->assembled = PETSC_FALSE;
4304: B_mpi->ops->destroy = MatDestroy_MPIAIJ_SeqsToMPI;
4305: merge->bi = bi;
4306: merge->bj = bj;
4307: merge->buf_ri = buf_ri;
4308: merge->buf_rj = buf_rj;
4309: merge->coi = PETSC_NULL;
4310: merge->coj = PETSC_NULL;
4311: merge->owners_co = PETSC_NULL;
4313: /* attach the supporting struct to B_mpi for reuse */
4314: PetscContainerCreate(PETSC_COMM_SELF,&container);
4315: PetscContainerSetPointer(container,merge);
4316: PetscObjectCompose((PetscObject)B_mpi,"MatMergeSeqsToMPI",(PetscObject)container);
4317: *mpimat = B_mpi;
4319: PetscCommDestroy(&comm);
4320: PetscLogEventEnd(MAT_Seqstompisym,seqmat,0,0,0);
4321: return(0);
4322: }
4326: PetscErrorCode MatMerge_SeqsToMPI(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,MatReuse scall,Mat *mpimat)
4327: {
4328: PetscErrorCode ierr;
4331: PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
4332: if (scall == MAT_INITIAL_MATRIX){
4333: MatMerge_SeqsToMPISymbolic(comm,seqmat,m,n,mpimat);
4334: }
4335: MatMerge_SeqsToMPINumeric(seqmat,*mpimat);
4336: PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
4337: return(0);
4338: }
4342: /*@
4343: MatGetLocalMat - Creates a SeqAIJ matrix by taking all its local rows
4345: Not Collective
4347: Input Parameters:
4348: + A - the matrix
4349: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
4351: Output Parameter:
4352: . A_loc - the local sequential matrix generated
4354: Level: developer
4356: @*/
4357: PetscErrorCode MatGetLocalMat(Mat A,MatReuse scall,Mat *A_loc)
4358: {
4359: PetscErrorCode ierr;
4360: Mat_MPIAIJ *mpimat=(Mat_MPIAIJ*)A->data;
4361: Mat_SeqAIJ *mat,*a=(Mat_SeqAIJ*)(mpimat->A)->data,*b=(Mat_SeqAIJ*)(mpimat->B)->data;
4362: PetscInt *ai=a->i,*aj=a->j,*bi=b->i,*bj=b->j,*cmap=mpimat->garray;
4363: MatScalar *aa=a->a,*ba=b->a,*cam;
4364: PetscScalar *ca;
4365: PetscInt am=A->rmap->n,i,j,k,cstart=A->cmap->rstart;
4366: PetscInt *ci,*cj,col,ncols_d,ncols_o,jo;
4369: PetscLogEventBegin(MAT_Getlocalmat,A,0,0,0);
4370: if (scall == MAT_INITIAL_MATRIX){
4371: PetscMalloc((1+am)*sizeof(PetscInt),&ci);
4372: ci[0] = 0;
4373: for (i=0; i<am; i++){
4374: ci[i+1] = ci[i] + (ai[i+1] - ai[i]) + (bi[i+1] - bi[i]);
4375: }
4376: PetscMalloc((1+ci[am])*sizeof(PetscInt),&cj);
4377: PetscMalloc((1+ci[am])*sizeof(PetscScalar),&ca);
4378: k = 0;
4379: for (i=0; i<am; i++) {
4380: ncols_o = bi[i+1] - bi[i];
4381: ncols_d = ai[i+1] - ai[i];
4382: /* off-diagonal portion of A */
4383: for (jo=0; jo<ncols_o; jo++) {
4384: col = cmap[*bj];
4385: if (col >= cstart) break;
4386: cj[k] = col; bj++;
4387: ca[k++] = *ba++;
4388: }
4389: /* diagonal portion of A */
4390: for (j=0; j<ncols_d; j++) {
4391: cj[k] = cstart + *aj++;
4392: ca[k++] = *aa++;
4393: }
4394: /* off-diagonal portion of A */
4395: for (j=jo; j<ncols_o; j++) {
4396: cj[k] = cmap[*bj++];
4397: ca[k++] = *ba++;
4398: }
4399: }
4400: /* put together the new matrix */
4401: MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ci,cj,ca,A_loc);
4402: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
4403: /* Since these are PETSc arrays, change flags to free them as necessary. */
4404: mat = (Mat_SeqAIJ*)(*A_loc)->data;
4405: mat->free_a = PETSC_TRUE;
4406: mat->free_ij = PETSC_TRUE;
4407: mat->nonew = 0;
4408: } else if (scall == MAT_REUSE_MATRIX){
4409: mat=(Mat_SeqAIJ*)(*A_loc)->data;
4410: ci = mat->i; cj = mat->j; cam = mat->a;
4411: for (i=0; i<am; i++) {
4412: /* off-diagonal portion of A */
4413: ncols_o = bi[i+1] - bi[i];
4414: for (jo=0; jo<ncols_o; jo++) {
4415: col = cmap[*bj];
4416: if (col >= cstart) break;
4417: *cam++ = *ba++; bj++;
4418: }
4419: /* diagonal portion of A */
4420: ncols_d = ai[i+1] - ai[i];
4421: for (j=0; j<ncols_d; j++) *cam++ = *aa++;
4422: /* off-diagonal portion of A */
4423: for (j=jo; j<ncols_o; j++) {
4424: *cam++ = *ba++; bj++;
4425: }
4426: }
4427: } else {
4428: SETERRQ1(PETSC_ERR_ARG_WRONG,"Invalid MatReuse %d",(int)scall);
4429: }
4431: PetscLogEventEnd(MAT_Getlocalmat,A,0,0,0);
4432: return(0);
4433: }
4437: /*@C
4438: MatGetLocalMatCondensed - Creates a SeqAIJ matrix by taking all its local rows and NON-ZERO columns
4440: Not Collective
4442: Input Parameters:
4443: + A - the matrix
4444: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
4445: - row, col - index sets of rows and columns to extract (or PETSC_NULL)
4447: Output Parameter:
4448: . A_loc - the local sequential matrix generated
4450: Level: developer
4452: @*/
4453: PetscErrorCode MatGetLocalMatCondensed(Mat A,MatReuse scall,IS *row,IS *col,Mat *A_loc)
4454: {
4455: Mat_MPIAIJ *a=(Mat_MPIAIJ*)A->data;
4456: PetscErrorCode ierr;
4457: PetscInt i,start,end,ncols,nzA,nzB,*cmap,imark,*idx;
4458: IS isrowa,iscola;
4459: Mat *aloc;
4462: PetscLogEventBegin(MAT_Getlocalmatcondensed,A,0,0,0);
4463: if (!row){
4464: start = A->rmap->rstart; end = A->rmap->rend;
4465: ISCreateStride(PETSC_COMM_SELF,end-start,start,1,&isrowa);
4466: } else {
4467: isrowa = *row;
4468: }
4469: if (!col){
4470: start = A->cmap->rstart;
4471: cmap = a->garray;
4472: nzA = a->A->cmap->n;
4473: nzB = a->B->cmap->n;
4474: PetscMalloc((nzA+nzB)*sizeof(PetscInt), &idx);
4475: ncols = 0;
4476: for (i=0; i<nzB; i++) {
4477: if (cmap[i] < start) idx[ncols++] = cmap[i];
4478: else break;
4479: }
4480: imark = i;
4481: for (i=0; i<nzA; i++) idx[ncols++] = start + i;
4482: for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i];
4483: ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,&iscola);
4484: PetscFree(idx);
4485: } else {
4486: iscola = *col;
4487: }
4488: if (scall != MAT_INITIAL_MATRIX){
4489: PetscMalloc(sizeof(Mat),&aloc);
4490: aloc[0] = *A_loc;
4491: }
4492: MatGetSubMatrices(A,1,&isrowa,&iscola,scall,&aloc);
4493: *A_loc = aloc[0];
4494: PetscFree(aloc);
4495: if (!row){
4496: ISDestroy(isrowa);
4497: }
4498: if (!col){
4499: ISDestroy(iscola);
4500: }
4501: PetscLogEventEnd(MAT_Getlocalmatcondensed,A,0,0,0);
4502: return(0);
4503: }
4507: /*@C
4508: MatGetBrowsOfAcols - Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A
4510: Collective on Mat
4512: Input Parameters:
4513: + A,B - the matrices in mpiaij format
4514: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
4515: - rowb, colb - index sets of rows and columns of B to extract (or PETSC_NULL)
4517: Output Parameter:
4518: + rowb, colb - index sets of rows and columns of B to extract
4519: . brstart - row index of B_seq from which next B->rmap->n rows are taken from B's local rows
4520: - B_seq - the sequential matrix generated
4522: Level: developer
4524: @*/
4525: PetscErrorCode MatGetBrowsOfAcols(Mat A,Mat B,MatReuse scall,IS *rowb,IS *colb,PetscInt *brstart,Mat *B_seq)
4526: {
4527: Mat_MPIAIJ *a=(Mat_MPIAIJ*)A->data;
4528: PetscErrorCode ierr;
4529: PetscInt *idx,i,start,ncols,nzA,nzB,*cmap,imark;
4530: IS isrowb,iscolb;
4531: Mat *bseq;
4532:
4534: if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend){
4535: SETERRQ4(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);
4536: }
4537: PetscLogEventBegin(MAT_GetBrowsOfAcols,A,B,0,0);
4538:
4539: if (scall == MAT_INITIAL_MATRIX){
4540: start = A->cmap->rstart;
4541: cmap = a->garray;
4542: nzA = a->A->cmap->n;
4543: nzB = a->B->cmap->n;
4544: PetscMalloc((nzA+nzB)*sizeof(PetscInt), &idx);
4545: ncols = 0;
4546: for (i=0; i<nzB; i++) { /* row < local row index */
4547: if (cmap[i] < start) idx[ncols++] = cmap[i];
4548: else break;
4549: }
4550: imark = i;
4551: for (i=0; i<nzA; i++) idx[ncols++] = start + i; /* local rows */
4552: for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
4553: ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,&isrowb);
4554: PetscFree(idx);
4555: *brstart = imark;
4556: ISCreateStride(PETSC_COMM_SELF,B->cmap->N,0,1,&iscolb);
4557: } else {
4558: if (!rowb || !colb) SETERRQ(PETSC_ERR_SUP,"IS rowb and colb must be provided for MAT_REUSE_MATRIX");
4559: isrowb = *rowb; iscolb = *colb;
4560: PetscMalloc(sizeof(Mat),&bseq);
4561: bseq[0] = *B_seq;
4562: }
4563: MatGetSubMatrices(B,1,&isrowb,&iscolb,scall,&bseq);
4564: *B_seq = bseq[0];
4565: PetscFree(bseq);
4566: if (!rowb){
4567: ISDestroy(isrowb);
4568: } else {
4569: *rowb = isrowb;
4570: }
4571: if (!colb){
4572: ISDestroy(iscolb);
4573: } else {
4574: *colb = iscolb;
4575: }
4576: PetscLogEventEnd(MAT_GetBrowsOfAcols,A,B,0,0);
4577: return(0);
4578: }
4582: /*@C
4583: MatGetBrowsOfAoCols - Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns
4584: of the OFF-DIAGONAL portion of local A
4586: Collective on Mat
4588: Input Parameters:
4589: + A,B - the matrices in mpiaij format
4590: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
4591: . startsj - starting point in B's sending and receiving j-arrays, saved for MAT_REUSE (or PETSC_NULL)
4592: - bufa_ptr - array for sending matrix values, saved for MAT_REUSE (or PETSC_NULL)
4594: Output Parameter:
4595: + B_oth - the sequential matrix generated
4597: Level: developer
4599: @*/
4600: PetscErrorCode MatGetBrowsOfAoCols(Mat A,Mat B,MatReuse scall,PetscInt **startsj,MatScalar **bufa_ptr,Mat *B_oth)
4601: {
4602: VecScatter_MPI_General *gen_to,*gen_from;
4603: PetscErrorCode ierr;
4604: Mat_MPIAIJ *a=(Mat_MPIAIJ*)A->data;
4605: Mat_SeqAIJ *b_oth;
4606: VecScatter ctx=a->Mvctx;
4607: MPI_Comm comm=((PetscObject)ctx)->comm;
4608: PetscMPIInt *rprocs,*sprocs,tag=((PetscObject)ctx)->tag,rank;
4609: PetscInt *rowlen,*bufj,*bufJ,ncols,aBn=a->B->cmap->n,row,*b_othi,*b_othj;
4610: PetscScalar *rvalues,*svalues;
4611: MatScalar *b_otha,*bufa,*bufA;
4612: PetscInt i,j,k,l,ll,nrecvs,nsends,nrows,*srow,*rstarts,*rstartsj = 0,*sstarts,*sstartsj,len;
4613: MPI_Request *rwaits = PETSC_NULL,*swaits = PETSC_NULL;
4614: MPI_Status *sstatus,rstatus;
4615: PetscMPIInt jj;
4616: PetscInt *cols,sbs,rbs;
4617: PetscScalar *vals;
4620: if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend){
4621: SETERRQ4(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);
4622: }
4623: PetscLogEventBegin(MAT_GetBrowsOfAocols,A,B,0,0);
4624: MPI_Comm_rank(comm,&rank);
4626: gen_to = (VecScatter_MPI_General*)ctx->todata;
4627: gen_from = (VecScatter_MPI_General*)ctx->fromdata;
4628: rvalues = gen_from->values; /* holds the length of receiving row */
4629: svalues = gen_to->values; /* holds the length of sending row */
4630: nrecvs = gen_from->n;
4631: nsends = gen_to->n;
4633: PetscMalloc2(nrecvs,MPI_Request,&rwaits,nsends,MPI_Request,&swaits);
4634: srow = gen_to->indices; /* local row index to be sent */
4635: sstarts = gen_to->starts;
4636: sprocs = gen_to->procs;
4637: sstatus = gen_to->sstatus;
4638: sbs = gen_to->bs;
4639: rstarts = gen_from->starts;
4640: rprocs = gen_from->procs;
4641: rbs = gen_from->bs;
4643: if (!startsj || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
4644: if (scall == MAT_INITIAL_MATRIX){
4645: /* i-array */
4646: /*---------*/
4647: /* post receives */
4648: for (i=0; i<nrecvs; i++){
4649: rowlen = (PetscInt*)rvalues + rstarts[i]*rbs;
4650: nrows = (rstarts[i+1]-rstarts[i])*rbs; /* num of indices to be received */
4651: MPI_Irecv(rowlen,nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
4652: }
4654: /* pack the outgoing message */
4655: PetscMalloc((nsends+nrecvs+3)*sizeof(PetscInt),&sstartsj);
4656: rstartsj = sstartsj + nsends +1;
4657: sstartsj[0] = 0; rstartsj[0] = 0;
4658: len = 0; /* total length of j or a array to be sent */
4659: k = 0;
4660: for (i=0; i<nsends; i++){
4661: rowlen = (PetscInt*)svalues + sstarts[i]*sbs;
4662: nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
4663: for (j=0; j<nrows; j++) {
4664: row = srow[k] + B->rmap->range[rank]; /* global row idx */
4665: for (l=0; l<sbs; l++){
4666: MatGetRow_MPIAIJ(B,row+l,&ncols,PETSC_NULL,PETSC_NULL); /* rowlength */
4667: rowlen[j*sbs+l] = ncols;
4668: len += ncols;
4669: MatRestoreRow_MPIAIJ(B,row+l,&ncols,PETSC_NULL,PETSC_NULL);
4670: }
4671: k++;
4672: }
4673: MPI_Isend(rowlen,nrows*sbs,MPIU_INT,sprocs[i],tag,comm,swaits+i);
4674: sstartsj[i+1] = len; /* starting point of (i+1)-th outgoing msg in bufj and bufa */
4675: }
4676: /* recvs and sends of i-array are completed */
4677: i = nrecvs;
4678: while (i--) {
4679: MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
4680: }
4681: if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
4683: /* allocate buffers for sending j and a arrays */
4684: PetscMalloc((len+1)*sizeof(PetscInt),&bufj);
4685: PetscMalloc((len+1)*sizeof(PetscScalar),&bufa);
4687: /* create i-array of B_oth */
4688: PetscMalloc((aBn+2)*sizeof(PetscInt),&b_othi);
4689: b_othi[0] = 0;
4690: len = 0; /* total length of j or a array to be received */
4691: k = 0;
4692: for (i=0; i<nrecvs; i++){
4693: rowlen = (PetscInt*)rvalues + rstarts[i]*rbs;
4694: nrows = rbs*(rstarts[i+1]-rstarts[i]); /* num of rows to be recieved */
4695: for (j=0; j<nrows; j++) {
4696: b_othi[k+1] = b_othi[k] + rowlen[j];
4697: len += rowlen[j]; k++;
4698: }
4699: rstartsj[i+1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
4700: }
4702: /* allocate space for j and a arrrays of B_oth */
4703: PetscMalloc((b_othi[aBn]+1)*sizeof(PetscInt),&b_othj);
4704: PetscMalloc((b_othi[aBn]+1)*sizeof(MatScalar),&b_otha);
4706: /* j-array */
4707: /*---------*/
4708: /* post receives of j-array */
4709: for (i=0; i<nrecvs; i++){
4710: nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
4711: MPI_Irecv(b_othj+rstartsj[i],nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
4712: }
4714: /* pack the outgoing message j-array */
4715: k = 0;
4716: for (i=0; i<nsends; i++){
4717: nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
4718: bufJ = bufj+sstartsj[i];
4719: for (j=0; j<nrows; j++) {
4720: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
4721: for (ll=0; ll<sbs; ll++){
4722: MatGetRow_MPIAIJ(B,row+ll,&ncols,&cols,PETSC_NULL);
4723: for (l=0; l<ncols; l++){
4724: *bufJ++ = cols[l];
4725: }
4726: MatRestoreRow_MPIAIJ(B,row+ll,&ncols,&cols,PETSC_NULL);
4727: }
4728: }
4729: MPI_Isend(bufj+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_INT,sprocs[i],tag,comm,swaits+i);
4730: }
4732: /* recvs and sends of j-array are completed */
4733: i = nrecvs;
4734: while (i--) {
4735: MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
4736: }
4737: if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
4738: } else if (scall == MAT_REUSE_MATRIX){
4739: sstartsj = *startsj;
4740: rstartsj = sstartsj + nsends +1;
4741: bufa = *bufa_ptr;
4742: b_oth = (Mat_SeqAIJ*)(*B_oth)->data;
4743: b_otha = b_oth->a;
4744: } else {
4745: SETERRQ(PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not posses an object container");
4746: }
4748: /* a-array */
4749: /*---------*/
4750: /* post receives of a-array */
4751: for (i=0; i<nrecvs; i++){
4752: nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
4753: MPI_Irecv(b_otha+rstartsj[i],nrows,MPIU_SCALAR,rprocs[i],tag,comm,rwaits+i);
4754: }
4756: /* pack the outgoing message a-array */
4757: k = 0;
4758: for (i=0; i<nsends; i++){
4759: nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
4760: bufA = bufa+sstartsj[i];
4761: for (j=0; j<nrows; j++) {
4762: row = srow[k++] + B->rmap->range[rank]; /* global row idx */
4763: for (ll=0; ll<sbs; ll++){
4764: MatGetRow_MPIAIJ(B,row+ll,&ncols,PETSC_NULL,&vals);
4765: for (l=0; l<ncols; l++){
4766: *bufA++ = vals[l];
4767: }
4768: MatRestoreRow_MPIAIJ(B,row+ll,&ncols,PETSC_NULL,&vals);
4769: }
4770: }
4771: MPI_Isend(bufa+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_SCALAR,sprocs[i],tag,comm,swaits+i);
4772: }
4773: /* recvs and sends of a-array are completed */
4774: i = nrecvs;
4775: while (i--) {
4776: MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
4777: }
4778: if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
4779: PetscFree2(rwaits,swaits);
4781: if (scall == MAT_INITIAL_MATRIX){
4782: /* put together the new matrix */
4783: MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,aBn,B->cmap->N,b_othi,b_othj,b_otha,B_oth);
4785: /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
4786: /* Since these are PETSc arrays, change flags to free them as necessary. */
4787: b_oth = (Mat_SeqAIJ *)(*B_oth)->data;
4788: b_oth->free_a = PETSC_TRUE;
4789: b_oth->free_ij = PETSC_TRUE;
4790: b_oth->nonew = 0;
4792: PetscFree(bufj);
4793: if (!startsj || !bufa_ptr){
4794: PetscFree(sstartsj);
4795: PetscFree(bufa_ptr);
4796: } else {
4797: *startsj = sstartsj;
4798: *bufa_ptr = bufa;
4799: }
4800: }
4801: PetscLogEventEnd(MAT_GetBrowsOfAocols,A,B,0,0);
4802: return(0);
4803: }
4807: /*@C
4808: MatGetCommunicationStructs - Provides access to the communication structures used in matrix-vector multiplication.
4810: Not Collective
4812: Input Parameters:
4813: . A - The matrix in mpiaij format
4815: Output Parameter:
4816: + lvec - The local vector holding off-process values from the argument to a matrix-vector product
4817: . colmap - A map from global column index to local index into lvec
4818: - multScatter - A scatter from the argument of a matrix-vector product to lvec
4820: Level: developer
4822: @*/
4823: #if defined (PETSC_USE_CTABLE)
4824: PetscErrorCode MatGetCommunicationStructs(Mat A, Vec *lvec, PetscTable *colmap, VecScatter *multScatter)
4825: #else
4826: PetscErrorCode MatGetCommunicationStructs(Mat A, Vec *lvec, PetscInt *colmap[], VecScatter *multScatter)
4827: #endif
4828: {
4829: Mat_MPIAIJ *a;
4836: a = (Mat_MPIAIJ *) A->data;
4837: if (lvec) *lvec = a->lvec;
4838: if (colmap) *colmap = a->colmap;
4839: if (multScatter) *multScatter = a->Mvctx;
4840: return(0);
4841: }
4848: #include ../src/mat/impls/dense/mpi/mpidense.h
4852: /*
4853: Computes (B'*A')' since computing B*A directly is untenable
4855: n p p
4856: ( ) ( ) ( )
4857: m ( A ) * n ( B ) = m ( C )
4858: ( ) ( ) ( )
4860: */
4861: PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A,Mat B,Mat C)
4862: {
4863: PetscErrorCode ierr;
4864: Mat At,Bt,Ct;
4867: MatTranspose(A,MAT_INITIAL_MATRIX,&At);
4868: MatTranspose(B,MAT_INITIAL_MATRIX,&Bt);
4869: MatMatMult(Bt,At,MAT_INITIAL_MATRIX,1.0,&Ct);
4870: MatDestroy(At);
4871: MatDestroy(Bt);
4872: MatTranspose(Ct,MAT_REUSE_MATRIX,&C);
4873: MatDestroy(Ct);
4874: return(0);
4875: }
4879: PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
4880: {
4882: PetscInt m=A->rmap->n,n=B->cmap->n;
4883: Mat Cmat;
4886: if (A->cmap->n != B->rmap->n) SETERRQ2(PETSC_ERR_ARG_SIZ,"A->cmap->n %d != B->rmap->n %d\n",A->cmap->n,B->rmap->n);
4887: MatCreate(((PetscObject)A)->comm,&Cmat);
4888: MatSetSizes(Cmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4889: MatSetType(Cmat,MATMPIDENSE);
4890: MatMPIDenseSetPreallocation(Cmat,PETSC_NULL);
4891: MatAssemblyBegin(Cmat,MAT_FINAL_ASSEMBLY);
4892: MatAssemblyEnd(Cmat,MAT_FINAL_ASSEMBLY);
4893: *C = Cmat;
4894: return(0);
4895: }
4897: /* ----------------------------------------------------------------*/
4900: PetscErrorCode MatMatMult_MPIDense_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
4901: {
4905: if (scall == MAT_INITIAL_MATRIX){
4906: MatMatMultSymbolic_MPIDense_MPIAIJ(A,B,fill,C);
4907: }
4908: MatMatMultNumeric_MPIDense_MPIAIJ(A,B,*C);
4909: return(0);
4910: }
4913: #if defined(PETSC_HAVE_MUMPS)
4915: #endif
4916: #if defined(PETSC_HAVE_PASTIX)
4918: #endif
4919: #if defined(PETSC_HAVE_SUPERLU_DIST)
4921: #endif
4922: #if defined(PETSC_HAVE_SPOOLES)
4924: #endif
4927: /*MC
4928: MATMPIAIJ - MATMPIAIJ = "mpiaij" - A matrix type to be used for parallel sparse matrices.
4930: Options Database Keys:
4931: . -mat_type mpiaij - sets the matrix type to "mpiaij" during a call to MatSetFromOptions()
4933: Level: beginner
4935: .seealso: MatCreateMPIAIJ()
4936: M*/
4941: PetscErrorCode MatCreate_MPIAIJ(Mat B)
4942: {
4943: Mat_MPIAIJ *b;
4945: PetscMPIInt size;
4948: MPI_Comm_size(((PetscObject)B)->comm,&size);
4950: PetscNewLog(B,Mat_MPIAIJ,&b);
4951: B->data = (void*)b;
4952: PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));
4953: B->rmap->bs = 1;
4954: B->assembled = PETSC_FALSE;
4955: B->mapping = 0;
4957: B->insertmode = NOT_SET_VALUES;
4958: b->size = size;
4959: MPI_Comm_rank(((PetscObject)B)->comm,&b->rank);
4961: /* build cache for off array entries formed */
4962: MatStashCreate_Private(((PetscObject)B)->comm,1,&B->stash);
4963: b->donotstash = PETSC_FALSE;
4964: b->colmap = 0;
4965: b->garray = 0;
4966: b->roworiented = PETSC_TRUE;
4968: /* stuff used for matrix vector multiply */
4969: b->lvec = PETSC_NULL;
4970: b->Mvctx = PETSC_NULL;
4972: /* stuff for MatGetRow() */
4973: b->rowindices = 0;
4974: b->rowvalues = 0;
4975: b->getrowactive = PETSC_FALSE;
4977: #if defined(PETSC_HAVE_SPOOLES)
4978: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatGetFactor_mpiaij_spooles_C",
4979: "MatGetFactor_mpiaij_spooles",
4980: MatGetFactor_mpiaij_spooles);
4981: #endif
4982: #if defined(PETSC_HAVE_MUMPS)
4983: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatGetFactor_mpiaij_mumps_C",
4984: "MatGetFactor_mpiaij_mumps",
4985: MatGetFactor_mpiaij_mumps);
4986: #endif
4987: #if defined(PETSC_HAVE_PASTIX)
4988: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatGetFactor_mpiaij_pastix_C",
4989: "MatGetFactor_mpiaij_pastix",
4990: MatGetFactor_mpiaij_pastix);
4991: #endif
4992: #if defined(PETSC_HAVE_SUPERLU_DIST)
4993: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatGetFactor_mpiaij_superlu_dist_C",
4994: "MatGetFactor_mpiaij_superlu_dist",
4995: MatGetFactor_mpiaij_superlu_dist);
4996: #endif
4997: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatStoreValues_C",
4998: "MatStoreValues_MPIAIJ",
4999: MatStoreValues_MPIAIJ);
5000: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatRetrieveValues_C",
5001: "MatRetrieveValues_MPIAIJ",
5002: MatRetrieveValues_MPIAIJ);
5003: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatGetDiagonalBlock_C",
5004: "MatGetDiagonalBlock_MPIAIJ",
5005: MatGetDiagonalBlock_MPIAIJ);
5006: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatIsTranspose_C",
5007: "MatIsTranspose_MPIAIJ",
5008: MatIsTranspose_MPIAIJ);
5009: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatMPIAIJSetPreallocation_C",
5010: "MatMPIAIJSetPreallocation_MPIAIJ",
5011: MatMPIAIJSetPreallocation_MPIAIJ);
5012: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatMPIAIJSetPreallocationCSR_C",
5013: "MatMPIAIJSetPreallocationCSR_MPIAIJ",
5014: MatMPIAIJSetPreallocationCSR_MPIAIJ);
5015: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatDiagonalScaleLocal_C",
5016: "MatDiagonalScaleLocal_MPIAIJ",
5017: MatDiagonalScaleLocal_MPIAIJ);
5018: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatConvert_mpiaij_mpicsrperm_C",
5019: "MatConvert_MPIAIJ_MPICSRPERM",
5020: MatConvert_MPIAIJ_MPICSRPERM);
5021: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatConvert_mpiaij_mpicrl_C",
5022: "MatConvert_MPIAIJ_MPICRL",
5023: MatConvert_MPIAIJ_MPICRL);
5024: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatMatMult_mpidense_mpiaij_C",
5025: "MatMatMult_MPIDense_MPIAIJ",
5026: MatMatMult_MPIDense_MPIAIJ);
5027: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatMatMultSymbolic_mpidense_mpiaij_C",
5028: "MatMatMultSymbolic_MPIDense_MPIAIJ",
5029: MatMatMultSymbolic_MPIDense_MPIAIJ);
5030: PetscObjectComposeFunctionDynamic((PetscObject)B,"MatMatMultNumeric_mpidense_mpiaij_C",
5031: "MatMatMultNumeric_MPIDense_MPIAIJ",
5032: MatMatMultNumeric_MPIDense_MPIAIJ);
5033: PetscObjectChangeTypeName((PetscObject)B,MATMPIAIJ);
5034: return(0);
5035: }
5040: /*@
5041: MatCreateMPIAIJWithSplitArrays - creates a MPI AIJ matrix using arrays that contain the "diagonal"
5042: and "off-diagonal" part of the matrix in CSR format.
5044: Collective on MPI_Comm
5046: Input Parameters:
5047: + comm - MPI communicator
5048: . m - number of local rows (Cannot be PETSC_DECIDE)
5049: . n - This value should be the same as the local size used in creating the
5050: x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
5051: calculated if N is given) For square matrices n is almost always m.
5052: . M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
5053: . N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
5054: . i - row indices for "diagonal" portion of matrix
5055: . j - column indices
5056: . a - matrix values
5057: . oi - row indices for "off-diagonal" portion of matrix
5058: . oj - column indices
5059: - oa - matrix values
5061: Output Parameter:
5062: . mat - the matrix
5064: Level: advanced
5066: Notes:
5067: The i, j, and a arrays ARE NOT copied by this routine into the internal format used by PETSc.
5069: The i and j indices are 0 based
5070:
5071: See MatCreateMPIAIJ() for the definition of "diagonal" and "off-diagonal" portion of the matrix
5074: .keywords: matrix, aij, compressed row, sparse, parallel
5076: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
5077: MPIAIJ, MatCreateMPIAIJ(), MatCreateMPIAIJWithArrays()
5078: @*/
5079: PetscErrorCode MatCreateMPIAIJWithSplitArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscInt i[],PetscInt j[],PetscScalar a[],
5080: PetscInt oi[], PetscInt oj[],PetscScalar oa[],Mat *mat)
5081: {
5083: Mat_MPIAIJ *maij;
5086: if (m < 0) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
5087: if (i[0]) {
5088: SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
5089: }
5090: if (oi[0]) {
5091: SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"oi (row indices) must start with 0");
5092: }
5093: MatCreate(comm,mat);
5094: MatSetSizes(*mat,m,n,M,N);
5095: MatSetType(*mat,MATMPIAIJ);
5096: maij = (Mat_MPIAIJ*) (*mat)->data;
5097: maij->donotstash = PETSC_TRUE;
5098: (*mat)->preallocated = PETSC_TRUE;
5100: PetscMapSetBlockSize((*mat)->rmap,1);
5101: PetscMapSetBlockSize((*mat)->cmap,1);
5102: PetscMapSetUp((*mat)->rmap);
5103: PetscMapSetUp((*mat)->cmap);
5105: MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,m,n,i,j,a,&maij->A);
5106: MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,m,(*mat)->cmap->N,oi,oj,oa,&maij->B);
5108: MatAssemblyBegin(maij->A,MAT_FINAL_ASSEMBLY);
5109: MatAssemblyEnd(maij->A,MAT_FINAL_ASSEMBLY);
5110: MatAssemblyBegin(maij->B,MAT_FINAL_ASSEMBLY);
5111: MatAssemblyEnd(maij->B,MAT_FINAL_ASSEMBLY);
5113: MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
5114: MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
5115: return(0);
5116: }
5118: /*
5119: Special version for direct calls from Fortran
5120: */
5121: #if defined(PETSC_HAVE_FORTRAN_CAPS)
5122: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
5123: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
5124: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
5125: #endif
5127: /* Change these macros so can be used in void function */
5128: #undef CHKERRQ
5129: #define CHKERRQ(ierr) CHKERRABORT(((PetscObject)mat)->comm,ierr)
5130: #undef SETERRQ2
5131: #define SETERRQ2(ierr,b,c,d) CHKERRABORT(((PetscObject)mat)->comm,ierr)
5132: #undef SETERRQ
5133: #define SETERRQ(ierr,b) CHKERRABORT(((PetscObject)mat)->comm,ierr)
5138: void PETSC_STDCALL matsetvaluesmpiaij_(Mat *mmat,PetscInt *mm,const PetscInt im[],PetscInt *mn,const PetscInt in[],const PetscScalar v[],InsertMode *maddv,PetscErrorCode *_ierr)
5139: {
5140: Mat mat = *mmat;
5141: PetscInt m = *mm, n = *mn;
5142: InsertMode addv = *maddv;
5143: Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;
5144: PetscScalar value;
5145: PetscErrorCode ierr;
5147: MatPreallocated(mat);
5148: if (mat->insertmode == NOT_SET_VALUES) {
5149: mat->insertmode = addv;
5150: }
5151: #if defined(PETSC_USE_DEBUG)
5152: else if (mat->insertmode != addv) {
5153: SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
5154: }
5155: #endif
5156: {
5157: PetscInt i,j,rstart = mat->rmap->rstart,rend = mat->rmap->rend;
5158: PetscInt cstart = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
5159: PetscTruth roworiented = aij->roworiented;
5161: /* Some Variables required in the macro */
5162: Mat A = aij->A;
5163: Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
5164: PetscInt *aimax = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
5165: MatScalar *aa = a->a;
5166: PetscTruth ignorezeroentries = (((a->ignorezeroentries)&&(addv==ADD_VALUES))?PETSC_TRUE:PETSC_FALSE);
5167: Mat B = aij->B;
5168: Mat_SeqAIJ *b = (Mat_SeqAIJ*)B->data;
5169: PetscInt *bimax = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
5170: MatScalar *ba = b->a;
5172: PetscInt *rp1,*rp2,ii,nrow1,nrow2,_i,rmax1,rmax2,N,low1,high1,low2,high2,t,lastcol1,lastcol2;
5173: PetscInt nonew = a->nonew;
5174: MatScalar *ap1,*ap2;
5177: for (i=0; i<m; i++) {
5178: if (im[i] < 0) continue;
5179: #if defined(PETSC_USE_DEBUG)
5180: if (im[i] >= mat->rmap->N) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",im[i],mat->rmap->N-1);
5181: #endif
5182: if (im[i] >= rstart && im[i] < rend) {
5183: row = im[i] - rstart;
5184: lastcol1 = -1;
5185: rp1 = aj + ai[row];
5186: ap1 = aa + ai[row];
5187: rmax1 = aimax[row];
5188: nrow1 = ailen[row];
5189: low1 = 0;
5190: high1 = nrow1;
5191: lastcol2 = -1;
5192: rp2 = bj + bi[row];
5193: ap2 = ba + bi[row];
5194: rmax2 = bimax[row];
5195: nrow2 = bilen[row];
5196: low2 = 0;
5197: high2 = nrow2;
5199: for (j=0; j<n; j++) {
5200: if (roworiented) value = v[i*n+j]; else value = v[i+j*m];
5201: if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES)) continue;
5202: if (in[j] >= cstart && in[j] < cend){
5203: col = in[j] - cstart;
5204: MatSetValues_SeqAIJ_A_Private(row,col,value,addv);
5205: } else if (in[j] < 0) continue;
5206: #if defined(PETSC_USE_DEBUG)
5207: else if (in[j] >= mat->cmap->N) {SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[j],mat->cmap->N-1);}
5208: #endif
5209: else {
5210: if (mat->was_assembled) {
5211: if (!aij->colmap) {
5212: CreateColmap_MPIAIJ_Private(mat);
5213: }
5214: #if defined (PETSC_USE_CTABLE)
5215: PetscTableFind(aij->colmap,in[j]+1,&col);
5216: col--;
5217: #else
5218: col = aij->colmap[in[j]] - 1;
5219: #endif
5220: if (col < 0 && !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
5221: DisAssemble_MPIAIJ(mat);
5222: col = in[j];
5223: /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
5224: B = aij->B;
5225: b = (Mat_SeqAIJ*)B->data;
5226: bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j;
5227: rp2 = bj + bi[row];
5228: ap2 = ba + bi[row];
5229: rmax2 = bimax[row];
5230: nrow2 = bilen[row];
5231: low2 = 0;
5232: high2 = nrow2;
5233: bm = aij->B->rmap->n;
5234: ba = b->a;
5235: }
5236: } else col = in[j];
5237: MatSetValues_SeqAIJ_B_Private(row,col,value,addv);
5238: }
5239: }
5240: } else {
5241: if (!aij->donotstash) {
5242: if (roworiented) {
5243: if (ignorezeroentries && v[i*n] == 0.0) continue;
5244: MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n);
5245: } else {
5246: if (ignorezeroentries && v[i] == 0.0) continue;
5247: MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m);
5248: }
5249: }
5250: }
5251: }}
5252: PetscFunctionReturnVoid();
5253: }