Actual source code: aij.c

petsc-3.10.3 2018-12-18
Report Typos and Errors

  2: /*
  3:     Defines the basic matrix operations for the AIJ (compressed row)
  4:   matrix storage format.
  5: */


  8:  #include <../src/mat/impls/aij/seq/aij.h>
  9:  #include <petscblaslapack.h>
 10:  #include <petscbt.h>
 11:  #include <petsc/private/kernels/blocktranspose.h>

 13: PetscErrorCode MatSeqAIJSetTypeFromOptions(Mat A)
 14: {
 15:   PetscErrorCode       ierr;
 16:   PetscBool            flg;
 17:   char                 type[256];

 20:   PetscObjectOptionsBegin((PetscObject)A);
 21:   PetscOptionsFList("-mat_seqaij_type","Matrix SeqAIJ type","MatSeqAIJSetType",MatSeqAIJList,"seqaij",type,256,&flg);
 22:   if (flg) {
 23:     MatSeqAIJSetType(A,type);
 24:   }
 25:   PetscOptionsEnd();
 26:   return(0);
 27: }

 29: PetscErrorCode MatGetColumnNorms_SeqAIJ(Mat A,NormType type,PetscReal *norms)
 30: {
 32:   PetscInt       i,m,n;
 33:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)A->data;

 36:   MatGetSize(A,&m,&n);
 37:   PetscMemzero(norms,n*sizeof(PetscReal));
 38:   if (type == NORM_2) {
 39:     for (i=0; i<aij->i[m]; i++) {
 40:       norms[aij->j[i]] += PetscAbsScalar(aij->a[i]*aij->a[i]);
 41:     }
 42:   } else if (type == NORM_1) {
 43:     for (i=0; i<aij->i[m]; i++) {
 44:       norms[aij->j[i]] += PetscAbsScalar(aij->a[i]);
 45:     }
 46:   } else if (type == NORM_INFINITY) {
 47:     for (i=0; i<aij->i[m]; i++) {
 48:       norms[aij->j[i]] = PetscMax(PetscAbsScalar(aij->a[i]),norms[aij->j[i]]);
 49:     }
 50:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Unknown NormType");

 52:   if (type == NORM_2) {
 53:     for (i=0; i<n; i++) norms[i] = PetscSqrtReal(norms[i]);
 54:   }
 55:   return(0);
 56: }

 58: PetscErrorCode MatFindOffBlockDiagonalEntries_SeqAIJ(Mat A,IS *is)
 59: {
 60:   Mat_SeqAIJ      *a  = (Mat_SeqAIJ*)A->data;
 61:   PetscInt        i,m=A->rmap->n,cnt = 0, bs = A->rmap->bs;
 62:   const PetscInt  *jj = a->j,*ii = a->i;
 63:   PetscInt        *rows;
 64:   PetscErrorCode  ierr;

 67:   for (i=0; i<m; i++) {
 68:     if ((ii[i] != ii[i+1]) && ((jj[ii[i]] < bs*(i/bs)) || (jj[ii[i+1]-1] > bs*((i+bs)/bs)-1))) {
 69:       cnt++;
 70:     }
 71:   }
 72:   PetscMalloc1(cnt,&rows);
 73:   cnt  = 0;
 74:   for (i=0; i<m; i++) {
 75:     if ((ii[i] != ii[i+1]) && ((jj[ii[i]] < bs*(i/bs)) || (jj[ii[i+1]-1] > bs*((i+bs)/bs)-1))) {
 76:       rows[cnt] = i;
 77:       cnt++;
 78:     }
 79:   }
 80:   ISCreateGeneral(PETSC_COMM_SELF,cnt,rows,PETSC_OWN_POINTER,is);
 81:   return(0);
 82: }

 84: PetscErrorCode MatFindZeroDiagonals_SeqAIJ_Private(Mat A,PetscInt *nrows,PetscInt **zrows)
 85: {
 86:   Mat_SeqAIJ      *a  = (Mat_SeqAIJ*)A->data;
 87:   const MatScalar *aa = a->a;
 88:   PetscInt        i,m=A->rmap->n,cnt = 0;
 89:   const PetscInt  *ii = a->i,*jj = a->j,*diag;
 90:   PetscInt        *rows;
 91:   PetscErrorCode  ierr;

 94:   MatMarkDiagonal_SeqAIJ(A);
 95:   diag = a->diag;
 96:   for (i=0; i<m; i++) {
 97:     if ((diag[i] >= ii[i+1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) {
 98:       cnt++;
 99:     }
100:   }
101:   PetscMalloc1(cnt,&rows);
102:   cnt  = 0;
103:   for (i=0; i<m; i++) {
104:     if ((diag[i] >= ii[i+1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) {
105:       rows[cnt++] = i;
106:     }
107:   }
108:   *nrows = cnt;
109:   *zrows = rows;
110:   return(0);
111: }

113: PetscErrorCode MatFindZeroDiagonals_SeqAIJ(Mat A,IS *zrows)
114: {
115:   PetscInt       nrows,*rows;

119:   *zrows = NULL;
120:   MatFindZeroDiagonals_SeqAIJ_Private(A,&nrows,&rows);
121:   ISCreateGeneral(PetscObjectComm((PetscObject)A),nrows,rows,PETSC_OWN_POINTER,zrows);
122:   return(0);
123: }

125: PetscErrorCode MatFindNonzeroRows_SeqAIJ(Mat A,IS *keptrows)
126: {
127:   Mat_SeqAIJ      *a = (Mat_SeqAIJ*)A->data;
128:   const MatScalar *aa;
129:   PetscInt        m=A->rmap->n,cnt = 0;
130:   const PetscInt  *ii;
131:   PetscInt        n,i,j,*rows;
132:   PetscErrorCode  ierr;

135:   *keptrows = 0;
136:   ii        = a->i;
137:   for (i=0; i<m; i++) {
138:     n = ii[i+1] - ii[i];
139:     if (!n) {
140:       cnt++;
141:       goto ok1;
142:     }
143:     aa = a->a + ii[i];
144:     for (j=0; j<n; j++) {
145:       if (aa[j] != 0.0) goto ok1;
146:     }
147:     cnt++;
148: ok1:;
149:   }
150:   if (!cnt) return(0);
151:   PetscMalloc1(A->rmap->n-cnt,&rows);
152:   cnt  = 0;
153:   for (i=0; i<m; i++) {
154:     n = ii[i+1] - ii[i];
155:     if (!n) continue;
156:     aa = a->a + ii[i];
157:     for (j=0; j<n; j++) {
158:       if (aa[j] != 0.0) {
159:         rows[cnt++] = i;
160:         break;
161:       }
162:     }
163:   }
164:   ISCreateGeneral(PETSC_COMM_SELF,cnt,rows,PETSC_OWN_POINTER,keptrows);
165:   return(0);
166: }

168: PetscErrorCode  MatDiagonalSet_SeqAIJ(Mat Y,Vec D,InsertMode is)
169: {
170:   PetscErrorCode    ierr;
171:   Mat_SeqAIJ        *aij = (Mat_SeqAIJ*) Y->data;
172:   PetscInt          i,m = Y->rmap->n;
173:   const PetscInt    *diag;
174:   MatScalar         *aa = aij->a;
175:   const PetscScalar *v;
176:   PetscBool         missing;

179:   if (Y->assembled) {
180:     MatMissingDiagonal_SeqAIJ(Y,&missing,NULL);
181:     if (!missing) {
182:       diag = aij->diag;
183:       VecGetArrayRead(D,&v);
184:       if (is == INSERT_VALUES) {
185:         for (i=0; i<m; i++) {
186:           aa[diag[i]] = v[i];
187:         }
188:       } else {
189:         for (i=0; i<m; i++) {
190:           aa[diag[i]] += v[i];
191:         }
192:       }
193:       VecRestoreArrayRead(D,&v);
194:       return(0);
195:     }
196:     MatSeqAIJInvalidateDiagonal(Y);
197:   }
198:   MatDiagonalSet_Default(Y,D,is);
199:   return(0);
200: }

202: PetscErrorCode MatGetRowIJ_SeqAIJ(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *m,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
203: {
204:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
206:   PetscInt       i,ishift;

209:   *m = A->rmap->n;
210:   if (!ia) return(0);
211:   ishift = 0;
212:   if (symmetric && !A->structurally_symmetric) {
213:     MatToSymmetricIJ_SeqAIJ(A->rmap->n,a->i,a->j,PETSC_TRUE,ishift,oshift,(PetscInt**)ia,(PetscInt**)ja);
214:   } else if (oshift == 1) {
215:     PetscInt *tia;
216:     PetscInt nz = a->i[A->rmap->n];
217:     /* malloc space and  add 1 to i and j indices */
218:     PetscMalloc1(A->rmap->n+1,&tia);
219:     for (i=0; i<A->rmap->n+1; i++) tia[i] = a->i[i] + 1;
220:     *ia = tia;
221:     if (ja) {
222:       PetscInt *tja;
223:       PetscMalloc1(nz+1,&tja);
224:       for (i=0; i<nz; i++) tja[i] = a->j[i] + 1;
225:       *ja = tja;
226:     }
227:   } else {
228:     *ia = a->i;
229:     if (ja) *ja = a->j;
230:   }
231:   return(0);
232: }

234: PetscErrorCode MatRestoreRowIJ_SeqAIJ(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
235: {

239:   if (!ia) return(0);
240:   if ((symmetric && !A->structurally_symmetric) || oshift == 1) {
241:     PetscFree(*ia);
242:     if (ja) {PetscFree(*ja);}
243:   }
244:   return(0);
245: }

247: PetscErrorCode MatGetColumnIJ_SeqAIJ(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *nn,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
248: {
249:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
251:   PetscInt       i,*collengths,*cia,*cja,n = A->cmap->n,m = A->rmap->n;
252:   PetscInt       nz = a->i[m],row,*jj,mr,col;

255:   *nn = n;
256:   if (!ia) return(0);
257:   if (symmetric) {
258:     MatToSymmetricIJ_SeqAIJ(A->rmap->n,a->i,a->j,PETSC_TRUE,0,oshift,(PetscInt**)ia,(PetscInt**)ja);
259:   } else {
260:     PetscCalloc1(n+1,&collengths);
261:     PetscMalloc1(n+1,&cia);
262:     PetscMalloc1(nz+1,&cja);
263:     jj   = a->j;
264:     for (i=0; i<nz; i++) {
265:       collengths[jj[i]]++;
266:     }
267:     cia[0] = oshift;
268:     for (i=0; i<n; i++) {
269:       cia[i+1] = cia[i] + collengths[i];
270:     }
271:     PetscMemzero(collengths,n*sizeof(PetscInt));
272:     jj   = a->j;
273:     for (row=0; row<m; row++) {
274:       mr = a->i[row+1] - a->i[row];
275:       for (i=0; i<mr; i++) {
276:         col = *jj++;

278:         cja[cia[col] + collengths[col]++ - oshift] = row + oshift;
279:       }
280:     }
281:     PetscFree(collengths);
282:     *ia  = cia; *ja = cja;
283:   }
284:   return(0);
285: }

287: PetscErrorCode MatRestoreColumnIJ_SeqAIJ(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
288: {

292:   if (!ia) return(0);

294:   PetscFree(*ia);
295:   PetscFree(*ja);
296:   return(0);
297: }

299: /*
300:  MatGetColumnIJ_SeqAIJ_Color() and MatRestoreColumnIJ_SeqAIJ_Color() are customized from
301:  MatGetColumnIJ_SeqAIJ() and MatRestoreColumnIJ_SeqAIJ() by adding an output
302:  spidx[], index of a->a, to be used in MatTransposeColoringCreate_SeqAIJ() and MatFDColoringCreate_SeqXAIJ()
303: */
304: PetscErrorCode MatGetColumnIJ_SeqAIJ_Color(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *nn,const PetscInt *ia[],const PetscInt *ja[],PetscInt *spidx[],PetscBool  *done)
305: {
306:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
308:   PetscInt       i,*collengths,*cia,*cja,n = A->cmap->n,m = A->rmap->n;
309:   PetscInt       nz = a->i[m],row,*jj,mr,col;
310:   PetscInt       *cspidx;

313:   *nn = n;
314:   if (!ia) return(0);

316:   PetscCalloc1(n+1,&collengths);
317:   PetscMalloc1(n+1,&cia);
318:   PetscMalloc1(nz+1,&cja);
319:   PetscMalloc1(nz+1,&cspidx);
320:   jj   = a->j;
321:   for (i=0; i<nz; i++) {
322:     collengths[jj[i]]++;
323:   }
324:   cia[0] = oshift;
325:   for (i=0; i<n; i++) {
326:     cia[i+1] = cia[i] + collengths[i];
327:   }
328:   PetscMemzero(collengths,n*sizeof(PetscInt));
329:   jj   = a->j;
330:   for (row=0; row<m; row++) {
331:     mr = a->i[row+1] - a->i[row];
332:     for (i=0; i<mr; i++) {
333:       col = *jj++;
334:       cspidx[cia[col] + collengths[col] - oshift] = a->i[row] + i; /* index of a->j */
335:       cja[cia[col] + collengths[col]++ - oshift]  = row + oshift;
336:     }
337:   }
338:   PetscFree(collengths);
339:   *ia    = cia; *ja = cja;
340:   *spidx = cspidx;
341:   return(0);
342: }

344: PetscErrorCode MatRestoreColumnIJ_SeqAIJ_Color(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscInt *spidx[],PetscBool  *done)
345: {

349:   MatRestoreColumnIJ_SeqAIJ(A,oshift,symmetric,inodecompressed,n,ia,ja,done);
350:   PetscFree(*spidx);
351:   return(0);
352: }

354: PetscErrorCode MatSetValuesRow_SeqAIJ(Mat A,PetscInt row,const PetscScalar v[])
355: {
356:   Mat_SeqAIJ     *a  = (Mat_SeqAIJ*)A->data;
357:   PetscInt       *ai = a->i;

361:   PetscMemcpy(a->a+ai[row],v,(ai[row+1]-ai[row])*sizeof(PetscScalar));
362:   return(0);
363: }

365: /*
366:     MatSeqAIJSetValuesLocalFast - An optimized version of MatSetValuesLocal() for SeqAIJ matrices with several assumptions

368:       -   a single row of values is set with each call
369:       -   no row or column indices are negative or (in error) larger than the number of rows or columns
370:       -   the values are always added to the matrix, not set
371:       -   no new locations are introduced in the nonzero structure of the matrix

373:      This does NOT assume the global column indices are sorted

375: */

377:  #include <petsc/private/isimpl.h>
378: PetscErrorCode MatSeqAIJSetValuesLocalFast(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode is)
379: {
380:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
381:   PetscInt       low,high,t,row,nrow,i,col,l;
382:   const PetscInt *rp,*ai = a->i,*ailen = a->ilen,*aj = a->j;
383:   PetscInt       lastcol = -1;
384:   MatScalar      *ap,value,*aa = a->a;
385:   const PetscInt *ridx = A->rmap->mapping->indices,*cidx = A->cmap->mapping->indices;

387:   row = ridx[im[0]];
388:   rp   = aj + ai[row];
389:   ap = aa + ai[row];
390:   nrow = ailen[row];
391:   low  = 0;
392:   high = nrow;
393:   for (l=0; l<n; l++) { /* loop over added columns */
394:     col = cidx[in[l]];
395:     value = v[l];

397:     if (col <= lastcol) low = 0;
398:     else high = nrow;
399:     lastcol = col;
400:     while (high-low > 5) {
401:       t = (low+high)/2;
402:       if (rp[t] > col) high = t;
403:       else low = t;
404:     }
405:     for (i=low; i<high; i++) {
406:       if (rp[i] == col) {
407:         ap[i] += value;
408:         low = i + 1;
409:         break;
410:       }
411:     }
412:   }
413:   return 0;
414: }

416: PetscErrorCode MatSetValues_SeqAIJ(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode is)
417: {
418:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
419:   PetscInt       *rp,k,low,high,t,ii,row,nrow,i,col,l,rmax,N;
420:   PetscInt       *imax = a->imax,*ai = a->i,*ailen = a->ilen;
422:   PetscInt       *aj = a->j,nonew = a->nonew,lastcol = -1;
423:   MatScalar      *ap=NULL,value=0.0,*aa = a->a;
424:   PetscBool      ignorezeroentries = a->ignorezeroentries;
425:   PetscBool      roworiented       = a->roworiented;

428:   for (k=0; k<m; k++) { /* loop over added rows */
429:     row = im[k];
430:     if (row < 0) continue;
431: #if defined(PETSC_USE_DEBUG)
432:     if (row >= A->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",row,A->rmap->n-1);
433: #endif
434:     rp   = aj + ai[row];
435:     if (!A->structure_only) ap = aa + ai[row];
436:     rmax = imax[row]; nrow = ailen[row];
437:     low  = 0;
438:     high = nrow;
439:     for (l=0; l<n; l++) { /* loop over added columns */
440:       if (in[l] < 0) continue;
441: #if defined(PETSC_USE_DEBUG)
442:       if (in[l] >= A->cmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[l],A->cmap->n-1);
443: #endif
444:       col = in[l];
445:       if (!A->structure_only) {
446:         if (roworiented) {
447:           value = v[l + k*n];
448:         } else {
449:           value = v[k + l*m];
450:         }
451:       } else { /* A->structure_only */
452:         value = 1; /* avoid 'continue' below?  */
453:       }
454:       if ((value == 0.0 && ignorezeroentries) && (is == ADD_VALUES) && row != col) continue;

456:       if (col <= lastcol) low = 0;
457:       else high = nrow;
458:       lastcol = col;
459:       while (high-low > 5) {
460:         t = (low+high)/2;
461:         if (rp[t] > col) high = t;
462:         else low = t;
463:       }
464:       for (i=low; i<high; i++) {
465:         if (rp[i] > col) break;
466:         if (rp[i] == col) {
467:           if (!A->structure_only) {
468:             if (is == ADD_VALUES) ap[i] += value;
469:             else ap[i] = value;
470:           }
471:           low = i + 1;
472:           goto noinsert;
473:         }
474:       }
475:       if (value == 0.0 && ignorezeroentries && row != col) goto noinsert;
476:       if (nonew == 1) goto noinsert;
477:       if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero at (%D,%D) in the matrix",row,col);
478:       if (A->structure_only) {
479:         MatSeqXAIJReallocateAIJ_structure_only(A,A->rmap->n,1,nrow,row,col,rmax,ai,aj,rp,imax,nonew,MatScalar);
480:       } else {
481:         MatSeqXAIJReallocateAIJ(A,A->rmap->n,1,nrow,row,col,rmax,aa,ai,aj,rp,ap,imax,nonew,MatScalar);
482:       }
483:       N = nrow++ - 1; a->nz++; high++;
484:       /* shift up all the later entries in this row */
485:       for (ii=N; ii>=i; ii--) {
486:         rp[ii+1] = rp[ii];
487:         if (!A->structure_only) ap[ii+1] = ap[ii];
488:       }
489:       rp[i] = col;
490:       if (!A->structure_only) ap[i] = value;
491:       low   = i + 1;
492:       A->nonzerostate++;
493: noinsert:;
494:     }
495:     ailen[row] = nrow;
496:   }
497:   return(0);
498: }


501: PetscErrorCode MatGetValues_SeqAIJ(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],PetscScalar v[])
502: {
503:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
504:   PetscInt   *rp,k,low,high,t,row,nrow,i,col,l,*aj = a->j;
505:   PetscInt   *ai = a->i,*ailen = a->ilen;
506:   MatScalar  *ap,*aa = a->a;

509:   for (k=0; k<m; k++) { /* loop over rows */
510:     row = im[k];
511:     if (row < 0) {v += n; continue;} /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",row); */
512:     if (row >= A->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",row,A->rmap->n-1);
513:     rp   = aj + ai[row]; ap = aa + ai[row];
514:     nrow = ailen[row];
515:     for (l=0; l<n; l++) { /* loop over columns */
516:       if (in[l] < 0) {v++; continue;} /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",in[l]); */
517:       if (in[l] >= A->cmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[l],A->cmap->n-1);
518:       col  = in[l];
519:       high = nrow; low = 0; /* assume unsorted */
520:       while (high-low > 5) {
521:         t = (low+high)/2;
522:         if (rp[t] > col) high = t;
523:         else low = t;
524:       }
525:       for (i=low; i<high; i++) {
526:         if (rp[i] > col) break;
527:         if (rp[i] == col) {
528:           *v++ = ap[i];
529:           goto finished;
530:         }
531:       }
532:       *v++ = 0.0;
533: finished:;
534:     }
535:   }
536:   return(0);
537: }


540: PetscErrorCode MatView_SeqAIJ_Binary(Mat A,PetscViewer viewer)
541: {
542:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
544:   PetscInt       i,*col_lens;
545:   int            fd;
546:   FILE           *file;

549:   PetscViewerBinaryGetDescriptor(viewer,&fd);
550:   PetscMalloc1(4+A->rmap->n,&col_lens);

552:   col_lens[0] = MAT_FILE_CLASSID;
553:   col_lens[1] = A->rmap->n;
554:   col_lens[2] = A->cmap->n;
555:   col_lens[3] = a->nz;

557:   /* store lengths of each row and write (including header) to file */
558:   for (i=0; i<A->rmap->n; i++) {
559:     col_lens[4+i] = a->i[i+1] - a->i[i];
560:   }
561:   PetscBinaryWrite(fd,col_lens,4+A->rmap->n,PETSC_INT,PETSC_TRUE);
562:   PetscFree(col_lens);

564:   /* store column indices (zero start index) */
565:   PetscBinaryWrite(fd,a->j,a->nz,PETSC_INT,PETSC_FALSE);

567:   /* store nonzero values */
568:   PetscBinaryWrite(fd,a->a,a->nz,PETSC_SCALAR,PETSC_FALSE);

570:   PetscViewerBinaryGetInfoPointer(viewer,&file);
571:   if (file) {
572:     fprintf(file,"-matload_block_size %d\n",(int)PetscAbs(A->rmap->bs));
573:   }
574:   return(0);
575: }

577: static PetscErrorCode MatView_SeqAIJ_ASCII_structonly(Mat A,PetscViewer viewer)
578: {
580:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
581:   PetscInt       i,k,m=A->rmap->N;

584:   PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
585:   for (i=0; i<m; i++) {
586:     PetscViewerASCIIPrintf(viewer,"row %D:",i);
587:     for (k=a->i[i]; k<a->i[i+1]; k++) {
588:       PetscViewerASCIIPrintf(viewer," (%D) ",a->j[k]);
589:     }
590:     PetscViewerASCIIPrintf(viewer,"\n");
591:   }
592:   PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
593:   return(0);
594: }

596: extern PetscErrorCode MatSeqAIJFactorInfo_Matlab(Mat,PetscViewer);

598: PetscErrorCode MatView_SeqAIJ_ASCII(Mat A,PetscViewer viewer)
599: {
600:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
601:   PetscErrorCode    ierr;
602:   PetscInt          i,j,m = A->rmap->n;
603:   const char        *name;
604:   PetscViewerFormat format;

607:   if (A->structure_only) {
608:     MatView_SeqAIJ_ASCII_structonly(A,viewer);
609:     return(0);
610:   }

612:   PetscViewerGetFormat(viewer,&format);
613:   if (format == PETSC_VIEWER_ASCII_MATLAB) {
614:     PetscInt nofinalvalue = 0;
615:     if (m && ((a->i[m] == a->i[m-1]) || (a->j[a->nz-1] != A->cmap->n-1))) {
616:       /* Need a dummy value to ensure the dimension of the matrix. */
617:       nofinalvalue = 1;
618:     }
619:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
620:     PetscViewerASCIIPrintf(viewer,"%% Size = %D %D \n",m,A->cmap->n);
621:     PetscViewerASCIIPrintf(viewer,"%% Nonzeros = %D \n",a->nz);
622: #if defined(PETSC_USE_COMPLEX)
623:     PetscViewerASCIIPrintf(viewer,"zzz = zeros(%D,4);\n",a->nz+nofinalvalue);
624: #else
625:     PetscViewerASCIIPrintf(viewer,"zzz = zeros(%D,3);\n",a->nz+nofinalvalue);
626: #endif
627:     PetscViewerASCIIPrintf(viewer,"zzz = [\n");

629:     for (i=0; i<m; i++) {
630:       for (j=a->i[i]; j<a->i[i+1]; j++) {
631: #if defined(PETSC_USE_COMPLEX)
632:         PetscViewerASCIIPrintf(viewer,"%D %D  %18.16e %18.16e\n",i+1,a->j[j]+1,(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
633: #else
634:         PetscViewerASCIIPrintf(viewer,"%D %D  %18.16e\n",i+1,a->j[j]+1,(double)a->a[j]);
635: #endif
636:       }
637:     }
638:     if (nofinalvalue) {
639: #if defined(PETSC_USE_COMPLEX)
640:       PetscViewerASCIIPrintf(viewer,"%D %D  %18.16e %18.16e\n",m,A->cmap->n,0.,0.);
641: #else
642:       PetscViewerASCIIPrintf(viewer,"%D %D  %18.16e\n",m,A->cmap->n,0.0);
643: #endif
644:     }
645:     PetscObjectGetName((PetscObject)A,&name);
646:     PetscViewerASCIIPrintf(viewer,"];\n %s = spconvert(zzz);\n",name);
647:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
648:   } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO || format == PETSC_VIEWER_ASCII_INFO) {
649:     return(0);
650:   } else if (format == PETSC_VIEWER_ASCII_COMMON) {
651:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
652:     for (i=0; i<m; i++) {
653:       PetscViewerASCIIPrintf(viewer,"row %D:",i);
654:       for (j=a->i[i]; j<a->i[i+1]; j++) {
655: #if defined(PETSC_USE_COMPLEX)
656:         if (PetscImaginaryPart(a->a[j]) > 0.0 && PetscRealPart(a->a[j]) != 0.0) {
657:           PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
658:         } else if (PetscImaginaryPart(a->a[j]) < 0.0 && PetscRealPart(a->a[j]) != 0.0) {
659:           PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)-PetscImaginaryPart(a->a[j]));
660:         } else if (PetscRealPart(a->a[j]) != 0.0) {
661:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
662:         }
663: #else
664:         if (a->a[j] != 0.0) {PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);}
665: #endif
666:       }
667:       PetscViewerASCIIPrintf(viewer,"\n");
668:     }
669:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
670:   } else if (format == PETSC_VIEWER_ASCII_SYMMODU) {
671:     PetscInt nzd=0,fshift=1,*sptr;
672:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
673:     PetscMalloc1(m+1,&sptr);
674:     for (i=0; i<m; i++) {
675:       sptr[i] = nzd+1;
676:       for (j=a->i[i]; j<a->i[i+1]; j++) {
677:         if (a->j[j] >= i) {
678: #if defined(PETSC_USE_COMPLEX)
679:           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) nzd++;
680: #else
681:           if (a->a[j] != 0.0) nzd++;
682: #endif
683:         }
684:       }
685:     }
686:     sptr[m] = nzd+1;
687:     PetscViewerASCIIPrintf(viewer," %D %D\n\n",m,nzd);
688:     for (i=0; i<m+1; i+=6) {
689:       if (i+4<m) {
690:         PetscViewerASCIIPrintf(viewer," %D %D %D %D %D %D\n",sptr[i],sptr[i+1],sptr[i+2],sptr[i+3],sptr[i+4],sptr[i+5]);
691:       } else if (i+3<m) {
692:         PetscViewerASCIIPrintf(viewer," %D %D %D %D %D\n",sptr[i],sptr[i+1],sptr[i+2],sptr[i+3],sptr[i+4]);
693:       } else if (i+2<m) {
694:         PetscViewerASCIIPrintf(viewer," %D %D %D %D\n",sptr[i],sptr[i+1],sptr[i+2],sptr[i+3]);
695:       } else if (i+1<m) {
696:         PetscViewerASCIIPrintf(viewer," %D %D %D\n",sptr[i],sptr[i+1],sptr[i+2]);
697:       } else if (i<m) {
698:         PetscViewerASCIIPrintf(viewer," %D %D\n",sptr[i],sptr[i+1]);
699:       } else {
700:         PetscViewerASCIIPrintf(viewer," %D\n",sptr[i]);
701:       }
702:     }
703:     PetscViewerASCIIPrintf(viewer,"\n");
704:     PetscFree(sptr);
705:     for (i=0; i<m; i++) {
706:       for (j=a->i[i]; j<a->i[i+1]; j++) {
707:         if (a->j[j] >= i) {PetscViewerASCIIPrintf(viewer," %D ",a->j[j]+fshift);}
708:       }
709:       PetscViewerASCIIPrintf(viewer,"\n");
710:     }
711:     PetscViewerASCIIPrintf(viewer,"\n");
712:     for (i=0; i<m; i++) {
713:       for (j=a->i[i]; j<a->i[i+1]; j++) {
714:         if (a->j[j] >= i) {
715: #if defined(PETSC_USE_COMPLEX)
716:           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) {
717:             PetscViewerASCIIPrintf(viewer," %18.16e %18.16e ",(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
718:           }
719: #else
720:           if (a->a[j] != 0.0) {PetscViewerASCIIPrintf(viewer," %18.16e ",(double)a->a[j]);}
721: #endif
722:         }
723:       }
724:       PetscViewerASCIIPrintf(viewer,"\n");
725:     }
726:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
727:   } else if (format == PETSC_VIEWER_ASCII_DENSE) {
728:     PetscInt    cnt = 0,jcnt;
729:     PetscScalar value;
730: #if defined(PETSC_USE_COMPLEX)
731:     PetscBool   realonly = PETSC_TRUE;

733:     for (i=0; i<a->i[m]; i++) {
734:       if (PetscImaginaryPart(a->a[i]) != 0.0) {
735:         realonly = PETSC_FALSE;
736:         break;
737:       }
738:     }
739: #endif

741:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
742:     for (i=0; i<m; i++) {
743:       jcnt = 0;
744:       for (j=0; j<A->cmap->n; j++) {
745:         if (jcnt < a->i[i+1]-a->i[i] && j == a->j[cnt]) {
746:           value = a->a[cnt++];
747:           jcnt++;
748:         } else {
749:           value = 0.0;
750:         }
751: #if defined(PETSC_USE_COMPLEX)
752:         if (realonly) {
753:           PetscViewerASCIIPrintf(viewer," %7.5e ",(double)PetscRealPart(value));
754:         } else {
755:           PetscViewerASCIIPrintf(viewer," %7.5e+%7.5e i ",(double)PetscRealPart(value),(double)PetscImaginaryPart(value));
756:         }
757: #else
758:         PetscViewerASCIIPrintf(viewer," %7.5e ",(double)value);
759: #endif
760:       }
761:       PetscViewerASCIIPrintf(viewer,"\n");
762:     }
763:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
764:   } else if (format == PETSC_VIEWER_ASCII_MATRIXMARKET) {
765:     PetscInt fshift=1;
766:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
767: #if defined(PETSC_USE_COMPLEX)
768:     PetscViewerASCIIPrintf(viewer,"%%%%MatrixMarket matrix coordinate complex general\n");
769: #else
770:     PetscViewerASCIIPrintf(viewer,"%%%%MatrixMarket matrix coordinate real general\n");
771: #endif
772:     PetscViewerASCIIPrintf(viewer,"%D %D %D\n", m, A->cmap->n, a->nz);
773:     for (i=0; i<m; i++) {
774:       for (j=a->i[i]; j<a->i[i+1]; j++) {
775: #if defined(PETSC_USE_COMPLEX)
776:         PetscViewerASCIIPrintf(viewer,"%D %D %g %g\n", i+fshift,a->j[j]+fshift,(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
777: #else
778:         PetscViewerASCIIPrintf(viewer,"%D %D %g\n", i+fshift, a->j[j]+fshift, (double)a->a[j]);
779: #endif
780:       }
781:     }
782:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
783:   } else {
784:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
785:     if (A->factortype) {
786:       for (i=0; i<m; i++) {
787:         PetscViewerASCIIPrintf(viewer,"row %D:",i);
788:         /* L part */
789:         for (j=a->i[i]; j<a->i[i+1]; j++) {
790: #if defined(PETSC_USE_COMPLEX)
791:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
792:             PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
793:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
794:             PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)(-PetscImaginaryPart(a->a[j])));
795:           } else {
796:             PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
797:           }
798: #else
799:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);
800: #endif
801:         }
802:         /* diagonal */
803:         j = a->diag[i];
804: #if defined(PETSC_USE_COMPLEX)
805:         if (PetscImaginaryPart(a->a[j]) > 0.0) {
806:           PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(1.0/a->a[j]),(double)PetscImaginaryPart(1.0/a->a[j]));
807:         } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
808:           PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(1.0/a->a[j]),(double)(-PetscImaginaryPart(1.0/a->a[j])));
809:         } else {
810:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(1.0/a->a[j]));
811:         }
812: #else
813:         PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)(1.0/a->a[j]));
814: #endif

816:         /* U part */
817:         for (j=a->diag[i+1]+1; j<a->diag[i]; j++) {
818: #if defined(PETSC_USE_COMPLEX)
819:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
820:             PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
821:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
822:             PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)(-PetscImaginaryPart(a->a[j])));
823:           } else {
824:             PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
825:           }
826: #else
827:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);
828: #endif
829:         }
830:         PetscViewerASCIIPrintf(viewer,"\n");
831:       }
832:     } else {
833:       for (i=0; i<m; i++) {
834:         PetscViewerASCIIPrintf(viewer,"row %D:",i);
835:         for (j=a->i[i]; j<a->i[i+1]; j++) {
836: #if defined(PETSC_USE_COMPLEX)
837:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
838:             PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
839:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
840:             PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)-PetscImaginaryPart(a->a[j]));
841:           } else {
842:             PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
843:           }
844: #else
845:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);
846: #endif
847:         }
848:         PetscViewerASCIIPrintf(viewer,"\n");
849:       }
850:     }
851:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
852:   }
853:   PetscViewerFlush(viewer);
854:   return(0);
855: }

857:  #include <petscdraw.h>
858: PetscErrorCode MatView_SeqAIJ_Draw_Zoom(PetscDraw draw,void *Aa)
859: {
860:   Mat               A  = (Mat) Aa;
861:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
862:   PetscErrorCode    ierr;
863:   PetscInt          i,j,m = A->rmap->n;
864:   int               color;
865:   PetscReal         xl,yl,xr,yr,x_l,x_r,y_l,y_r;
866:   PetscViewer       viewer;
867:   PetscViewerFormat format;

870:   PetscObjectQuery((PetscObject)A,"Zoomviewer",(PetscObject*)&viewer);
871:   PetscViewerGetFormat(viewer,&format);
872:   PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);

874:   /* loop over matrix elements drawing boxes */

876:   if (format != PETSC_VIEWER_DRAW_CONTOUR) {
877:     PetscDrawCollectiveBegin(draw);
878:     /* Blue for negative, Cyan for zero and  Red for positive */
879:     color = PETSC_DRAW_BLUE;
880:     for (i=0; i<m; i++) {
881:       y_l = m - i - 1.0; y_r = y_l + 1.0;
882:       for (j=a->i[i]; j<a->i[i+1]; j++) {
883:         x_l = a->j[j]; x_r = x_l + 1.0;
884:         if (PetscRealPart(a->a[j]) >=  0.) continue;
885:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
886:       }
887:     }
888:     color = PETSC_DRAW_CYAN;
889:     for (i=0; i<m; i++) {
890:       y_l = m - i - 1.0; y_r = y_l + 1.0;
891:       for (j=a->i[i]; j<a->i[i+1]; j++) {
892:         x_l = a->j[j]; x_r = x_l + 1.0;
893:         if (a->a[j] !=  0.) continue;
894:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
895:       }
896:     }
897:     color = PETSC_DRAW_RED;
898:     for (i=0; i<m; i++) {
899:       y_l = m - i - 1.0; y_r = y_l + 1.0;
900:       for (j=a->i[i]; j<a->i[i+1]; j++) {
901:         x_l = a->j[j]; x_r = x_l + 1.0;
902:         if (PetscRealPart(a->a[j]) <=  0.) continue;
903:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
904:       }
905:     }
906:     PetscDrawCollectiveEnd(draw);
907:   } else {
908:     /* use contour shading to indicate magnitude of values */
909:     /* first determine max of all nonzero values */
910:     PetscReal minv = 0.0, maxv = 0.0;
911:     PetscInt  nz = a->nz, count = 0;
912:     PetscDraw popup;

914:     for (i=0; i<nz; i++) {
915:       if (PetscAbsScalar(a->a[i]) > maxv) maxv = PetscAbsScalar(a->a[i]);
916:     }
917:     if (minv >= maxv) maxv = minv + PETSC_SMALL;
918:     PetscDrawGetPopup(draw,&popup);
919:     PetscDrawScalePopup(popup,minv,maxv);

921:     PetscDrawCollectiveBegin(draw);
922:     for (i=0; i<m; i++) {
923:       y_l = m - i - 1.0;
924:       y_r = y_l + 1.0;
925:       for (j=a->i[i]; j<a->i[i+1]; j++) {
926:         x_l = a->j[j];
927:         x_r = x_l + 1.0;
928:         color = PetscDrawRealToColor(PetscAbsScalar(a->a[count]),minv,maxv);
929:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
930:         count++;
931:       }
932:     }
933:     PetscDrawCollectiveEnd(draw);
934:   }
935:   return(0);
936: }

938:  #include <petscdraw.h>
939: PetscErrorCode MatView_SeqAIJ_Draw(Mat A,PetscViewer viewer)
940: {
942:   PetscDraw      draw;
943:   PetscReal      xr,yr,xl,yl,h,w;
944:   PetscBool      isnull;

947:   PetscViewerDrawGetDraw(viewer,0,&draw);
948:   PetscDrawIsNull(draw,&isnull);
949:   if (isnull) return(0);

951:   xr   = A->cmap->n; yr  = A->rmap->n; h = yr/10.0; w = xr/10.0;
952:   xr  += w;          yr += h;         xl = -w;     yl = -h;
953:   PetscDrawSetCoordinates(draw,xl,yl,xr,yr);
954:   PetscObjectCompose((PetscObject)A,"Zoomviewer",(PetscObject)viewer);
955:   PetscDrawZoom(draw,MatView_SeqAIJ_Draw_Zoom,A);
956:   PetscObjectCompose((PetscObject)A,"Zoomviewer",NULL);
957:   PetscDrawSave(draw);
958:   return(0);
959: }

961: PetscErrorCode MatView_SeqAIJ(Mat A,PetscViewer viewer)
962: {
964:   PetscBool      iascii,isbinary,isdraw;

967:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
968:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
969:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
970:   if (iascii) {
971:     MatView_SeqAIJ_ASCII(A,viewer);
972:   } else if (isbinary) {
973:     MatView_SeqAIJ_Binary(A,viewer);
974:   } else if (isdraw) {
975:     MatView_SeqAIJ_Draw(A,viewer);
976:   }
977:   MatView_SeqAIJ_Inode(A,viewer);
978:   return(0);
979: }

981: PetscErrorCode MatAssemblyEnd_SeqAIJ(Mat A,MatAssemblyType mode)
982: {
983:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
985:   PetscInt       fshift = 0,i,j,*ai = a->i,*aj = a->j,*imax = a->imax;
986:   PetscInt       m      = A->rmap->n,*ip,N,*ailen = a->ilen,rmax = 0;
987:   MatScalar      *aa    = a->a,*ap;
988:   PetscReal      ratio  = 0.6;

991:   if (mode == MAT_FLUSH_ASSEMBLY) return(0);

993:   if (m) rmax = ailen[0]; /* determine row with most nonzeros */
994:   for (i=1; i<m; i++) {
995:     /* move each row back by the amount of empty slots (fshift) before it*/
996:     fshift += imax[i-1] - ailen[i-1];
997:     rmax    = PetscMax(rmax,ailen[i]);
998:     if (fshift) {
999:       ip = aj + ai[i];
1000:       ap = aa + ai[i];
1001:       N  = ailen[i];
1002:       for (j=0; j<N; j++) {
1003:         ip[j-fshift] = ip[j];
1004:         if (!A->structure_only) ap[j-fshift] = ap[j];
1005:       }
1006:     }
1007:     ai[i] = ai[i-1] + ailen[i-1];
1008:   }
1009:   if (m) {
1010:     fshift += imax[m-1] - ailen[m-1];
1011:     ai[m]   = ai[m-1] + ailen[m-1];
1012:   }

1014:   /* reset ilen and imax for each row */
1015:   a->nonzerorowcnt = 0;
1016:   if (A->structure_only) {
1017:     PetscFree2(a->imax,a->ilen);
1018:   } else { /* !A->structure_only */
1019:     for (i=0; i<m; i++) {
1020:       ailen[i] = imax[i] = ai[i+1] - ai[i];
1021:       a->nonzerorowcnt += ((ai[i+1] - ai[i]) > 0);
1022:     }
1023:   }
1024:   a->nz = ai[m];
1025:   if (fshift && a->nounused == -1) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB, "Unused space detected in matrix: %D X %D, %D unneeded", m, A->cmap->n, fshift);

1027:   MatMarkDiagonal_SeqAIJ(A);
1028:   PetscInfo4(A,"Matrix size: %D X %D; storage space: %D unneeded,%D used\n",m,A->cmap->n,fshift,a->nz);
1029:   PetscInfo1(A,"Number of mallocs during MatSetValues() is %D\n",a->reallocs);
1030:   PetscInfo1(A,"Maximum nonzeros in any row is %D\n",rmax);

1032:   A->info.mallocs    += a->reallocs;
1033:   a->reallocs         = 0;
1034:   A->info.nz_unneeded = (PetscReal)fshift;
1035:   a->rmax             = rmax;

1037:   if (!A->structure_only) {
1038:     MatCheckCompressedRow(A,a->nonzerorowcnt,&a->compressedrow,a->i,m,ratio);
1039:   }
1040:   MatAssemblyEnd_SeqAIJ_Inode(A,mode);
1041:   MatSeqAIJInvalidateDiagonal(A);
1042:   return(0);
1043: }

1045: PetscErrorCode MatRealPart_SeqAIJ(Mat A)
1046: {
1047:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1048:   PetscInt       i,nz = a->nz;
1049:   MatScalar      *aa = a->a;

1053:   for (i=0; i<nz; i++) aa[i] = PetscRealPart(aa[i]);
1054:   MatSeqAIJInvalidateDiagonal(A);
1055:   return(0);
1056: }

1058: PetscErrorCode MatImaginaryPart_SeqAIJ(Mat A)
1059: {
1060:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1061:   PetscInt       i,nz = a->nz;
1062:   MatScalar      *aa = a->a;

1066:   for (i=0; i<nz; i++) aa[i] = PetscImaginaryPart(aa[i]);
1067:   MatSeqAIJInvalidateDiagonal(A);
1068:   return(0);
1069: }

1071: PetscErrorCode MatZeroEntries_SeqAIJ(Mat A)
1072: {
1073:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

1077:   PetscMemzero(a->a,(a->i[A->rmap->n])*sizeof(PetscScalar));
1078:   MatSeqAIJInvalidateDiagonal(A);
1079:   return(0);
1080: }

1082: PetscErrorCode MatDestroy_SeqAIJ(Mat A)
1083: {
1084:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

1088: #if defined(PETSC_USE_LOG)
1089:   PetscLogObjectState((PetscObject)A,"Rows=%D, Cols=%D, NZ=%D",A->rmap->n,A->cmap->n,a->nz);
1090: #endif
1091:   MatSeqXAIJFreeAIJ(A,&a->a,&a->j,&a->i);
1092:   ISDestroy(&a->row);
1093:   ISDestroy(&a->col);
1094:   PetscFree(a->diag);
1095:   PetscFree(a->ibdiag);
1096:   PetscFree2(a->imax,a->ilen);
1097:   PetscFree(a->ipre);
1098:   PetscFree3(a->idiag,a->mdiag,a->ssor_work);
1099:   PetscFree(a->solve_work);
1100:   ISDestroy(&a->icol);
1101:   PetscFree(a->saved_values);
1102:   ISColoringDestroy(&a->coloring);
1103:   PetscFree2(a->compressedrow.i,a->compressedrow.rindex);
1104:   PetscFree(a->matmult_abdense);

1106:   MatDestroy_SeqAIJ_Inode(A);
1107:   PetscFree(A->data);

1109:   PetscObjectChangeTypeName((PetscObject)A,0);
1110:   PetscObjectComposeFunction((PetscObject)A,"MatSeqAIJSetColumnIndices_C",NULL);
1111:   PetscObjectComposeFunction((PetscObject)A,"MatStoreValues_C",NULL);
1112:   PetscObjectComposeFunction((PetscObject)A,"MatRetrieveValues_C",NULL);
1113:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqsbaij_C",NULL);
1114:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqbaij_C",NULL);
1115:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqaijperm_C",NULL);
1116: #if defined(PETSC_HAVE_ELEMENTAL)
1117:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_elemental_C",NULL);
1118: #endif
1119: #if defined(PETSC_HAVE_HYPRE)
1120:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_hypre_C",NULL);
1121:   PetscObjectComposeFunction((PetscObject)A,"MatMatMatMult_transpose_seqaij_seqaij_C",NULL);
1122: #endif
1123:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqdense_C",NULL);
1124:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqsell_C",NULL);
1125:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_is_C",NULL);
1126:   PetscObjectComposeFunction((PetscObject)A,"MatIsTranspose_C",NULL);
1127:   PetscObjectComposeFunction((PetscObject)A,"MatSeqAIJSetPreallocation_C",NULL);
1128:   PetscObjectComposeFunction((PetscObject)A,"MatResetPreallocation_C",NULL);
1129:   PetscObjectComposeFunction((PetscObject)A,"MatSeqAIJSetPreallocationCSR_C",NULL);
1130:   PetscObjectComposeFunction((PetscObject)A,"MatReorderForNonzeroDiagonal_C",NULL);
1131:   PetscObjectComposeFunction((PetscObject)A,"MatPtAP_is_seqaij_C",NULL);
1132:   return(0);
1133: }

1135: PetscErrorCode MatSetOption_SeqAIJ(Mat A,MatOption op,PetscBool flg)
1136: {
1137:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

1141:   switch (op) {
1142:   case MAT_ROW_ORIENTED:
1143:     a->roworiented = flg;
1144:     break;
1145:   case MAT_KEEP_NONZERO_PATTERN:
1146:     a->keepnonzeropattern = flg;
1147:     break;
1148:   case MAT_NEW_NONZERO_LOCATIONS:
1149:     a->nonew = (flg ? 0 : 1);
1150:     break;
1151:   case MAT_NEW_NONZERO_LOCATION_ERR:
1152:     a->nonew = (flg ? -1 : 0);
1153:     break;
1154:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1155:     a->nonew = (flg ? -2 : 0);
1156:     break;
1157:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1158:     a->nounused = (flg ? -1 : 0);
1159:     break;
1160:   case MAT_IGNORE_ZERO_ENTRIES:
1161:     a->ignorezeroentries = flg;
1162:     break;
1163:   case MAT_SPD:
1164:   case MAT_SYMMETRIC:
1165:   case MAT_STRUCTURALLY_SYMMETRIC:
1166:   case MAT_HERMITIAN:
1167:   case MAT_SYMMETRY_ETERNAL:
1168:   case MAT_STRUCTURE_ONLY:
1169:     /* These options are handled directly by MatSetOption() */
1170:     break;
1171:   case MAT_NEW_DIAGONALS:
1172:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1173:   case MAT_USE_HASH_TABLE:
1174:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1175:     break;
1176:   case MAT_USE_INODES:
1177:     /* Not an error because MatSetOption_SeqAIJ_Inode handles this one */
1178:     break;
1179:   case MAT_SUBMAT_SINGLEIS:
1180:     A->submat_singleis = flg;
1181:     break;
1182:   default:
1183:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unknown option %d",op);
1184:   }
1185:   MatSetOption_SeqAIJ_Inode(A,op,flg);
1186:   return(0);
1187: }

1189: PetscErrorCode MatGetDiagonal_SeqAIJ(Mat A,Vec v)
1190: {
1191:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1193:   PetscInt       i,j,n,*ai=a->i,*aj=a->j,nz;
1194:   PetscScalar    *aa=a->a,*x,zero=0.0;

1197:   VecGetLocalSize(v,&n);
1198:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");

1200:   if (A->factortype == MAT_FACTOR_ILU || A->factortype == MAT_FACTOR_LU) {
1201:     PetscInt *diag=a->diag;
1202:     VecGetArray(v,&x);
1203:     for (i=0; i<n; i++) x[i] = 1.0/aa[diag[i]];
1204:     VecRestoreArray(v,&x);
1205:     return(0);
1206:   }

1208:   VecSet(v,zero);
1209:   VecGetArray(v,&x);
1210:   for (i=0; i<n; i++) {
1211:     nz = ai[i+1] - ai[i];
1212:     if (!nz) x[i] = 0.0;
1213:     for (j=ai[i]; j<ai[i+1]; j++) {
1214:       if (aj[j] == i) {
1215:         x[i] = aa[j];
1216:         break;
1217:       }
1218:     }
1219:   }
1220:   VecRestoreArray(v,&x);
1221:   return(0);
1222: }

1224: #include <../src/mat/impls/aij/seq/ftn-kernels/fmult.h>
1225: PetscErrorCode MatMultTransposeAdd_SeqAIJ(Mat A,Vec xx,Vec zz,Vec yy)
1226: {
1227:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1228:   PetscScalar       *y;
1229:   const PetscScalar *x;
1230:   PetscErrorCode    ierr;
1231:   PetscInt          m = A->rmap->n;
1232: #if !defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1233:   const MatScalar   *v;
1234:   PetscScalar       alpha;
1235:   PetscInt          n,i,j;
1236:   const PetscInt    *idx,*ii,*ridx=NULL;
1237:   Mat_CompressedRow cprow    = a->compressedrow;
1238:   PetscBool         usecprow = cprow.use;
1239: #endif

1242:   if (zz != yy) {VecCopy(zz,yy);}
1243:   VecGetArrayRead(xx,&x);
1244:   VecGetArray(yy,&y);

1246: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1247:   fortranmulttransposeaddaij_(&m,x,a->i,a->j,a->a,y);
1248: #else
1249:   if (usecprow) {
1250:     m    = cprow.nrows;
1251:     ii   = cprow.i;
1252:     ridx = cprow.rindex;
1253:   } else {
1254:     ii = a->i;
1255:   }
1256:   for (i=0; i<m; i++) {
1257:     idx = a->j + ii[i];
1258:     v   = a->a + ii[i];
1259:     n   = ii[i+1] - ii[i];
1260:     if (usecprow) {
1261:       alpha = x[ridx[i]];
1262:     } else {
1263:       alpha = x[i];
1264:     }
1265:     for (j=0; j<n; j++) y[idx[j]] += alpha*v[j];
1266:   }
1267: #endif
1268:   PetscLogFlops(2.0*a->nz);
1269:   VecRestoreArrayRead(xx,&x);
1270:   VecRestoreArray(yy,&y);
1271:   return(0);
1272: }

1274: PetscErrorCode MatMultTranspose_SeqAIJ(Mat A,Vec xx,Vec yy)
1275: {

1279:   VecSet(yy,0.0);
1280:   MatMultTransposeAdd_SeqAIJ(A,xx,yy,yy);
1281:   return(0);
1282: }

1284: #include <../src/mat/impls/aij/seq/ftn-kernels/fmult.h>

1286: PetscErrorCode MatMult_SeqAIJ(Mat A,Vec xx,Vec yy)
1287: {
1288:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1289:   PetscScalar       *y;
1290:   const PetscScalar *x;
1291:   const MatScalar   *aa;
1292:   PetscErrorCode    ierr;
1293:   PetscInt          m=A->rmap->n;
1294:   const PetscInt    *aj,*ii,*ridx=NULL;
1295:   PetscInt          n,i;
1296:   PetscScalar       sum;
1297:   PetscBool         usecprow=a->compressedrow.use;

1299: #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1300: #pragma disjoint(*x,*y,*aa)
1301: #endif

1304:   VecGetArrayRead(xx,&x);
1305:   VecGetArray(yy,&y);
1306:   ii   = a->i;
1307:   if (usecprow) { /* use compressed row format */
1308:     PetscMemzero(y,m*sizeof(PetscScalar));
1309:     m    = a->compressedrow.nrows;
1310:     ii   = a->compressedrow.i;
1311:     ridx = a->compressedrow.rindex;
1312:     for (i=0; i<m; i++) {
1313:       n           = ii[i+1] - ii[i];
1314:       aj          = a->j + ii[i];
1315:       aa          = a->a + ii[i];
1316:       sum         = 0.0;
1317:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1318:       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1319:       y[*ridx++] = sum;
1320:     }
1321:   } else { /* do not use compressed row format */
1322: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTAIJ)
1323:     aj   = a->j;
1324:     aa   = a->a;
1325:     fortranmultaij_(&m,x,ii,aj,aa,y);
1326: #else
1327:     for (i=0; i<m; i++) {
1328:       n           = ii[i+1] - ii[i];
1329:       aj          = a->j + ii[i];
1330:       aa          = a->a + ii[i];
1331:       sum         = 0.0;
1332:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1333:       y[i] = sum;
1334:     }
1335: #endif
1336:   }
1337:   PetscLogFlops(2.0*a->nz - a->nonzerorowcnt);
1338:   VecRestoreArrayRead(xx,&x);
1339:   VecRestoreArray(yy,&y);
1340:   return(0);
1341: }

1343: PetscErrorCode MatMultMax_SeqAIJ(Mat A,Vec xx,Vec yy)
1344: {
1345:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1346:   PetscScalar       *y;
1347:   const PetscScalar *x;
1348:   const MatScalar   *aa;
1349:   PetscErrorCode    ierr;
1350:   PetscInt          m=A->rmap->n;
1351:   const PetscInt    *aj,*ii,*ridx=NULL;
1352:   PetscInt          n,i,nonzerorow=0;
1353:   PetscScalar       sum;
1354:   PetscBool         usecprow=a->compressedrow.use;

1356: #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1357: #pragma disjoint(*x,*y,*aa)
1358: #endif

1361:   VecGetArrayRead(xx,&x);
1362:   VecGetArray(yy,&y);
1363:   if (usecprow) { /* use compressed row format */
1364:     m    = a->compressedrow.nrows;
1365:     ii   = a->compressedrow.i;
1366:     ridx = a->compressedrow.rindex;
1367:     for (i=0; i<m; i++) {
1368:       n           = ii[i+1] - ii[i];
1369:       aj          = a->j + ii[i];
1370:       aa          = a->a + ii[i];
1371:       sum         = 0.0;
1372:       nonzerorow += (n>0);
1373:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1374:       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1375:       y[*ridx++] = sum;
1376:     }
1377:   } else { /* do not use compressed row format */
1378:     ii = a->i;
1379:     for (i=0; i<m; i++) {
1380:       n           = ii[i+1] - ii[i];
1381:       aj          = a->j + ii[i];
1382:       aa          = a->a + ii[i];
1383:       sum         = 0.0;
1384:       nonzerorow += (n>0);
1385:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1386:       y[i] = sum;
1387:     }
1388:   }
1389:   PetscLogFlops(2.0*a->nz - nonzerorow);
1390:   VecRestoreArrayRead(xx,&x);
1391:   VecRestoreArray(yy,&y);
1392:   return(0);
1393: }

1395: PetscErrorCode MatMultAddMax_SeqAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1396: {
1397:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1398:   PetscScalar       *y,*z;
1399:   const PetscScalar *x;
1400:   const MatScalar   *aa;
1401:   PetscErrorCode    ierr;
1402:   PetscInt          m = A->rmap->n,*aj,*ii;
1403:   PetscInt          n,i,*ridx=NULL;
1404:   PetscScalar       sum;
1405:   PetscBool         usecprow=a->compressedrow.use;

1408:   VecGetArrayRead(xx,&x);
1409:   VecGetArrayPair(yy,zz,&y,&z);
1410:   if (usecprow) { /* use compressed row format */
1411:     if (zz != yy) {
1412:       PetscMemcpy(z,y,m*sizeof(PetscScalar));
1413:     }
1414:     m    = a->compressedrow.nrows;
1415:     ii   = a->compressedrow.i;
1416:     ridx = a->compressedrow.rindex;
1417:     for (i=0; i<m; i++) {
1418:       n   = ii[i+1] - ii[i];
1419:       aj  = a->j + ii[i];
1420:       aa  = a->a + ii[i];
1421:       sum = y[*ridx];
1422:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1423:       z[*ridx++] = sum;
1424:     }
1425:   } else { /* do not use compressed row format */
1426:     ii = a->i;
1427:     for (i=0; i<m; i++) {
1428:       n   = ii[i+1] - ii[i];
1429:       aj  = a->j + ii[i];
1430:       aa  = a->a + ii[i];
1431:       sum = y[i];
1432:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1433:       z[i] = sum;
1434:     }
1435:   }
1436:   PetscLogFlops(2.0*a->nz);
1437:   VecRestoreArrayRead(xx,&x);
1438:   VecRestoreArrayPair(yy,zz,&y,&z);
1439:   return(0);
1440: }

1442: #include <../src/mat/impls/aij/seq/ftn-kernels/fmultadd.h>
1443: PetscErrorCode MatMultAdd_SeqAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1444: {
1445:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1446:   PetscScalar       *y,*z;
1447:   const PetscScalar *x;
1448:   const MatScalar   *aa;
1449:   PetscErrorCode    ierr;
1450:   const PetscInt    *aj,*ii,*ridx=NULL;
1451:   PetscInt          m = A->rmap->n,n,i;
1452:   PetscScalar       sum;
1453:   PetscBool         usecprow=a->compressedrow.use;

1456:   VecGetArrayRead(xx,&x);
1457:   VecGetArrayPair(yy,zz,&y,&z);
1458:   if (usecprow) { /* use compressed row format */
1459:     if (zz != yy) {
1460:       PetscMemcpy(z,y,m*sizeof(PetscScalar));
1461:     }
1462:     m    = a->compressedrow.nrows;
1463:     ii   = a->compressedrow.i;
1464:     ridx = a->compressedrow.rindex;
1465:     for (i=0; i<m; i++) {
1466:       n   = ii[i+1] - ii[i];
1467:       aj  = a->j + ii[i];
1468:       aa  = a->a + ii[i];
1469:       sum = y[*ridx];
1470:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1471:       z[*ridx++] = sum;
1472:     }
1473:   } else { /* do not use compressed row format */
1474:     ii = a->i;
1475: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTADDAIJ)
1476:     aj = a->j;
1477:     aa = a->a;
1478:     fortranmultaddaij_(&m,x,ii,aj,aa,y,z);
1479: #else
1480:     for (i=0; i<m; i++) {
1481:       n   = ii[i+1] - ii[i];
1482:       aj  = a->j + ii[i];
1483:       aa  = a->a + ii[i];
1484:       sum = y[i];
1485:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1486:       z[i] = sum;
1487:     }
1488: #endif
1489:   }
1490:   PetscLogFlops(2.0*a->nz);
1491:   VecRestoreArrayRead(xx,&x);
1492:   VecRestoreArrayPair(yy,zz,&y,&z);
1493:   return(0);
1494: }

1496: /*
1497:      Adds diagonal pointers to sparse matrix structure.
1498: */
1499: PetscErrorCode MatMarkDiagonal_SeqAIJ(Mat A)
1500: {
1501:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1503:   PetscInt       i,j,m = A->rmap->n;

1506:   if (!a->diag) {
1507:     PetscMalloc1(m,&a->diag);
1508:     PetscLogObjectMemory((PetscObject)A, m*sizeof(PetscInt));
1509:   }
1510:   for (i=0; i<A->rmap->n; i++) {
1511:     a->diag[i] = a->i[i+1];
1512:     for (j=a->i[i]; j<a->i[i+1]; j++) {
1513:       if (a->j[j] == i) {
1514:         a->diag[i] = j;
1515:         break;
1516:       }
1517:     }
1518:   }
1519:   return(0);
1520: }

1522: /*
1523:      Checks for missing diagonals
1524: */
1525: PetscErrorCode MatMissingDiagonal_SeqAIJ(Mat A,PetscBool  *missing,PetscInt *d)
1526: {
1527:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1528:   PetscInt       *diag,*ii = a->i,i;

1532:   *missing = PETSC_FALSE;
1533:   if (A->rmap->n > 0 && !ii) {
1534:     *missing = PETSC_TRUE;
1535:     if (d) *d = 0;
1536:     PetscInfo(A,"Matrix has no entries therefore is missing diagonal\n");
1537:   } else {
1538:     diag = a->diag;
1539:     for (i=0; i<A->rmap->n; i++) {
1540:       if (diag[i] >= ii[i+1]) {
1541:         *missing = PETSC_TRUE;
1542:         if (d) *d = i;
1543:         PetscInfo1(A,"Matrix is missing diagonal number %D\n",i);
1544:         break;
1545:       }
1546:     }
1547:   }
1548:   return(0);
1549: }

1551:  #include <petscblaslapack.h>
1552:  #include <petsc/private/kernels/blockinvert.h>

1554: /*
1555:     Note that values is allocated externally by the PC and then passed into this routine
1556: */
1557: PetscErrorCode MatInvertVariableBlockDiagonal_SeqAIJ(Mat A,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *diag)
1558: {
1559:   PetscErrorCode  ierr;
1560:   PetscInt        n = A->rmap->n, i, ncnt = 0, *indx,j,bsizemax = 0,*v_pivots;
1561:   PetscBool       allowzeropivot,zeropivotdetected=PETSC_FALSE;
1562:   const PetscReal shift = 0.0;
1563:   PetscInt        ipvt[5];
1564:   PetscScalar     work[25],*v_work;

1567:   allowzeropivot = PetscNot(A->erroriffailure);
1568:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
1569:   if (ncnt != n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Total blocksizes %D doesn't match number matrix rows %D",ncnt,n);
1570:   for (i=0; i<nblocks; i++) {
1571:     bsizemax = PetscMax(bsizemax,bsizes[i]);
1572:   }
1573:   PetscMalloc1(bsizemax,&indx);
1574:   if (bsizemax > 7) {
1575:     PetscMalloc2(bsizemax,&v_work,bsizemax,&v_pivots);
1576:   }
1577:   ncnt = 0;
1578:   for (i=0; i<nblocks; i++) {
1579:     for (j=0; j<bsizes[i]; j++) indx[j] = ncnt+j;
1580:     MatGetValues(A,bsizes[i],indx,bsizes[i],indx,diag);
1581:     switch (bsizes[i]) {
1582:     case 1:
1583:       *diag = 1.0/(*diag);
1584:       break;
1585:     case 2:
1586:       PetscKernel_A_gets_inverse_A_2(diag,shift,allowzeropivot,&zeropivotdetected);
1587:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1588:       PetscKernel_A_gets_transpose_A_2(diag);
1589:       break;
1590:     case 3:
1591:       PetscKernel_A_gets_inverse_A_3(diag,shift,allowzeropivot,&zeropivotdetected);
1592:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1593:       PetscKernel_A_gets_transpose_A_3(diag);
1594:       break;
1595:     case 4:
1596:       PetscKernel_A_gets_inverse_A_4(diag,shift,allowzeropivot,&zeropivotdetected);
1597:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1598:       PetscKernel_A_gets_transpose_A_4(diag);
1599:       break;
1600:     case 5:
1601:       PetscKernel_A_gets_inverse_A_5(diag,ipvt,work,shift,allowzeropivot,&zeropivotdetected);
1602:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1603:       PetscKernel_A_gets_transpose_A_5(diag);
1604:       break;
1605:     case 6:
1606:       PetscKernel_A_gets_inverse_A_6(diag,shift,allowzeropivot,&zeropivotdetected);
1607:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1608:       PetscKernel_A_gets_transpose_A_6(diag);
1609:       break;
1610:     case 7:
1611:       PetscKernel_A_gets_inverse_A_7(diag,shift,allowzeropivot,&zeropivotdetected);
1612:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1613:       PetscKernel_A_gets_transpose_A_7(diag);
1614:       break;
1615:     default:
1616:       PetscKernel_A_gets_inverse_A(bsizes[i],diag,v_pivots,v_work,allowzeropivot,&zeropivotdetected);
1617:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1618:       PetscKernel_A_gets_transpose_A_N(diag,bsizes[i]);
1619:     }
1620:     ncnt   += bsizes[i];
1621:     diag += bsizes[i]*bsizes[i];
1622:   }
1623:   if (bsizemax > 7) {
1624:     PetscFree2(v_work,v_pivots);
1625:   }
1626:   PetscFree(indx);
1627:   return(0);
1628: }

1630: /*
1631:    Negative shift indicates do not generate an error if there is a zero diagonal, just invert it anyways
1632: */
1633: PetscErrorCode  MatInvertDiagonal_SeqAIJ(Mat A,PetscScalar omega,PetscScalar fshift)
1634: {
1635:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*) A->data;
1637:   PetscInt       i,*diag,m = A->rmap->n;
1638:   MatScalar      *v = a->a;
1639:   PetscScalar    *idiag,*mdiag;

1642:   if (a->idiagvalid) return(0);
1643:   MatMarkDiagonal_SeqAIJ(A);
1644:   diag = a->diag;
1645:   if (!a->idiag) {
1646:     PetscMalloc3(m,&a->idiag,m,&a->mdiag,m,&a->ssor_work);
1647:     PetscLogObjectMemory((PetscObject)A, 3*m*sizeof(PetscScalar));
1648:     v    = a->a;
1649:   }
1650:   mdiag = a->mdiag;
1651:   idiag = a->idiag;

1653:   if (omega == 1.0 && PetscRealPart(fshift) <= 0.0) {
1654:     for (i=0; i<m; i++) {
1655:       mdiag[i] = v[diag[i]];
1656:       if (!PetscAbsScalar(mdiag[i])) { /* zero diagonal */
1657:         if (PetscRealPart(fshift)) {
1658:           PetscInfo1(A,"Zero diagonal on row %D\n",i);
1659:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1660:           A->factorerror_zeropivot_value = 0.0;
1661:           A->factorerror_zeropivot_row   = i;
1662:         } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Zero diagonal on row %D",i);
1663:       }
1664:       idiag[i] = 1.0/v[diag[i]];
1665:     }
1666:     PetscLogFlops(m);
1667:   } else {
1668:     for (i=0; i<m; i++) {
1669:       mdiag[i] = v[diag[i]];
1670:       idiag[i] = omega/(fshift + v[diag[i]]);
1671:     }
1672:     PetscLogFlops(2.0*m);
1673:   }
1674:   a->idiagvalid = PETSC_TRUE;
1675:   return(0);
1676: }

1678: #include <../src/mat/impls/aij/seq/ftn-kernels/frelax.h>
1679: PetscErrorCode MatSOR_SeqAIJ(Mat A,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
1680: {
1681:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1682:   PetscScalar       *x,d,sum,*t,scale;
1683:   const MatScalar   *v,*idiag=0,*mdiag;
1684:   const PetscScalar *b, *bs,*xb, *ts;
1685:   PetscErrorCode    ierr;
1686:   PetscInt          n,m = A->rmap->n,i;
1687:   const PetscInt    *idx,*diag;

1690:   its = its*lits;

1692:   if (fshift != a->fshift || omega != a->omega) a->idiagvalid = PETSC_FALSE; /* must recompute idiag[] */
1693:   if (!a->idiagvalid) {MatInvertDiagonal_SeqAIJ(A,omega,fshift);}
1694:   a->fshift = fshift;
1695:   a->omega  = omega;

1697:   diag  = a->diag;
1698:   t     = a->ssor_work;
1699:   idiag = a->idiag;
1700:   mdiag = a->mdiag;

1702:   VecGetArray(xx,&x);
1703:   VecGetArrayRead(bb,&b);
1704:   /* We count flops by assuming the upper triangular and lower triangular parts have the same number of nonzeros */
1705:   if (flag == SOR_APPLY_UPPER) {
1706:     /* apply (U + D/omega) to the vector */
1707:     bs = b;
1708:     for (i=0; i<m; i++) {
1709:       d   = fshift + mdiag[i];
1710:       n   = a->i[i+1] - diag[i] - 1;
1711:       idx = a->j + diag[i] + 1;
1712:       v   = a->a + diag[i] + 1;
1713:       sum = b[i]*d/omega;
1714:       PetscSparseDensePlusDot(sum,bs,v,idx,n);
1715:       x[i] = sum;
1716:     }
1717:     VecRestoreArray(xx,&x);
1718:     VecRestoreArrayRead(bb,&b);
1719:     PetscLogFlops(a->nz);
1720:     return(0);
1721:   }

1723:   if (flag == SOR_APPLY_LOWER) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"SOR_APPLY_LOWER is not implemented");
1724:   else if (flag & SOR_EISENSTAT) {
1725:     /* Let  A = L + U + D; where L is lower trianglar,
1726:     U is upper triangular, E = D/omega; This routine applies

1728:             (L + E)^{-1} A (U + E)^{-1}

1730:     to a vector efficiently using Eisenstat's trick.
1731:     */
1732:     scale = (2.0/omega) - 1.0;

1734:     /*  x = (E + U)^{-1} b */
1735:     for (i=m-1; i>=0; i--) {
1736:       n   = a->i[i+1] - diag[i] - 1;
1737:       idx = a->j + diag[i] + 1;
1738:       v   = a->a + diag[i] + 1;
1739:       sum = b[i];
1740:       PetscSparseDenseMinusDot(sum,x,v,idx,n);
1741:       x[i] = sum*idiag[i];
1742:     }

1744:     /*  t = b - (2*E - D)x */
1745:     v = a->a;
1746:     for (i=0; i<m; i++) t[i] = b[i] - scale*(v[*diag++])*x[i];

1748:     /*  t = (E + L)^{-1}t */
1749:     ts   = t;
1750:     diag = a->diag;
1751:     for (i=0; i<m; i++) {
1752:       n   = diag[i] - a->i[i];
1753:       idx = a->j + a->i[i];
1754:       v   = a->a + a->i[i];
1755:       sum = t[i];
1756:       PetscSparseDenseMinusDot(sum,ts,v,idx,n);
1757:       t[i] = sum*idiag[i];
1758:       /*  x = x + t */
1759:       x[i] += t[i];
1760:     }

1762:     PetscLogFlops(6.0*m-1 + 2.0*a->nz);
1763:     VecRestoreArray(xx,&x);
1764:     VecRestoreArrayRead(bb,&b);
1765:     return(0);
1766:   }
1767:   if (flag & SOR_ZERO_INITIAL_GUESS) {
1768:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1769:       for (i=0; i<m; i++) {
1770:         n   = diag[i] - a->i[i];
1771:         idx = a->j + a->i[i];
1772:         v   = a->a + a->i[i];
1773:         sum = b[i];
1774:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1775:         t[i] = sum;
1776:         x[i] = sum*idiag[i];
1777:       }
1778:       xb   = t;
1779:       PetscLogFlops(a->nz);
1780:     } else xb = b;
1781:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1782:       for (i=m-1; i>=0; i--) {
1783:         n   = a->i[i+1] - diag[i] - 1;
1784:         idx = a->j + diag[i] + 1;
1785:         v   = a->a + diag[i] + 1;
1786:         sum = xb[i];
1787:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1788:         if (xb == b) {
1789:           x[i] = sum*idiag[i];
1790:         } else {
1791:           x[i] = (1-omega)*x[i] + sum*idiag[i];  /* omega in idiag */
1792:         }
1793:       }
1794:       PetscLogFlops(a->nz); /* assumes 1/2 in upper */
1795:     }
1796:     its--;
1797:   }
1798:   while (its--) {
1799:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1800:       for (i=0; i<m; i++) {
1801:         /* lower */
1802:         n   = diag[i] - a->i[i];
1803:         idx = a->j + a->i[i];
1804:         v   = a->a + a->i[i];
1805:         sum = b[i];
1806:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1807:         t[i] = sum;             /* save application of the lower-triangular part */
1808:         /* upper */
1809:         n   = a->i[i+1] - diag[i] - 1;
1810:         idx = a->j + diag[i] + 1;
1811:         v   = a->a + diag[i] + 1;
1812:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1813:         x[i] = (1. - omega)*x[i] + sum*idiag[i]; /* omega in idiag */
1814:       }
1815:       xb   = t;
1816:       PetscLogFlops(2.0*a->nz);
1817:     } else xb = b;
1818:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1819:       for (i=m-1; i>=0; i--) {
1820:         sum = xb[i];
1821:         if (xb == b) {
1822:           /* whole matrix (no checkpointing available) */
1823:           n   = a->i[i+1] - a->i[i];
1824:           idx = a->j + a->i[i];
1825:           v   = a->a + a->i[i];
1826:           PetscSparseDenseMinusDot(sum,x,v,idx,n);
1827:           x[i] = (1. - omega)*x[i] + (sum + mdiag[i]*x[i])*idiag[i];
1828:         } else { /* lower-triangular part has been saved, so only apply upper-triangular */
1829:           n   = a->i[i+1] - diag[i] - 1;
1830:           idx = a->j + diag[i] + 1;
1831:           v   = a->a + diag[i] + 1;
1832:           PetscSparseDenseMinusDot(sum,x,v,idx,n);
1833:           x[i] = (1. - omega)*x[i] + sum*idiag[i];  /* omega in idiag */
1834:         }
1835:       }
1836:       if (xb == b) {
1837:         PetscLogFlops(2.0*a->nz);
1838:       } else {
1839:         PetscLogFlops(a->nz); /* assumes 1/2 in upper */
1840:       }
1841:     }
1842:   }
1843:   VecRestoreArray(xx,&x);
1844:   VecRestoreArrayRead(bb,&b);
1845:   return(0);
1846: }


1849: PetscErrorCode MatGetInfo_SeqAIJ(Mat A,MatInfoType flag,MatInfo *info)
1850: {
1851:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;

1854:   info->block_size   = 1.0;
1855:   info->nz_allocated = (double)a->maxnz;
1856:   info->nz_used      = (double)a->nz;
1857:   info->nz_unneeded  = (double)(a->maxnz - a->nz);
1858:   info->assemblies   = (double)A->num_ass;
1859:   info->mallocs      = (double)A->info.mallocs;
1860:   info->memory       = ((PetscObject)A)->mem;
1861:   if (A->factortype) {
1862:     info->fill_ratio_given  = A->info.fill_ratio_given;
1863:     info->fill_ratio_needed = A->info.fill_ratio_needed;
1864:     info->factor_mallocs    = A->info.factor_mallocs;
1865:   } else {
1866:     info->fill_ratio_given  = 0;
1867:     info->fill_ratio_needed = 0;
1868:     info->factor_mallocs    = 0;
1869:   }
1870:   return(0);
1871: }

1873: PetscErrorCode MatZeroRows_SeqAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1874: {
1875:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1876:   PetscInt          i,m = A->rmap->n - 1;
1877:   PetscErrorCode    ierr;
1878:   const PetscScalar *xx;
1879:   PetscScalar       *bb;
1880:   PetscInt          d = 0;

1883:   if (x && b) {
1884:     VecGetArrayRead(x,&xx);
1885:     VecGetArray(b,&bb);
1886:     for (i=0; i<N; i++) {
1887:       if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1888:       bb[rows[i]] = diag*xx[rows[i]];
1889:     }
1890:     VecRestoreArrayRead(x,&xx);
1891:     VecRestoreArray(b,&bb);
1892:   }

1894:   if (a->keepnonzeropattern) {
1895:     for (i=0; i<N; i++) {
1896:       if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1897:       PetscMemzero(&a->a[a->i[rows[i]]],a->ilen[rows[i]]*sizeof(PetscScalar));
1898:     }
1899:     if (diag != 0.0) {
1900:       for (i=0; i<N; i++) {
1901:         d = rows[i];
1902:         if (a->diag[d] >= a->i[d+1]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Matrix is missing diagonal entry in the zeroed row %D",d);
1903:       }
1904:       for (i=0; i<N; i++) {
1905:         a->a[a->diag[rows[i]]] = diag;
1906:       }
1907:     }
1908:   } else {
1909:     if (diag != 0.0) {
1910:       for (i=0; i<N; i++) {
1911:         if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1912:         if (a->ilen[rows[i]] > 0) {
1913:           a->ilen[rows[i]]    = 1;
1914:           a->a[a->i[rows[i]]] = diag;
1915:           a->j[a->i[rows[i]]] = rows[i];
1916:         } else { /* in case row was completely empty */
1917:           MatSetValues_SeqAIJ(A,1,&rows[i],1,&rows[i],&diag,INSERT_VALUES);
1918:         }
1919:       }
1920:     } else {
1921:       for (i=0; i<N; i++) {
1922:         if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1923:         a->ilen[rows[i]] = 0;
1924:       }
1925:     }
1926:     A->nonzerostate++;
1927:   }
1928:   (*A->ops->assemblyend)(A,MAT_FINAL_ASSEMBLY);
1929:   return(0);
1930: }

1932: PetscErrorCode MatZeroRowsColumns_SeqAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1933: {
1934:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1935:   PetscInt          i,j,m = A->rmap->n - 1,d = 0;
1936:   PetscErrorCode    ierr;
1937:   PetscBool         missing,*zeroed,vecs = PETSC_FALSE;
1938:   const PetscScalar *xx;
1939:   PetscScalar       *bb;

1942:   if (x && b) {
1943:     VecGetArrayRead(x,&xx);
1944:     VecGetArray(b,&bb);
1945:     vecs = PETSC_TRUE;
1946:   }
1947:   PetscCalloc1(A->rmap->n,&zeroed);
1948:   for (i=0; i<N; i++) {
1949:     if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1950:     PetscMemzero(&a->a[a->i[rows[i]]],a->ilen[rows[i]]*sizeof(PetscScalar));

1952:     zeroed[rows[i]] = PETSC_TRUE;
1953:   }
1954:   for (i=0; i<A->rmap->n; i++) {
1955:     if (!zeroed[i]) {
1956:       for (j=a->i[i]; j<a->i[i+1]; j++) {
1957:         if (zeroed[a->j[j]]) {
1958:           if (vecs) bb[i] -= a->a[j]*xx[a->j[j]];
1959:           a->a[j] = 0.0;
1960:         }
1961:       }
1962:     } else if (vecs) bb[i] = diag*xx[i];
1963:   }
1964:   if (x && b) {
1965:     VecRestoreArrayRead(x,&xx);
1966:     VecRestoreArray(b,&bb);
1967:   }
1968:   PetscFree(zeroed);
1969:   if (diag != 0.0) {
1970:     MatMissingDiagonal_SeqAIJ(A,&missing,&d);
1971:     if (missing) {
1972:       if (a->nonew) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Matrix is missing diagonal entry in row %D",d);
1973:       else {
1974:         for (i=0; i<N; i++) {
1975:           MatSetValues_SeqAIJ(A,1,&rows[i],1,&rows[i],&diag,INSERT_VALUES);
1976:         }
1977:       }
1978:     } else {
1979:       for (i=0; i<N; i++) {
1980:         a->a[a->diag[rows[i]]] = diag;
1981:       }
1982:     }
1983:   }
1984:   (*A->ops->assemblyend)(A,MAT_FINAL_ASSEMBLY);
1985:   return(0);
1986: }

1988: PetscErrorCode MatGetRow_SeqAIJ(Mat A,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1989: {
1990:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
1991:   PetscInt   *itmp;

1994:   if (row < 0 || row >= A->rmap->n) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row %D out of range",row);

1996:   *nz = a->i[row+1] - a->i[row];
1997:   if (v) *v = a->a + a->i[row];
1998:   if (idx) {
1999:     itmp = a->j + a->i[row];
2000:     if (*nz) *idx = itmp;
2001:     else *idx = 0;
2002:   }
2003:   return(0);
2004: }

2006: /* remove this function? */
2007: PetscErrorCode MatRestoreRow_SeqAIJ(Mat A,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
2008: {
2010:   return(0);
2011: }

2013: PetscErrorCode MatNorm_SeqAIJ(Mat A,NormType type,PetscReal *nrm)
2014: {
2015:   Mat_SeqAIJ     *a  = (Mat_SeqAIJ*)A->data;
2016:   MatScalar      *v  = a->a;
2017:   PetscReal      sum = 0.0;
2019:   PetscInt       i,j;

2022:   if (type == NORM_FROBENIUS) {
2023: #if defined(PETSC_USE_REAL___FP16)
2024:     PetscBLASInt one = 1,nz = a->nz;
2025:     *nrm = BLASnrm2_(&nz,v,&one);
2026: #else
2027:     for (i=0; i<a->nz; i++) {
2028:       sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
2029:     }
2030:     *nrm = PetscSqrtReal(sum);
2031: #endif
2032:     PetscLogFlops(2*a->nz);
2033:   } else if (type == NORM_1) {
2034:     PetscReal *tmp;
2035:     PetscInt  *jj = a->j;
2036:     PetscCalloc1(A->cmap->n+1,&tmp);
2037:     *nrm = 0.0;
2038:     for (j=0; j<a->nz; j++) {
2039:       tmp[*jj++] += PetscAbsScalar(*v);  v++;
2040:     }
2041:     for (j=0; j<A->cmap->n; j++) {
2042:       if (tmp[j] > *nrm) *nrm = tmp[j];
2043:     }
2044:     PetscFree(tmp);
2045:     PetscLogFlops(PetscMax(a->nz-1,0));
2046:   } else if (type == NORM_INFINITY) {
2047:     *nrm = 0.0;
2048:     for (j=0; j<A->rmap->n; j++) {
2049:       v   = a->a + a->i[j];
2050:       sum = 0.0;
2051:       for (i=0; i<a->i[j+1]-a->i[j]; i++) {
2052:         sum += PetscAbsScalar(*v); v++;
2053:       }
2054:       if (sum > *nrm) *nrm = sum;
2055:     }
2056:     PetscLogFlops(PetscMax(a->nz-1,0));
2057:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for two norm");
2058:   return(0);
2059: }

2061: /* Merged from MatGetSymbolicTranspose_SeqAIJ() - replace MatGetSymbolicTranspose_SeqAIJ()? */
2062: PetscErrorCode MatTransposeSymbolic_SeqAIJ(Mat A,Mat *B)
2063: {
2065:   PetscInt       i,j,anzj;
2066:   Mat_SeqAIJ     *a=(Mat_SeqAIJ*)A->data,*b;
2067:   PetscInt       an=A->cmap->N,am=A->rmap->N;
2068:   PetscInt       *ati,*atj,*atfill,*ai=a->i,*aj=a->j;

2071:   /* Allocate space for symbolic transpose info and work array */
2072:   PetscCalloc1(an+1,&ati);
2073:   PetscMalloc1(ai[am],&atj);
2074:   PetscMalloc1(an,&atfill);

2076:   /* Walk through aj and count ## of non-zeros in each row of A^T. */
2077:   /* Note: offset by 1 for fast conversion into csr format. */
2078:   for (i=0;i<ai[am];i++) ati[aj[i]+1] += 1;
2079:   /* Form ati for csr format of A^T. */
2080:   for (i=0;i<an;i++) ati[i+1] += ati[i];

2082:   /* Copy ati into atfill so we have locations of the next free space in atj */
2083:   PetscMemcpy(atfill,ati,an*sizeof(PetscInt));

2085:   /* Walk through A row-wise and mark nonzero entries of A^T. */
2086:   for (i=0;i<am;i++) {
2087:     anzj = ai[i+1] - ai[i];
2088:     for (j=0;j<anzj;j++) {
2089:       atj[atfill[*aj]] = i;
2090:       atfill[*aj++]   += 1;
2091:     }
2092:   }

2094:   /* Clean up temporary space and complete requests. */
2095:   PetscFree(atfill);
2096:   MatCreateSeqAIJWithArrays(PetscObjectComm((PetscObject)A),an,am,ati,atj,NULL,B);
2097:   MatSetBlockSizes(*B,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));

2099:   b          = (Mat_SeqAIJ*)((*B)->data);
2100:   b->free_a  = PETSC_FALSE;
2101:   b->free_ij = PETSC_TRUE;
2102:   b->nonew   = 0;
2103:   return(0);
2104: }

2106: PetscErrorCode MatTranspose_SeqAIJ(Mat A,MatReuse reuse,Mat *B)
2107: {
2108:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2109:   Mat            C;
2111:   PetscInt       i,*aj = a->j,*ai = a->i,m = A->rmap->n,len,*col;
2112:   MatScalar      *array = a->a;

2115:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
2116:     PetscCalloc1(1+A->cmap->n,&col);

2118:     for (i=0; i<ai[m]; i++) col[aj[i]] += 1;
2119:     MatCreate(PetscObjectComm((PetscObject)A),&C);
2120:     MatSetSizes(C,A->cmap->n,m,A->cmap->n,m);
2121:     MatSetBlockSizes(C,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
2122:     MatSetType(C,((PetscObject)A)->type_name);
2123:     MatSeqAIJSetPreallocation_SeqAIJ(C,0,col);
2124:     PetscFree(col);
2125:   } else {
2126:     C = *B;
2127:   }

2129:   for (i=0; i<m; i++) {
2130:     len    = ai[i+1]-ai[i];
2131:     MatSetValues_SeqAIJ(C,len,aj,1,&i,array,INSERT_VALUES);
2132:     array += len;
2133:     aj    += len;
2134:   }
2135:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2136:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

2138:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
2139:     *B = C;
2140:   } else {
2141:     MatHeaderMerge(A,&C);
2142:   }
2143:   return(0);
2144: }

2146: PetscErrorCode  MatIsTranspose_SeqAIJ(Mat A,Mat B,PetscReal tol,PetscBool  *f)
2147: {
2148:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*) A->data,*bij = (Mat_SeqAIJ*) B->data;
2149:   PetscInt       *adx,*bdx,*aii,*bii,*aptr,*bptr;
2150:   MatScalar      *va,*vb;
2152:   PetscInt       ma,na,mb,nb, i;

2155:   MatGetSize(A,&ma,&na);
2156:   MatGetSize(B,&mb,&nb);
2157:   if (ma!=nb || na!=mb) {
2158:     *f = PETSC_FALSE;
2159:     return(0);
2160:   }
2161:   aii  = aij->i; bii = bij->i;
2162:   adx  = aij->j; bdx = bij->j;
2163:   va   = aij->a; vb = bij->a;
2164:   PetscMalloc1(ma,&aptr);
2165:   PetscMalloc1(mb,&bptr);
2166:   for (i=0; i<ma; i++) aptr[i] = aii[i];
2167:   for (i=0; i<mb; i++) bptr[i] = bii[i];

2169:   *f = PETSC_TRUE;
2170:   for (i=0; i<ma; i++) {
2171:     while (aptr[i]<aii[i+1]) {
2172:       PetscInt    idc,idr;
2173:       PetscScalar vc,vr;
2174:       /* column/row index/value */
2175:       idc = adx[aptr[i]];
2176:       idr = bdx[bptr[idc]];
2177:       vc  = va[aptr[i]];
2178:       vr  = vb[bptr[idc]];
2179:       if (i!=idr || PetscAbsScalar(vc-vr) > tol) {
2180:         *f = PETSC_FALSE;
2181:         goto done;
2182:       } else {
2183:         aptr[i]++;
2184:         if (B || i!=idc) bptr[idc]++;
2185:       }
2186:     }
2187:   }
2188: done:
2189:   PetscFree(aptr);
2190:   PetscFree(bptr);
2191:   return(0);
2192: }

2194: PetscErrorCode  MatIsHermitianTranspose_SeqAIJ(Mat A,Mat B,PetscReal tol,PetscBool  *f)
2195: {
2196:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*) A->data,*bij = (Mat_SeqAIJ*) B->data;
2197:   PetscInt       *adx,*bdx,*aii,*bii,*aptr,*bptr;
2198:   MatScalar      *va,*vb;
2200:   PetscInt       ma,na,mb,nb, i;

2203:   MatGetSize(A,&ma,&na);
2204:   MatGetSize(B,&mb,&nb);
2205:   if (ma!=nb || na!=mb) {
2206:     *f = PETSC_FALSE;
2207:     return(0);
2208:   }
2209:   aii  = aij->i; bii = bij->i;
2210:   adx  = aij->j; bdx = bij->j;
2211:   va   = aij->a; vb = bij->a;
2212:   PetscMalloc1(ma,&aptr);
2213:   PetscMalloc1(mb,&bptr);
2214:   for (i=0; i<ma; i++) aptr[i] = aii[i];
2215:   for (i=0; i<mb; i++) bptr[i] = bii[i];

2217:   *f = PETSC_TRUE;
2218:   for (i=0; i<ma; i++) {
2219:     while (aptr[i]<aii[i+1]) {
2220:       PetscInt    idc,idr;
2221:       PetscScalar vc,vr;
2222:       /* column/row index/value */
2223:       idc = adx[aptr[i]];
2224:       idr = bdx[bptr[idc]];
2225:       vc  = va[aptr[i]];
2226:       vr  = vb[bptr[idc]];
2227:       if (i!=idr || PetscAbsScalar(vc-PetscConj(vr)) > tol) {
2228:         *f = PETSC_FALSE;
2229:         goto done;
2230:       } else {
2231:         aptr[i]++;
2232:         if (B || i!=idc) bptr[idc]++;
2233:       }
2234:     }
2235:   }
2236: done:
2237:   PetscFree(aptr);
2238:   PetscFree(bptr);
2239:   return(0);
2240: }

2242: PetscErrorCode MatIsSymmetric_SeqAIJ(Mat A,PetscReal tol,PetscBool  *f)
2243: {

2247:   MatIsTranspose_SeqAIJ(A,A,tol,f);
2248:   return(0);
2249: }

2251: PetscErrorCode MatIsHermitian_SeqAIJ(Mat A,PetscReal tol,PetscBool  *f)
2252: {

2256:   MatIsHermitianTranspose_SeqAIJ(A,A,tol,f);
2257:   return(0);
2258: }

2260: PetscErrorCode MatDiagonalScale_SeqAIJ(Mat A,Vec ll,Vec rr)
2261: {
2262:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
2263:   const PetscScalar *l,*r;
2264:   PetscScalar       x;
2265:   MatScalar         *v;
2266:   PetscErrorCode    ierr;
2267:   PetscInt          i,j,m = A->rmap->n,n = A->cmap->n,M,nz = a->nz;
2268:   const PetscInt    *jj;

2271:   if (ll) {
2272:     /* The local size is used so that VecMPI can be passed to this routine
2273:        by MatDiagonalScale_MPIAIJ */
2274:     VecGetLocalSize(ll,&m);
2275:     if (m != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Left scaling vector wrong length");
2276:     VecGetArrayRead(ll,&l);
2277:     v    = a->a;
2278:     for (i=0; i<m; i++) {
2279:       x = l[i];
2280:       M = a->i[i+1] - a->i[i];
2281:       for (j=0; j<M; j++) (*v++) *= x;
2282:     }
2283:     VecRestoreArrayRead(ll,&l);
2284:     PetscLogFlops(nz);
2285:   }
2286:   if (rr) {
2287:     VecGetLocalSize(rr,&n);
2288:     if (n != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Right scaling vector wrong length");
2289:     VecGetArrayRead(rr,&r);
2290:     v    = a->a; jj = a->j;
2291:     for (i=0; i<nz; i++) (*v++) *= r[*jj++];
2292:     VecRestoreArrayRead(rr,&r);
2293:     PetscLogFlops(nz);
2294:   }
2295:   MatSeqAIJInvalidateDiagonal(A);
2296:   return(0);
2297: }

2299: PetscErrorCode MatCreateSubMatrix_SeqAIJ(Mat A,IS isrow,IS iscol,PetscInt csize,MatReuse scall,Mat *B)
2300: {
2301:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*c;
2303:   PetscInt       *smap,i,k,kstart,kend,oldcols = A->cmap->n,*lens;
2304:   PetscInt       row,mat_i,*mat_j,tcol,first,step,*mat_ilen,sum,lensi;
2305:   const PetscInt *irow,*icol;
2306:   PetscInt       nrows,ncols;
2307:   PetscInt       *starts,*j_new,*i_new,*aj = a->j,*ai = a->i,ii,*ailen = a->ilen;
2308:   MatScalar      *a_new,*mat_a;
2309:   Mat            C;
2310:   PetscBool      stride;


2314:   ISGetIndices(isrow,&irow);
2315:   ISGetLocalSize(isrow,&nrows);
2316:   ISGetLocalSize(iscol,&ncols);

2318:   PetscObjectTypeCompare((PetscObject)iscol,ISSTRIDE,&stride);
2319:   if (stride) {
2320:     ISStrideGetInfo(iscol,&first,&step);
2321:   } else {
2322:     first = 0;
2323:     step  = 0;
2324:   }
2325:   if (stride && step == 1) {
2326:     /* special case of contiguous rows */
2327:     PetscMalloc2(nrows,&lens,nrows,&starts);
2328:     /* loop over new rows determining lens and starting points */
2329:     for (i=0; i<nrows; i++) {
2330:       kstart = ai[irow[i]];
2331:       kend   = kstart + ailen[irow[i]];
2332:       starts[i] = kstart;
2333:       for (k=kstart; k<kend; k++) {
2334:         if (aj[k] >= first) {
2335:           starts[i] = k;
2336:           break;
2337:         }
2338:       }
2339:       sum = 0;
2340:       while (k < kend) {
2341:         if (aj[k++] >= first+ncols) break;
2342:         sum++;
2343:       }
2344:       lens[i] = sum;
2345:     }
2346:     /* create submatrix */
2347:     if (scall == MAT_REUSE_MATRIX) {
2348:       PetscInt n_cols,n_rows;
2349:       MatGetSize(*B,&n_rows,&n_cols);
2350:       if (n_rows != nrows || n_cols != ncols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Reused submatrix wrong size");
2351:       MatZeroEntries(*B);
2352:       C    = *B;
2353:     } else {
2354:       PetscInt rbs,cbs;
2355:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2356:       MatSetSizes(C,nrows,ncols,PETSC_DETERMINE,PETSC_DETERMINE);
2357:       ISGetBlockSize(isrow,&rbs);
2358:       ISGetBlockSize(iscol,&cbs);
2359:       MatSetBlockSizes(C,rbs,cbs);
2360:       MatSetType(C,((PetscObject)A)->type_name);
2361:       MatSeqAIJSetPreallocation_SeqAIJ(C,0,lens);
2362:     }
2363:     c = (Mat_SeqAIJ*)C->data;

2365:     /* loop over rows inserting into submatrix */
2366:     a_new = c->a;
2367:     j_new = c->j;
2368:     i_new = c->i;

2370:     for (i=0; i<nrows; i++) {
2371:       ii    = starts[i];
2372:       lensi = lens[i];
2373:       for (k=0; k<lensi; k++) {
2374:         *j_new++ = aj[ii+k] - first;
2375:       }
2376:       PetscMemcpy(a_new,a->a + starts[i],lensi*sizeof(PetscScalar));
2377:       a_new     += lensi;
2378:       i_new[i+1] = i_new[i] + lensi;
2379:       c->ilen[i] = lensi;
2380:     }
2381:     PetscFree2(lens,starts);
2382:   } else {
2383:     ISGetIndices(iscol,&icol);
2384:     PetscCalloc1(oldcols,&smap);
2385:     PetscMalloc1(1+nrows,&lens);
2386:     for (i=0; i<ncols; i++) {
2387: #if defined(PETSC_USE_DEBUG)
2388:       if (icol[i] >= oldcols) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Requesting column beyond largest column icol[%D] %D <= A->cmap->n %D",i,icol[i],oldcols);
2389: #endif
2390:       smap[icol[i]] = i+1;
2391:     }

2393:     /* determine lens of each row */
2394:     for (i=0; i<nrows; i++) {
2395:       kstart  = ai[irow[i]];
2396:       kend    = kstart + a->ilen[irow[i]];
2397:       lens[i] = 0;
2398:       for (k=kstart; k<kend; k++) {
2399:         if (smap[aj[k]]) {
2400:           lens[i]++;
2401:         }
2402:       }
2403:     }
2404:     /* Create and fill new matrix */
2405:     if (scall == MAT_REUSE_MATRIX) {
2406:       PetscBool equal;

2408:       c = (Mat_SeqAIJ*)((*B)->data);
2409:       if ((*B)->rmap->n  != nrows || (*B)->cmap->n != ncols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. wrong size");
2410:       PetscMemcmp(c->ilen,lens,(*B)->rmap->n*sizeof(PetscInt),&equal);
2411:       if (!equal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. wrong no of nonzeros");
2412:       PetscMemzero(c->ilen,(*B)->rmap->n*sizeof(PetscInt));
2413:       C    = *B;
2414:     } else {
2415:       PetscInt rbs,cbs;
2416:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2417:       MatSetSizes(C,nrows,ncols,PETSC_DETERMINE,PETSC_DETERMINE);
2418:       ISGetBlockSize(isrow,&rbs);
2419:       ISGetBlockSize(iscol,&cbs);
2420:       MatSetBlockSizes(C,rbs,cbs);
2421:       MatSetType(C,((PetscObject)A)->type_name);
2422:       MatSeqAIJSetPreallocation_SeqAIJ(C,0,lens);
2423:     }
2424:     c = (Mat_SeqAIJ*)(C->data);
2425:     for (i=0; i<nrows; i++) {
2426:       row      = irow[i];
2427:       kstart   = ai[row];
2428:       kend     = kstart + a->ilen[row];
2429:       mat_i    = c->i[i];
2430:       mat_j    = c->j + mat_i;
2431:       mat_a    = c->a + mat_i;
2432:       mat_ilen = c->ilen + i;
2433:       for (k=kstart; k<kend; k++) {
2434:         if ((tcol=smap[a->j[k]])) {
2435:           *mat_j++ = tcol - 1;
2436:           *mat_a++ = a->a[k];
2437:           (*mat_ilen)++;

2439:         }
2440:       }
2441:     }
2442:     /* Free work space */
2443:     ISRestoreIndices(iscol,&icol);
2444:     PetscFree(smap);
2445:     PetscFree(lens);
2446:     /* sort */
2447:     for (i = 0; i < nrows; i++) {
2448:       PetscInt ilen;

2450:       mat_i = c->i[i];
2451:       mat_j = c->j + mat_i;
2452:       mat_a = c->a + mat_i;
2453:       ilen  = c->ilen[i];
2454:       PetscSortIntWithScalarArray(ilen,mat_j,mat_a);
2455:     }
2456:   }
2457:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2458:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

2460:   ISRestoreIndices(isrow,&irow);
2461:   *B   = C;
2462:   return(0);
2463: }

2465: PetscErrorCode  MatGetMultiProcBlock_SeqAIJ(Mat mat,MPI_Comm subComm,MatReuse scall,Mat *subMat)
2466: {
2468:   Mat            B;

2471:   if (scall == MAT_INITIAL_MATRIX) {
2472:     MatCreate(subComm,&B);
2473:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->n,mat->cmap->n);
2474:     MatSetBlockSizesFromMats(B,mat,mat);
2475:     MatSetType(B,MATSEQAIJ);
2476:     MatDuplicateNoCreate_SeqAIJ(B,mat,MAT_COPY_VALUES,PETSC_TRUE);
2477:     *subMat = B;
2478:   } else {
2479:     MatCopy_SeqAIJ(mat,*subMat,SAME_NONZERO_PATTERN);
2480:   }
2481:   return(0);
2482: }

2484: PetscErrorCode MatILUFactor_SeqAIJ(Mat inA,IS row,IS col,const MatFactorInfo *info)
2485: {
2486:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)inA->data;
2488:   Mat            outA;
2489:   PetscBool      row_identity,col_identity;

2492:   if (info->levels != 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only levels=0 supported for in-place ilu");

2494:   ISIdentity(row,&row_identity);
2495:   ISIdentity(col,&col_identity);

2497:   outA             = inA;
2498:   outA->factortype = MAT_FACTOR_LU;
2499:   PetscFree(inA->solvertype);
2500:   PetscStrallocpy(MATSOLVERPETSC,&inA->solvertype);

2502:   PetscObjectReference((PetscObject)row);
2503:   ISDestroy(&a->row);

2505:   a->row = row;

2507:   PetscObjectReference((PetscObject)col);
2508:   ISDestroy(&a->col);

2510:   a->col = col;

2512:   /* Create the inverse permutation so that it can be used in MatLUFactorNumeric() */
2513:   ISDestroy(&a->icol);
2514:   ISInvertPermutation(col,PETSC_DECIDE,&a->icol);
2515:   PetscLogObjectParent((PetscObject)inA,(PetscObject)a->icol);

2517:   if (!a->solve_work) { /* this matrix may have been factored before */
2518:     PetscMalloc1(inA->rmap->n+1,&a->solve_work);
2519:     PetscLogObjectMemory((PetscObject)inA, (inA->rmap->n+1)*sizeof(PetscScalar));
2520:   }

2522:   MatMarkDiagonal_SeqAIJ(inA);
2523:   if (row_identity && col_identity) {
2524:     MatLUFactorNumeric_SeqAIJ_inplace(outA,inA,info);
2525:   } else {
2526:     MatLUFactorNumeric_SeqAIJ_InplaceWithPerm(outA,inA,info);
2527:   }
2528:   return(0);
2529: }

2531: PetscErrorCode MatScale_SeqAIJ(Mat inA,PetscScalar alpha)
2532: {
2533:   Mat_SeqAIJ     *a     = (Mat_SeqAIJ*)inA->data;
2534:   PetscScalar    oalpha = alpha;
2536:   PetscBLASInt   one = 1,bnz;

2539:   PetscBLASIntCast(a->nz,&bnz);
2540:   PetscStackCallBLAS("BLASscal",BLASscal_(&bnz,&oalpha,a->a,&one));
2541:   PetscLogFlops(a->nz);
2542:   MatSeqAIJInvalidateDiagonal(inA);
2543:   return(0);
2544: }

2546: PetscErrorCode MatDestroySubMatrix_Private(Mat_SubSppt *submatj)
2547: {
2549:   PetscInt       i;

2552:   if (!submatj->id) { /* delete data that are linked only to submats[id=0] */
2553:     PetscFree4(submatj->sbuf1,submatj->ptr,submatj->tmp,submatj->ctr);

2555:     for (i=0; i<submatj->nrqr; ++i) {
2556:       PetscFree(submatj->sbuf2[i]);
2557:     }
2558:     PetscFree3(submatj->sbuf2,submatj->req_size,submatj->req_source1);

2560:     if (submatj->rbuf1) {
2561:       PetscFree(submatj->rbuf1[0]);
2562:       PetscFree(submatj->rbuf1);
2563:     }

2565:     for (i=0; i<submatj->nrqs; ++i) {
2566:       PetscFree(submatj->rbuf3[i]);
2567:     }
2568:     PetscFree3(submatj->req_source2,submatj->rbuf2,submatj->rbuf3);
2569:     PetscFree(submatj->pa);
2570:   }

2572: #if defined(PETSC_USE_CTABLE)
2573:   PetscTableDestroy((PetscTable*)&submatj->rmap);
2574:   if (submatj->cmap_loc) {PetscFree(submatj->cmap_loc);}
2575:   PetscFree(submatj->rmap_loc);
2576: #else
2577:   PetscFree(submatj->rmap);
2578: #endif

2580:   if (!submatj->allcolumns) {
2581: #if defined(PETSC_USE_CTABLE)
2582:     PetscTableDestroy((PetscTable*)&submatj->cmap);
2583: #else
2584:     PetscFree(submatj->cmap);
2585: #endif
2586:   }
2587:   PetscFree(submatj->row2proc);

2589:   PetscFree(submatj);
2590:   return(0);
2591: }

2593: PetscErrorCode MatDestroySubMatrix_SeqAIJ(Mat C)
2594: {
2596:   Mat_SeqAIJ     *c = (Mat_SeqAIJ*)C->data;
2597:   Mat_SubSppt    *submatj = c->submatis1;

2600:   (*submatj->destroy)(C);
2601:   MatDestroySubMatrix_Private(submatj);
2602:   return(0);
2603: }

2605: PetscErrorCode MatDestroySubMatrices_SeqAIJ(PetscInt n,Mat *mat[])
2606: {
2608:   PetscInt       i;
2609:   Mat            C;
2610:   Mat_SeqAIJ     *c;
2611:   Mat_SubSppt    *submatj;

2614:   for (i=0; i<n; i++) {
2615:     C       = (*mat)[i];
2616:     c       = (Mat_SeqAIJ*)C->data;
2617:     submatj = c->submatis1;
2618:     if (submatj) {
2619:       if (--((PetscObject)C)->refct <= 0) {
2620:         (*submatj->destroy)(C);
2621:         MatDestroySubMatrix_Private(submatj);
2622:         PetscFree(C->defaultvectype);
2623:         PetscLayoutDestroy(&C->rmap);
2624:         PetscLayoutDestroy(&C->cmap);
2625:         PetscHeaderDestroy(&C);
2626:       }
2627:     } else {
2628:       MatDestroy(&C);
2629:     }
2630:   }

2632:   PetscFree(*mat);
2633:   return(0);
2634: }

2636: PetscErrorCode MatCreateSubMatrices_SeqAIJ(Mat A,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *B[])
2637: {
2639:   PetscInt       i;

2642:   if (scall == MAT_INITIAL_MATRIX) {
2643:     PetscCalloc1(n+1,B);
2644:   }

2646:   for (i=0; i<n; i++) {
2647:     MatCreateSubMatrix_SeqAIJ(A,irow[i],icol[i],PETSC_DECIDE,scall,&(*B)[i]);
2648:   }
2649:   return(0);
2650: }

2652: PetscErrorCode MatIncreaseOverlap_SeqAIJ(Mat A,PetscInt is_max,IS is[],PetscInt ov)
2653: {
2654:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2656:   PetscInt       row,i,j,k,l,m,n,*nidx,isz,val;
2657:   const PetscInt *idx;
2658:   PetscInt       start,end,*ai,*aj;
2659:   PetscBT        table;

2662:   m  = A->rmap->n;
2663:   ai = a->i;
2664:   aj = a->j;

2666:   if (ov < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"illegal negative overlap value used");

2668:   PetscMalloc1(m+1,&nidx);
2669:   PetscBTCreate(m,&table);

2671:   for (i=0; i<is_max; i++) {
2672:     /* Initialize the two local arrays */
2673:     isz  = 0;
2674:     PetscBTMemzero(m,table);

2676:     /* Extract the indices, assume there can be duplicate entries */
2677:     ISGetIndices(is[i],&idx);
2678:     ISGetLocalSize(is[i],&n);

2680:     /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2681:     for (j=0; j<n; ++j) {
2682:       if (!PetscBTLookupSet(table,idx[j])) nidx[isz++] = idx[j];
2683:     }
2684:     ISRestoreIndices(is[i],&idx);
2685:     ISDestroy(&is[i]);

2687:     k = 0;
2688:     for (j=0; j<ov; j++) { /* for each overlap */
2689:       n = isz;
2690:       for (; k<n; k++) { /* do only those rows in nidx[k], which are not done yet */
2691:         row   = nidx[k];
2692:         start = ai[row];
2693:         end   = ai[row+1];
2694:         for (l = start; l<end; l++) {
2695:           val = aj[l];
2696:           if (!PetscBTLookupSet(table,val)) nidx[isz++] = val;
2697:         }
2698:       }
2699:     }
2700:     ISCreateGeneral(PETSC_COMM_SELF,isz,nidx,PETSC_COPY_VALUES,(is+i));
2701:   }
2702:   PetscBTDestroy(&table);
2703:   PetscFree(nidx);
2704:   return(0);
2705: }

2707: /* -------------------------------------------------------------- */
2708: PetscErrorCode MatPermute_SeqAIJ(Mat A,IS rowp,IS colp,Mat *B)
2709: {
2710:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2712:   PetscInt       i,nz = 0,m = A->rmap->n,n = A->cmap->n;
2713:   const PetscInt *row,*col;
2714:   PetscInt       *cnew,j,*lens;
2715:   IS             icolp,irowp;
2716:   PetscInt       *cwork = NULL;
2717:   PetscScalar    *vwork = NULL;

2720:   ISInvertPermutation(rowp,PETSC_DECIDE,&irowp);
2721:   ISGetIndices(irowp,&row);
2722:   ISInvertPermutation(colp,PETSC_DECIDE,&icolp);
2723:   ISGetIndices(icolp,&col);

2725:   /* determine lengths of permuted rows */
2726:   PetscMalloc1(m+1,&lens);
2727:   for (i=0; i<m; i++) lens[row[i]] = a->i[i+1] - a->i[i];
2728:   MatCreate(PetscObjectComm((PetscObject)A),B);
2729:   MatSetSizes(*B,m,n,m,n);
2730:   MatSetBlockSizesFromMats(*B,A,A);
2731:   MatSetType(*B,((PetscObject)A)->type_name);
2732:   MatSeqAIJSetPreallocation_SeqAIJ(*B,0,lens);
2733:   PetscFree(lens);

2735:   PetscMalloc1(n,&cnew);
2736:   for (i=0; i<m; i++) {
2737:     MatGetRow_SeqAIJ(A,i,&nz,&cwork,&vwork);
2738:     for (j=0; j<nz; j++) cnew[j] = col[cwork[j]];
2739:     MatSetValues_SeqAIJ(*B,1,&row[i],nz,cnew,vwork,INSERT_VALUES);
2740:     MatRestoreRow_SeqAIJ(A,i,&nz,&cwork,&vwork);
2741:   }
2742:   PetscFree(cnew);

2744:   (*B)->assembled = PETSC_FALSE;

2746:   MatAssemblyBegin(*B,MAT_FINAL_ASSEMBLY);
2747:   MatAssemblyEnd(*B,MAT_FINAL_ASSEMBLY);
2748:   ISRestoreIndices(irowp,&row);
2749:   ISRestoreIndices(icolp,&col);
2750:   ISDestroy(&irowp);
2751:   ISDestroy(&icolp);
2752:   return(0);
2753: }

2755: PetscErrorCode MatCopy_SeqAIJ(Mat A,Mat B,MatStructure str)
2756: {

2760:   /* If the two matrices have the same copy implementation, use fast copy. */
2761:   if (str == SAME_NONZERO_PATTERN && (A->ops->copy == B->ops->copy)) {
2762:     Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
2763:     Mat_SeqAIJ *b = (Mat_SeqAIJ*)B->data;

2765:     if (a->i[A->rmap->n] != b->i[B->rmap->n]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Number of nonzeros in two matrices are different");
2766:     PetscMemcpy(b->a,a->a,(a->i[A->rmap->n])*sizeof(PetscScalar));
2767:     PetscObjectStateIncrease((PetscObject)B);
2768:   } else {
2769:     MatCopy_Basic(A,B,str);
2770:   }
2771:   return(0);
2772: }

2774: PetscErrorCode MatSetUp_SeqAIJ(Mat A)
2775: {

2779:    MatSeqAIJSetPreallocation_SeqAIJ(A,PETSC_DEFAULT,0);
2780:   return(0);
2781: }

2783: PetscErrorCode MatSeqAIJGetArray_SeqAIJ(Mat A,PetscScalar *array[])
2784: {
2785:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;

2788:   *array = a->a;
2789:   return(0);
2790: }

2792: PetscErrorCode MatSeqAIJRestoreArray_SeqAIJ(Mat A,PetscScalar *array[])
2793: {
2795:   return(0);
2796: }

2798: /*
2799:    Computes the number of nonzeros per row needed for preallocation when X and Y
2800:    have different nonzero structure.
2801: */
2802: PetscErrorCode MatAXPYGetPreallocation_SeqX_private(PetscInt m,const PetscInt *xi,const PetscInt *xj,const PetscInt *yi,const PetscInt *yj,PetscInt *nnz)
2803: {
2804:   PetscInt       i,j,k,nzx,nzy;

2807:   /* Set the number of nonzeros in the new matrix */
2808:   for (i=0; i<m; i++) {
2809:     const PetscInt *xjj = xj+xi[i],*yjj = yj+yi[i];
2810:     nzx = xi[i+1] - xi[i];
2811:     nzy = yi[i+1] - yi[i];
2812:     nnz[i] = 0;
2813:     for (j=0,k=0; j<nzx; j++) {                   /* Point in X */
2814:       for (; k<nzy && yjj[k]<xjj[j]; k++) nnz[i]++; /* Catch up to X */
2815:       if (k<nzy && yjj[k]==xjj[j]) k++;             /* Skip duplicate */
2816:       nnz[i]++;
2817:     }
2818:     for (; k<nzy; k++) nnz[i]++;
2819:   }
2820:   return(0);
2821: }

2823: PetscErrorCode MatAXPYGetPreallocation_SeqAIJ(Mat Y,Mat X,PetscInt *nnz)
2824: {
2825:   PetscInt       m = Y->rmap->N;
2826:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data;
2827:   Mat_SeqAIJ     *y = (Mat_SeqAIJ*)Y->data;

2831:   /* Set the number of nonzeros in the new matrix */
2832:   MatAXPYGetPreallocation_SeqX_private(m,x->i,x->j,y->i,y->j,nnz);
2833:   return(0);
2834: }

2836: PetscErrorCode MatAXPY_SeqAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
2837: {
2839:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data,*y = (Mat_SeqAIJ*)Y->data;
2840:   PetscBLASInt   one=1,bnz;

2843:   PetscBLASIntCast(x->nz,&bnz);
2844:   if (str == SAME_NONZERO_PATTERN) {
2845:     PetscScalar alpha = a;
2846:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2847:     MatSeqAIJInvalidateDiagonal(Y);
2848:     PetscObjectStateIncrease((PetscObject)Y);
2849:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2850:     MatAXPY_Basic(Y,a,X,str);
2851:   } else {
2852:     Mat      B;
2853:     PetscInt *nnz;
2854:     PetscMalloc1(Y->rmap->N,&nnz);
2855:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
2856:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
2857:     MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);
2858:     MatSetBlockSizesFromMats(B,Y,Y);
2859:     MatSetType(B,(MatType) ((PetscObject)Y)->type_name);
2860:     MatAXPYGetPreallocation_SeqAIJ(Y,X,nnz);
2861:     MatSeqAIJSetPreallocation(B,0,nnz);
2862:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
2863:     MatHeaderReplace(Y,&B);
2864:     PetscFree(nnz);
2865:   }
2866:   return(0);
2867: }

2869: PetscErrorCode  MatConjugate_SeqAIJ(Mat mat)
2870: {
2871: #if defined(PETSC_USE_COMPLEX)
2872:   Mat_SeqAIJ  *aij = (Mat_SeqAIJ*)mat->data;
2873:   PetscInt    i,nz;
2874:   PetscScalar *a;

2877:   nz = aij->nz;
2878:   a  = aij->a;
2879:   for (i=0; i<nz; i++) a[i] = PetscConj(a[i]);
2880: #else
2882: #endif
2883:   return(0);
2884: }

2886: PetscErrorCode MatGetRowMaxAbs_SeqAIJ(Mat A,Vec v,PetscInt idx[])
2887: {
2888:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2890:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
2891:   PetscReal      atmp;
2892:   PetscScalar    *x;
2893:   MatScalar      *aa;

2896:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2897:   aa = a->a;
2898:   ai = a->i;
2899:   aj = a->j;

2901:   VecSet(v,0.0);
2902:   VecGetArray(v,&x);
2903:   VecGetLocalSize(v,&n);
2904:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
2905:   for (i=0; i<m; i++) {
2906:     ncols = ai[1] - ai[0]; ai++;
2907:     x[i]  = 0.0;
2908:     for (j=0; j<ncols; j++) {
2909:       atmp = PetscAbsScalar(*aa);
2910:       if (PetscAbsScalar(x[i]) < atmp) {x[i] = atmp; if (idx) idx[i] = *aj;}
2911:       aa++; aj++;
2912:     }
2913:   }
2914:   VecRestoreArray(v,&x);
2915:   return(0);
2916: }

2918: PetscErrorCode MatGetRowMax_SeqAIJ(Mat A,Vec v,PetscInt idx[])
2919: {
2920:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2922:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
2923:   PetscScalar    *x;
2924:   MatScalar      *aa;

2927:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2928:   aa = a->a;
2929:   ai = a->i;
2930:   aj = a->j;

2932:   VecSet(v,0.0);
2933:   VecGetArray(v,&x);
2934:   VecGetLocalSize(v,&n);
2935:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
2936:   for (i=0; i<m; i++) {
2937:     ncols = ai[1] - ai[0]; ai++;
2938:     if (ncols == A->cmap->n) { /* row is dense */
2939:       x[i] = *aa; if (idx) idx[i] = 0;
2940:     } else {  /* row is sparse so already KNOW maximum is 0.0 or higher */
2941:       x[i] = 0.0;
2942:       if (idx) {
2943:         idx[i] = 0; /* in case ncols is zero */
2944:         for (j=0;j<ncols;j++) { /* find first implicit 0.0 in the row */
2945:           if (aj[j] > j) {
2946:             idx[i] = j;
2947:             break;
2948:           }
2949:         }
2950:       }
2951:     }
2952:     for (j=0; j<ncols; j++) {
2953:       if (PetscRealPart(x[i]) < PetscRealPart(*aa)) {x[i] = *aa; if (idx) idx[i] = *aj;}
2954:       aa++; aj++;
2955:     }
2956:   }
2957:   VecRestoreArray(v,&x);
2958:   return(0);
2959: }

2961: PetscErrorCode MatGetRowMinAbs_SeqAIJ(Mat A,Vec v,PetscInt idx[])
2962: {
2963:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2965:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
2966:   PetscReal      atmp;
2967:   PetscScalar    *x;
2968:   MatScalar      *aa;

2971:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2972:   aa = a->a;
2973:   ai = a->i;
2974:   aj = a->j;

2976:   VecSet(v,0.0);
2977:   VecGetArray(v,&x);
2978:   VecGetLocalSize(v,&n);
2979:   if (n != A->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector, %D vs. %D rows", A->rmap->n, n);
2980:   for (i=0; i<m; i++) {
2981:     ncols = ai[1] - ai[0]; ai++;
2982:     if (ncols) {
2983:       /* Get first nonzero */
2984:       for (j = 0; j < ncols; j++) {
2985:         atmp = PetscAbsScalar(aa[j]);
2986:         if (atmp > 1.0e-12) {
2987:           x[i] = atmp;
2988:           if (idx) idx[i] = aj[j];
2989:           break;
2990:         }
2991:       }
2992:       if (j == ncols) {x[i] = PetscAbsScalar(*aa); if (idx) idx[i] = *aj;}
2993:     } else {
2994:       x[i] = 0.0; if (idx) idx[i] = 0;
2995:     }
2996:     for (j = 0; j < ncols; j++) {
2997:       atmp = PetscAbsScalar(*aa);
2998:       if (atmp > 1.0e-12 && PetscAbsScalar(x[i]) > atmp) {x[i] = atmp; if (idx) idx[i] = *aj;}
2999:       aa++; aj++;
3000:     }
3001:   }
3002:   VecRestoreArray(v,&x);
3003:   return(0);
3004: }

3006: PetscErrorCode MatGetRowMin_SeqAIJ(Mat A,Vec v,PetscInt idx[])
3007: {
3008:   Mat_SeqAIJ      *a = (Mat_SeqAIJ*)A->data;
3009:   PetscErrorCode  ierr;
3010:   PetscInt        i,j,m = A->rmap->n,ncols,n;
3011:   const PetscInt  *ai,*aj;
3012:   PetscScalar     *x;
3013:   const MatScalar *aa;

3016:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3017:   aa = a->a;
3018:   ai = a->i;
3019:   aj = a->j;

3021:   VecSet(v,0.0);
3022:   VecGetArray(v,&x);
3023:   VecGetLocalSize(v,&n);
3024:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
3025:   for (i=0; i<m; i++) {
3026:     ncols = ai[1] - ai[0]; ai++;
3027:     if (ncols == A->cmap->n) { /* row is dense */
3028:       x[i] = *aa; if (idx) idx[i] = 0;
3029:     } else {  /* row is sparse so already KNOW minimum is 0.0 or lower */
3030:       x[i] = 0.0;
3031:       if (idx) {   /* find first implicit 0.0 in the row */
3032:         idx[i] = 0; /* in case ncols is zero */
3033:         for (j=0; j<ncols; j++) {
3034:           if (aj[j] > j) {
3035:             idx[i] = j;
3036:             break;
3037:           }
3038:         }
3039:       }
3040:     }
3041:     for (j=0; j<ncols; j++) {
3042:       if (PetscRealPart(x[i]) > PetscRealPart(*aa)) {x[i] = *aa; if (idx) idx[i] = *aj;}
3043:       aa++; aj++;
3044:     }
3045:   }
3046:   VecRestoreArray(v,&x);
3047:   return(0);
3048: }

3050: PetscErrorCode MatInvertBlockDiagonal_SeqAIJ(Mat A,const PetscScalar **values)
3051: {
3052:   Mat_SeqAIJ      *a = (Mat_SeqAIJ*) A->data;
3053:   PetscErrorCode  ierr;
3054:   PetscInt        i,bs = PetscAbs(A->rmap->bs),mbs = A->rmap->n/bs,ipvt[5],bs2 = bs*bs,*v_pivots,ij[7],*IJ,j;
3055:   MatScalar       *diag,work[25],*v_work;
3056:   const PetscReal shift = 0.0;
3057:   PetscBool       allowzeropivot,zeropivotdetected=PETSC_FALSE;

3060:   allowzeropivot = PetscNot(A->erroriffailure);
3061:   if (a->ibdiagvalid) {
3062:     if (values) *values = a->ibdiag;
3063:     return(0);
3064:   }
3065:   MatMarkDiagonal_SeqAIJ(A);
3066:   if (!a->ibdiag) {
3067:     PetscMalloc1(bs2*mbs,&a->ibdiag);
3068:     PetscLogObjectMemory((PetscObject)A,bs2*mbs*sizeof(PetscScalar));
3069:   }
3070:   diag = a->ibdiag;
3071:   if (values) *values = a->ibdiag;
3072:   /* factor and invert each block */
3073:   switch (bs) {
3074:   case 1:
3075:     for (i=0; i<mbs; i++) {
3076:       MatGetValues(A,1,&i,1,&i,diag+i);
3077:       if (PetscAbsScalar(diag[i] + shift) < PETSC_MACHINE_EPSILON) {
3078:         if (allowzeropivot) {
3079:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3080:           A->factorerror_zeropivot_value = PetscAbsScalar(diag[i]);
3081:           A->factorerror_zeropivot_row   = i;
3082:           PetscInfo3(A,"Zero pivot, row %D pivot %g tolerance %g\n",i,(double)PetscAbsScalar(diag[i]),(double)PETSC_MACHINE_EPSILON);
3083:         } else SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_MAT_LU_ZRPVT,"Zero pivot, row %D pivot %g tolerance %g",i,(double)PetscAbsScalar(diag[i]),(double)PETSC_MACHINE_EPSILON);
3084:       }
3085:       diag[i] = (PetscScalar)1.0 / (diag[i] + shift);
3086:     }
3087:     break;
3088:   case 2:
3089:     for (i=0; i<mbs; i++) {
3090:       ij[0] = 2*i; ij[1] = 2*i + 1;
3091:       MatGetValues(A,2,ij,2,ij,diag);
3092:       PetscKernel_A_gets_inverse_A_2(diag,shift,allowzeropivot,&zeropivotdetected);
3093:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3094:       PetscKernel_A_gets_transpose_A_2(diag);
3095:       diag += 4;
3096:     }
3097:     break;
3098:   case 3:
3099:     for (i=0; i<mbs; i++) {
3100:       ij[0] = 3*i; ij[1] = 3*i + 1; ij[2] = 3*i + 2;
3101:       MatGetValues(A,3,ij,3,ij,diag);
3102:       PetscKernel_A_gets_inverse_A_3(diag,shift,allowzeropivot,&zeropivotdetected);
3103:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3104:       PetscKernel_A_gets_transpose_A_3(diag);
3105:       diag += 9;
3106:     }
3107:     break;
3108:   case 4:
3109:     for (i=0; i<mbs; i++) {
3110:       ij[0] = 4*i; ij[1] = 4*i + 1; ij[2] = 4*i + 2; ij[3] = 4*i + 3;
3111:       MatGetValues(A,4,ij,4,ij,diag);
3112:       PetscKernel_A_gets_inverse_A_4(diag,shift,allowzeropivot,&zeropivotdetected);
3113:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3114:       PetscKernel_A_gets_transpose_A_4(diag);
3115:       diag += 16;
3116:     }
3117:     break;
3118:   case 5:
3119:     for (i=0; i<mbs; i++) {
3120:       ij[0] = 5*i; ij[1] = 5*i + 1; ij[2] = 5*i + 2; ij[3] = 5*i + 3; ij[4] = 5*i + 4;
3121:       MatGetValues(A,5,ij,5,ij,diag);
3122:       PetscKernel_A_gets_inverse_A_5(diag,ipvt,work,shift,allowzeropivot,&zeropivotdetected);
3123:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3124:       PetscKernel_A_gets_transpose_A_5(diag);
3125:       diag += 25;
3126:     }
3127:     break;
3128:   case 6:
3129:     for (i=0; i<mbs; i++) {
3130:       ij[0] = 6*i; ij[1] = 6*i + 1; ij[2] = 6*i + 2; ij[3] = 6*i + 3; ij[4] = 6*i + 4; ij[5] = 6*i + 5;
3131:       MatGetValues(A,6,ij,6,ij,diag);
3132:       PetscKernel_A_gets_inverse_A_6(diag,shift,allowzeropivot,&zeropivotdetected);
3133:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3134:       PetscKernel_A_gets_transpose_A_6(diag);
3135:       diag += 36;
3136:     }
3137:     break;
3138:   case 7:
3139:     for (i=0; i<mbs; i++) {
3140:       ij[0] = 7*i; ij[1] = 7*i + 1; ij[2] = 7*i + 2; ij[3] = 7*i + 3; ij[4] = 7*i + 4; ij[5] = 7*i + 5; ij[5] = 7*i + 6;
3141:       MatGetValues(A,7,ij,7,ij,diag);
3142:       PetscKernel_A_gets_inverse_A_7(diag,shift,allowzeropivot,&zeropivotdetected);
3143:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3144:       PetscKernel_A_gets_transpose_A_7(diag);
3145:       diag += 49;
3146:     }
3147:     break;
3148:   default:
3149:     PetscMalloc3(bs,&v_work,bs,&v_pivots,bs,&IJ);
3150:     for (i=0; i<mbs; i++) {
3151:       for (j=0; j<bs; j++) {
3152:         IJ[j] = bs*i + j;
3153:       }
3154:       MatGetValues(A,bs,IJ,bs,IJ,diag);
3155:       PetscKernel_A_gets_inverse_A(bs,diag,v_pivots,v_work,allowzeropivot,&zeropivotdetected);
3156:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3157:       PetscKernel_A_gets_transpose_A_N(diag,bs);
3158:       diag += bs2;
3159:     }
3160:     PetscFree3(v_work,v_pivots,IJ);
3161:   }
3162:   a->ibdiagvalid = PETSC_TRUE;
3163:   return(0);
3164: }

3166: static PetscErrorCode  MatSetRandom_SeqAIJ(Mat x,PetscRandom rctx)
3167: {
3169:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)x->data;
3170:   PetscScalar    a;
3171:   PetscInt       m,n,i,j,col;

3174:   if (!x->assembled) {
3175:     MatGetSize(x,&m,&n);
3176:     for (i=0; i<m; i++) {
3177:       for (j=0; j<aij->imax[i]; j++) {
3178:         PetscRandomGetValue(rctx,&a);
3179:         col  = (PetscInt)(n*PetscRealPart(a));
3180:         MatSetValues(x,1,&i,1,&col,&a,ADD_VALUES);
3181:       }
3182:     }
3183:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet coded");
3184:   MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);
3185:   MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);
3186:   return(0);
3187: }

3189: PetscErrorCode MatShift_SeqAIJ(Mat Y,PetscScalar a)
3190: {
3192:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)Y->data;

3195:   if (!Y->preallocated || !aij->nz) {
3196:     MatSeqAIJSetPreallocation(Y,1,NULL);
3197:   }
3198:   MatShift_Basic(Y,a);
3199:   return(0);
3200: }

3202: /* -------------------------------------------------------------------*/
3203: static struct _MatOps MatOps_Values = { MatSetValues_SeqAIJ,
3204:                                         MatGetRow_SeqAIJ,
3205:                                         MatRestoreRow_SeqAIJ,
3206:                                         MatMult_SeqAIJ,
3207:                                 /*  4*/ MatMultAdd_SeqAIJ,
3208:                                         MatMultTranspose_SeqAIJ,
3209:                                         MatMultTransposeAdd_SeqAIJ,
3210:                                         0,
3211:                                         0,
3212:                                         0,
3213:                                 /* 10*/ 0,
3214:                                         MatLUFactor_SeqAIJ,
3215:                                         0,
3216:                                         MatSOR_SeqAIJ,
3217:                                         MatTranspose_SeqAIJ_FAST,
3218:                                 /*1 5*/ MatGetInfo_SeqAIJ,
3219:                                         MatEqual_SeqAIJ,
3220:                                         MatGetDiagonal_SeqAIJ,
3221:                                         MatDiagonalScale_SeqAIJ,
3222:                                         MatNorm_SeqAIJ,
3223:                                 /* 20*/ 0,
3224:                                         MatAssemblyEnd_SeqAIJ,
3225:                                         MatSetOption_SeqAIJ,
3226:                                         MatZeroEntries_SeqAIJ,
3227:                                 /* 24*/ MatZeroRows_SeqAIJ,
3228:                                         0,
3229:                                         0,
3230:                                         0,
3231:                                         0,
3232:                                 /* 29*/ MatSetUp_SeqAIJ,
3233:                                         0,
3234:                                         0,
3235:                                         0,
3236:                                         0,
3237:                                 /* 34*/ MatDuplicate_SeqAIJ,
3238:                                         0,
3239:                                         0,
3240:                                         MatILUFactor_SeqAIJ,
3241:                                         0,
3242:                                 /* 39*/ MatAXPY_SeqAIJ,
3243:                                         MatCreateSubMatrices_SeqAIJ,
3244:                                         MatIncreaseOverlap_SeqAIJ,
3245:                                         MatGetValues_SeqAIJ,
3246:                                         MatCopy_SeqAIJ,
3247:                                 /* 44*/ MatGetRowMax_SeqAIJ,
3248:                                         MatScale_SeqAIJ,
3249:                                         MatShift_SeqAIJ,
3250:                                         MatDiagonalSet_SeqAIJ,
3251:                                         MatZeroRowsColumns_SeqAIJ,
3252:                                 /* 49*/ MatSetRandom_SeqAIJ,
3253:                                         MatGetRowIJ_SeqAIJ,
3254:                                         MatRestoreRowIJ_SeqAIJ,
3255:                                         MatGetColumnIJ_SeqAIJ,
3256:                                         MatRestoreColumnIJ_SeqAIJ,
3257:                                 /* 54*/ MatFDColoringCreate_SeqXAIJ,
3258:                                         0,
3259:                                         0,
3260:                                         MatPermute_SeqAIJ,
3261:                                         0,
3262:                                 /* 59*/ 0,
3263:                                         MatDestroy_SeqAIJ,
3264:                                         MatView_SeqAIJ,
3265:                                         0,
3266:                                         MatMatMatMult_SeqAIJ_SeqAIJ_SeqAIJ,
3267:                                 /* 64*/ MatMatMatMultSymbolic_SeqAIJ_SeqAIJ_SeqAIJ,
3268:                                         MatMatMatMultNumeric_SeqAIJ_SeqAIJ_SeqAIJ,
3269:                                         0,
3270:                                         0,
3271:                                         0,
3272:                                 /* 69*/ MatGetRowMaxAbs_SeqAIJ,
3273:                                         MatGetRowMinAbs_SeqAIJ,
3274:                                         0,
3275:                                         0,
3276:                                         0,
3277:                                 /* 74*/ 0,
3278:                                         MatFDColoringApply_AIJ,
3279:                                         0,
3280:                                         0,
3281:                                         0,
3282:                                 /* 79*/ MatFindZeroDiagonals_SeqAIJ,
3283:                                         0,
3284:                                         0,
3285:                                         0,
3286:                                         MatLoad_SeqAIJ,
3287:                                 /* 84*/ MatIsSymmetric_SeqAIJ,
3288:                                         MatIsHermitian_SeqAIJ,
3289:                                         0,
3290:                                         0,
3291:                                         0,
3292:                                 /* 89*/ MatMatMult_SeqAIJ_SeqAIJ,
3293:                                         MatMatMultSymbolic_SeqAIJ_SeqAIJ,
3294:                                         MatMatMultNumeric_SeqAIJ_SeqAIJ,
3295:                                         MatPtAP_SeqAIJ_SeqAIJ,
3296:                                         MatPtAPSymbolic_SeqAIJ_SeqAIJ_SparseAxpy,
3297:                                 /* 94*/ MatPtAPNumeric_SeqAIJ_SeqAIJ_SparseAxpy,
3298:                                         MatMatTransposeMult_SeqAIJ_SeqAIJ,
3299:                                         MatMatTransposeMultSymbolic_SeqAIJ_SeqAIJ,
3300:                                         MatMatTransposeMultNumeric_SeqAIJ_SeqAIJ,
3301:                                         0,
3302:                                 /* 99*/ 0,
3303:                                         0,
3304:                                         0,
3305:                                         MatConjugate_SeqAIJ,
3306:                                         0,
3307:                                 /*104*/ MatSetValuesRow_SeqAIJ,
3308:                                         MatRealPart_SeqAIJ,
3309:                                         MatImaginaryPart_SeqAIJ,
3310:                                         0,
3311:                                         0,
3312:                                 /*109*/ MatMatSolve_SeqAIJ,
3313:                                         0,
3314:                                         MatGetRowMin_SeqAIJ,
3315:                                         0,
3316:                                         MatMissingDiagonal_SeqAIJ,
3317:                                 /*114*/ 0,
3318:                                         0,
3319:                                         0,
3320:                                         0,
3321:                                         0,
3322:                                 /*119*/ 0,
3323:                                         0,
3324:                                         0,
3325:                                         0,
3326:                                         MatGetMultiProcBlock_SeqAIJ,
3327:                                 /*124*/ MatFindNonzeroRows_SeqAIJ,
3328:                                         MatGetColumnNorms_SeqAIJ,
3329:                                         MatInvertBlockDiagonal_SeqAIJ,
3330:                                         MatInvertVariableBlockDiagonal_SeqAIJ,
3331:                                         0,
3332:                                 /*129*/ 0,
3333:                                         MatTransposeMatMult_SeqAIJ_SeqAIJ,
3334:                                         MatTransposeMatMultSymbolic_SeqAIJ_SeqAIJ,
3335:                                         MatTransposeMatMultNumeric_SeqAIJ_SeqAIJ,
3336:                                         MatTransposeColoringCreate_SeqAIJ,
3337:                                 /*134*/ MatTransColoringApplySpToDen_SeqAIJ,
3338:                                         MatTransColoringApplyDenToSp_SeqAIJ,
3339:                                         MatRARt_SeqAIJ_SeqAIJ,
3340:                                         MatRARtSymbolic_SeqAIJ_SeqAIJ,
3341:                                         MatRARtNumeric_SeqAIJ_SeqAIJ,
3342:                                  /*139*/0,
3343:                                         0,
3344:                                         0,
3345:                                         MatFDColoringSetUp_SeqXAIJ,
3346:                                         MatFindOffBlockDiagonalEntries_SeqAIJ,
3347:                                  /*144*/MatCreateMPIMatConcatenateSeqMat_SeqAIJ,
3348:                                         MatDestroySubMatrices_SeqAIJ
3349: };

3351: PetscErrorCode  MatSeqAIJSetColumnIndices_SeqAIJ(Mat mat,PetscInt *indices)
3352: {
3353:   Mat_SeqAIJ *aij = (Mat_SeqAIJ*)mat->data;
3354:   PetscInt   i,nz,n;

3357:   nz = aij->maxnz;
3358:   n  = mat->rmap->n;
3359:   for (i=0; i<nz; i++) {
3360:     aij->j[i] = indices[i];
3361:   }
3362:   aij->nz = nz;
3363:   for (i=0; i<n; i++) {
3364:     aij->ilen[i] = aij->imax[i];
3365:   }
3366:   return(0);
3367: }

3369: /*@
3370:     MatSeqAIJSetColumnIndices - Set the column indices for all the rows
3371:        in the matrix.

3373:   Input Parameters:
3374: +  mat - the SeqAIJ matrix
3375: -  indices - the column indices

3377:   Level: advanced

3379:   Notes:
3380:     This can be called if you have precomputed the nonzero structure of the
3381:   matrix and want to provide it to the matrix object to improve the performance
3382:   of the MatSetValues() operation.

3384:     You MUST have set the correct numbers of nonzeros per row in the call to
3385:   MatCreateSeqAIJ(), and the columns indices MUST be sorted.

3387:     MUST be called before any calls to MatSetValues();

3389:     The indices should start with zero, not one.

3391: @*/
3392: PetscErrorCode  MatSeqAIJSetColumnIndices(Mat mat,PetscInt *indices)
3393: {

3399:   PetscUseMethod(mat,"MatSeqAIJSetColumnIndices_C",(Mat,PetscInt*),(mat,indices));
3400:   return(0);
3401: }

3403: /* ----------------------------------------------------------------------------------------*/

3405: PetscErrorCode  MatStoreValues_SeqAIJ(Mat mat)
3406: {
3407:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)mat->data;
3409:   size_t         nz = aij->i[mat->rmap->n];

3412:   if (!aij->nonew) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");

3414:   /* allocate space for values if not already there */
3415:   if (!aij->saved_values) {
3416:     PetscMalloc1(nz+1,&aij->saved_values);
3417:     PetscLogObjectMemory((PetscObject)mat,(nz+1)*sizeof(PetscScalar));
3418:   }

3420:   /* copy values over */
3421:   PetscMemcpy(aij->saved_values,aij->a,nz*sizeof(PetscScalar));
3422:   return(0);
3423: }

3425: /*@
3426:     MatStoreValues - Stashes a copy of the matrix values; this allows, for
3427:        example, reuse of the linear part of a Jacobian, while recomputing the
3428:        nonlinear portion.

3430:    Collect on Mat

3432:   Input Parameters:
3433: .  mat - the matrix (currently only AIJ matrices support this option)

3435:   Level: advanced

3437:   Common Usage, with SNESSolve():
3438: $    Create Jacobian matrix
3439: $    Set linear terms into matrix
3440: $    Apply boundary conditions to matrix, at this time matrix must have
3441: $      final nonzero structure (i.e. setting the nonlinear terms and applying
3442: $      boundary conditions again will not change the nonzero structure
3443: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3444: $    MatStoreValues(mat);
3445: $    Call SNESSetJacobian() with matrix
3446: $    In your Jacobian routine
3447: $      MatRetrieveValues(mat);
3448: $      Set nonlinear terms in matrix

3450:   Common Usage without SNESSolve(), i.e. when you handle nonlinear solve yourself:
3451: $    // build linear portion of Jacobian
3452: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3453: $    MatStoreValues(mat);
3454: $    loop over nonlinear iterations
3455: $       MatRetrieveValues(mat);
3456: $       // call MatSetValues(mat,...) to set nonliner portion of Jacobian
3457: $       // call MatAssemblyBegin/End() on matrix
3458: $       Solve linear system with Jacobian
3459: $    endloop

3461:   Notes:
3462:     Matrix must already be assemblied before calling this routine
3463:     Must set the matrix option MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE); before
3464:     calling this routine.

3466:     When this is called multiple times it overwrites the previous set of stored values
3467:     and does not allocated additional space.

3469: .seealso: MatRetrieveValues()

3471: @*/
3472: PetscErrorCode  MatStoreValues(Mat mat)
3473: {

3478:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3479:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3480:   PetscUseMethod(mat,"MatStoreValues_C",(Mat),(mat));
3481:   return(0);
3482: }

3484: PetscErrorCode  MatRetrieveValues_SeqAIJ(Mat mat)
3485: {
3486:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)mat->data;
3488:   PetscInt       nz = aij->i[mat->rmap->n];

3491:   if (!aij->nonew) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");
3492:   if (!aij->saved_values) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call MatStoreValues(A);first");
3493:   /* copy values over */
3494:   PetscMemcpy(aij->a,aij->saved_values,nz*sizeof(PetscScalar));
3495:   return(0);
3496: }

3498: /*@
3499:     MatRetrieveValues - Retrieves the copy of the matrix values; this allows, for
3500:        example, reuse of the linear part of a Jacobian, while recomputing the
3501:        nonlinear portion.

3503:    Collect on Mat

3505:   Input Parameters:
3506: .  mat - the matrix (currently only AIJ matrices support this option)

3508:   Level: advanced

3510: .seealso: MatStoreValues()

3512: @*/
3513: PetscErrorCode  MatRetrieveValues(Mat mat)
3514: {

3519:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3520:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3521:   PetscUseMethod(mat,"MatRetrieveValues_C",(Mat),(mat));
3522:   return(0);
3523: }


3526: /* --------------------------------------------------------------------------------*/
3527: /*@C
3528:    MatCreateSeqAIJ - Creates a sparse matrix in AIJ (compressed row) format
3529:    (the default parallel PETSc format).  For good matrix assembly performance
3530:    the user should preallocate the matrix storage by setting the parameter nz
3531:    (or the array nnz).  By setting these parameters accurately, performance
3532:    during matrix assembly can be increased by more than a factor of 50.

3534:    Collective on MPI_Comm

3536:    Input Parameters:
3537: +  comm - MPI communicator, set to PETSC_COMM_SELF
3538: .  m - number of rows
3539: .  n - number of columns
3540: .  nz - number of nonzeros per row (same for all rows)
3541: -  nnz - array containing the number of nonzeros in the various rows
3542:          (possibly different for each row) or NULL

3544:    Output Parameter:
3545: .  A - the matrix

3547:    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
3548:    MatXXXXSetPreallocation() paradgm instead of this routine directly.
3549:    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]

3551:    Notes:
3552:    If nnz is given then nz is ignored

3554:    The AIJ format (also called the Yale sparse matrix format or
3555:    compressed row storage), is fully compatible with standard Fortran 77
3556:    storage.  That is, the stored row and column indices can begin at
3557:    either one (as in Fortran) or zero.  See the users' manual for details.

3559:    Specify the preallocated storage with either nz or nnz (not both).
3560:    Set nz=PETSC_DEFAULT and nnz=NULL for PETSc to control dynamic memory
3561:    allocation.  For large problems you MUST preallocate memory or you
3562:    will get TERRIBLE performance, see the users' manual chapter on matrices.

3564:    By default, this format uses inodes (identical nodes) when possible, to
3565:    improve numerical efficiency of matrix-vector products and solves. We
3566:    search for consecutive rows with the same nonzero structure, thereby
3567:    reusing matrix information to achieve increased efficiency.

3569:    Options Database Keys:
3570: +  -mat_no_inode  - Do not use inodes
3571: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3573:    Level: intermediate

3575: .seealso: MatCreate(), MatCreateAIJ(), MatSetValues(), MatSeqAIJSetColumnIndices(), MatCreateSeqAIJWithArrays()

3577: @*/
3578: PetscErrorCode  MatCreateSeqAIJ(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt nz,const PetscInt nnz[],Mat *A)
3579: {

3583:   MatCreate(comm,A);
3584:   MatSetSizes(*A,m,n,m,n);
3585:   MatSetType(*A,MATSEQAIJ);
3586:   MatSeqAIJSetPreallocation_SeqAIJ(*A,nz,nnz);
3587:   return(0);
3588: }

3590: /*@C
3591:    MatSeqAIJSetPreallocation - For good matrix assembly performance
3592:    the user should preallocate the matrix storage by setting the parameter nz
3593:    (or the array nnz).  By setting these parameters accurately, performance
3594:    during matrix assembly can be increased by more than a factor of 50.

3596:    Collective on MPI_Comm

3598:    Input Parameters:
3599: +  B - The matrix
3600: .  nz - number of nonzeros per row (same for all rows)
3601: -  nnz - array containing the number of nonzeros in the various rows
3602:          (possibly different for each row) or NULL

3604:    Notes:
3605:      If nnz is given then nz is ignored

3607:     The AIJ format (also called the Yale sparse matrix format or
3608:    compressed row storage), is fully compatible with standard Fortran 77
3609:    storage.  That is, the stored row and column indices can begin at
3610:    either one (as in Fortran) or zero.  See the users' manual for details.

3612:    Specify the preallocated storage with either nz or nnz (not both).
3613:    Set nz=PETSC_DEFAULT and nnz=NULL for PETSc to control dynamic memory
3614:    allocation.  For large problems you MUST preallocate memory or you
3615:    will get TERRIBLE performance, see the users' manual chapter on matrices.

3617:    You can call MatGetInfo() to get information on how effective the preallocation was;
3618:    for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
3619:    You can also run with the option -info and look for messages with the string
3620:    malloc in them to see if additional memory allocation was needed.

3622:    Developers: Use nz of MAT_SKIP_ALLOCATION to not allocate any space for the matrix
3623:    entries or columns indices

3625:    By default, this format uses inodes (identical nodes) when possible, to
3626:    improve numerical efficiency of matrix-vector products and solves. We
3627:    search for consecutive rows with the same nonzero structure, thereby
3628:    reusing matrix information to achieve increased efficiency.

3630:    Options Database Keys:
3631: +  -mat_no_inode  - Do not use inodes
3632: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3634:    Level: intermediate

3636: .seealso: MatCreate(), MatCreateAIJ(), MatSetValues(), MatSeqAIJSetColumnIndices(), MatCreateSeqAIJWithArrays(), MatGetInfo()

3638: @*/
3639: PetscErrorCode  MatSeqAIJSetPreallocation(Mat B,PetscInt nz,const PetscInt nnz[])
3640: {

3646:   PetscTryMethod(B,"MatSeqAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[]),(B,nz,nnz));
3647:   return(0);
3648: }

3650: PetscErrorCode  MatSeqAIJSetPreallocation_SeqAIJ(Mat B,PetscInt nz,const PetscInt *nnz)
3651: {
3652:   Mat_SeqAIJ     *b;
3653:   PetscBool      skipallocation = PETSC_FALSE,realalloc = PETSC_FALSE;
3655:   PetscInt       i;

3658:   if (nz >= 0 || nnz) realalloc = PETSC_TRUE;
3659:   if (nz == MAT_SKIP_ALLOCATION) {
3660:     skipallocation = PETSC_TRUE;
3661:     nz             = 0;
3662:   }
3663:   PetscLayoutSetUp(B->rmap);
3664:   PetscLayoutSetUp(B->cmap);

3666:   if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 5;
3667:   if (nz < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"nz cannot be less than 0: value %D",nz);
3668:   if (nnz) {
3669:     for (i=0; i<B->rmap->n; i++) {
3670:       if (nnz[i] < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"nnz cannot be less than 0: local row %D value %D",i,nnz[i]);
3671:       if (nnz[i] > B->cmap->n) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"nnz cannot be greater than row length: local row %D value %d rowlength %D",i,nnz[i],B->cmap->n);
3672:     }
3673:   }

3675:   B->preallocated = PETSC_TRUE;

3677:   b = (Mat_SeqAIJ*)B->data;

3679:   if (!skipallocation) {
3680:     if (!b->imax) {
3681:       PetscMalloc2(B->rmap->n,&b->imax,B->rmap->n,&b->ilen);
3682:       PetscLogObjectMemory((PetscObject)B,2*B->rmap->n*sizeof(PetscInt));
3683:     }
3684:     if (!b->ipre) {
3685:       PetscMalloc1(B->rmap->n,&b->ipre);
3686:       PetscLogObjectMemory((PetscObject)B,B->rmap->n*sizeof(PetscInt));
3687:     }
3688:     if (!nnz) {
3689:       if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 10;
3690:       else if (nz < 0) nz = 1;
3691:       for (i=0; i<B->rmap->n; i++) b->imax[i] = nz;
3692:       nz = nz*B->rmap->n;
3693:     } else {
3694:       nz = 0;
3695:       for (i=0; i<B->rmap->n; i++) {b->imax[i] = nnz[i]; nz += nnz[i];}
3696:     }
3697:     /* b->ilen will count nonzeros in each row so far. */
3698:     for (i=0; i<B->rmap->n; i++) b->ilen[i] = 0;

3700:     /* allocate the matrix space */
3701:     /* FIXME: should B's old memory be unlogged? */
3702:     MatSeqXAIJFreeAIJ(B,&b->a,&b->j,&b->i);
3703:     if (B->structure_only) {
3704:       PetscMalloc1(nz,&b->j);
3705:       PetscMalloc1(B->rmap->n+1,&b->i);
3706:       PetscLogObjectMemory((PetscObject)B,(B->rmap->n+1)*sizeof(PetscInt)+nz*sizeof(PetscInt));
3707:     } else {
3708:       PetscMalloc3(nz,&b->a,nz,&b->j,B->rmap->n+1,&b->i);
3709:       PetscLogObjectMemory((PetscObject)B,(B->rmap->n+1)*sizeof(PetscInt)+nz*(sizeof(PetscScalar)+sizeof(PetscInt)));
3710:     }
3711:     b->i[0] = 0;
3712:     for (i=1; i<B->rmap->n+1; i++) {
3713:       b->i[i] = b->i[i-1] + b->imax[i-1];
3714:     }
3715:     if (B->structure_only) {
3716:       b->singlemalloc = PETSC_FALSE;
3717:       b->free_a       = PETSC_FALSE;
3718:     } else {
3719:       b->singlemalloc = PETSC_TRUE;
3720:       b->free_a       = PETSC_TRUE;
3721:     }
3722:     b->free_ij      = PETSC_TRUE;
3723:   } else {
3724:     b->free_a  = PETSC_FALSE;
3725:     b->free_ij = PETSC_FALSE;
3726:   }

3728:   if (b->ipre && nnz != b->ipre  && b->imax) {
3729:     /* reserve user-requested sparsity */
3730:     PetscMemcpy(b->ipre,b->imax,B->rmap->n*sizeof(PetscInt));
3731:   }


3734:   b->nz               = 0;
3735:   b->maxnz            = nz;
3736:   B->info.nz_unneeded = (double)b->maxnz;
3737:   if (realalloc) {
3738:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
3739:   }
3740:   B->was_assembled = PETSC_FALSE;
3741:   B->assembled     = PETSC_FALSE;
3742:   return(0);
3743: }


3746: PetscErrorCode MatResetPreallocation_SeqAIJ(Mat A)
3747: {
3748:   Mat_SeqAIJ     *a;
3749:   PetscInt       i;

3754:   a = (Mat_SeqAIJ*)A->data;
3755:   /* if no saved info, we error out */
3756:   if (!a->ipre) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_NULL,"No saved preallocation info \n");

3758:   if (!a->i || !a->j || !a->a || !a->imax || !a->ilen) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_NULL,"Memory info is incomplete, and can not reset preallocation \n");

3760:   PetscMemcpy(a->imax,a->ipre,A->rmap->n*sizeof(PetscInt));
3761:   PetscMemzero(a->ilen,A->rmap->n*sizeof(PetscInt));
3762:   a->i[0] = 0;
3763:   for (i=1; i<A->rmap->n+1; i++) {
3764:     a->i[i] = a->i[i-1] + a->imax[i-1];
3765:   }
3766:   A->preallocated     = PETSC_TRUE;
3767:   a->nz               = 0;
3768:   a->maxnz            = a->i[A->rmap->n];
3769:   A->info.nz_unneeded = (double)a->maxnz;
3770:   A->was_assembled    = PETSC_FALSE;
3771:   A->assembled        = PETSC_FALSE;
3772:   return(0);
3773: }

3775: /*@
3776:    MatSeqAIJSetPreallocationCSR - Allocates memory for a sparse sequential matrix in AIJ format.

3778:    Input Parameters:
3779: +  B - the matrix
3780: .  i - the indices into j for the start of each row (starts with zero)
3781: .  j - the column indices for each row (starts with zero) these must be sorted for each row
3782: -  v - optional values in the matrix

3784:    Level: developer

3786:    The i,j,v values are COPIED with this routine; to avoid the copy use MatCreateSeqAIJWithArrays()

3788: .keywords: matrix, aij, compressed row, sparse, sequential

3790: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatSeqAIJSetPreallocation(), MatCreateSeqAIJ(), MATSEQAIJ
3791: @*/
3792: PetscErrorCode MatSeqAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[],const PetscScalar v[])
3793: {

3799:   PetscTryMethod(B,"MatSeqAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));
3800:   return(0);
3801: }

3803: PetscErrorCode  MatSeqAIJSetPreallocationCSR_SeqAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
3804: {
3805:   PetscInt       i;
3806:   PetscInt       m,n;
3807:   PetscInt       nz;
3808:   PetscInt       *nnz, nz_max = 0;
3809:   PetscScalar    *values;

3813:   if (Ii[0]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Ii[0] must be 0 it is %D", Ii[0]);

3815:   PetscLayoutSetUp(B->rmap);
3816:   PetscLayoutSetUp(B->cmap);

3818:   MatGetSize(B, &m, &n);
3819:   PetscMalloc1(m+1, &nnz);
3820:   for (i = 0; i < m; i++) {
3821:     nz     = Ii[i+1]- Ii[i];
3822:     nz_max = PetscMax(nz_max, nz);
3823:     if (nz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Local row %D has a negative number of columns %D", i, nnz);
3824:     nnz[i] = nz;
3825:   }
3826:   MatSeqAIJSetPreallocation(B, 0, nnz);
3827:   PetscFree(nnz);

3829:   if (v) {
3830:     values = (PetscScalar*) v;
3831:   } else {
3832:     PetscCalloc1(nz_max, &values);
3833:   }

3835:   for (i = 0; i < m; i++) {
3836:     nz   = Ii[i+1] - Ii[i];
3837:     MatSetValues_SeqAIJ(B, 1, &i, nz, J+Ii[i], values + (v ? Ii[i] : 0), INSERT_VALUES);
3838:   }

3840:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3841:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

3843:   if (!v) {
3844:     PetscFree(values);
3845:   }
3846:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
3847:   return(0);
3848: }

3850:  #include <../src/mat/impls/dense/seq/dense.h>
3851:  #include <petsc/private/kernels/petscaxpy.h>

3853: /*
3854:     Computes (B'*A')' since computing B*A directly is untenable

3856:                n                       p                          p
3857:         (              )       (              )         (                  )
3858:       m (      A       )  *  n (       B      )   =   m (         C        )
3859:         (              )       (              )         (                  )

3861: */
3862: PetscErrorCode MatMatMultNumeric_SeqDense_SeqAIJ(Mat A,Mat B,Mat C)
3863: {
3864:   PetscErrorCode    ierr;
3865:   Mat_SeqDense      *sub_a = (Mat_SeqDense*)A->data;
3866:   Mat_SeqAIJ        *sub_b = (Mat_SeqAIJ*)B->data;
3867:   Mat_SeqDense      *sub_c = (Mat_SeqDense*)C->data;
3868:   PetscInt          i,n,m,q,p;
3869:   const PetscInt    *ii,*idx;
3870:   const PetscScalar *b,*a,*a_q;
3871:   PetscScalar       *c,*c_q;

3874:   m    = A->rmap->n;
3875:   n    = A->cmap->n;
3876:   p    = B->cmap->n;
3877:   a    = sub_a->v;
3878:   b    = sub_b->a;
3879:   c    = sub_c->v;
3880:   PetscMemzero(c,m*p*sizeof(PetscScalar));

3882:   ii  = sub_b->i;
3883:   idx = sub_b->j;
3884:   for (i=0; i<n; i++) {
3885:     q = ii[i+1] - ii[i];
3886:     while (q-->0) {
3887:       c_q = c + m*(*idx);
3888:       a_q = a + m*i;
3889:       PetscKernelAXPY(c_q,*b,a_q,m);
3890:       idx++;
3891:       b++;
3892:     }
3893:   }
3894:   return(0);
3895: }

3897: PetscErrorCode MatMatMultSymbolic_SeqDense_SeqAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
3898: {
3900:   PetscInt       m=A->rmap->n,n=B->cmap->n;
3901:   Mat            Cmat;

3904:   if (A->cmap->n != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"A->cmap->n %D != B->rmap->n %D\n",A->cmap->n,B->rmap->n);
3905:   MatCreate(PetscObjectComm((PetscObject)A),&Cmat);
3906:   MatSetSizes(Cmat,m,n,m,n);
3907:   MatSetBlockSizesFromMats(Cmat,A,B);
3908:   MatSetType(Cmat,MATSEQDENSE);
3909:   MatSeqDenseSetPreallocation(Cmat,NULL);

3911:   Cmat->ops->matmultnumeric = MatMatMultNumeric_SeqDense_SeqAIJ;

3913:   *C = Cmat;
3914:   return(0);
3915: }

3917: /* ----------------------------------------------------------------*/
3918: PETSC_INTERN PetscErrorCode MatMatMult_SeqDense_SeqAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
3919: {

3923:   if (scall == MAT_INITIAL_MATRIX) {
3924:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
3925:     MatMatMultSymbolic_SeqDense_SeqAIJ(A,B,fill,C);
3926:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
3927:   }
3928:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
3929:   MatMatMultNumeric_SeqDense_SeqAIJ(A,B,*C);
3930:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
3931:   return(0);
3932: }


3935: /*MC
3936:    MATSEQAIJ - MATSEQAIJ = "seqaij" - A matrix type to be used for sequential sparse matrices,
3937:    based on compressed sparse row format.

3939:    Options Database Keys:
3940: . -mat_type seqaij - sets the matrix type to "seqaij" during a call to MatSetFromOptions()

3942:   Level: beginner

3944: .seealso: MatCreateSeqAIJ(), MatSetFromOptions(), MatSetType(), MatCreate(), MatType
3945: M*/

3947: /*MC
3948:    MATAIJ - MATAIJ = "aij" - A matrix type to be used for sparse matrices.

3950:    This matrix type is identical to MATSEQAIJ when constructed with a single process communicator,
3951:    and MATMPIAIJ otherwise.  As a result, for single process communicators,
3952:   MatSeqAIJSetPreallocation is supported, and similarly MatMPIAIJSetPreallocation is supported
3953:   for communicators controlling multiple processes.  It is recommended that you call both of
3954:   the above preallocation routines for simplicity.

3956:    Options Database Keys:
3957: . -mat_type aij - sets the matrix type to "aij" during a call to MatSetFromOptions()

3959:   Developer Notes:
3960:     Subclasses include MATAIJCUSPARSE, MATAIJPERM, MATAIJSELL, MATAIJMKL, MATAIJCRL, and also automatically switches over to use inodes when
3961:    enough exist.

3963:   Level: beginner

3965: .seealso: MatCreateAIJ(), MatCreateSeqAIJ(), MATSEQAIJ,MATMPIAIJ
3966: M*/

3968: /*MC
3969:    MATAIJCRL - MATAIJCRL = "aijcrl" - A matrix type to be used for sparse matrices.

3971:    This matrix type is identical to MATSEQAIJCRL when constructed with a single process communicator,
3972:    and MATMPIAIJCRL otherwise.  As a result, for single process communicators,
3973:    MatSeqAIJSetPreallocation() is supported, and similarly MatMPIAIJSetPreallocation() is supported
3974:   for communicators controlling multiple processes.  It is recommended that you call both of
3975:   the above preallocation routines for simplicity.

3977:    Options Database Keys:
3978: . -mat_type aijcrl - sets the matrix type to "aijcrl" during a call to MatSetFromOptions()

3980:   Level: beginner

3982: .seealso: MatCreateMPIAIJCRL,MATSEQAIJCRL,MATMPIAIJCRL, MATSEQAIJCRL, MATMPIAIJCRL
3983: M*/

3985: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCRL(Mat,MatType,MatReuse,Mat*);
3986: #if defined(PETSC_HAVE_ELEMENTAL)
3987: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_Elemental(Mat,MatType,MatReuse,Mat*);
3988: #endif
3989: #if defined(PETSC_HAVE_HYPRE)
3990: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat A,MatType,MatReuse,Mat*);
3991: PETSC_INTERN PetscErrorCode MatMatMatMult_Transpose_AIJ_AIJ(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
3992: #endif
3993: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqDense(Mat,MatType,MatReuse,Mat*);

3995: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3996: PETSC_EXTERN PetscErrorCode  MatlabEnginePut_SeqAIJ(PetscObject,void*);
3997: PETSC_EXTERN PetscErrorCode  MatlabEngineGet_SeqAIJ(PetscObject,void*);
3998: #endif

4000: PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqSELL(Mat,MatType,MatReuse,Mat*);
4001: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat,MatType,MatReuse,Mat*);
4002: PETSC_INTERN PetscErrorCode MatPtAP_IS_XAIJ(Mat,Mat,MatReuse,PetscReal,Mat*);

4004: /*@C
4005:    MatSeqAIJGetArray - gives access to the array where the data for a MATSEQAIJ matrix is stored

4007:    Not Collective

4009:    Input Parameter:
4010: .  mat - a MATSEQAIJ matrix

4012:    Output Parameter:
4013: .   array - pointer to the data

4015:    Level: intermediate

4017: .seealso: MatSeqAIJRestoreArray(), MatSeqAIJGetArrayF90()
4018: @*/
4019: PetscErrorCode  MatSeqAIJGetArray(Mat A,PetscScalar **array)
4020: {

4024:   PetscUseMethod(A,"MatSeqAIJGetArray_C",(Mat,PetscScalar**),(A,array));
4025:   return(0);
4026: }

4028: /*@C
4029:    MatSeqAIJGetMaxRowNonzeros - returns the maximum number of nonzeros in any row

4031:    Not Collective

4033:    Input Parameter:
4034: .  mat - a MATSEQAIJ matrix

4036:    Output Parameter:
4037: .   nz - the maximum number of nonzeros in any row

4039:    Level: intermediate

4041: .seealso: MatSeqAIJRestoreArray(), MatSeqAIJGetArrayF90()
4042: @*/
4043: PetscErrorCode  MatSeqAIJGetMaxRowNonzeros(Mat A,PetscInt *nz)
4044: {
4045:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)A->data;

4048:   *nz = aij->rmax;
4049:   return(0);
4050: }

4052: /*@C
4053:    MatSeqAIJRestoreArray - returns access to the array where the data for a MATSEQAIJ matrix is stored obtained by MatSeqAIJGetArray()

4055:    Not Collective

4057:    Input Parameters:
4058: .  mat - a MATSEQAIJ matrix
4059: .  array - pointer to the data

4061:    Level: intermediate

4063: .seealso: MatSeqAIJGetArray(), MatSeqAIJRestoreArrayF90()
4064: @*/
4065: PetscErrorCode  MatSeqAIJRestoreArray(Mat A,PetscScalar **array)
4066: {

4070:   PetscUseMethod(A,"MatSeqAIJRestoreArray_C",(Mat,PetscScalar**),(A,array));
4071:   return(0);
4072: }

4074: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJ(Mat B)
4075: {
4076:   Mat_SeqAIJ     *b;
4078:   PetscMPIInt    size;

4081:   MPI_Comm_size(PetscObjectComm((PetscObject)B),&size);
4082:   if (size > 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Comm must be of size 1");

4084:   PetscNewLog(B,&b);

4086:   B->data = (void*)b;

4088:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));

4090:   b->row                = 0;
4091:   b->col                = 0;
4092:   b->icol               = 0;
4093:   b->reallocs           = 0;
4094:   b->ignorezeroentries  = PETSC_FALSE;
4095:   b->roworiented        = PETSC_TRUE;
4096:   b->nonew              = 0;
4097:   b->diag               = 0;
4098:   b->solve_work         = 0;
4099:   B->spptr              = 0;
4100:   b->saved_values       = 0;
4101:   b->idiag              = 0;
4102:   b->mdiag              = 0;
4103:   b->ssor_work          = 0;
4104:   b->omega              = 1.0;
4105:   b->fshift             = 0.0;
4106:   b->idiagvalid         = PETSC_FALSE;
4107:   b->ibdiagvalid        = PETSC_FALSE;
4108:   b->keepnonzeropattern = PETSC_FALSE;

4110:   PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJ);
4111:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJGetArray_C",MatSeqAIJGetArray_SeqAIJ);
4112:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJRestoreArray_C",MatSeqAIJRestoreArray_SeqAIJ);

4114: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4115:   PetscObjectComposeFunction((PetscObject)B,"PetscMatlabEnginePut_C",MatlabEnginePut_SeqAIJ);
4116:   PetscObjectComposeFunction((PetscObject)B,"PetscMatlabEngineGet_C",MatlabEngineGet_SeqAIJ);
4117: #endif

4119:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetColumnIndices_C",MatSeqAIJSetColumnIndices_SeqAIJ);
4120:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_SeqAIJ);
4121:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_SeqAIJ);
4122:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqsbaij_C",MatConvert_SeqAIJ_SeqSBAIJ);
4123:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqbaij_C",MatConvert_SeqAIJ_SeqBAIJ);
4124:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijperm_C",MatConvert_SeqAIJ_SeqAIJPERM);
4125:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijsell_C",MatConvert_SeqAIJ_SeqAIJSELL);
4126: #if defined(PETSC_HAVE_MKL_SPARSE)
4127:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijmkl_C",MatConvert_SeqAIJ_SeqAIJMKL);
4128: #endif
4129:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijcrl_C",MatConvert_SeqAIJ_SeqAIJCRL);
4130: #if defined(PETSC_HAVE_ELEMENTAL)
4131:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_elemental_C",MatConvert_SeqAIJ_Elemental);
4132: #endif
4133: #if defined(PETSC_HAVE_HYPRE)
4134:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_hypre_C",MatConvert_AIJ_HYPRE);
4135:   PetscObjectComposeFunction((PetscObject)B,"MatMatMatMult_transpose_seqaij_seqaij_C",MatMatMatMult_Transpose_AIJ_AIJ);
4136: #endif
4137:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqdense_C",MatConvert_SeqAIJ_SeqDense);
4138:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqsell_C",MatConvert_SeqAIJ_SeqSELL);
4139:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_is_C",MatConvert_XAIJ_IS);
4140:   PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_SeqAIJ);
4141:   PetscObjectComposeFunction((PetscObject)B,"MatIsHermitianTranspose_C",MatIsTranspose_SeqAIJ);
4142:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetPreallocation_C",MatSeqAIJSetPreallocation_SeqAIJ);
4143:   PetscObjectComposeFunction((PetscObject)B,"MatResetPreallocation_C",MatResetPreallocation_SeqAIJ);
4144:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetPreallocationCSR_C",MatSeqAIJSetPreallocationCSR_SeqAIJ);
4145:   PetscObjectComposeFunction((PetscObject)B,"MatReorderForNonzeroDiagonal_C",MatReorderForNonzeroDiagonal_SeqAIJ);
4146:   PetscObjectComposeFunction((PetscObject)B,"MatMatMult_seqdense_seqaij_C",MatMatMult_SeqDense_SeqAIJ);
4147:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultSymbolic_seqdense_seqaij_C",MatMatMultSymbolic_SeqDense_SeqAIJ);
4148:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultNumeric_seqdense_seqaij_C",MatMatMultNumeric_SeqDense_SeqAIJ);
4149:   PetscObjectComposeFunction((PetscObject)B,"MatPtAP_is_seqaij_C",MatPtAP_IS_XAIJ);
4150:   MatCreate_SeqAIJ_Inode(B);
4151:   PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJ);
4152:   MatSeqAIJSetTypeFromOptions(B);  /* this allows changing the matrix subtype to say MATSEQAIJPERM */
4153:   return(0);
4154: }

4156: /*
4157:     Given a matrix generated with MatGetFactor() duplicates all the information in A into B
4158: */
4159: PetscErrorCode MatDuplicateNoCreate_SeqAIJ(Mat C,Mat A,MatDuplicateOption cpvalues,PetscBool mallocmatspace)
4160: {
4161:   Mat_SeqAIJ     *c,*a = (Mat_SeqAIJ*)A->data;
4163:   PetscInt       i,m = A->rmap->n;

4166:   c = (Mat_SeqAIJ*)C->data;

4168:   C->factortype = A->factortype;
4169:   c->row        = 0;
4170:   c->col        = 0;
4171:   c->icol       = 0;
4172:   c->reallocs   = 0;

4174:   C->assembled = PETSC_TRUE;

4176:   PetscLayoutReference(A->rmap,&C->rmap);
4177:   PetscLayoutReference(A->cmap,&C->cmap);

4179:   PetscMalloc2(m,&c->imax,m,&c->ilen);
4180:   PetscLogObjectMemory((PetscObject)C, 2*m*sizeof(PetscInt));
4181:   for (i=0; i<m; i++) {
4182:     c->imax[i] = a->imax[i];
4183:     c->ilen[i] = a->ilen[i];
4184:   }

4186:   /* allocate the matrix space */
4187:   if (mallocmatspace) {
4188:     PetscMalloc3(a->i[m],&c->a,a->i[m],&c->j,m+1,&c->i);
4189:     PetscLogObjectMemory((PetscObject)C, a->i[m]*(sizeof(PetscScalar)+sizeof(PetscInt))+(m+1)*sizeof(PetscInt));

4191:     c->singlemalloc = PETSC_TRUE;

4193:     PetscMemcpy(c->i,a->i,(m+1)*sizeof(PetscInt));
4194:     if (m > 0) {
4195:       PetscMemcpy(c->j,a->j,(a->i[m])*sizeof(PetscInt));
4196:       if (cpvalues == MAT_COPY_VALUES) {
4197:         PetscMemcpy(c->a,a->a,(a->i[m])*sizeof(PetscScalar));
4198:       } else {
4199:         PetscMemzero(c->a,(a->i[m])*sizeof(PetscScalar));
4200:       }
4201:     }
4202:   }

4204:   c->ignorezeroentries = a->ignorezeroentries;
4205:   c->roworiented       = a->roworiented;
4206:   c->nonew             = a->nonew;
4207:   if (a->diag) {
4208:     PetscMalloc1(m+1,&c->diag);
4209:     PetscLogObjectMemory((PetscObject)C,(m+1)*sizeof(PetscInt));
4210:     for (i=0; i<m; i++) {
4211:       c->diag[i] = a->diag[i];
4212:     }
4213:   } else c->diag = 0;

4215:   c->solve_work         = 0;
4216:   c->saved_values       = 0;
4217:   c->idiag              = 0;
4218:   c->ssor_work          = 0;
4219:   c->keepnonzeropattern = a->keepnonzeropattern;
4220:   c->free_a             = PETSC_TRUE;
4221:   c->free_ij            = PETSC_TRUE;

4223:   c->rmax         = a->rmax;
4224:   c->nz           = a->nz;
4225:   c->maxnz        = a->nz;       /* Since we allocate exactly the right amount */
4226:   C->preallocated = PETSC_TRUE;

4228:   c->compressedrow.use   = a->compressedrow.use;
4229:   c->compressedrow.nrows = a->compressedrow.nrows;
4230:   if (a->compressedrow.use) {
4231:     i    = a->compressedrow.nrows;
4232:     PetscMalloc2(i+1,&c->compressedrow.i,i,&c->compressedrow.rindex);
4233:     PetscMemcpy(c->compressedrow.i,a->compressedrow.i,(i+1)*sizeof(PetscInt));
4234:     PetscMemcpy(c->compressedrow.rindex,a->compressedrow.rindex,i*sizeof(PetscInt));
4235:   } else {
4236:     c->compressedrow.use    = PETSC_FALSE;
4237:     c->compressedrow.i      = NULL;
4238:     c->compressedrow.rindex = NULL;
4239:   }
4240:   c->nonzerorowcnt = a->nonzerorowcnt;
4241:   C->nonzerostate  = A->nonzerostate;

4243:   MatDuplicate_SeqAIJ_Inode(A,cpvalues,&C);
4244:   PetscFunctionListDuplicate(((PetscObject)A)->qlist,&((PetscObject)C)->qlist);
4245:   return(0);
4246: }

4248: PetscErrorCode MatDuplicate_SeqAIJ(Mat A,MatDuplicateOption cpvalues,Mat *B)
4249: {

4253:   MatCreate(PetscObjectComm((PetscObject)A),B);
4254:   MatSetSizes(*B,A->rmap->n,A->cmap->n,A->rmap->n,A->cmap->n);
4255:   if (!(A->rmap->n % A->rmap->bs) && !(A->cmap->n % A->cmap->bs)) {
4256:     MatSetBlockSizesFromMats(*B,A,A);
4257:   }
4258:   MatSetType(*B,((PetscObject)A)->type_name);
4259:   MatDuplicateNoCreate_SeqAIJ(*B,A,cpvalues,PETSC_TRUE);
4260:   return(0);
4261: }

4263: PetscErrorCode MatLoad_SeqAIJ(Mat newMat, PetscViewer viewer)
4264: {
4265:   Mat_SeqAIJ     *a;
4267:   PetscInt       i,sum,nz,header[4],*rowlengths = 0,M,N,rows,cols;
4268:   int            fd;
4269:   PetscMPIInt    size;
4270:   MPI_Comm       comm;
4271:   PetscInt       bs = newMat->rmap->bs;

4274:   /* force binary viewer to load .info file if it has not yet done so */
4275:   PetscViewerSetUp(viewer);
4276:   PetscObjectGetComm((PetscObject)viewer,&comm);
4277:   MPI_Comm_size(comm,&size);
4278:   if (size > 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"view must have one processor");

4280:   PetscOptionsBegin(comm,NULL,"Options for loading SEQAIJ matrix","Mat");
4281:   PetscOptionsInt("-matload_block_size","Set the blocksize used to store the matrix","MatLoad",bs,&bs,NULL);
4282:   PetscOptionsEnd();
4283:   if (bs < 0) bs = 1;
4284:   MatSetBlockSize(newMat,bs);

4286:   PetscViewerBinaryGetDescriptor(viewer,&fd);
4287:   PetscBinaryRead(fd,header,4,PETSC_INT);
4288:   if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"not matrix object in file");
4289:   M = header[1]; N = header[2]; nz = header[3];

4291:   if (nz < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"Matrix stored in special format on disk,cannot load as SeqAIJ");

4293:   /* read in row lengths */
4294:   PetscMalloc1(M,&rowlengths);
4295:   PetscBinaryRead(fd,rowlengths,M,PETSC_INT);

4297:   /* check if sum of rowlengths is same as nz */
4298:   for (i=0,sum=0; i< M; i++) sum +=rowlengths[i];
4299:   if (sum != nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_READ,"Inconsistant matrix data in file. no-nonzeros = %dD, sum-row-lengths = %D\n",nz,sum);

4301:   /* set global size if not set already*/
4302:   if (newMat->rmap->n < 0 && newMat->rmap->N < 0 && newMat->cmap->n < 0 && newMat->cmap->N < 0) {
4303:     MatSetSizes(newMat,PETSC_DECIDE,PETSC_DECIDE,M,N);
4304:   } else {
4305:     /* if sizes and type are already set, check if the matrix  global sizes are correct */
4306:     MatGetSize(newMat,&rows,&cols);
4307:     if (rows < 0 && cols < 0) { /* user might provide local size instead of global size */
4308:       MatGetLocalSize(newMat,&rows,&cols);
4309:     }
4310:     if (M != rows ||  N != cols) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Matrix in file of different length (%D, %D) than the input matrix (%D, %D)",M,N,rows,cols);
4311:   }
4312:   MatSeqAIJSetPreallocation_SeqAIJ(newMat,0,rowlengths);
4313:   a    = (Mat_SeqAIJ*)newMat->data;

4315:   PetscBinaryRead(fd,a->j,nz,PETSC_INT);

4317:   /* read in nonzero values */
4318:   PetscBinaryRead(fd,a->a,nz,PETSC_SCALAR);

4320:   /* set matrix "i" values */
4321:   a->i[0] = 0;
4322:   for (i=1; i<= M; i++) {
4323:     a->i[i]      = a->i[i-1] + rowlengths[i-1];
4324:     a->ilen[i-1] = rowlengths[i-1];
4325:   }
4326:   PetscFree(rowlengths);

4328:   MatAssemblyBegin(newMat,MAT_FINAL_ASSEMBLY);
4329:   MatAssemblyEnd(newMat,MAT_FINAL_ASSEMBLY);
4330:   return(0);
4331: }

4333: PetscErrorCode MatEqual_SeqAIJ(Mat A,Mat B,PetscBool * flg)
4334: {
4335:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*b = (Mat_SeqAIJ*)B->data;
4337: #if defined(PETSC_USE_COMPLEX)
4338:   PetscInt k;
4339: #endif

4342:   /* If the  matrix dimensions are not equal,or no of nonzeros */
4343:   if ((A->rmap->n != B->rmap->n) || (A->cmap->n != B->cmap->n) ||(a->nz != b->nz)) {
4344:     *flg = PETSC_FALSE;
4345:     return(0);
4346:   }

4348:   /* if the a->i are the same */
4349:   PetscMemcmp(a->i,b->i,(A->rmap->n+1)*sizeof(PetscInt),flg);
4350:   if (!*flg) return(0);

4352:   /* if a->j are the same */
4353:   PetscMemcmp(a->j,b->j,(a->nz)*sizeof(PetscInt),flg);
4354:   if (!*flg) return(0);

4356:   /* if a->a are the same */
4357: #if defined(PETSC_USE_COMPLEX)
4358:   for (k=0; k<a->nz; k++) {
4359:     if (PetscRealPart(a->a[k]) != PetscRealPart(b->a[k]) || PetscImaginaryPart(a->a[k]) != PetscImaginaryPart(b->a[k])) {
4360:       *flg = PETSC_FALSE;
4361:       return(0);
4362:     }
4363:   }
4364: #else
4365:   PetscMemcmp(a->a,b->a,(a->nz)*sizeof(PetscScalar),flg);
4366: #endif
4367:   return(0);
4368: }

4370: /*@
4371:      MatCreateSeqAIJWithArrays - Creates an sequential AIJ matrix using matrix elements (in CSR format)
4372:               provided by the user.

4374:       Collective on MPI_Comm

4376:    Input Parameters:
4377: +   comm - must be an MPI communicator of size 1
4378: .   m - number of rows
4379: .   n - number of columns
4380: .   i - row indices
4381: .   j - column indices
4382: -   a - matrix values

4384:    Output Parameter:
4385: .   mat - the matrix

4387:    Level: intermediate

4389:    Notes:
4390:        The i, j, and a arrays are not copied by this routine, the user must free these arrays
4391:     once the matrix is destroyed and not before

4393:        You cannot set new nonzero locations into this matrix, that will generate an error.

4395:        The i and j indices are 0 based

4397:        The format which is used for the sparse matrix input, is equivalent to a
4398:     row-major ordering.. i.e for the following matrix, the input data expected is
4399:     as shown

4401: $        1 0 0
4402: $        2 0 3
4403: $        4 5 6
4404: $
4405: $        i =  {0,1,3,6}  [size = nrow+1  = 3+1]
4406: $        j =  {0,0,2,0,1,2}  [size = 6]; values must be sorted for each row
4407: $        v =  {1,2,3,4,5,6}  [size = 6]


4410: .seealso: MatCreate(), MatCreateAIJ(), MatCreateSeqAIJ(), MatCreateMPIAIJWithArrays(), MatMPIAIJSetPreallocationCSR()

4412: @*/
4413: PetscErrorCode  MatCreateSeqAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt i[],PetscInt j[],PetscScalar a[],Mat *mat)
4414: {
4416:   PetscInt       ii;
4417:   Mat_SeqAIJ     *aij;
4418: #if defined(PETSC_USE_DEBUG)
4419:   PetscInt jj;
4420: #endif

4423:   if (m > 0 && i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4424:   MatCreate(comm,mat);
4425:   MatSetSizes(*mat,m,n,m,n);
4426:   /* MatSetBlockSizes(*mat,,); */
4427:   MatSetType(*mat,MATSEQAIJ);
4428:   MatSeqAIJSetPreallocation_SeqAIJ(*mat,MAT_SKIP_ALLOCATION,0);
4429:   aij  = (Mat_SeqAIJ*)(*mat)->data;
4430:   PetscMalloc2(m,&aij->imax,m,&aij->ilen);

4432:   aij->i            = i;
4433:   aij->j            = j;
4434:   aij->a            = a;
4435:   aij->singlemalloc = PETSC_FALSE;
4436:   aij->nonew        = -1;             /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
4437:   aij->free_a       = PETSC_FALSE;
4438:   aij->free_ij      = PETSC_FALSE;

4440:   for (ii=0; ii<m; ii++) {
4441:     aij->ilen[ii] = aij->imax[ii] = i[ii+1] - i[ii];
4442: #if defined(PETSC_USE_DEBUG)
4443:     if (i[ii+1] - i[ii] < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row length in i (row indices) row = %D length = %D",ii,i[ii+1] - i[ii]);
4444:     for (jj=i[ii]+1; jj<i[ii+1]; jj++) {
4445:       if (j[jj] < j[jj-1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column entry number %D (actual colum %D) in row %D is not sorted",jj-i[ii],j[jj],ii);
4446:       if (j[jj] == j[jj-1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column entry number %D (actual colum %D) in row %D is identical to previous entry",jj-i[ii],j[jj],ii);
4447:     }
4448: #endif
4449:   }
4450: #if defined(PETSC_USE_DEBUG)
4451:   for (ii=0; ii<aij->i[m]; ii++) {
4452:     if (j[ii] < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column index at location = %D index = %D",ii,j[ii]);
4453:     if (j[ii] > n - 1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column index to large at location = %D index = %D",ii,j[ii]);
4454:   }
4455: #endif

4457:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
4458:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
4459:   return(0);
4460: }
4461: /*@C
4462:      MatCreateSeqAIJFromTriple - Creates an sequential AIJ matrix using matrix elements (in COO format)
4463:               provided by the user.

4465:       Collective on MPI_Comm

4467:    Input Parameters:
4468: +   comm - must be an MPI communicator of size 1
4469: .   m   - number of rows
4470: .   n   - number of columns
4471: .   i   - row indices
4472: .   j   - column indices
4473: .   a   - matrix values
4474: .   nz  - number of nonzeros
4475: -   idx - 0 or 1 based

4477:    Output Parameter:
4478: .   mat - the matrix

4480:    Level: intermediate

4482:    Notes:
4483:        The i and j indices are 0 based

4485:        The format which is used for the sparse matrix input, is equivalent to a
4486:     row-major ordering.. i.e for the following matrix, the input data expected is
4487:     as shown:

4489:         1 0 0
4490:         2 0 3
4491:         4 5 6

4493:         i =  {0,1,1,2,2,2}
4494:         j =  {0,0,2,0,1,2}
4495:         v =  {1,2,3,4,5,6}


4498: .seealso: MatCreate(), MatCreateAIJ(), MatCreateSeqAIJ(), MatCreateSeqAIJWithArrays(), MatMPIAIJSetPreallocationCSR()

4500: @*/
4501: PetscErrorCode  MatCreateSeqAIJFromTriple(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt i[],PetscInt j[],PetscScalar a[],Mat *mat,PetscInt nz,PetscBool idx)
4502: {
4504:   PetscInt       ii, *nnz, one = 1,row,col;


4508:   PetscCalloc1(m,&nnz);
4509:   for (ii = 0; ii < nz; ii++) {
4510:     nnz[i[ii] - !!idx] += 1;
4511:   }
4512:   MatCreate(comm,mat);
4513:   MatSetSizes(*mat,m,n,m,n);
4514:   MatSetType(*mat,MATSEQAIJ);
4515:   MatSeqAIJSetPreallocation_SeqAIJ(*mat,0,nnz);
4516:   for (ii = 0; ii < nz; ii++) {
4517:     if (idx) {
4518:       row = i[ii] - 1;
4519:       col = j[ii] - 1;
4520:     } else {
4521:       row = i[ii];
4522:       col = j[ii];
4523:     }
4524:     MatSetValues(*mat,one,&row,one,&col,&a[ii],ADD_VALUES);
4525:   }
4526:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
4527:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
4528:   PetscFree(nnz);
4529:   return(0);
4530: }

4532: PetscErrorCode MatSeqAIJInvalidateDiagonal(Mat A)
4533: {
4534:   Mat_SeqAIJ     *a=(Mat_SeqAIJ*)A->data;

4538:   a->idiagvalid  = PETSC_FALSE;
4539:   a->ibdiagvalid = PETSC_FALSE;

4541:   MatSeqAIJInvalidateDiagonal_Inode(A);
4542:   return(0);
4543: }

4545: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
4546: {
4548:   PetscMPIInt    size;

4551:   MPI_Comm_size(comm,&size);
4552:   if (size == 1) {
4553:     if (scall == MAT_INITIAL_MATRIX) {
4554:       MatDuplicate(inmat,MAT_COPY_VALUES,outmat);
4555:     } else {
4556:       MatCopy(inmat,*outmat,SAME_NONZERO_PATTERN);
4557:     }
4558:   } else {
4559:     MatCreateMPIMatConcatenateSeqMat_MPIAIJ(comm,inmat,n,scall,outmat);
4560:   }
4561:   return(0);
4562: }

4564: /*
4565:  Permute A into C's *local* index space using rowemb,colemb.
4566:  The embedding are supposed to be injections and the above implies that the range of rowemb is a subset
4567:  of [0,m), colemb is in [0,n).
4568:  If pattern == DIFFERENT_NONZERO_PATTERN, C is preallocated according to A.
4569:  */
4570: PetscErrorCode MatSetSeqMat_SeqAIJ(Mat C,IS rowemb,IS colemb,MatStructure pattern,Mat B)
4571: {
4572:   /* If making this function public, change the error returned in this function away from _PLIB. */
4574:   Mat_SeqAIJ     *Baij;
4575:   PetscBool      seqaij;
4576:   PetscInt       m,n,*nz,i,j,count;
4577:   PetscScalar    v;
4578:   const PetscInt *rowindices,*colindices;

4581:   if (!B) return(0);
4582:   /* Check to make sure the target matrix (and embeddings) are compatible with C and each other. */
4583:   PetscObjectBaseTypeCompare((PetscObject)B,MATSEQAIJ,&seqaij);
4584:   if (!seqaij) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is of wrong type");
4585:   if (rowemb) {
4586:     ISGetLocalSize(rowemb,&m);
4587:     if (m != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Row IS of size %D is incompatible with matrix row size %D",m,B->rmap->n);
4588:   } else {
4589:     if (C->rmap->n != B->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is row-incompatible with the target matrix");
4590:   }
4591:   if (colemb) {
4592:     ISGetLocalSize(colemb,&n);
4593:     if (n != B->cmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Diag col IS of size %D is incompatible with input matrix col size %D",n,B->cmap->n);
4594:   } else {
4595:     if (C->cmap->n != B->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is col-incompatible with the target matrix");
4596:   }

4598:   Baij = (Mat_SeqAIJ*)(B->data);
4599:   if (pattern == DIFFERENT_NONZERO_PATTERN) {
4600:     PetscMalloc1(B->rmap->n,&nz);
4601:     for (i=0; i<B->rmap->n; i++) {
4602:       nz[i] = Baij->i[i+1] - Baij->i[i];
4603:     }
4604:     MatSeqAIJSetPreallocation(C,0,nz);
4605:     PetscFree(nz);
4606:   }
4607:   if (pattern == SUBSET_NONZERO_PATTERN) {
4608:     MatZeroEntries(C);
4609:   }
4610:   count = 0;
4611:   rowindices = NULL;
4612:   colindices = NULL;
4613:   if (rowemb) {
4614:     ISGetIndices(rowemb,&rowindices);
4615:   }
4616:   if (colemb) {
4617:     ISGetIndices(colemb,&colindices);
4618:   }
4619:   for (i=0; i<B->rmap->n; i++) {
4620:     PetscInt row;
4621:     row = i;
4622:     if (rowindices) row = rowindices[i];
4623:     for (j=Baij->i[i]; j<Baij->i[i+1]; j++) {
4624:       PetscInt col;
4625:       col  = Baij->j[count];
4626:       if (colindices) col = colindices[col];
4627:       v    = Baij->a[count];
4628:       MatSetValues(C,1,&row,1,&col,&v,INSERT_VALUES);
4629:       ++count;
4630:     }
4631:   }
4632:   /* FIXME: set C's nonzerostate correctly. */
4633:   /* Assembly for C is necessary. */
4634:   C->preallocated = PETSC_TRUE;
4635:   C->assembled     = PETSC_TRUE;
4636:   C->was_assembled = PETSC_FALSE;
4637:   return(0);
4638: }

4640: PetscFunctionList MatSeqAIJList = NULL;

4642: /*@C
4643:    MatSeqAIJSetType - Converts a MATSEQAIJ matrix to a subtype

4645:    Collective on Mat

4647:    Input Parameters:
4648: +  mat      - the matrix object
4649: -  matype   - matrix type

4651:    Options Database Key:
4652: .  -mat_seqai_type  <method> - for example seqaijcrl


4655:   Level: intermediate

4657: .keywords: Mat, MatType, set, method

4659: .seealso: PCSetType(), VecSetType(), MatCreate(), MatType, Mat
4660: @*/
4661: PetscErrorCode  MatSeqAIJSetType(Mat mat, MatType matype)
4662: {
4663:   PetscErrorCode ierr,(*r)(Mat,MatType,MatReuse,Mat*);
4664:   PetscBool      sametype;

4668:   PetscObjectTypeCompare((PetscObject)mat,matype,&sametype);
4669:   if (sametype) return(0);

4671:    PetscFunctionListFind(MatSeqAIJList,matype,&r);
4672:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unknown Mat type given: %s",matype);
4673:   (*r)(mat,matype,MAT_INPLACE_MATRIX,&mat);
4674:   return(0);
4675: }


4678: /*@C
4679:   MatSeqAIJRegister -  - Adds a new sub-matrix type for sequential AIJ matrices

4681:    Not Collective

4683:    Input Parameters:
4684: +  name - name of a new user-defined matrix type, for example MATSEQAIJCRL
4685: -  function - routine to convert to subtype

4687:    Notes:
4688:    MatSeqAIJRegister() may be called multiple times to add several user-defined solvers.


4691:    Then, your matrix can be chosen with the procedural interface at runtime via the option
4692: $     -mat_seqaij_type my_mat

4694:    Level: advanced

4696: .keywords: Mat, register

4698: .seealso: MatSeqAIJRegisterAll()


4701:   Level: advanced
4702: @*/
4703: PetscErrorCode  MatSeqAIJRegister(const char sname[],PetscErrorCode (*function)(Mat,MatType,MatReuse,Mat *))
4704: {

4708:   MatInitializePackage();
4709:   PetscFunctionListAdd(&MatSeqAIJList,sname,function);
4710:   return(0);
4711: }

4713: PetscBool MatSeqAIJRegisterAllCalled = PETSC_FALSE;

4715: /*@C
4716:   MatSeqAIJRegisterAll - Registers all of the matrix subtypes of SeqAIJ

4718:   Not Collective

4720:   Level: advanced

4722:   Developers Note: CUSP and CUSPARSE do not yet support the  MatConvert_SeqAIJ..() paradigm and thus cannot be registered here

4724: .keywords: KSP, register, all

4726: .seealso:  MatRegisterAll(), MatSeqAIJRegister()
4727: @*/
4728: PetscErrorCode  MatSeqAIJRegisterAll(void)
4729: {

4733:   if (MatSeqAIJRegisterAllCalled) return(0);
4734:   MatSeqAIJRegisterAllCalled = PETSC_TRUE;

4736:   MatSeqAIJRegister(MATSEQAIJCRL,      MatConvert_SeqAIJ_SeqAIJCRL);
4737:   MatSeqAIJRegister(MATSEQAIJPERM,     MatConvert_SeqAIJ_SeqAIJPERM);
4738:   MatSeqAIJRegister(MATSEQAIJSELL,     MatConvert_SeqAIJ_SeqAIJSELL);
4739: #if defined(PETSC_HAVE_MKL_SPARSE)
4740:   MatSeqAIJRegister(MATSEQAIJMKL,      MatConvert_SeqAIJ_SeqAIJMKL);
4741: #endif
4742: #if defined(PETSC_HAVE_VIENNACL) && defined(PETSC_HAVE_VIENNACL_NO_CUDA)
4743:   MatSeqAIJRegister(MATMPIAIJVIENNACL, MatConvert_SeqAIJ_SeqAIJViennaCL);
4744: #endif
4745:   return(0);
4746: }

4748: /*
4749:     Special version for direct calls from Fortran
4750: */
4751:  #include <petsc/private/fortranimpl.h>
4752: #if defined(PETSC_HAVE_FORTRAN_CAPS)
4753: #define matsetvaluesseqaij_ MATSETVALUESSEQAIJ
4754: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
4755: #define matsetvaluesseqaij_ matsetvaluesseqaij
4756: #endif

4758: /* Change these macros so can be used in void function */
4759: #undef CHKERRQ
4760: #define CHKERRQ(ierr) CHKERRABORT(PetscObjectComm((PetscObject)A),ierr)
4761: #undef SETERRQ2
4762: #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
4763: #undef SETERRQ3
4764: #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)

4766: PETSC_EXTERN void PETSC_STDCALL matsetvaluesseqaij_(Mat *AA,PetscInt *mm,const PetscInt im[],PetscInt *nn,const PetscInt in[],const PetscScalar v[],InsertMode *isis, PetscErrorCode *_ierr)
4767: {
4768:   Mat            A  = *AA;
4769:   PetscInt       m  = *mm, n = *nn;
4770:   InsertMode     is = *isis;
4771:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
4772:   PetscInt       *rp,k,low,high,t,ii,row,nrow,i,col,l,rmax,N;
4773:   PetscInt       *imax,*ai,*ailen;
4775:   PetscInt       *aj,nonew = a->nonew,lastcol = -1;
4776:   MatScalar      *ap,value,*aa;
4777:   PetscBool      ignorezeroentries = a->ignorezeroentries;
4778:   PetscBool      roworiented       = a->roworiented;

4781:   MatCheckPreallocated(A,1);
4782:   imax  = a->imax;
4783:   ai    = a->i;
4784:   ailen = a->ilen;
4785:   aj    = a->j;
4786:   aa    = a->a;

4788:   for (k=0; k<m; k++) { /* loop over added rows */
4789:     row = im[k];
4790:     if (row < 0) continue;
4791: #if defined(PETSC_USE_DEBUG)
4792:     if (row >= A->rmap->n) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Row too large");
4793: #endif
4794:     rp   = aj + ai[row]; ap = aa + ai[row];
4795:     rmax = imax[row]; nrow = ailen[row];
4796:     low  = 0;
4797:     high = nrow;
4798:     for (l=0; l<n; l++) { /* loop over added columns */
4799:       if (in[l] < 0) continue;
4800: #if defined(PETSC_USE_DEBUG)
4801:       if (in[l] >= A->cmap->n) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Column too large");
4802: #endif
4803:       col = in[l];
4804:       if (roworiented) value = v[l + k*n];
4805:       else value = v[k + l*m];

4807:       if (value == 0.0 && ignorezeroentries && (is == ADD_VALUES)) continue;

4809:       if (col <= lastcol) low = 0;
4810:       else high = nrow;
4811:       lastcol = col;
4812:       while (high-low > 5) {
4813:         t = (low+high)/2;
4814:         if (rp[t] > col) high = t;
4815:         else             low  = t;
4816:       }
4817:       for (i=low; i<high; i++) {
4818:         if (rp[i] > col) break;
4819:         if (rp[i] == col) {
4820:           if (is == ADD_VALUES) ap[i] += value;
4821:           else                  ap[i] = value;
4822:           goto noinsert;
4823:         }
4824:       }
4825:       if (value == 0.0 && ignorezeroentries) goto noinsert;
4826:       if (nonew == 1) goto noinsert;
4827:       if (nonew == -1) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero in the matrix");
4828:       MatSeqXAIJReallocateAIJ(A,A->rmap->n,1,nrow,row,col,rmax,aa,ai,aj,rp,ap,imax,nonew,MatScalar);
4829:       N = nrow++ - 1; a->nz++; high++;
4830:       /* shift up all the later entries in this row */
4831:       for (ii=N; ii>=i; ii--) {
4832:         rp[ii+1] = rp[ii];
4833:         ap[ii+1] = ap[ii];
4834:       }
4835:       rp[i] = col;
4836:       ap[i] = value;
4837:       A->nonzerostate++;
4838: noinsert:;
4839:       low = i + 1;
4840:     }
4841:     ailen[row] = nrow;
4842:   }
4843:   PetscFunctionReturnVoid();
4844: }