Actual source code: aij.c

petsc-master 2017-11-21
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:   PetscFree3(a->idiag,a->mdiag,a->ssor_work);
1098:   PetscFree(a->solve_work);
1099:   ISDestroy(&a->icol);
1100:   PetscFree(a->saved_values);
1101:   ISColoringDestroy(&a->coloring);
1102:   PetscFree2(a->compressedrow.i,a->compressedrow.rindex);
1103:   PetscFree(a->matmult_abdense);

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

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

1130: PetscErrorCode MatSetOption_SeqAIJ(Mat A,MatOption op,PetscBool flg)
1131: {
1132:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

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

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

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

1195:   if (A->factortype == MAT_FACTOR_ILU || A->factortype == MAT_FACTOR_LU) {
1196:     PetscInt *diag=a->diag;
1197:     VecGetArray(v,&x);
1198:     for (i=0; i<n; i++) x[i] = 1.0/aa[diag[i]];
1199:     VecRestoreArray(v,&x);
1200:     return(0);
1201:   }

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

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

1237:   if (zz != yy) {VecCopy(zz,yy);}
1238:   VecGetArrayRead(xx,&x);
1239:   VecGetArray(yy,&y);

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

1269: PetscErrorCode MatMultTranspose_SeqAIJ(Mat A,Vec xx,Vec yy)
1270: {

1274:   VecSet(yy,0.0);
1275:   MatMultTransposeAdd_SeqAIJ(A,xx,yy,yy);
1276:   return(0);
1277: }

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

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

1294: #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1295: #pragma disjoint(*x,*y,*aa)
1296: #endif

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

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

1351: #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1352: #pragma disjoint(*x,*y,*aa)
1353: #endif

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

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

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

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

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

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

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

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

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

1552: /*
1553:    Negative shift indicates do not generate an error if there is a zero diagonal, just invert it anyways
1554: */
1555: PetscErrorCode  MatInvertDiagonal_SeqAIJ(Mat A,PetscScalar omega,PetscScalar fshift)
1556: {
1557:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*) A->data;
1559:   PetscInt       i,*diag,m = A->rmap->n;
1560:   MatScalar      *v = a->a;
1561:   PetscScalar    *idiag,*mdiag;

1564:   if (a->idiagvalid) return(0);
1565:   MatMarkDiagonal_SeqAIJ(A);
1566:   diag = a->diag;
1567:   if (!a->idiag) {
1568:     PetscMalloc3(m,&a->idiag,m,&a->mdiag,m,&a->ssor_work);
1569:     PetscLogObjectMemory((PetscObject)A, 3*m*sizeof(PetscScalar));
1570:     v    = a->a;
1571:   }
1572:   mdiag = a->mdiag;
1573:   idiag = a->idiag;

1575:   if (omega == 1.0 && PetscRealPart(fshift) <= 0.0) {
1576:     for (i=0; i<m; i++) {
1577:       mdiag[i] = v[diag[i]];
1578:       if (!PetscAbsScalar(mdiag[i])) { /* zero diagonal */
1579:         if (PetscRealPart(fshift)) {
1580:           PetscInfo1(A,"Zero diagonal on row %D\n",i);
1581:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1582:           A->factorerror_zeropivot_value = 0.0;
1583:           A->factorerror_zeropivot_row   = i;
1584:         } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Zero diagonal on row %D",i);
1585:       }
1586:       idiag[i] = 1.0/v[diag[i]];
1587:     }
1588:     PetscLogFlops(m);
1589:   } else {
1590:     for (i=0; i<m; i++) {
1591:       mdiag[i] = v[diag[i]];
1592:       idiag[i] = omega/(fshift + v[diag[i]]);
1593:     }
1594:     PetscLogFlops(2.0*m);
1595:   }
1596:   a->idiagvalid = PETSC_TRUE;
1597:   return(0);
1598: }

1600: #include <../src/mat/impls/aij/seq/ftn-kernels/frelax.h>
1601: PetscErrorCode MatSOR_SeqAIJ(Mat A,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
1602: {
1603:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1604:   PetscScalar       *x,d,sum,*t,scale;
1605:   const MatScalar   *v,*idiag=0,*mdiag;
1606:   const PetscScalar *b, *bs,*xb, *ts;
1607:   PetscErrorCode    ierr;
1608:   PetscInt          n,m = A->rmap->n,i;
1609:   const PetscInt    *idx,*diag;

1612:   its = its*lits;

1614:   if (fshift != a->fshift || omega != a->omega) a->idiagvalid = PETSC_FALSE; /* must recompute idiag[] */
1615:   if (!a->idiagvalid) {MatInvertDiagonal_SeqAIJ(A,omega,fshift);}
1616:   a->fshift = fshift;
1617:   a->omega  = omega;

1619:   diag  = a->diag;
1620:   t     = a->ssor_work;
1621:   idiag = a->idiag;
1622:   mdiag = a->mdiag;

1624:   VecGetArray(xx,&x);
1625:   VecGetArrayRead(bb,&b);
1626:   /* We count flops by assuming the upper triangular and lower triangular parts have the same number of nonzeros */
1627:   if (flag == SOR_APPLY_UPPER) {
1628:     /* apply (U + D/omega) to the vector */
1629:     bs = b;
1630:     for (i=0; i<m; i++) {
1631:       d   = fshift + mdiag[i];
1632:       n   = a->i[i+1] - diag[i] - 1;
1633:       idx = a->j + diag[i] + 1;
1634:       v   = a->a + diag[i] + 1;
1635:       sum = b[i]*d/omega;
1636:       PetscSparseDensePlusDot(sum,bs,v,idx,n);
1637:       x[i] = sum;
1638:     }
1639:     VecRestoreArray(xx,&x);
1640:     VecRestoreArrayRead(bb,&b);
1641:     PetscLogFlops(a->nz);
1642:     return(0);
1643:   }

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

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

1652:     to a vector efficiently using Eisenstat's trick.
1653:     */
1654:     scale = (2.0/omega) - 1.0;

1656:     /*  x = (E + U)^{-1} b */
1657:     for (i=m-1; i>=0; i--) {
1658:       n   = a->i[i+1] - diag[i] - 1;
1659:       idx = a->j + diag[i] + 1;
1660:       v   = a->a + diag[i] + 1;
1661:       sum = b[i];
1662:       PetscSparseDenseMinusDot(sum,x,v,idx,n);
1663:       x[i] = sum*idiag[i];
1664:     }

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

1670:     /*  t = (E + L)^{-1}t */
1671:     ts   = t;
1672:     diag = a->diag;
1673:     for (i=0; i<m; i++) {
1674:       n   = diag[i] - a->i[i];
1675:       idx = a->j + a->i[i];
1676:       v   = a->a + a->i[i];
1677:       sum = t[i];
1678:       PetscSparseDenseMinusDot(sum,ts,v,idx,n);
1679:       t[i] = sum*idiag[i];
1680:       /*  x = x + t */
1681:       x[i] += t[i];
1682:     }

1684:     PetscLogFlops(6.0*m-1 + 2.0*a->nz);
1685:     VecRestoreArray(xx,&x);
1686:     VecRestoreArrayRead(bb,&b);
1687:     return(0);
1688:   }
1689:   if (flag & SOR_ZERO_INITIAL_GUESS) {
1690:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1691:       for (i=0; i<m; i++) {
1692:         n   = diag[i] - a->i[i];
1693:         idx = a->j + a->i[i];
1694:         v   = a->a + a->i[i];
1695:         sum = b[i];
1696:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1697:         t[i] = sum;
1698:         x[i] = sum*idiag[i];
1699:       }
1700:       xb   = t;
1701:       PetscLogFlops(a->nz);
1702:     } else xb = b;
1703:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1704:       for (i=m-1; i>=0; i--) {
1705:         n   = a->i[i+1] - diag[i] - 1;
1706:         idx = a->j + diag[i] + 1;
1707:         v   = a->a + diag[i] + 1;
1708:         sum = xb[i];
1709:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1710:         if (xb == b) {
1711:           x[i] = sum*idiag[i];
1712:         } else {
1713:           x[i] = (1-omega)*x[i] + sum*idiag[i];  /* omega in idiag */
1714:         }
1715:       }
1716:       PetscLogFlops(a->nz); /* assumes 1/2 in upper */
1717:     }
1718:     its--;
1719:   }
1720:   while (its--) {
1721:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1722:       for (i=0; i<m; i++) {
1723:         /* lower */
1724:         n   = diag[i] - a->i[i];
1725:         idx = a->j + a->i[i];
1726:         v   = a->a + a->i[i];
1727:         sum = b[i];
1728:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1729:         t[i] = sum;             /* save application of the lower-triangular part */
1730:         /* upper */
1731:         n   = a->i[i+1] - diag[i] - 1;
1732:         idx = a->j + diag[i] + 1;
1733:         v   = a->a + diag[i] + 1;
1734:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
1735:         x[i] = (1. - omega)*x[i] + sum*idiag[i]; /* omega in idiag */
1736:       }
1737:       xb   = t;
1738:       PetscLogFlops(2.0*a->nz);
1739:     } else xb = b;
1740:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1741:       for (i=m-1; i>=0; i--) {
1742:         sum = xb[i];
1743:         if (xb == b) {
1744:           /* whole matrix (no checkpointing available) */
1745:           n   = a->i[i+1] - a->i[i];
1746:           idx = a->j + a->i[i];
1747:           v   = a->a + a->i[i];
1748:           PetscSparseDenseMinusDot(sum,x,v,idx,n);
1749:           x[i] = (1. - omega)*x[i] + (sum + mdiag[i]*x[i])*idiag[i];
1750:         } else { /* lower-triangular part has been saved, so only apply upper-triangular */
1751:           n   = a->i[i+1] - diag[i] - 1;
1752:           idx = a->j + diag[i] + 1;
1753:           v   = a->a + diag[i] + 1;
1754:           PetscSparseDenseMinusDot(sum,x,v,idx,n);
1755:           x[i] = (1. - omega)*x[i] + sum*idiag[i];  /* omega in idiag */
1756:         }
1757:       }
1758:       if (xb == b) {
1759:         PetscLogFlops(2.0*a->nz);
1760:       } else {
1761:         PetscLogFlops(a->nz); /* assumes 1/2 in upper */
1762:       }
1763:     }
1764:   }
1765:   VecRestoreArray(xx,&x);
1766:   VecRestoreArrayRead(bb,&b);
1767:   return(0);
1768: }


1771: PetscErrorCode MatGetInfo_SeqAIJ(Mat A,MatInfoType flag,MatInfo *info)
1772: {
1773:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;

1776:   info->block_size   = 1.0;
1777:   info->nz_allocated = (double)a->maxnz;
1778:   info->nz_used      = (double)a->nz;
1779:   info->nz_unneeded  = (double)(a->maxnz - a->nz);
1780:   info->assemblies   = (double)A->num_ass;
1781:   info->mallocs      = (double)A->info.mallocs;
1782:   info->memory       = ((PetscObject)A)->mem;
1783:   if (A->factortype) {
1784:     info->fill_ratio_given  = A->info.fill_ratio_given;
1785:     info->fill_ratio_needed = A->info.fill_ratio_needed;
1786:     info->factor_mallocs    = A->info.factor_mallocs;
1787:   } else {
1788:     info->fill_ratio_given  = 0;
1789:     info->fill_ratio_needed = 0;
1790:     info->factor_mallocs    = 0;
1791:   }
1792:   return(0);
1793: }

1795: PetscErrorCode MatZeroRows_SeqAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1796: {
1797:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1798:   PetscInt          i,m = A->rmap->n - 1;
1799:   PetscErrorCode    ierr;
1800:   const PetscScalar *xx;
1801:   PetscScalar       *bb;
1802:   PetscInt          d = 0;

1805:   if (x && b) {
1806:     VecGetArrayRead(x,&xx);
1807:     VecGetArray(b,&bb);
1808:     for (i=0; i<N; i++) {
1809:       if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1810:       bb[rows[i]] = diag*xx[rows[i]];
1811:     }
1812:     VecRestoreArrayRead(x,&xx);
1813:     VecRestoreArray(b,&bb);
1814:   }

1816:   if (a->keepnonzeropattern) {
1817:     for (i=0; i<N; i++) {
1818:       if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1819:       PetscMemzero(&a->a[a->i[rows[i]]],a->ilen[rows[i]]*sizeof(PetscScalar));
1820:     }
1821:     if (diag != 0.0) {
1822:       for (i=0; i<N; i++) {
1823:         d = rows[i];
1824:         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);
1825:       }
1826:       for (i=0; i<N; i++) {
1827:         a->a[a->diag[rows[i]]] = diag;
1828:       }
1829:     }
1830:   } else {
1831:     if (diag != 0.0) {
1832:       for (i=0; i<N; i++) {
1833:         if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1834:         if (a->ilen[rows[i]] > 0) {
1835:           a->ilen[rows[i]]    = 1;
1836:           a->a[a->i[rows[i]]] = diag;
1837:           a->j[a->i[rows[i]]] = rows[i];
1838:         } else { /* in case row was completely empty */
1839:           MatSetValues_SeqAIJ(A,1,&rows[i],1,&rows[i],&diag,INSERT_VALUES);
1840:         }
1841:       }
1842:     } else {
1843:       for (i=0; i<N; i++) {
1844:         if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1845:         a->ilen[rows[i]] = 0;
1846:       }
1847:     }
1848:     A->nonzerostate++;
1849:   }
1850:   (*A->ops->assemblyend)(A,MAT_FINAL_ASSEMBLY);
1851:   return(0);
1852: }

1854: PetscErrorCode MatZeroRowsColumns_SeqAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1855: {
1856:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1857:   PetscInt          i,j,m = A->rmap->n - 1,d = 0;
1858:   PetscErrorCode    ierr;
1859:   PetscBool         missing,*zeroed,vecs = PETSC_FALSE;
1860:   const PetscScalar *xx;
1861:   PetscScalar       *bb;

1864:   if (x && b) {
1865:     VecGetArrayRead(x,&xx);
1866:     VecGetArray(b,&bb);
1867:     vecs = PETSC_TRUE;
1868:   }
1869:   PetscCalloc1(A->rmap->n,&zeroed);
1870:   for (i=0; i<N; i++) {
1871:     if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
1872:     PetscMemzero(&a->a[a->i[rows[i]]],a->ilen[rows[i]]*sizeof(PetscScalar));

1874:     zeroed[rows[i]] = PETSC_TRUE;
1875:   }
1876:   for (i=0; i<A->rmap->n; i++) {
1877:     if (!zeroed[i]) {
1878:       for (j=a->i[i]; j<a->i[i+1]; j++) {
1879:         if (zeroed[a->j[j]]) {
1880:           if (vecs) bb[i] -= a->a[j]*xx[a->j[j]];
1881:           a->a[j] = 0.0;
1882:         }
1883:       }
1884:     } else if (vecs) bb[i] = diag*xx[i];
1885:   }
1886:   if (x && b) {
1887:     VecRestoreArrayRead(x,&xx);
1888:     VecRestoreArray(b,&bb);
1889:   }
1890:   PetscFree(zeroed);
1891:   if (diag != 0.0) {
1892:     MatMissingDiagonal_SeqAIJ(A,&missing,&d);
1893:     if (missing) {
1894:       if (a->nonew) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Matrix is missing diagonal entry in row %D",d);
1895:       else {
1896:         for (i=0; i<N; i++) {
1897:           MatSetValues_SeqAIJ(A,1,&rows[i],1,&rows[i],&diag,INSERT_VALUES);
1898:         }
1899:       }
1900:     } else {
1901:       for (i=0; i<N; i++) {
1902:         a->a[a->diag[rows[i]]] = diag;
1903:       }
1904:     }
1905:   }
1906:   (*A->ops->assemblyend)(A,MAT_FINAL_ASSEMBLY);
1907:   return(0);
1908: }

1910: PetscErrorCode MatGetRow_SeqAIJ(Mat A,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1911: {
1912:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
1913:   PetscInt   *itmp;

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

1918:   *nz = a->i[row+1] - a->i[row];
1919:   if (v) *v = a->a + a->i[row];
1920:   if (idx) {
1921:     itmp = a->j + a->i[row];
1922:     if (*nz) *idx = itmp;
1923:     else *idx = 0;
1924:   }
1925:   return(0);
1926: }

1928: /* remove this function? */
1929: PetscErrorCode MatRestoreRow_SeqAIJ(Mat A,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1930: {
1932:   return(0);
1933: }

1935: PetscErrorCode MatNorm_SeqAIJ(Mat A,NormType type,PetscReal *nrm)
1936: {
1937:   Mat_SeqAIJ     *a  = (Mat_SeqAIJ*)A->data;
1938:   MatScalar      *v  = a->a;
1939:   PetscReal      sum = 0.0;
1941:   PetscInt       i,j;

1944:   if (type == NORM_FROBENIUS) {
1945: #if defined(PETSC_USE_REAL___FP16)
1946:     PetscBLASInt one = 1,nz = a->nz;
1947:     *nrm = BLASnrm2_(&nz,v,&one);
1948: #else
1949:     for (i=0; i<a->nz; i++) {
1950:       sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1951:     }
1952:     *nrm = PetscSqrtReal(sum);
1953: #endif
1954:     PetscLogFlops(2*a->nz);
1955:   } else if (type == NORM_1) {
1956:     PetscReal *tmp;
1957:     PetscInt  *jj = a->j;
1958:     PetscCalloc1(A->cmap->n+1,&tmp);
1959:     *nrm = 0.0;
1960:     for (j=0; j<a->nz; j++) {
1961:       tmp[*jj++] += PetscAbsScalar(*v);  v++;
1962:     }
1963:     for (j=0; j<A->cmap->n; j++) {
1964:       if (tmp[j] > *nrm) *nrm = tmp[j];
1965:     }
1966:     PetscFree(tmp);
1967:     PetscLogFlops(PetscMax(a->nz-1,0));
1968:   } else if (type == NORM_INFINITY) {
1969:     *nrm = 0.0;
1970:     for (j=0; j<A->rmap->n; j++) {
1971:       v   = a->a + a->i[j];
1972:       sum = 0.0;
1973:       for (i=0; i<a->i[j+1]-a->i[j]; i++) {
1974:         sum += PetscAbsScalar(*v); v++;
1975:       }
1976:       if (sum > *nrm) *nrm = sum;
1977:     }
1978:     PetscLogFlops(PetscMax(a->nz-1,0));
1979:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for two norm");
1980:   return(0);
1981: }

1983: /* Merged from MatGetSymbolicTranspose_SeqAIJ() - replace MatGetSymbolicTranspose_SeqAIJ()? */
1984: PetscErrorCode MatTransposeSymbolic_SeqAIJ(Mat A,Mat *B)
1985: {
1987:   PetscInt       i,j,anzj;
1988:   Mat_SeqAIJ     *a=(Mat_SeqAIJ*)A->data,*b;
1989:   PetscInt       an=A->cmap->N,am=A->rmap->N;
1990:   PetscInt       *ati,*atj,*atfill,*ai=a->i,*aj=a->j;

1993:   /* Allocate space for symbolic transpose info and work array */
1994:   PetscCalloc1(an+1,&ati);
1995:   PetscMalloc1(ai[am],&atj);
1996:   PetscMalloc1(an,&atfill);

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

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

2007:   /* Walk through A row-wise and mark nonzero entries of A^T. */
2008:   for (i=0;i<am;i++) {
2009:     anzj = ai[i+1] - ai[i];
2010:     for (j=0;j<anzj;j++) {
2011:       atj[atfill[*aj]] = i;
2012:       atfill[*aj++]   += 1;
2013:     }
2014:   }

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

2021:   b          = (Mat_SeqAIJ*)((*B)->data);
2022:   b->free_a  = PETSC_FALSE;
2023:   b->free_ij = PETSC_TRUE;
2024:   b->nonew   = 0;
2025:   return(0);
2026: }

2028: PetscErrorCode MatTranspose_SeqAIJ(Mat A,MatReuse reuse,Mat *B)
2029: {
2030:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2031:   Mat            C;
2033:   PetscInt       i,*aj = a->j,*ai = a->i,m = A->rmap->n,len,*col;
2034:   MatScalar      *array = a->a;

2037:   if (reuse == MAT_INPLACE_MATRIX && m != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Square matrix only for in-place");

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

2042:     for (i=0; i<ai[m]; i++) col[aj[i]] += 1;
2043:     MatCreate(PetscObjectComm((PetscObject)A),&C);
2044:     MatSetSizes(C,A->cmap->n,m,A->cmap->n,m);
2045:     MatSetBlockSizes(C,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
2046:     MatSetType(C,((PetscObject)A)->type_name);
2047:     MatSeqAIJSetPreallocation_SeqAIJ(C,0,col);
2048:     PetscFree(col);
2049:   } else {
2050:     C = *B;
2051:   }

2053:   for (i=0; i<m; i++) {
2054:     len    = ai[i+1]-ai[i];
2055:     MatSetValues_SeqAIJ(C,len,aj,1,&i,array,INSERT_VALUES);
2056:     array += len;
2057:     aj    += len;
2058:   }
2059:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2060:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

2062:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
2063:     *B = C;
2064:   } else {
2065:     MatHeaderMerge(A,&C);
2066:   }
2067:   return(0);
2068: }

2070: PetscErrorCode  MatIsTranspose_SeqAIJ(Mat A,Mat B,PetscReal tol,PetscBool  *f)
2071: {
2072:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*) A->data,*bij = (Mat_SeqAIJ*) B->data;
2073:   PetscInt       *adx,*bdx,*aii,*bii,*aptr,*bptr;
2074:   MatScalar      *va,*vb;
2076:   PetscInt       ma,na,mb,nb, i;

2079:   MatGetSize(A,&ma,&na);
2080:   MatGetSize(B,&mb,&nb);
2081:   if (ma!=nb || na!=mb) {
2082:     *f = PETSC_FALSE;
2083:     return(0);
2084:   }
2085:   aii  = aij->i; bii = bij->i;
2086:   adx  = aij->j; bdx = bij->j;
2087:   va   = aij->a; vb = bij->a;
2088:   PetscMalloc1(ma,&aptr);
2089:   PetscMalloc1(mb,&bptr);
2090:   for (i=0; i<ma; i++) aptr[i] = aii[i];
2091:   for (i=0; i<mb; i++) bptr[i] = bii[i];

2093:   *f = PETSC_TRUE;
2094:   for (i=0; i<ma; i++) {
2095:     while (aptr[i]<aii[i+1]) {
2096:       PetscInt    idc,idr;
2097:       PetscScalar vc,vr;
2098:       /* column/row index/value */
2099:       idc = adx[aptr[i]];
2100:       idr = bdx[bptr[idc]];
2101:       vc  = va[aptr[i]];
2102:       vr  = vb[bptr[idc]];
2103:       if (i!=idr || PetscAbsScalar(vc-vr) > tol) {
2104:         *f = PETSC_FALSE;
2105:         goto done;
2106:       } else {
2107:         aptr[i]++;
2108:         if (B || i!=idc) bptr[idc]++;
2109:       }
2110:     }
2111:   }
2112: done:
2113:   PetscFree(aptr);
2114:   PetscFree(bptr);
2115:   return(0);
2116: }

2118: PetscErrorCode  MatIsHermitianTranspose_SeqAIJ(Mat A,Mat B,PetscReal tol,PetscBool  *f)
2119: {
2120:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*) A->data,*bij = (Mat_SeqAIJ*) B->data;
2121:   PetscInt       *adx,*bdx,*aii,*bii,*aptr,*bptr;
2122:   MatScalar      *va,*vb;
2124:   PetscInt       ma,na,mb,nb, i;

2127:   MatGetSize(A,&ma,&na);
2128:   MatGetSize(B,&mb,&nb);
2129:   if (ma!=nb || na!=mb) {
2130:     *f = PETSC_FALSE;
2131:     return(0);
2132:   }
2133:   aii  = aij->i; bii = bij->i;
2134:   adx  = aij->j; bdx = bij->j;
2135:   va   = aij->a; vb = bij->a;
2136:   PetscMalloc1(ma,&aptr);
2137:   PetscMalloc1(mb,&bptr);
2138:   for (i=0; i<ma; i++) aptr[i] = aii[i];
2139:   for (i=0; i<mb; i++) bptr[i] = bii[i];

2141:   *f = PETSC_TRUE;
2142:   for (i=0; i<ma; i++) {
2143:     while (aptr[i]<aii[i+1]) {
2144:       PetscInt    idc,idr;
2145:       PetscScalar vc,vr;
2146:       /* column/row index/value */
2147:       idc = adx[aptr[i]];
2148:       idr = bdx[bptr[idc]];
2149:       vc  = va[aptr[i]];
2150:       vr  = vb[bptr[idc]];
2151:       if (i!=idr || PetscAbsScalar(vc-PetscConj(vr)) > tol) {
2152:         *f = PETSC_FALSE;
2153:         goto done;
2154:       } else {
2155:         aptr[i]++;
2156:         if (B || i!=idc) bptr[idc]++;
2157:       }
2158:     }
2159:   }
2160: done:
2161:   PetscFree(aptr);
2162:   PetscFree(bptr);
2163:   return(0);
2164: }

2166: PetscErrorCode MatIsSymmetric_SeqAIJ(Mat A,PetscReal tol,PetscBool  *f)
2167: {

2171:   MatIsTranspose_SeqAIJ(A,A,tol,f);
2172:   return(0);
2173: }

2175: PetscErrorCode MatIsHermitian_SeqAIJ(Mat A,PetscReal tol,PetscBool  *f)
2176: {

2180:   MatIsHermitianTranspose_SeqAIJ(A,A,tol,f);
2181:   return(0);
2182: }

2184: PetscErrorCode MatDiagonalScale_SeqAIJ(Mat A,Vec ll,Vec rr)
2185: {
2186:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
2187:   const PetscScalar *l,*r;
2188:   PetscScalar       x;
2189:   MatScalar         *v;
2190:   PetscErrorCode    ierr;
2191:   PetscInt          i,j,m = A->rmap->n,n = A->cmap->n,M,nz = a->nz;
2192:   const PetscInt    *jj;

2195:   if (ll) {
2196:     /* The local size is used so that VecMPI can be passed to this routine
2197:        by MatDiagonalScale_MPIAIJ */
2198:     VecGetLocalSize(ll,&m);
2199:     if (m != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Left scaling vector wrong length");
2200:     VecGetArrayRead(ll,&l);
2201:     v    = a->a;
2202:     for (i=0; i<m; i++) {
2203:       x = l[i];
2204:       M = a->i[i+1] - a->i[i];
2205:       for (j=0; j<M; j++) (*v++) *= x;
2206:     }
2207:     VecRestoreArrayRead(ll,&l);
2208:     PetscLogFlops(nz);
2209:   }
2210:   if (rr) {
2211:     VecGetLocalSize(rr,&n);
2212:     if (n != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Right scaling vector wrong length");
2213:     VecGetArrayRead(rr,&r);
2214:     v    = a->a; jj = a->j;
2215:     for (i=0; i<nz; i++) (*v++) *= r[*jj++];
2216:     VecRestoreArrayRead(rr,&r);
2217:     PetscLogFlops(nz);
2218:   }
2219:   MatSeqAIJInvalidateDiagonal(A);
2220:   return(0);
2221: }

2223: PetscErrorCode MatCreateSubMatrix_SeqAIJ(Mat A,IS isrow,IS iscol,PetscInt csize,MatReuse scall,Mat *B)
2224: {
2225:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*c;
2227:   PetscInt       *smap,i,k,kstart,kend,oldcols = A->cmap->n,*lens;
2228:   PetscInt       row,mat_i,*mat_j,tcol,first,step,*mat_ilen,sum,lensi;
2229:   const PetscInt *irow,*icol;
2230:   PetscInt       nrows,ncols;
2231:   PetscInt       *starts,*j_new,*i_new,*aj = a->j,*ai = a->i,ii,*ailen = a->ilen;
2232:   MatScalar      *a_new,*mat_a;
2233:   Mat            C;
2234:   PetscBool      stride;


2238:   ISGetIndices(isrow,&irow);
2239:   ISGetLocalSize(isrow,&nrows);
2240:   ISGetLocalSize(iscol,&ncols);

2242:   PetscObjectTypeCompare((PetscObject)iscol,ISSTRIDE,&stride);
2243:   if (stride) {
2244:     ISStrideGetInfo(iscol,&first,&step);
2245:   } else {
2246:     first = 0;
2247:     step  = 0;
2248:   }
2249:   if (stride && step == 1) {
2250:     /* special case of contiguous rows */
2251:     PetscMalloc2(nrows,&lens,nrows,&starts);
2252:     /* loop over new rows determining lens and starting points */
2253:     for (i=0; i<nrows; i++) {
2254:       kstart = ai[irow[i]];
2255:       kend   = kstart + ailen[irow[i]];
2256:       starts[i] = kstart;
2257:       for (k=kstart; k<kend; k++) {
2258:         if (aj[k] >= first) {
2259:           starts[i] = k;
2260:           break;
2261:         }
2262:       }
2263:       sum = 0;
2264:       while (k < kend) {
2265:         if (aj[k++] >= first+ncols) break;
2266:         sum++;
2267:       }
2268:       lens[i] = sum;
2269:     }
2270:     /* create submatrix */
2271:     if (scall == MAT_REUSE_MATRIX) {
2272:       PetscInt n_cols,n_rows;
2273:       MatGetSize(*B,&n_rows,&n_cols);
2274:       if (n_rows != nrows || n_cols != ncols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Reused submatrix wrong size");
2275:       MatZeroEntries(*B);
2276:       C    = *B;
2277:     } else {
2278:       PetscInt rbs,cbs;
2279:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2280:       MatSetSizes(C,nrows,ncols,PETSC_DETERMINE,PETSC_DETERMINE);
2281:       ISGetBlockSize(isrow,&rbs);
2282:       ISGetBlockSize(iscol,&cbs);
2283:       MatSetBlockSizes(C,rbs,cbs);
2284:       MatSetType(C,((PetscObject)A)->type_name);
2285:       MatSeqAIJSetPreallocation_SeqAIJ(C,0,lens);
2286:     }
2287:     c = (Mat_SeqAIJ*)C->data;

2289:     /* loop over rows inserting into submatrix */
2290:     a_new = c->a;
2291:     j_new = c->j;
2292:     i_new = c->i;

2294:     for (i=0; i<nrows; i++) {
2295:       ii    = starts[i];
2296:       lensi = lens[i];
2297:       for (k=0; k<lensi; k++) {
2298:         *j_new++ = aj[ii+k] - first;
2299:       }
2300:       PetscMemcpy(a_new,a->a + starts[i],lensi*sizeof(PetscScalar));
2301:       a_new     += lensi;
2302:       i_new[i+1] = i_new[i] + lensi;
2303:       c->ilen[i] = lensi;
2304:     }
2305:     PetscFree2(lens,starts);
2306:   } else {
2307:     ISGetIndices(iscol,&icol);
2308:     PetscCalloc1(oldcols,&smap);
2309:     PetscMalloc1(1+nrows,&lens);
2310:     for (i=0; i<ncols; i++) {
2311: #if defined(PETSC_USE_DEBUG)
2312:       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);
2313: #endif
2314:       smap[icol[i]] = i+1;
2315:     }

2317:     /* determine lens of each row */
2318:     for (i=0; i<nrows; i++) {
2319:       kstart  = ai[irow[i]];
2320:       kend    = kstart + a->ilen[irow[i]];
2321:       lens[i] = 0;
2322:       for (k=kstart; k<kend; k++) {
2323:         if (smap[aj[k]]) {
2324:           lens[i]++;
2325:         }
2326:       }
2327:     }
2328:     /* Create and fill new matrix */
2329:     if (scall == MAT_REUSE_MATRIX) {
2330:       PetscBool equal;

2332:       c = (Mat_SeqAIJ*)((*B)->data);
2333:       if ((*B)->rmap->n  != nrows || (*B)->cmap->n != ncols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. wrong size");
2334:       PetscMemcmp(c->ilen,lens,(*B)->rmap->n*sizeof(PetscInt),&equal);
2335:       if (!equal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. wrong no of nonzeros");
2336:       PetscMemzero(c->ilen,(*B)->rmap->n*sizeof(PetscInt));
2337:       C    = *B;
2338:     } else {
2339:       PetscInt rbs,cbs;
2340:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2341:       MatSetSizes(C,nrows,ncols,PETSC_DETERMINE,PETSC_DETERMINE);
2342:       ISGetBlockSize(isrow,&rbs);
2343:       ISGetBlockSize(iscol,&cbs);
2344:       MatSetBlockSizes(C,rbs,cbs);
2345:       MatSetType(C,((PetscObject)A)->type_name);
2346:       MatSeqAIJSetPreallocation_SeqAIJ(C,0,lens);
2347:     }
2348:     c = (Mat_SeqAIJ*)(C->data);
2349:     for (i=0; i<nrows; i++) {
2350:       row      = irow[i];
2351:       kstart   = ai[row];
2352:       kend     = kstart + a->ilen[row];
2353:       mat_i    = c->i[i];
2354:       mat_j    = c->j + mat_i;
2355:       mat_a    = c->a + mat_i;
2356:       mat_ilen = c->ilen + i;
2357:       for (k=kstart; k<kend; k++) {
2358:         if ((tcol=smap[a->j[k]])) {
2359:           *mat_j++ = tcol - 1;
2360:           *mat_a++ = a->a[k];
2361:           (*mat_ilen)++;

2363:         }
2364:       }
2365:     }
2366:     /* Free work space */
2367:     ISRestoreIndices(iscol,&icol);
2368:     PetscFree(smap);
2369:     PetscFree(lens);
2370:     /* sort */
2371:     for (i = 0; i < nrows; i++) {
2372:       PetscInt ilen;

2374:       mat_i = c->i[i];
2375:       mat_j = c->j + mat_i;
2376:       mat_a = c->a + mat_i;
2377:       ilen  = c->ilen[i];
2378:       PetscSortIntWithScalarArray(ilen,mat_j,mat_a);
2379:     }
2380:   }
2381:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2382:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

2384:   ISRestoreIndices(isrow,&irow);
2385:   *B   = C;
2386:   return(0);
2387: }

2389: PetscErrorCode  MatGetMultiProcBlock_SeqAIJ(Mat mat,MPI_Comm subComm,MatReuse scall,Mat *subMat)
2390: {
2392:   Mat            B;

2395:   if (scall == MAT_INITIAL_MATRIX) {
2396:     MatCreate(subComm,&B);
2397:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->n,mat->cmap->n);
2398:     MatSetBlockSizesFromMats(B,mat,mat);
2399:     MatSetType(B,MATSEQAIJ);
2400:     MatDuplicateNoCreate_SeqAIJ(B,mat,MAT_COPY_VALUES,PETSC_TRUE);
2401:     *subMat = B;
2402:   } else {
2403:     MatCopy_SeqAIJ(mat,*subMat,SAME_NONZERO_PATTERN);
2404:   }
2405:   return(0);
2406: }

2408: PetscErrorCode MatILUFactor_SeqAIJ(Mat inA,IS row,IS col,const MatFactorInfo *info)
2409: {
2410:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)inA->data;
2412:   Mat            outA;
2413:   PetscBool      row_identity,col_identity;

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

2418:   ISIdentity(row,&row_identity);
2419:   ISIdentity(col,&col_identity);

2421:   outA             = inA;
2422:   outA->factortype = MAT_FACTOR_LU;
2423:   PetscFree(inA->solvertype);
2424:   PetscStrallocpy(MATSOLVERPETSC,&inA->solvertype);

2426:   PetscObjectReference((PetscObject)row);
2427:   ISDestroy(&a->row);

2429:   a->row = row;

2431:   PetscObjectReference((PetscObject)col);
2432:   ISDestroy(&a->col);

2434:   a->col = col;

2436:   /* Create the inverse permutation so that it can be used in MatLUFactorNumeric() */
2437:   ISDestroy(&a->icol);
2438:   ISInvertPermutation(col,PETSC_DECIDE,&a->icol);
2439:   PetscLogObjectParent((PetscObject)inA,(PetscObject)a->icol);

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

2446:   MatMarkDiagonal_SeqAIJ(inA);
2447:   if (row_identity && col_identity) {
2448:     MatLUFactorNumeric_SeqAIJ_inplace(outA,inA,info);
2449:   } else {
2450:     MatLUFactorNumeric_SeqAIJ_InplaceWithPerm(outA,inA,info);
2451:   }
2452:   return(0);
2453: }

2455: PetscErrorCode MatScale_SeqAIJ(Mat inA,PetscScalar alpha)
2456: {
2457:   Mat_SeqAIJ     *a     = (Mat_SeqAIJ*)inA->data;
2458:   PetscScalar    oalpha = alpha;
2460:   PetscBLASInt   one = 1,bnz;

2463:   PetscBLASIntCast(a->nz,&bnz);
2464:   PetscStackCallBLAS("BLASscal",BLASscal_(&bnz,&oalpha,a->a,&one));
2465:   PetscLogFlops(a->nz);
2466:   MatSeqAIJInvalidateDiagonal(inA);
2467:   return(0);
2468: }

2470: PetscErrorCode MatDestroySubMatrix_Private(Mat_SubSppt *submatj)
2471: {
2473:   PetscInt       i;

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

2479:     for (i=0; i<submatj->nrqr; ++i) {
2480:       PetscFree(submatj->sbuf2[i]);
2481:     }
2482:     PetscFree3(submatj->sbuf2,submatj->req_size,submatj->req_source1);

2484:     if (submatj->rbuf1) {
2485:       PetscFree(submatj->rbuf1[0]);
2486:       PetscFree(submatj->rbuf1);
2487:     }

2489:     for (i=0; i<submatj->nrqs; ++i) {
2490:       PetscFree(submatj->rbuf3[i]);
2491:     }
2492:     PetscFree3(submatj->req_source2,submatj->rbuf2,submatj->rbuf3);
2493:     PetscFree(submatj->pa);
2494:   }

2496: #if defined(PETSC_USE_CTABLE)
2497:   PetscTableDestroy((PetscTable*)&submatj->rmap);
2498:   if (submatj->cmap_loc) {PetscFree(submatj->cmap_loc);}
2499:   PetscFree(submatj->rmap_loc);
2500: #else
2501:   PetscFree(submatj->rmap);
2502: #endif

2504:   if (!submatj->allcolumns) {
2505: #if defined(PETSC_USE_CTABLE)
2506:     PetscTableDestroy((PetscTable*)&submatj->cmap);
2507: #else
2508:     PetscFree(submatj->cmap);
2509: #endif
2510:   }
2511:   PetscFree(submatj->row2proc);

2513:   PetscFree(submatj);
2514:   return(0);
2515: }

2517: PetscErrorCode MatDestroySubMatrix_SeqAIJ(Mat C)
2518: {
2520:   Mat_SeqAIJ     *c = (Mat_SeqAIJ*)C->data;
2521:   Mat_SubSppt    *submatj = c->submatis1;

2524:   submatj->destroy(C);
2525:   MatDestroySubMatrix_Private(submatj);
2526:   return(0);
2527: }

2529: PetscErrorCode MatDestroySubMatrices_SeqAIJ(PetscInt n,Mat *mat[])
2530: {
2532:   PetscInt       i;
2533:   Mat            C;
2534:   Mat_SeqAIJ     *c;
2535:   Mat_SubSppt    *submatj;

2538:   for (i=0; i<n; i++) {
2539:     C       = (*mat)[i];
2540:     c       = (Mat_SeqAIJ*)C->data;
2541:     submatj = c->submatis1;
2542:     if (submatj) {
2543:       submatj->destroy(C);
2544:       MatDestroySubMatrix_Private(submatj);
2545:       PetscLayoutDestroy(&C->rmap);
2546:       PetscLayoutDestroy(&C->cmap);
2547:       PetscHeaderDestroy(&C);
2548:     } else {
2549:       MatDestroy(&C);
2550:     }
2551:   }

2553:   PetscFree(*mat);
2554:   return(0);
2555: }

2557: PetscErrorCode MatCreateSubMatrices_SeqAIJ(Mat A,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *B[])
2558: {
2560:   PetscInt       i;

2563:   if (scall == MAT_INITIAL_MATRIX) {
2564:     PetscCalloc1(n+1,B);
2565:   }

2567:   for (i=0; i<n; i++) {
2568:     MatCreateSubMatrix_SeqAIJ(A,irow[i],icol[i],PETSC_DECIDE,scall,&(*B)[i]);
2569:   }
2570:   return(0);
2571: }

2573: PetscErrorCode MatIncreaseOverlap_SeqAIJ(Mat A,PetscInt is_max,IS is[],PetscInt ov)
2574: {
2575:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2577:   PetscInt       row,i,j,k,l,m,n,*nidx,isz,val;
2578:   const PetscInt *idx;
2579:   PetscInt       start,end,*ai,*aj;
2580:   PetscBT        table;

2583:   m  = A->rmap->n;
2584:   ai = a->i;
2585:   aj = a->j;

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

2589:   PetscMalloc1(m+1,&nidx);
2590:   PetscBTCreate(m,&table);

2592:   for (i=0; i<is_max; i++) {
2593:     /* Initialize the two local arrays */
2594:     isz  = 0;
2595:     PetscBTMemzero(m,table);

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

2601:     /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2602:     for (j=0; j<n; ++j) {
2603:       if (!PetscBTLookupSet(table,idx[j])) nidx[isz++] = idx[j];
2604:     }
2605:     ISRestoreIndices(is[i],&idx);
2606:     ISDestroy(&is[i]);

2608:     k = 0;
2609:     for (j=0; j<ov; j++) { /* for each overlap */
2610:       n = isz;
2611:       for (; k<n; k++) { /* do only those rows in nidx[k], which are not done yet */
2612:         row   = nidx[k];
2613:         start = ai[row];
2614:         end   = ai[row+1];
2615:         for (l = start; l<end; l++) {
2616:           val = aj[l];
2617:           if (!PetscBTLookupSet(table,val)) nidx[isz++] = val;
2618:         }
2619:       }
2620:     }
2621:     ISCreateGeneral(PETSC_COMM_SELF,isz,nidx,PETSC_COPY_VALUES,(is+i));
2622:   }
2623:   PetscBTDestroy(&table);
2624:   PetscFree(nidx);
2625:   return(0);
2626: }

2628: /* -------------------------------------------------------------- */
2629: PetscErrorCode MatPermute_SeqAIJ(Mat A,IS rowp,IS colp,Mat *B)
2630: {
2631:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2633:   PetscInt       i,nz = 0,m = A->rmap->n,n = A->cmap->n;
2634:   const PetscInt *row,*col;
2635:   PetscInt       *cnew,j,*lens;
2636:   IS             icolp,irowp;
2637:   PetscInt       *cwork = NULL;
2638:   PetscScalar    *vwork = NULL;

2641:   ISInvertPermutation(rowp,PETSC_DECIDE,&irowp);
2642:   ISGetIndices(irowp,&row);
2643:   ISInvertPermutation(colp,PETSC_DECIDE,&icolp);
2644:   ISGetIndices(icolp,&col);

2646:   /* determine lengths of permuted rows */
2647:   PetscMalloc1(m+1,&lens);
2648:   for (i=0; i<m; i++) lens[row[i]] = a->i[i+1] - a->i[i];
2649:   MatCreate(PetscObjectComm((PetscObject)A),B);
2650:   MatSetSizes(*B,m,n,m,n);
2651:   MatSetBlockSizesFromMats(*B,A,A);
2652:   MatSetType(*B,((PetscObject)A)->type_name);
2653:   MatSeqAIJSetPreallocation_SeqAIJ(*B,0,lens);
2654:   PetscFree(lens);

2656:   PetscMalloc1(n,&cnew);
2657:   for (i=0; i<m; i++) {
2658:     MatGetRow_SeqAIJ(A,i,&nz,&cwork,&vwork);
2659:     for (j=0; j<nz; j++) cnew[j] = col[cwork[j]];
2660:     MatSetValues_SeqAIJ(*B,1,&row[i],nz,cnew,vwork,INSERT_VALUES);
2661:     MatRestoreRow_SeqAIJ(A,i,&nz,&cwork,&vwork);
2662:   }
2663:   PetscFree(cnew);

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

2667:   MatAssemblyBegin(*B,MAT_FINAL_ASSEMBLY);
2668:   MatAssemblyEnd(*B,MAT_FINAL_ASSEMBLY);
2669:   ISRestoreIndices(irowp,&row);
2670:   ISRestoreIndices(icolp,&col);
2671:   ISDestroy(&irowp);
2672:   ISDestroy(&icolp);
2673:   return(0);
2674: }

2676: PetscErrorCode MatCopy_SeqAIJ(Mat A,Mat B,MatStructure str)
2677: {

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

2686:     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");
2687:     PetscMemcpy(b->a,a->a,(a->i[A->rmap->n])*sizeof(PetscScalar));
2688:     PetscObjectStateIncrease((PetscObject)B);
2689:   } else {
2690:     MatCopy_Basic(A,B,str);
2691:   }
2692:   return(0);
2693: }

2695: PetscErrorCode MatSetUp_SeqAIJ(Mat A)
2696: {

2700:    MatSeqAIJSetPreallocation_SeqAIJ(A,PETSC_DEFAULT,0);
2701:   return(0);
2702: }

2704: PetscErrorCode MatSeqAIJGetArray_SeqAIJ(Mat A,PetscScalar *array[])
2705: {
2706:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;

2709:   *array = a->a;
2710:   return(0);
2711: }

2713: PetscErrorCode MatSeqAIJRestoreArray_SeqAIJ(Mat A,PetscScalar *array[])
2714: {
2716:   return(0);
2717: }

2719: /*
2720:    Computes the number of nonzeros per row needed for preallocation when X and Y
2721:    have different nonzero structure.
2722: */
2723: PetscErrorCode MatAXPYGetPreallocation_SeqX_private(PetscInt m,const PetscInt *xi,const PetscInt *xj,const PetscInt *yi,const PetscInt *yj,PetscInt *nnz)
2724: {
2725:   PetscInt       i,j,k,nzx,nzy;

2728:   /* Set the number of nonzeros in the new matrix */
2729:   for (i=0; i<m; i++) {
2730:     const PetscInt *xjj = xj+xi[i],*yjj = yj+yi[i];
2731:     nzx = xi[i+1] - xi[i];
2732:     nzy = yi[i+1] - yi[i];
2733:     nnz[i] = 0;
2734:     for (j=0,k=0; j<nzx; j++) {                   /* Point in X */
2735:       for (; k<nzy && yjj[k]<xjj[j]; k++) nnz[i]++; /* Catch up to X */
2736:       if (k<nzy && yjj[k]==xjj[j]) k++;             /* Skip duplicate */
2737:       nnz[i]++;
2738:     }
2739:     for (; k<nzy; k++) nnz[i]++;
2740:   }
2741:   return(0);
2742: }

2744: PetscErrorCode MatAXPYGetPreallocation_SeqAIJ(Mat Y,Mat X,PetscInt *nnz)
2745: {
2746:   PetscInt       m = Y->rmap->N;
2747:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data;
2748:   Mat_SeqAIJ     *y = (Mat_SeqAIJ*)Y->data;

2752:   /* Set the number of nonzeros in the new matrix */
2753:   MatAXPYGetPreallocation_SeqX_private(m,x->i,x->j,y->i,y->j,nnz);
2754:   return(0);
2755: }

2757: PetscErrorCode MatAXPY_SeqAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
2758: {
2760:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data,*y = (Mat_SeqAIJ*)Y->data;
2761:   PetscBLASInt   one=1,bnz;

2764:   PetscBLASIntCast(x->nz,&bnz);
2765:   if (str == SAME_NONZERO_PATTERN) {
2766:     PetscScalar alpha = a;
2767:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2768:     MatSeqAIJInvalidateDiagonal(Y);
2769:     PetscObjectStateIncrease((PetscObject)Y);
2770:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2771:     MatAXPY_Basic(Y,a,X,str);
2772:   } else {
2773:     Mat      B;
2774:     PetscInt *nnz;
2775:     PetscMalloc1(Y->rmap->N,&nnz);
2776:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
2777:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
2778:     MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);
2779:     MatSetBlockSizesFromMats(B,Y,Y);
2780:     MatSetType(B,(MatType) ((PetscObject)Y)->type_name);
2781:     MatAXPYGetPreallocation_SeqAIJ(Y,X,nnz);
2782:     MatSeqAIJSetPreallocation(B,0,nnz);
2783:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
2784:     MatHeaderReplace(Y,&B);
2785:     PetscFree(nnz);
2786:   }
2787:   return(0);
2788: }

2790: PetscErrorCode  MatConjugate_SeqAIJ(Mat mat)
2791: {
2792: #if defined(PETSC_USE_COMPLEX)
2793:   Mat_SeqAIJ  *aij = (Mat_SeqAIJ*)mat->data;
2794:   PetscInt    i,nz;
2795:   PetscScalar *a;

2798:   nz = aij->nz;
2799:   a  = aij->a;
2800:   for (i=0; i<nz; i++) a[i] = PetscConj(a[i]);
2801: #else
2803: #endif
2804:   return(0);
2805: }

2807: PetscErrorCode MatGetRowMaxAbs_SeqAIJ(Mat A,Vec v,PetscInt idx[])
2808: {
2809:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2811:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
2812:   PetscReal      atmp;
2813:   PetscScalar    *x;
2814:   MatScalar      *aa;

2817:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2818:   aa = a->a;
2819:   ai = a->i;
2820:   aj = a->j;

2822:   VecSet(v,0.0);
2823:   VecGetArray(v,&x);
2824:   VecGetLocalSize(v,&n);
2825:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
2826:   for (i=0; i<m; i++) {
2827:     ncols = ai[1] - ai[0]; ai++;
2828:     x[i]  = 0.0;
2829:     for (j=0; j<ncols; j++) {
2830:       atmp = PetscAbsScalar(*aa);
2831:       if (PetscAbsScalar(x[i]) < atmp) {x[i] = atmp; if (idx) idx[i] = *aj;}
2832:       aa++; aj++;
2833:     }
2834:   }
2835:   VecRestoreArray(v,&x);
2836:   return(0);
2837: }

2839: PetscErrorCode MatGetRowMax_SeqAIJ(Mat A,Vec v,PetscInt idx[])
2840: {
2841:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2843:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
2844:   PetscScalar    *x;
2845:   MatScalar      *aa;

2848:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2849:   aa = a->a;
2850:   ai = a->i;
2851:   aj = a->j;

2853:   VecSet(v,0.0);
2854:   VecGetArray(v,&x);
2855:   VecGetLocalSize(v,&n);
2856:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
2857:   for (i=0; i<m; i++) {
2858:     ncols = ai[1] - ai[0]; ai++;
2859:     if (ncols == A->cmap->n) { /* row is dense */
2860:       x[i] = *aa; if (idx) idx[i] = 0;
2861:     } else {  /* row is sparse so already KNOW maximum is 0.0 or higher */
2862:       x[i] = 0.0;
2863:       if (idx) {
2864:         idx[i] = 0; /* in case ncols is zero */
2865:         for (j=0;j<ncols;j++) { /* find first implicit 0.0 in the row */
2866:           if (aj[j] > j) {
2867:             idx[i] = j;
2868:             break;
2869:           }
2870:         }
2871:       }
2872:     }
2873:     for (j=0; j<ncols; j++) {
2874:       if (PetscRealPart(x[i]) < PetscRealPart(*aa)) {x[i] = *aa; if (idx) idx[i] = *aj;}
2875:       aa++; aj++;
2876:     }
2877:   }
2878:   VecRestoreArray(v,&x);
2879:   return(0);
2880: }

2882: PetscErrorCode MatGetRowMinAbs_SeqAIJ(Mat A,Vec v,PetscInt idx[])
2883: {
2884:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2886:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
2887:   PetscReal      atmp;
2888:   PetscScalar    *x;
2889:   MatScalar      *aa;

2892:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2893:   aa = a->a;
2894:   ai = a->i;
2895:   aj = a->j;

2897:   VecSet(v,0.0);
2898:   VecGetArray(v,&x);
2899:   VecGetLocalSize(v,&n);
2900:   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);
2901:   for (i=0; i<m; i++) {
2902:     ncols = ai[1] - ai[0]; ai++;
2903:     if (ncols) {
2904:       /* Get first nonzero */
2905:       for (j = 0; j < ncols; j++) {
2906:         atmp = PetscAbsScalar(aa[j]);
2907:         if (atmp > 1.0e-12) {
2908:           x[i] = atmp;
2909:           if (idx) idx[i] = aj[j];
2910:           break;
2911:         }
2912:       }
2913:       if (j == ncols) {x[i] = PetscAbsScalar(*aa); if (idx) idx[i] = *aj;}
2914:     } else {
2915:       x[i] = 0.0; if (idx) idx[i] = 0;
2916:     }
2917:     for (j = 0; j < ncols; j++) {
2918:       atmp = PetscAbsScalar(*aa);
2919:       if (atmp > 1.0e-12 && PetscAbsScalar(x[i]) > atmp) {x[i] = atmp; if (idx) idx[i] = *aj;}
2920:       aa++; aj++;
2921:     }
2922:   }
2923:   VecRestoreArray(v,&x);
2924:   return(0);
2925: }

2927: PetscErrorCode MatGetRowMin_SeqAIJ(Mat A,Vec v,PetscInt idx[])
2928: {
2929:   Mat_SeqAIJ      *a = (Mat_SeqAIJ*)A->data;
2930:   PetscErrorCode  ierr;
2931:   PetscInt        i,j,m = A->rmap->n,ncols,n;
2932:   const PetscInt  *ai,*aj;
2933:   PetscScalar     *x;
2934:   const MatScalar *aa;

2937:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2938:   aa = a->a;
2939:   ai = a->i;
2940:   aj = a->j;

2942:   VecSet(v,0.0);
2943:   VecGetArray(v,&x);
2944:   VecGetLocalSize(v,&n);
2945:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
2946:   for (i=0; i<m; i++) {
2947:     ncols = ai[1] - ai[0]; ai++;
2948:     if (ncols == A->cmap->n) { /* row is dense */
2949:       x[i] = *aa; if (idx) idx[i] = 0;
2950:     } else {  /* row is sparse so already KNOW minimum is 0.0 or lower */
2951:       x[i] = 0.0;
2952:       if (idx) {   /* find first implicit 0.0 in the row */
2953:         idx[i] = 0; /* in case ncols is zero */
2954:         for (j=0; j<ncols; j++) {
2955:           if (aj[j] > j) {
2956:             idx[i] = j;
2957:             break;
2958:           }
2959:         }
2960:       }
2961:     }
2962:     for (j=0; j<ncols; j++) {
2963:       if (PetscRealPart(x[i]) > PetscRealPart(*aa)) {x[i] = *aa; if (idx) idx[i] = *aj;}
2964:       aa++; aj++;
2965:     }
2966:   }
2967:   VecRestoreArray(v,&x);
2968:   return(0);
2969: }

2971:  #include <petscblaslapack.h>
2972:  #include <petsc/private/kernels/blockinvert.h>

2974: PetscErrorCode MatInvertBlockDiagonal_SeqAIJ(Mat A,const PetscScalar **values)
2975: {
2976:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*) A->data;
2978:   PetscInt       i,bs = PetscAbs(A->rmap->bs),mbs = A->rmap->n/bs,ipvt[5],bs2 = bs*bs,*v_pivots,ij[7],*IJ,j;
2979:   MatScalar      *diag,work[25],*v_work;
2980:   PetscReal      shift = 0.0;
2981:   PetscBool      allowzeropivot,zeropivotdetected=PETSC_FALSE;

2984:   allowzeropivot = PetscNot(A->erroriffailure);
2985:   if (a->ibdiagvalid) {
2986:     if (values) *values = a->ibdiag;
2987:     return(0);
2988:   }
2989:   MatMarkDiagonal_SeqAIJ(A);
2990:   if (!a->ibdiag) {
2991:     PetscMalloc1(bs2*mbs,&a->ibdiag);
2992:     PetscLogObjectMemory((PetscObject)A,bs2*mbs*sizeof(PetscScalar));
2993:   }
2994:   diag = a->ibdiag;
2995:   if (values) *values = a->ibdiag;
2996:   /* factor and invert each block */
2997:   switch (bs) {
2998:   case 1:
2999:     for (i=0; i<mbs; i++) {
3000:       MatGetValues(A,1,&i,1,&i,diag+i);
3001:       if (PetscAbsScalar(diag[i] + shift) < PETSC_MACHINE_EPSILON) {
3002:         if (allowzeropivot) {
3003:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3004:           A->factorerror_zeropivot_value = PetscAbsScalar(diag[i]);
3005:           A->factorerror_zeropivot_row   = i;
3006:           PetscInfo3(A,"Zero pivot, row %D pivot %g tolerance %g\n",i,(double)PetscAbsScalar(diag[i]),(double)PETSC_MACHINE_EPSILON);
3007:         } 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);
3008:       }
3009:       diag[i] = (PetscScalar)1.0 / (diag[i] + shift);
3010:     }
3011:     break;
3012:   case 2:
3013:     for (i=0; i<mbs; i++) {
3014:       ij[0] = 2*i; ij[1] = 2*i + 1;
3015:       MatGetValues(A,2,ij,2,ij,diag);
3016:       PetscKernel_A_gets_inverse_A_2(diag,shift,allowzeropivot,&zeropivotdetected);
3017:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3018:       PetscKernel_A_gets_transpose_A_2(diag);
3019:       diag += 4;
3020:     }
3021:     break;
3022:   case 3:
3023:     for (i=0; i<mbs; i++) {
3024:       ij[0] = 3*i; ij[1] = 3*i + 1; ij[2] = 3*i + 2;
3025:       MatGetValues(A,3,ij,3,ij,diag);
3026:       PetscKernel_A_gets_inverse_A_3(diag,shift,allowzeropivot,&zeropivotdetected);
3027:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3028:       PetscKernel_A_gets_transpose_A_3(diag);
3029:       diag += 9;
3030:     }
3031:     break;
3032:   case 4:
3033:     for (i=0; i<mbs; i++) {
3034:       ij[0] = 4*i; ij[1] = 4*i + 1; ij[2] = 4*i + 2; ij[3] = 4*i + 3;
3035:       MatGetValues(A,4,ij,4,ij,diag);
3036:       PetscKernel_A_gets_inverse_A_4(diag,shift,allowzeropivot,&zeropivotdetected);
3037:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3038:       PetscKernel_A_gets_transpose_A_4(diag);
3039:       diag += 16;
3040:     }
3041:     break;
3042:   case 5:
3043:     for (i=0; i<mbs; i++) {
3044:       ij[0] = 5*i; ij[1] = 5*i + 1; ij[2] = 5*i + 2; ij[3] = 5*i + 3; ij[4] = 5*i + 4;
3045:       MatGetValues(A,5,ij,5,ij,diag);
3046:       PetscKernel_A_gets_inverse_A_5(diag,ipvt,work,shift,allowzeropivot,&zeropivotdetected);
3047:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3048:       PetscKernel_A_gets_transpose_A_5(diag);
3049:       diag += 25;
3050:     }
3051:     break;
3052:   case 6:
3053:     for (i=0; i<mbs; i++) {
3054:       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;
3055:       MatGetValues(A,6,ij,6,ij,diag);
3056:       PetscKernel_A_gets_inverse_A_6(diag,shift,allowzeropivot,&zeropivotdetected);
3057:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3058:       PetscKernel_A_gets_transpose_A_6(diag);
3059:       diag += 36;
3060:     }
3061:     break;
3062:   case 7:
3063:     for (i=0; i<mbs; i++) {
3064:       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;
3065:       MatGetValues(A,7,ij,7,ij,diag);
3066:       PetscKernel_A_gets_inverse_A_7(diag,shift,allowzeropivot,&zeropivotdetected);
3067:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3068:       PetscKernel_A_gets_transpose_A_7(diag);
3069:       diag += 49;
3070:     }
3071:     break;
3072:   default:
3073:     PetscMalloc3(bs,&v_work,bs,&v_pivots,bs,&IJ);
3074:     for (i=0; i<mbs; i++) {
3075:       for (j=0; j<bs; j++) {
3076:         IJ[j] = bs*i + j;
3077:       }
3078:       MatGetValues(A,bs,IJ,bs,IJ,diag);
3079:       PetscKernel_A_gets_inverse_A(bs,diag,v_pivots,v_work,allowzeropivot,&zeropivotdetected);
3080:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3081:       PetscKernel_A_gets_transpose_A_N(diag,bs);
3082:       diag += bs2;
3083:     }
3084:     PetscFree3(v_work,v_pivots,IJ);
3085:   }
3086:   a->ibdiagvalid = PETSC_TRUE;
3087:   return(0);
3088: }

3090: static PetscErrorCode  MatSetRandom_SeqAIJ(Mat x,PetscRandom rctx)
3091: {
3093:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)x->data;
3094:   PetscScalar    a;
3095:   PetscInt       m,n,i,j,col;

3098:   if (!x->assembled) {
3099:     MatGetSize(x,&m,&n);
3100:     for (i=0; i<m; i++) {
3101:       for (j=0; j<aij->imax[i]; j++) {
3102:         PetscRandomGetValue(rctx,&a);
3103:         col  = (PetscInt)(n*PetscRealPart(a));
3104:         MatSetValues(x,1,&i,1,&col,&a,ADD_VALUES);
3105:       }
3106:     }
3107:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not yet coded");
3108:   MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);
3109:   MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);
3110:   return(0);
3111: }

3113: PetscErrorCode MatShift_SeqAIJ(Mat Y,PetscScalar a)
3114: {
3116:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)Y->data;

3119:   if (!Y->preallocated || !aij->nz) {
3120:     MatSeqAIJSetPreallocation(Y,1,NULL);
3121:   }
3122:   MatShift_Basic(Y,a);
3123:   return(0);
3124: }

3126: /* -------------------------------------------------------------------*/
3127: static struct _MatOps MatOps_Values = { MatSetValues_SeqAIJ,
3128:                                         MatGetRow_SeqAIJ,
3129:                                         MatRestoreRow_SeqAIJ,
3130:                                         MatMult_SeqAIJ,
3131:                                 /*  4*/ MatMultAdd_SeqAIJ,
3132:                                         MatMultTranspose_SeqAIJ,
3133:                                         MatMultTransposeAdd_SeqAIJ,
3134:                                         0,
3135:                                         0,
3136:                                         0,
3137:                                 /* 10*/ 0,
3138:                                         MatLUFactor_SeqAIJ,
3139:                                         0,
3140:                                         MatSOR_SeqAIJ,
3141:                                         MatTranspose_SeqAIJ,
3142:                                 /*1 5*/ MatGetInfo_SeqAIJ,
3143:                                         MatEqual_SeqAIJ,
3144:                                         MatGetDiagonal_SeqAIJ,
3145:                                         MatDiagonalScale_SeqAIJ,
3146:                                         MatNorm_SeqAIJ,
3147:                                 /* 20*/ 0,
3148:                                         MatAssemblyEnd_SeqAIJ,
3149:                                         MatSetOption_SeqAIJ,
3150:                                         MatZeroEntries_SeqAIJ,
3151:                                 /* 24*/ MatZeroRows_SeqAIJ,
3152:                                         0,
3153:                                         0,
3154:                                         0,
3155:                                         0,
3156:                                 /* 29*/ MatSetUp_SeqAIJ,
3157:                                         0,
3158:                                         0,
3159:                                         0,
3160:                                         0,
3161:                                 /* 34*/ MatDuplicate_SeqAIJ,
3162:                                         0,
3163:                                         0,
3164:                                         MatILUFactor_SeqAIJ,
3165:                                         0,
3166:                                 /* 39*/ MatAXPY_SeqAIJ,
3167:                                         MatCreateSubMatrices_SeqAIJ,
3168:                                         MatIncreaseOverlap_SeqAIJ,
3169:                                         MatGetValues_SeqAIJ,
3170:                                         MatCopy_SeqAIJ,
3171:                                 /* 44*/ MatGetRowMax_SeqAIJ,
3172:                                         MatScale_SeqAIJ,
3173:                                         MatShift_SeqAIJ,
3174:                                         MatDiagonalSet_SeqAIJ,
3175:                                         MatZeroRowsColumns_SeqAIJ,
3176:                                 /* 49*/ MatSetRandom_SeqAIJ,
3177:                                         MatGetRowIJ_SeqAIJ,
3178:                                         MatRestoreRowIJ_SeqAIJ,
3179:                                         MatGetColumnIJ_SeqAIJ,
3180:                                         MatRestoreColumnIJ_SeqAIJ,
3181:                                 /* 54*/ MatFDColoringCreate_SeqXAIJ,
3182:                                         0,
3183:                                         0,
3184:                                         MatPermute_SeqAIJ,
3185:                                         0,
3186:                                 /* 59*/ 0,
3187:                                         MatDestroy_SeqAIJ,
3188:                                         MatView_SeqAIJ,
3189:                                         0,
3190:                                         MatMatMatMult_SeqAIJ_SeqAIJ_SeqAIJ,
3191:                                 /* 64*/ MatMatMatMultSymbolic_SeqAIJ_SeqAIJ_SeqAIJ,
3192:                                         MatMatMatMultNumeric_SeqAIJ_SeqAIJ_SeqAIJ,
3193:                                         0,
3194:                                         0,
3195:                                         0,
3196:                                 /* 69*/ MatGetRowMaxAbs_SeqAIJ,
3197:                                         MatGetRowMinAbs_SeqAIJ,
3198:                                         0,
3199:                                         0,
3200:                                         0,
3201:                                 /* 74*/ 0,
3202:                                         MatFDColoringApply_AIJ,
3203:                                         0,
3204:                                         0,
3205:                                         0,
3206:                                 /* 79*/ MatFindZeroDiagonals_SeqAIJ,
3207:                                         0,
3208:                                         0,
3209:                                         0,
3210:                                         MatLoad_SeqAIJ,
3211:                                 /* 84*/ MatIsSymmetric_SeqAIJ,
3212:                                         MatIsHermitian_SeqAIJ,
3213:                                         0,
3214:                                         0,
3215:                                         0,
3216:                                 /* 89*/ MatMatMult_SeqAIJ_SeqAIJ,
3217:                                         MatMatMultSymbolic_SeqAIJ_SeqAIJ,
3218:                                         MatMatMultNumeric_SeqAIJ_SeqAIJ,
3219:                                         MatPtAP_SeqAIJ_SeqAIJ,
3220:                                         MatPtAPSymbolic_SeqAIJ_SeqAIJ_SparseAxpy,
3221:                                 /* 94*/ MatPtAPNumeric_SeqAIJ_SeqAIJ_SparseAxpy,
3222:                                         MatMatTransposeMult_SeqAIJ_SeqAIJ,
3223:                                         MatMatTransposeMultSymbolic_SeqAIJ_SeqAIJ,
3224:                                         MatMatTransposeMultNumeric_SeqAIJ_SeqAIJ,
3225:                                         0,
3226:                                 /* 99*/ 0,
3227:                                         0,
3228:                                         0,
3229:                                         MatConjugate_SeqAIJ,
3230:                                         0,
3231:                                 /*104*/ MatSetValuesRow_SeqAIJ,
3232:                                         MatRealPart_SeqAIJ,
3233:                                         MatImaginaryPart_SeqAIJ,
3234:                                         0,
3235:                                         0,
3236:                                 /*109*/ MatMatSolve_SeqAIJ,
3237:                                         0,
3238:                                         MatGetRowMin_SeqAIJ,
3239:                                         0,
3240:                                         MatMissingDiagonal_SeqAIJ,
3241:                                 /*114*/ 0,
3242:                                         0,
3243:                                         0,
3244:                                         0,
3245:                                         0,
3246:                                 /*119*/ 0,
3247:                                         0,
3248:                                         0,
3249:                                         0,
3250:                                         MatGetMultiProcBlock_SeqAIJ,
3251:                                 /*124*/ MatFindNonzeroRows_SeqAIJ,
3252:                                         MatGetColumnNorms_SeqAIJ,
3253:                                         MatInvertBlockDiagonal_SeqAIJ,
3254:                                         0,
3255:                                         0,
3256:                                 /*129*/ 0,
3257:                                         MatTransposeMatMult_SeqAIJ_SeqAIJ,
3258:                                         MatTransposeMatMultSymbolic_SeqAIJ_SeqAIJ,
3259:                                         MatTransposeMatMultNumeric_SeqAIJ_SeqAIJ,
3260:                                         MatTransposeColoringCreate_SeqAIJ,
3261:                                 /*134*/ MatTransColoringApplySpToDen_SeqAIJ,
3262:                                         MatTransColoringApplyDenToSp_SeqAIJ,
3263:                                         MatRARt_SeqAIJ_SeqAIJ,
3264:                                         MatRARtSymbolic_SeqAIJ_SeqAIJ,
3265:                                         MatRARtNumeric_SeqAIJ_SeqAIJ,
3266:                                  /*139*/0,
3267:                                         0,
3268:                                         0,
3269:                                         MatFDColoringSetUp_SeqXAIJ,
3270:                                         MatFindOffBlockDiagonalEntries_SeqAIJ,
3271:                                  /*144*/MatCreateMPIMatConcatenateSeqMat_SeqAIJ,
3272:                                         MatDestroySubMatrices_SeqAIJ
3273: };

3275: PetscErrorCode  MatSeqAIJSetColumnIndices_SeqAIJ(Mat mat,PetscInt *indices)
3276: {
3277:   Mat_SeqAIJ *aij = (Mat_SeqAIJ*)mat->data;
3278:   PetscInt   i,nz,n;

3281:   nz = aij->maxnz;
3282:   n  = mat->rmap->n;
3283:   for (i=0; i<nz; i++) {
3284:     aij->j[i] = indices[i];
3285:   }
3286:   aij->nz = nz;
3287:   for (i=0; i<n; i++) {
3288:     aij->ilen[i] = aij->imax[i];
3289:   }
3290:   return(0);
3291: }

3293: /*@
3294:     MatSeqAIJSetColumnIndices - Set the column indices for all the rows
3295:        in the matrix.

3297:   Input Parameters:
3298: +  mat - the SeqAIJ matrix
3299: -  indices - the column indices

3301:   Level: advanced

3303:   Notes:
3304:     This can be called if you have precomputed the nonzero structure of the
3305:   matrix and want to provide it to the matrix object to improve the performance
3306:   of the MatSetValues() operation.

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

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

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

3315: @*/
3316: PetscErrorCode  MatSeqAIJSetColumnIndices(Mat mat,PetscInt *indices)
3317: {

3323:   PetscUseMethod(mat,"MatSeqAIJSetColumnIndices_C",(Mat,PetscInt*),(mat,indices));
3324:   return(0);
3325: }

3327: /* ----------------------------------------------------------------------------------------*/

3329: PetscErrorCode  MatStoreValues_SeqAIJ(Mat mat)
3330: {
3331:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)mat->data;
3333:   size_t         nz = aij->i[mat->rmap->n];

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

3338:   /* allocate space for values if not already there */
3339:   if (!aij->saved_values) {
3340:     PetscMalloc1(nz+1,&aij->saved_values);
3341:     PetscLogObjectMemory((PetscObject)mat,(nz+1)*sizeof(PetscScalar));
3342:   }

3344:   /* copy values over */
3345:   PetscMemcpy(aij->saved_values,aij->a,nz*sizeof(PetscScalar));
3346:   return(0);
3347: }

3349: /*@
3350:     MatStoreValues - Stashes a copy of the matrix values; this allows, for
3351:        example, reuse of the linear part of a Jacobian, while recomputing the
3352:        nonlinear portion.

3354:    Collect on Mat

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

3359:   Level: advanced

3361:   Common Usage, with SNESSolve():
3362: $    Create Jacobian matrix
3363: $    Set linear terms into matrix
3364: $    Apply boundary conditions to matrix, at this time matrix must have
3365: $      final nonzero structure (i.e. setting the nonlinear terms and applying
3366: $      boundary conditions again will not change the nonzero structure
3367: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3368: $    MatStoreValues(mat);
3369: $    Call SNESSetJacobian() with matrix
3370: $    In your Jacobian routine
3371: $      MatRetrieveValues(mat);
3372: $      Set nonlinear terms in matrix

3374:   Common Usage without SNESSolve(), i.e. when you handle nonlinear solve yourself:
3375: $    // build linear portion of Jacobian
3376: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3377: $    MatStoreValues(mat);
3378: $    loop over nonlinear iterations
3379: $       MatRetrieveValues(mat);
3380: $       // call MatSetValues(mat,...) to set nonliner portion of Jacobian
3381: $       // call MatAssemblyBegin/End() on matrix
3382: $       Solve linear system with Jacobian
3383: $    endloop

3385:   Notes:
3386:     Matrix must already be assemblied before calling this routine
3387:     Must set the matrix option MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE); before
3388:     calling this routine.

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

3393: .seealso: MatRetrieveValues()

3395: @*/
3396: PetscErrorCode  MatStoreValues(Mat mat)
3397: {

3402:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3403:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3404:   PetscUseMethod(mat,"MatStoreValues_C",(Mat),(mat));
3405:   return(0);
3406: }

3408: PetscErrorCode  MatRetrieveValues_SeqAIJ(Mat mat)
3409: {
3410:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)mat->data;
3412:   PetscInt       nz = aij->i[mat->rmap->n];

3415:   if (!aij->nonew) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");
3416:   if (!aij->saved_values) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call MatStoreValues(A);first");
3417:   /* copy values over */
3418:   PetscMemcpy(aij->a,aij->saved_values,nz*sizeof(PetscScalar));
3419:   return(0);
3420: }

3422: /*@
3423:     MatRetrieveValues - Retrieves the copy of the matrix values; this allows, for
3424:        example, reuse of the linear part of a Jacobian, while recomputing the
3425:        nonlinear portion.

3427:    Collect on Mat

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

3432:   Level: advanced

3434: .seealso: MatStoreValues()

3436: @*/
3437: PetscErrorCode  MatRetrieveValues(Mat mat)
3438: {

3443:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3444:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3445:   PetscUseMethod(mat,"MatRetrieveValues_C",(Mat),(mat));
3446:   return(0);
3447: }


3450: /* --------------------------------------------------------------------------------*/
3451: /*@C
3452:    MatCreateSeqAIJ - Creates a sparse matrix in AIJ (compressed row) format
3453:    (the default parallel PETSc format).  For good matrix assembly performance
3454:    the user should preallocate the matrix storage by setting the parameter nz
3455:    (or the array nnz).  By setting these parameters accurately, performance
3456:    during matrix assembly can be increased by more than a factor of 50.

3458:    Collective on MPI_Comm

3460:    Input Parameters:
3461: +  comm - MPI communicator, set to PETSC_COMM_SELF
3462: .  m - number of rows
3463: .  n - number of columns
3464: .  nz - number of nonzeros per row (same for all rows)
3465: -  nnz - array containing the number of nonzeros in the various rows
3466:          (possibly different for each row) or NULL

3468:    Output Parameter:
3469: .  A - the matrix

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

3475:    Notes:
3476:    If nnz is given then nz is ignored

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

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

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

3493:    Options Database Keys:
3494: +  -mat_no_inode  - Do not use inodes
3495: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3497:    Level: intermediate

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

3501: @*/
3502: PetscErrorCode  MatCreateSeqAIJ(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt nz,const PetscInt nnz[],Mat *A)
3503: {

3507:   MatCreate(comm,A);
3508:   MatSetSizes(*A,m,n,m,n);
3509:   MatSetType(*A,MATSEQAIJ);
3510:   MatSeqAIJSetPreallocation_SeqAIJ(*A,nz,nnz);
3511:   return(0);
3512: }

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

3520:    Collective on MPI_Comm

3522:    Input Parameters:
3523: +  B - The matrix
3524: .  nz - number of nonzeros per row (same for all rows)
3525: -  nnz - array containing the number of nonzeros in the various rows
3526:          (possibly different for each row) or NULL

3528:    Notes:
3529:      If nnz is given then nz is ignored

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

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

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

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

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

3554:    Options Database Keys:
3555: +  -mat_no_inode  - Do not use inodes
3556: .  -mat_inode_limit <limit> - Sets inode limit (max limit=5)
3557: -  -mat_aij_oneindex - Internally use indexing starting at 1
3558:         rather than 0.  Note that when calling MatSetValues(),
3559:         the user still MUST index entries starting at 0!

3561:    Level: intermediate

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

3565: @*/
3566: PetscErrorCode  MatSeqAIJSetPreallocation(Mat B,PetscInt nz,const PetscInt nnz[])
3567: {

3573:   PetscTryMethod(B,"MatSeqAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[]),(B,nz,nnz));
3574:   return(0);
3575: }

3577: PetscErrorCode  MatSeqAIJSetPreallocation_SeqAIJ(Mat B,PetscInt nz,const PetscInt *nnz)
3578: {
3579:   Mat_SeqAIJ     *b;
3580:   PetscBool      skipallocation = PETSC_FALSE,realalloc = PETSC_FALSE;
3582:   PetscInt       i;

3585:   if (nz >= 0 || nnz) realalloc = PETSC_TRUE;
3586:   if (nz == MAT_SKIP_ALLOCATION) {
3587:     skipallocation = PETSC_TRUE;
3588:     nz             = 0;
3589:   }
3590:   PetscLayoutSetUp(B->rmap);
3591:   PetscLayoutSetUp(B->cmap);

3593:   if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 5;
3594:   if (nz < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"nz cannot be less than 0: value %D",nz);
3595:   if (nnz) {
3596:     for (i=0; i<B->rmap->n; i++) {
3597:       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]);
3598:       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);
3599:     }
3600:   }

3602:   B->preallocated = PETSC_TRUE;

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

3606:   if (!skipallocation) {
3607:     if (!b->imax) {
3608:       PetscMalloc2(B->rmap->n,&b->imax,B->rmap->n,&b->ilen);
3609:       PetscLogObjectMemory((PetscObject)B,2*B->rmap->n*sizeof(PetscInt));
3610:     }
3611:     if (!nnz) {
3612:       if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 10;
3613:       else if (nz < 0) nz = 1;
3614:       for (i=0; i<B->rmap->n; i++) b->imax[i] = nz;
3615:       nz = nz*B->rmap->n;
3616:     } else {
3617:       nz = 0;
3618:       for (i=0; i<B->rmap->n; i++) {b->imax[i] = nnz[i]; nz += nnz[i];}
3619:     }
3620:     /* b->ilen will count nonzeros in each row so far. */
3621:     for (i=0; i<B->rmap->n; i++) b->ilen[i] = 0;

3623:     /* allocate the matrix space */
3624:     /* FIXME: should B's old memory be unlogged? */
3625:     MatSeqXAIJFreeAIJ(B,&b->a,&b->j,&b->i);
3626:     if (B->structure_only) {
3627:       PetscMalloc1(nz,&b->j);
3628:       PetscMalloc1(B->rmap->n+1,&b->i);
3629:       PetscLogObjectMemory((PetscObject)B,(B->rmap->n+1)*sizeof(PetscInt)+nz*sizeof(PetscInt));
3630:     } else {
3631:       PetscMalloc3(nz,&b->a,nz,&b->j,B->rmap->n+1,&b->i);
3632:       PetscLogObjectMemory((PetscObject)B,(B->rmap->n+1)*sizeof(PetscInt)+nz*(sizeof(PetscScalar)+sizeof(PetscInt)));
3633:     }
3634:     b->i[0] = 0;
3635:     for (i=1; i<B->rmap->n+1; i++) {
3636:       b->i[i] = b->i[i-1] + b->imax[i-1];
3637:     }
3638:     if (B->structure_only) {
3639:       b->singlemalloc = PETSC_FALSE;
3640:       b->free_a       = PETSC_FALSE;
3641:     } else {
3642:       b->singlemalloc = PETSC_TRUE;
3643:       b->free_a       = PETSC_TRUE;
3644:     }
3645:     b->free_ij      = PETSC_TRUE;
3646:   } else {
3647:     b->free_a  = PETSC_FALSE;
3648:     b->free_ij = PETSC_FALSE;
3649:   }

3651:   b->nz               = 0;
3652:   b->maxnz            = nz;
3653:   B->info.nz_unneeded = (double)b->maxnz;
3654:   if (realalloc) {
3655:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
3656:   }
3657:   B->was_assembled = PETSC_FALSE;
3658:   B->assembled     = PETSC_FALSE;
3659:   return(0);
3660: }

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

3665:    Input Parameters:
3666: +  B - the matrix
3667: .  i - the indices into j for the start of each row (starts with zero)
3668: .  j - the column indices for each row (starts with zero) these must be sorted for each row
3669: -  v - optional values in the matrix

3671:    Level: developer

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

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

3677: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatSeqAIJSetPreallocation(), MatCreateSeqAIJ(), SeqAIJ
3678: @*/
3679: PetscErrorCode MatSeqAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[],const PetscScalar v[])
3680: {

3686:   PetscTryMethod(B,"MatSeqAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));
3687:   return(0);
3688: }

3690: PetscErrorCode  MatSeqAIJSetPreallocationCSR_SeqAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
3691: {
3692:   PetscInt       i;
3693:   PetscInt       m,n;
3694:   PetscInt       nz;
3695:   PetscInt       *nnz, nz_max = 0;
3696:   PetscScalar    *values;

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

3702:   PetscLayoutSetUp(B->rmap);
3703:   PetscLayoutSetUp(B->cmap);

3705:   MatGetSize(B, &m, &n);
3706:   PetscMalloc1(m+1, &nnz);
3707:   for (i = 0; i < m; i++) {
3708:     nz     = Ii[i+1]- Ii[i];
3709:     nz_max = PetscMax(nz_max, nz);
3710:     if (nz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Local row %D has a negative number of columns %D", i, nnz);
3711:     nnz[i] = nz;
3712:   }
3713:   MatSeqAIJSetPreallocation(B, 0, nnz);
3714:   PetscFree(nnz);

3716:   if (v) {
3717:     values = (PetscScalar*) v;
3718:   } else {
3719:     PetscCalloc1(nz_max, &values);
3720:   }

3722:   for (i = 0; i < m; i++) {
3723:     nz   = Ii[i+1] - Ii[i];
3724:     MatSetValues_SeqAIJ(B, 1, &i, nz, J+Ii[i], values + (v ? Ii[i] : 0), INSERT_VALUES);
3725:   }

3727:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3728:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

3730:   if (!v) {
3731:     PetscFree(values);
3732:   }
3733:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
3734:   return(0);
3735: }

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

3740: /*
3741:     Computes (B'*A')' since computing B*A directly is untenable

3743:                n                       p                          p
3744:         (              )       (              )         (                  )
3745:       m (      A       )  *  n (       B      )   =   m (         C        )
3746:         (              )       (              )         (                  )

3748: */
3749: PetscErrorCode MatMatMultNumeric_SeqDense_SeqAIJ(Mat A,Mat B,Mat C)
3750: {
3751:   PetscErrorCode    ierr;
3752:   Mat_SeqDense      *sub_a = (Mat_SeqDense*)A->data;
3753:   Mat_SeqAIJ        *sub_b = (Mat_SeqAIJ*)B->data;
3754:   Mat_SeqDense      *sub_c = (Mat_SeqDense*)C->data;
3755:   PetscInt          i,n,m,q,p;
3756:   const PetscInt    *ii,*idx;
3757:   const PetscScalar *b,*a,*a_q;
3758:   PetscScalar       *c,*c_q;

3761:   m    = A->rmap->n;
3762:   n    = A->cmap->n;
3763:   p    = B->cmap->n;
3764:   a    = sub_a->v;
3765:   b    = sub_b->a;
3766:   c    = sub_c->v;
3767:   PetscMemzero(c,m*p*sizeof(PetscScalar));

3769:   ii  = sub_b->i;
3770:   idx = sub_b->j;
3771:   for (i=0; i<n; i++) {
3772:     q = ii[i+1] - ii[i];
3773:     while (q-->0) {
3774:       c_q = c + m*(*idx);
3775:       a_q = a + m*i;
3776:       PetscKernelAXPY(c_q,*b,a_q,m);
3777:       idx++;
3778:       b++;
3779:     }
3780:   }
3781:   return(0);
3782: }

3784: PetscErrorCode MatMatMultSymbolic_SeqDense_SeqAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
3785: {
3787:   PetscInt       m=A->rmap->n,n=B->cmap->n;
3788:   Mat            Cmat;

3791:   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);
3792:   MatCreate(PetscObjectComm((PetscObject)A),&Cmat);
3793:   MatSetSizes(Cmat,m,n,m,n);
3794:   MatSetBlockSizesFromMats(Cmat,A,B);
3795:   MatSetType(Cmat,MATSEQDENSE);
3796:   MatSeqDenseSetPreallocation(Cmat,NULL);

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

3800:   *C = Cmat;
3801:   return(0);
3802: }

3804: /* ----------------------------------------------------------------*/
3805: PETSC_INTERN PetscErrorCode MatMatMult_SeqDense_SeqAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
3806: {

3810:   if (scall == MAT_INITIAL_MATRIX) {
3811:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
3812:     MatMatMultSymbolic_SeqDense_SeqAIJ(A,B,fill,C);
3813:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
3814:   }
3815:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
3816:   MatMatMultNumeric_SeqDense_SeqAIJ(A,B,*C);
3817:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
3818:   return(0);
3819: }


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

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

3829:   Level: beginner

3831: .seealso: MatCreateSeqAIJ(), MatSetFromOptions(), MatSetType(), MatCreate(), MatType
3832: M*/

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

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

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

3846:   Developer Notes: Subclasses include MATAIJCUSP, MATAIJPERM, MATAIJMKL, MATAIJCRL, and also automatically switches over to use inodes when
3847:    enough exist.

3849:   Level: beginner

3851: .seealso: MatCreateAIJ(), MatCreateSeqAIJ(), MATSEQAIJ,MATMPIAIJ
3852: M*/

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

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

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

3866:   Level: beginner

3868: .seealso: MatCreateMPIAIJCRL,MATSEQAIJCRL,MATMPIAIJCRL, MATSEQAIJCRL, MATMPIAIJCRL
3869: M*/

3871: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCRL(Mat,MatType,MatReuse,Mat*);
3872: #if defined(PETSC_HAVE_ELEMENTAL)
3873: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_Elemental(Mat,MatType,MatReuse,Mat*);
3874: #endif
3875: #if defined(PETSC_HAVE_HYPRE)
3876: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat A,MatType,MatReuse,Mat*);
3877: PETSC_INTERN PetscErrorCode MatMatMatMult_Transpose_AIJ_AIJ(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
3878: #endif
3879: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqDense(Mat,MatType,MatReuse,Mat*);

3881: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3882: PETSC_EXTERN PetscErrorCode  MatlabEnginePut_SeqAIJ(PetscObject,void*);
3883: PETSC_EXTERN PetscErrorCode  MatlabEngineGet_SeqAIJ(PetscObject,void*);
3884: #endif

3886: PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqELL(Mat,MatType,MatReuse,Mat*);

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

3891:    Not Collective

3893:    Input Parameter:
3894: .  mat - a MATSEQAIJ matrix

3896:    Output Parameter:
3897: .   array - pointer to the data

3899:    Level: intermediate

3901: .seealso: MatSeqAIJRestoreArray(), MatSeqAIJGetArrayF90()
3902: @*/
3903: PetscErrorCode  MatSeqAIJGetArray(Mat A,PetscScalar **array)
3904: {

3908:   PetscUseMethod(A,"MatSeqAIJGetArray_C",(Mat,PetscScalar**),(A,array));
3909:   return(0);
3910: }

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

3915:    Not Collective

3917:    Input Parameter:
3918: .  mat - a MATSEQAIJ matrix

3920:    Output Parameter:
3921: .   nz - the maximum number of nonzeros in any row

3923:    Level: intermediate

3925: .seealso: MatSeqAIJRestoreArray(), MatSeqAIJGetArrayF90()
3926: @*/
3927: PetscErrorCode  MatSeqAIJGetMaxRowNonzeros(Mat A,PetscInt *nz)
3928: {
3929:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)A->data;

3932:   *nz = aij->rmax;
3933:   return(0);
3934: }

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

3939:    Not Collective

3941:    Input Parameters:
3942: .  mat - a MATSEQAIJ matrix
3943: .  array - pointer to the data

3945:    Level: intermediate

3947: .seealso: MatSeqAIJGetArray(), MatSeqAIJRestoreArrayF90()
3948: @*/
3949: PetscErrorCode  MatSeqAIJRestoreArray(Mat A,PetscScalar **array)
3950: {

3954:   PetscUseMethod(A,"MatSeqAIJRestoreArray_C",(Mat,PetscScalar**),(A,array));
3955:   return(0);
3956: }

3958: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJ(Mat B)
3959: {
3960:   Mat_SeqAIJ     *b;
3962:   PetscMPIInt    size;

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

3968:   PetscNewLog(B,&b);

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

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

3974:   b->row                = 0;
3975:   b->col                = 0;
3976:   b->icol               = 0;
3977:   b->reallocs           = 0;
3978:   b->ignorezeroentries  = PETSC_FALSE;
3979:   b->roworiented        = PETSC_TRUE;
3980:   b->nonew              = 0;
3981:   b->diag               = 0;
3982:   b->solve_work         = 0;
3983:   B->spptr              = 0;
3984:   b->saved_values       = 0;
3985:   b->idiag              = 0;
3986:   b->mdiag              = 0;
3987:   b->ssor_work          = 0;
3988:   b->omega              = 1.0;
3989:   b->fshift             = 0.0;
3990:   b->idiagvalid         = PETSC_FALSE;
3991:   b->ibdiagvalid        = PETSC_FALSE;
3992:   b->keepnonzeropattern = PETSC_FALSE;

3994:   PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJ);
3995:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJGetArray_C",MatSeqAIJGetArray_SeqAIJ);
3996:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJRestoreArray_C",MatSeqAIJRestoreArray_SeqAIJ);

3998: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3999:   PetscObjectComposeFunction((PetscObject)B,"PetscMatlabEnginePut_C",MatlabEnginePut_SeqAIJ);
4000:   PetscObjectComposeFunction((PetscObject)B,"PetscMatlabEngineGet_C",MatlabEngineGet_SeqAIJ);
4001: #endif

4003:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetColumnIndices_C",MatSeqAIJSetColumnIndices_SeqAIJ);
4004:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_SeqAIJ);
4005:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_SeqAIJ);
4006:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqsbaij_C",MatConvert_SeqAIJ_SeqSBAIJ);
4007:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqbaij_C",MatConvert_SeqAIJ_SeqBAIJ);
4008:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijperm_C",MatConvert_SeqAIJ_SeqAIJPERM);
4009: #if defined(PETSC_HAVE_MKL_SPARSE)
4010:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijmkl_C",MatConvert_SeqAIJ_SeqAIJMKL);
4011: #endif
4012:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijcrl_C",MatConvert_SeqAIJ_SeqAIJCRL);
4013: #if defined(PETSC_HAVE_ELEMENTAL)
4014:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_elemental_C",MatConvert_SeqAIJ_Elemental);
4015: #endif
4016: #if defined(PETSC_HAVE_HYPRE)
4017:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_hypre_C",MatConvert_AIJ_HYPRE);
4018:   PetscObjectComposeFunction((PetscObject)B,"MatMatMatMult_transpose_seqaij_seqaij_C",MatMatMatMult_Transpose_AIJ_AIJ);
4019: #endif
4020:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqdense_C",MatConvert_SeqAIJ_SeqDense);
4021:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqell_C",MatConvert_SeqAIJ_SeqELL);
4022:   PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_SeqAIJ);
4023:   PetscObjectComposeFunction((PetscObject)B,"MatIsHermitianTranspose_C",MatIsTranspose_SeqAIJ);
4024:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetPreallocation_C",MatSeqAIJSetPreallocation_SeqAIJ);
4025:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetPreallocationCSR_C",MatSeqAIJSetPreallocationCSR_SeqAIJ);
4026:   PetscObjectComposeFunction((PetscObject)B,"MatReorderForNonzeroDiagonal_C",MatReorderForNonzeroDiagonal_SeqAIJ);
4027:   PetscObjectComposeFunction((PetscObject)B,"MatMatMult_seqdense_seqaij_C",MatMatMult_SeqDense_SeqAIJ);
4028:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultSymbolic_seqdense_seqaij_C",MatMatMultSymbolic_SeqDense_SeqAIJ);
4029:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultNumeric_seqdense_seqaij_C",MatMatMultNumeric_SeqDense_SeqAIJ);
4030:   MatCreate_SeqAIJ_Inode(B);
4031:   PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJ);
4032:   MatSeqAIJSetTypeFromOptions(B);  /* this allows changing the matrix subtype to say MATSEQAIJPERM */
4033:   return(0);
4034: }

4036: /*
4037:     Given a matrix generated with MatGetFactor() duplicates all the information in A into B
4038: */
4039: PetscErrorCode MatDuplicateNoCreate_SeqAIJ(Mat C,Mat A,MatDuplicateOption cpvalues,PetscBool mallocmatspace)
4040: {
4041:   Mat_SeqAIJ     *c,*a = (Mat_SeqAIJ*)A->data;
4043:   PetscInt       i,m = A->rmap->n;

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

4048:   C->factortype = A->factortype;
4049:   c->row        = 0;
4050:   c->col        = 0;
4051:   c->icol       = 0;
4052:   c->reallocs   = 0;

4054:   C->assembled = PETSC_TRUE;

4056:   PetscLayoutReference(A->rmap,&C->rmap);
4057:   PetscLayoutReference(A->cmap,&C->cmap);

4059:   PetscMalloc2(m,&c->imax,m,&c->ilen);
4060:   PetscLogObjectMemory((PetscObject)C, 2*m*sizeof(PetscInt));
4061:   for (i=0; i<m; i++) {
4062:     c->imax[i] = a->imax[i];
4063:     c->ilen[i] = a->ilen[i];
4064:   }

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

4071:     c->singlemalloc = PETSC_TRUE;

4073:     PetscMemcpy(c->i,a->i,(m+1)*sizeof(PetscInt));
4074:     if (m > 0) {
4075:       PetscMemcpy(c->j,a->j,(a->i[m])*sizeof(PetscInt));
4076:       if (cpvalues == MAT_COPY_VALUES) {
4077:         PetscMemcpy(c->a,a->a,(a->i[m])*sizeof(PetscScalar));
4078:       } else {
4079:         PetscMemzero(c->a,(a->i[m])*sizeof(PetscScalar));
4080:       }
4081:     }
4082:   }

4084:   c->ignorezeroentries = a->ignorezeroentries;
4085:   c->roworiented       = a->roworiented;
4086:   c->nonew             = a->nonew;
4087:   if (a->diag) {
4088:     PetscMalloc1(m+1,&c->diag);
4089:     PetscLogObjectMemory((PetscObject)C,(m+1)*sizeof(PetscInt));
4090:     for (i=0; i<m; i++) {
4091:       c->diag[i] = a->diag[i];
4092:     }
4093:   } else c->diag = 0;

4095:   c->solve_work         = 0;
4096:   c->saved_values       = 0;
4097:   c->idiag              = 0;
4098:   c->ssor_work          = 0;
4099:   c->keepnonzeropattern = a->keepnonzeropattern;
4100:   c->free_a             = PETSC_TRUE;
4101:   c->free_ij            = PETSC_TRUE;

4103:   c->rmax         = a->rmax;
4104:   c->nz           = a->nz;
4105:   c->maxnz        = a->nz;       /* Since we allocate exactly the right amount */
4106:   C->preallocated = PETSC_TRUE;

4108:   c->compressedrow.use   = a->compressedrow.use;
4109:   c->compressedrow.nrows = a->compressedrow.nrows;
4110:   if (a->compressedrow.use) {
4111:     i    = a->compressedrow.nrows;
4112:     PetscMalloc2(i+1,&c->compressedrow.i,i,&c->compressedrow.rindex);
4113:     PetscMemcpy(c->compressedrow.i,a->compressedrow.i,(i+1)*sizeof(PetscInt));
4114:     PetscMemcpy(c->compressedrow.rindex,a->compressedrow.rindex,i*sizeof(PetscInt));
4115:   } else {
4116:     c->compressedrow.use    = PETSC_FALSE;
4117:     c->compressedrow.i      = NULL;
4118:     c->compressedrow.rindex = NULL;
4119:   }
4120:   c->nonzerorowcnt = a->nonzerorowcnt;
4121:   C->nonzerostate  = A->nonzerostate;

4123:   MatDuplicate_SeqAIJ_Inode(A,cpvalues,&C);
4124:   PetscFunctionListDuplicate(((PetscObject)A)->qlist,&((PetscObject)C)->qlist);
4125:   return(0);
4126: }

4128: PetscErrorCode MatDuplicate_SeqAIJ(Mat A,MatDuplicateOption cpvalues,Mat *B)
4129: {

4133:   MatCreate(PetscObjectComm((PetscObject)A),B);
4134:   MatSetSizes(*B,A->rmap->n,A->cmap->n,A->rmap->n,A->cmap->n);
4135:   if (!(A->rmap->n % A->rmap->bs) && !(A->cmap->n % A->cmap->bs)) {
4136:     MatSetBlockSizesFromMats(*B,A,A);
4137:   }
4138:   MatSetType(*B,((PetscObject)A)->type_name);
4139:   MatDuplicateNoCreate_SeqAIJ(*B,A,cpvalues,PETSC_TRUE);
4140:   return(0);
4141: }

4143: PetscErrorCode MatLoad_SeqAIJ(Mat newMat, PetscViewer viewer)
4144: {
4145:   Mat_SeqAIJ     *a;
4147:   PetscInt       i,sum,nz,header[4],*rowlengths = 0,M,N,rows,cols;
4148:   int            fd;
4149:   PetscMPIInt    size;
4150:   MPI_Comm       comm;
4151:   PetscInt       bs = newMat->rmap->bs;

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

4160:   PetscOptionsBegin(comm,NULL,"Options for loading SEQAIJ matrix","Mat");
4161:   PetscOptionsInt("-matload_block_size","Set the blocksize used to store the matrix","MatLoad",bs,&bs,NULL);
4162:   PetscOptionsEnd();
4163:   if (bs < 0) bs = 1;
4164:   MatSetBlockSize(newMat,bs);

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

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

4173:   /* read in row lengths */
4174:   PetscMalloc1(M,&rowlengths);
4175:   PetscBinaryRead(fd,rowlengths,M,PETSC_INT);

4177:   /* check if sum of rowlengths is same as nz */
4178:   for (i=0,sum=0; i< M; i++) sum +=rowlengths[i];
4179:   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);

4181:   /* set global size if not set already*/
4182:   if (newMat->rmap->n < 0 && newMat->rmap->N < 0 && newMat->cmap->n < 0 && newMat->cmap->N < 0) {
4183:     MatSetSizes(newMat,PETSC_DECIDE,PETSC_DECIDE,M,N);
4184:   } else {
4185:     /* if sizes and type are already set, check if the matrix  global sizes are correct */
4186:     MatGetSize(newMat,&rows,&cols);
4187:     if (rows < 0 && cols < 0) { /* user might provide local size instead of global size */
4188:       MatGetLocalSize(newMat,&rows,&cols);
4189:     }
4190:     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);
4191:   }
4192:   MatSeqAIJSetPreallocation_SeqAIJ(newMat,0,rowlengths);
4193:   a    = (Mat_SeqAIJ*)newMat->data;

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

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

4200:   /* set matrix "i" values */
4201:   a->i[0] = 0;
4202:   for (i=1; i<= M; i++) {
4203:     a->i[i]      = a->i[i-1] + rowlengths[i-1];
4204:     a->ilen[i-1] = rowlengths[i-1];
4205:   }
4206:   PetscFree(rowlengths);

4208:   MatAssemblyBegin(newMat,MAT_FINAL_ASSEMBLY);
4209:   MatAssemblyEnd(newMat,MAT_FINAL_ASSEMBLY);
4210:   return(0);
4211: }

4213: PetscErrorCode MatEqual_SeqAIJ(Mat A,Mat B,PetscBool * flg)
4214: {
4215:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*b = (Mat_SeqAIJ*)B->data;
4217: #if defined(PETSC_USE_COMPLEX)
4218:   PetscInt k;
4219: #endif

4222:   /* If the  matrix dimensions are not equal,or no of nonzeros */
4223:   if ((A->rmap->n != B->rmap->n) || (A->cmap->n != B->cmap->n) ||(a->nz != b->nz)) {
4224:     *flg = PETSC_FALSE;
4225:     return(0);
4226:   }

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

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

4236:   /* if a->a are the same */
4237: #if defined(PETSC_USE_COMPLEX)
4238:   for (k=0; k<a->nz; k++) {
4239:     if (PetscRealPart(a->a[k]) != PetscRealPart(b->a[k]) || PetscImaginaryPart(a->a[k]) != PetscImaginaryPart(b->a[k])) {
4240:       *flg = PETSC_FALSE;
4241:       return(0);
4242:     }
4243:   }
4244: #else
4245:   PetscMemcmp(a->a,b->a,(a->nz)*sizeof(PetscScalar),flg);
4246: #endif
4247:   return(0);
4248: }

4250: /*@
4251:      MatCreateSeqAIJWithArrays - Creates an sequential AIJ matrix using matrix elements (in CSR format)
4252:               provided by the user.

4254:       Collective on MPI_Comm

4256:    Input Parameters:
4257: +   comm - must be an MPI communicator of size 1
4258: .   m - number of rows
4259: .   n - number of columns
4260: .   i - row indices
4261: .   j - column indices
4262: -   a - matrix values

4264:    Output Parameter:
4265: .   mat - the matrix

4267:    Level: intermediate

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

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

4275:        The i and j indices are 0 based

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

4281: $        1 0 0
4282: $        2 0 3
4283: $        4 5 6
4284: $
4285: $        i =  {0,1,3,6}  [size = nrow+1  = 3+1]
4286: $        j =  {0,0,2,0,1,2}  [size = 6]; values must be sorted for each row
4287: $        v =  {1,2,3,4,5,6}  [size = 6]


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

4292: @*/
4293: PetscErrorCode  MatCreateSeqAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt i[],PetscInt j[],PetscScalar a[],Mat *mat)
4294: {
4296:   PetscInt       ii;
4297:   Mat_SeqAIJ     *aij;
4298: #if defined(PETSC_USE_DEBUG)
4299:   PetscInt jj;
4300: #endif

4303:   if (m > 0 && i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4304:   MatCreate(comm,mat);
4305:   MatSetSizes(*mat,m,n,m,n);
4306:   /* MatSetBlockSizes(*mat,,); */
4307:   MatSetType(*mat,MATSEQAIJ);
4308:   MatSeqAIJSetPreallocation_SeqAIJ(*mat,MAT_SKIP_ALLOCATION,0);
4309:   aij  = (Mat_SeqAIJ*)(*mat)->data;
4310:   PetscMalloc2(m,&aij->imax,m,&aij->ilen);

4312:   aij->i            = i;
4313:   aij->j            = j;
4314:   aij->a            = a;
4315:   aij->singlemalloc = PETSC_FALSE;
4316:   aij->nonew        = -1;             /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
4317:   aij->free_a       = PETSC_FALSE;
4318:   aij->free_ij      = PETSC_FALSE;

4320:   for (ii=0; ii<m; ii++) {
4321:     aij->ilen[ii] = aij->imax[ii] = i[ii+1] - i[ii];
4322: #if defined(PETSC_USE_DEBUG)
4323:     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]);
4324:     for (jj=i[ii]+1; jj<i[ii+1]; jj++) {
4325:       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);
4326:       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);
4327:     }
4328: #endif
4329:   }
4330: #if defined(PETSC_USE_DEBUG)
4331:   for (ii=0; ii<aij->i[m]; ii++) {
4332:     if (j[ii] < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column index at location = %D index = %D",ii,j[ii]);
4333:     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]);
4334:   }
4335: #endif

4337:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
4338:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
4339:   return(0);
4340: }
4341: /*@C
4342:      MatCreateSeqAIJFromTriple - Creates an sequential AIJ matrix using matrix elements (in COO format)
4343:               provided by the user.

4345:       Collective on MPI_Comm

4347:    Input Parameters:
4348: +   comm - must be an MPI communicator of size 1
4349: .   m   - number of rows
4350: .   n   - number of columns
4351: .   i   - row indices
4352: .   j   - column indices
4353: .   a   - matrix values
4354: .   nz  - number of nonzeros
4355: -   idx - 0 or 1 based

4357:    Output Parameter:
4358: .   mat - the matrix

4360:    Level: intermediate

4362:    Notes:
4363:        The i and j indices are 0 based

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

4369:         1 0 0
4370:         2 0 3
4371:         4 5 6

4373:         i =  {0,1,1,2,2,2}
4374:         j =  {0,0,2,0,1,2}
4375:         v =  {1,2,3,4,5,6}


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

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


4388:   PetscCalloc1(m,&nnz);
4389:   for (ii = 0; ii < nz; ii++) {
4390:     nnz[i[ii] - !!idx] += 1;
4391:   }
4392:   MatCreate(comm,mat);
4393:   MatSetSizes(*mat,m,n,m,n);
4394:   MatSetType(*mat,MATSEQAIJ);
4395:   MatSeqAIJSetPreallocation_SeqAIJ(*mat,0,nnz);
4396:   for (ii = 0; ii < nz; ii++) {
4397:     if (idx) {
4398:       row = i[ii] - 1;
4399:       col = j[ii] - 1;
4400:     } else {
4401:       row = i[ii];
4402:       col = j[ii];
4403:     }
4404:     MatSetValues(*mat,one,&row,one,&col,&a[ii],ADD_VALUES);
4405:   }
4406:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
4407:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
4408:   PetscFree(nnz);
4409:   return(0);
4410: }

4412: PetscErrorCode MatSeqAIJInvalidateDiagonal(Mat A)
4413: {
4414:   Mat_SeqAIJ     *a=(Mat_SeqAIJ*)A->data;

4418:   a->idiagvalid  = PETSC_FALSE;
4419:   a->ibdiagvalid = PETSC_FALSE;

4421:   MatSeqAIJInvalidateDiagonal_Inode(A);
4422:   return(0);
4423: }

4425: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
4426: {
4428:   PetscMPIInt    size;

4431:   MPI_Comm_size(comm,&size);
4432:   if (size == 1) {
4433:     if (scall == MAT_INITIAL_MATRIX) {
4434:       MatDuplicate(inmat,MAT_COPY_VALUES,outmat);
4435:     } else {
4436:       MatCopy(inmat,*outmat,SAME_NONZERO_PATTERN);
4437:     }
4438:   } else {
4439:     MatCreateMPIMatConcatenateSeqMat_MPIAIJ(comm,inmat,n,scall,outmat);
4440:   }
4441:   return(0);
4442: }

4444: /*
4445:  Permute A into C's *local* index space using rowemb,colemb.
4446:  The embedding are supposed to be injections and the above implies that the range of rowemb is a subset
4447:  of [0,m), colemb is in [0,n).
4448:  If pattern == DIFFERENT_NONZERO_PATTERN, C is preallocated according to A.
4449:  */
4450: PetscErrorCode MatSetSeqMat_SeqAIJ(Mat C,IS rowemb,IS colemb,MatStructure pattern,Mat B)
4451: {
4452:   /* If making this function public, change the error returned in this function away from _PLIB. */
4454:   Mat_SeqAIJ     *Baij;
4455:   PetscBool      seqaij;
4456:   PetscInt       m,n,*nz,i,j,count;
4457:   PetscScalar    v;
4458:   const PetscInt *rowindices,*colindices;

4461:   if (!B) return(0);
4462:   /* Check to make sure the target matrix (and embeddings) are compatible with C and each other. */
4463:   PetscObjectBaseTypeCompare((PetscObject)B,MATSEQAIJ,&seqaij);
4464:   if (!seqaij) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is of wrong type");
4465:   if (rowemb) {
4466:     ISGetLocalSize(rowemb,&m);
4467:     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);
4468:   } else {
4469:     if (C->rmap->n != B->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is row-incompatible with the target matrix");
4470:   }
4471:   if (colemb) {
4472:     ISGetLocalSize(colemb,&n);
4473:     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);
4474:   } else {
4475:     if (C->cmap->n != B->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is col-incompatible with the target matrix");
4476:   }

4478:   Baij = (Mat_SeqAIJ*)(B->data);
4479:   if (pattern == DIFFERENT_NONZERO_PATTERN) {
4480:     PetscMalloc1(B->rmap->n,&nz);
4481:     for (i=0; i<B->rmap->n; i++) {
4482:       nz[i] = Baij->i[i+1] - Baij->i[i];
4483:     }
4484:     MatSeqAIJSetPreallocation(C,0,nz);
4485:     PetscFree(nz);
4486:   }
4487:   if (pattern == SUBSET_NONZERO_PATTERN) {
4488:     MatZeroEntries(C);
4489:   }
4490:   count = 0;
4491:   rowindices = NULL;
4492:   colindices = NULL;
4493:   if (rowemb) {
4494:     ISGetIndices(rowemb,&rowindices);
4495:   }
4496:   if (colemb) {
4497:     ISGetIndices(colemb,&colindices);
4498:   }
4499:   for (i=0; i<B->rmap->n; i++) {
4500:     PetscInt row;
4501:     row = i;
4502:     if (rowindices) row = rowindices[i];
4503:     for (j=Baij->i[i]; j<Baij->i[i+1]; j++) {
4504:       PetscInt col;
4505:       col  = Baij->j[count];
4506:       if (colindices) col = colindices[col];
4507:       v    = Baij->a[count];
4508:       MatSetValues(C,1,&row,1,&col,&v,INSERT_VALUES);
4509:       ++count;
4510:     }
4511:   }
4512:   /* FIXME: set C's nonzerostate correctly. */
4513:   /* Assembly for C is necessary. */
4514:   C->preallocated = PETSC_TRUE;
4515:   C->assembled     = PETSC_TRUE;
4516:   C->was_assembled = PETSC_FALSE;
4517:   return(0);
4518: }

4520: PetscFunctionList MatSeqAIJList = NULL;

4522: /*@C
4523:    MatSeqAIJSetType - Converts a MATSEQAIJ matrix to a subtype

4525:    Collective on Mat

4527:    Input Parameters:
4528: +  mat      - the matrix object
4529: -  matype   - matrix type

4531:    Options Database Key:
4532: .  -mat_seqai_type  <method> - for example seqaijcrl


4535:   Level: intermediate

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

4539: .seealso: PCSetType(), VecSetType(), MatCreate(), MatType, Mat
4540: @*/
4541: PetscErrorCode  MatSeqAIJSetType(Mat mat, MatType matype)
4542: {
4543:   PetscErrorCode ierr,(*r)(Mat,const MatType,MatReuse,Mat*);
4544:   PetscBool      sametype;

4548:   PetscObjectTypeCompare((PetscObject)mat,matype,&sametype);
4549:   if (sametype) return(0);

4551:    PetscFunctionListFind(MatSeqAIJList,matype,&r);
4552:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unknown Mat type given: %s",matype);
4553:   (*r)(mat,matype,MAT_INPLACE_MATRIX,&mat);
4554:   return(0);
4555: }

4557: 
4558: /*@C
4559:   MatSeqAIJRegister -  - Adds a new sub-matrix type for sequential AIJ matrices

4561:    Not Collective

4563:    Input Parameters:
4564: +  name - name of a new user-defined matrix type, for example MATSEQAIJCRL
4565: -  function - routine to convert to subtype

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


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

4574:    Level: advanced

4576: .keywords: Mat, register

4578: .seealso: MatSeqAIJRegisterAll()


4581:   Level: advanced
4582: @*/
4583: PetscErrorCode  MatSeqAIJRegister(const char sname[],PetscErrorCode (*function)(Mat,MatType,MatReuse,Mat *))
4584: {

4588:   PetscFunctionListAdd(&MatSeqAIJList,sname,function);
4589:   return(0);
4590: }

4592: PetscBool MatSeqAIJRegisterAllCalled = PETSC_FALSE;

4594: /*@C
4595:   MatSeqAIJRegisterAll - Registers all of the matrix subtypes of SeqAIJ

4597:   Not Collective

4599:   Level: advanced

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

4603: .keywords: KSP, register, all

4605: .seealso:  MatRegisterAll(), MatSeqAIJRegister()
4606: @*/
4607: PetscErrorCode  MatSeqAIJRegisterAll(void)
4608: {

4612:   if (MatSeqAIJRegisterAllCalled) return(0);
4613:   MatSeqAIJRegisterAllCalled = PETSC_TRUE;

4615:   MatSeqAIJRegister(MATSEQAIJCRL,      MatConvert_SeqAIJ_SeqAIJCRL);
4616:   MatSeqAIJRegister(MATSEQAIJPERM,     MatConvert_SeqAIJ_SeqAIJPERM);
4617: #if defined(PETSC_HAVE_MKL_SPARSE)
4618:   MatSeqAIJRegister(MATSEQAIJMKL,      MatConvert_SeqAIJ_SeqAIJMKL);
4619: #endif
4620: #if defined(PETSC_HAVE_VIENNACL) && defined(PETSC_HAVE_VIENNACL_NO_CUDA)
4621:   MatSeqAIJRegister(MATMPIAIJVIENNACL, MatConvert_SeqAIJ_SeqAIJViennaCL);
4622: #endif
4623:   return(0);
4624: }

4626: /*
4627:     Special version for direct calls from Fortran
4628: */
4629:  #include <petsc/private/fortranimpl.h>
4630: #if defined(PETSC_HAVE_FORTRAN_CAPS)
4631: #define matsetvaluesseqaij_ MATSETVALUESSEQAIJ
4632: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
4633: #define matsetvaluesseqaij_ matsetvaluesseqaij
4634: #endif

4636: /* Change these macros so can be used in void function */
4637: #undef CHKERRQ
4638: #define CHKERRQ(ierr) CHKERRABORT(PetscObjectComm((PetscObject)A),ierr)
4639: #undef SETERRQ2
4640: #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
4641: #undef SETERRQ3
4642: #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)

4644: 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)
4645: {
4646:   Mat            A  = *AA;
4647:   PetscInt       m  = *mm, n = *nn;
4648:   InsertMode     is = *isis;
4649:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
4650:   PetscInt       *rp,k,low,high,t,ii,row,nrow,i,col,l,rmax,N;
4651:   PetscInt       *imax,*ai,*ailen;
4653:   PetscInt       *aj,nonew = a->nonew,lastcol = -1;
4654:   MatScalar      *ap,value,*aa;
4655:   PetscBool      ignorezeroentries = a->ignorezeroentries;
4656:   PetscBool      roworiented       = a->roworiented;

4659:   MatCheckPreallocated(A,1);
4660:   imax  = a->imax;
4661:   ai    = a->i;
4662:   ailen = a->ilen;
4663:   aj    = a->j;
4664:   aa    = a->a;

4666:   for (k=0; k<m; k++) { /* loop over added rows */
4667:     row = im[k];
4668:     if (row < 0) continue;
4669: #if defined(PETSC_USE_DEBUG)
4670:     if (row >= A->rmap->n) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Row too large");
4671: #endif
4672:     rp   = aj + ai[row]; ap = aa + ai[row];
4673:     rmax = imax[row]; nrow = ailen[row];
4674:     low  = 0;
4675:     high = nrow;
4676:     for (l=0; l<n; l++) { /* loop over added columns */
4677:       if (in[l] < 0) continue;
4678: #if defined(PETSC_USE_DEBUG)
4679:       if (in[l] >= A->cmap->n) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Column too large");
4680: #endif
4681:       col = in[l];
4682:       if (roworiented) value = v[l + k*n];
4683:       else value = v[k + l*m];

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

4687:       if (col <= lastcol) low = 0;
4688:       else high = nrow;
4689:       lastcol = col;
4690:       while (high-low > 5) {
4691:         t = (low+high)/2;
4692:         if (rp[t] > col) high = t;
4693:         else             low  = t;
4694:       }
4695:       for (i=low; i<high; i++) {
4696:         if (rp[i] > col) break;
4697:         if (rp[i] == col) {
4698:           if (is == ADD_VALUES) ap[i] += value;
4699:           else                  ap[i] = value;
4700:           goto noinsert;
4701:         }
4702:       }
4703:       if (value == 0.0 && ignorezeroentries) goto noinsert;
4704:       if (nonew == 1) goto noinsert;
4705:       if (nonew == -1) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero in the matrix");
4706:       MatSeqXAIJReallocateAIJ(A,A->rmap->n,1,nrow,row,col,rmax,aa,ai,aj,rp,ap,imax,nonew,MatScalar);
4707:       N = nrow++ - 1; a->nz++; high++;
4708:       /* shift up all the later entries in this row */
4709:       for (ii=N; ii>=i; ii--) {
4710:         rp[ii+1] = rp[ii];
4711:         ap[ii+1] = ap[ii];
4712:       }
4713:       rp[i] = col;
4714:       ap[i] = value;
4715:       A->nonzerostate++;
4716: noinsert:;
4717:       low = i + 1;
4718:     }
4719:     ailen[row] = nrow;
4720:   }
4721:   PetscFunctionReturnVoid();
4722: }