Actual source code: aij.c

petsc-3.14.6 2021-03-30
Report Typos and Errors
  1: /*
  2:     Defines the basic matrix operations for the AIJ (compressed row)
  3:   matrix storage format.
  4: */


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

181:   if (Y->assembled) {
182:     MatMissingDiagonal_SeqAIJ(Y,&missing,NULL);
183:     if (!missing) {
184:       diag = aij->diag;
185:       VecGetArrayRead(D,&v);
186:       if (is == INSERT_VALUES) {
187: #if defined(PETSC_HAVE_DEVICE)
188:         inserted = PETSC_TRUE;
189: #endif
190:         for (i=0; i<m; i++) {
191:           aa[diag[i]] = v[i];
192:         }
193:       } else {
194:         for (i=0; i<m; i++) {
195: #if defined(PETSC_HAVE_DEVICE)
196:           if (v[i] != 0.0) inserted = PETSC_TRUE;
197: #endif
198:           aa[diag[i]] += v[i];
199:         }
200:       }
201: #if defined(PETSC_HAVE_DEVICE)
202:       if (inserted) Y->offloadmask = PETSC_OFFLOAD_CPU;
203: #endif
204:       VecRestoreArrayRead(D,&v);
205:       return(0);
206:     }
207:     MatSeqAIJInvalidateDiagonal(Y);
208:   }
209:   MatDiagonalSet_Default(Y,D,is);
210:   return(0);
211: }

213: PetscErrorCode MatGetRowIJ_SeqAIJ(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *m,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
214: {
215:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
217:   PetscInt       i,ishift;

220:   *m = A->rmap->n;
221:   if (!ia) return(0);
222:   ishift = 0;
223:   if (symmetric && !A->structurally_symmetric) {
224:     MatToSymmetricIJ_SeqAIJ(A->rmap->n,a->i,a->j,PETSC_TRUE,ishift,oshift,(PetscInt**)ia,(PetscInt**)ja);
225:   } else if (oshift == 1) {
226:     PetscInt *tia;
227:     PetscInt nz = a->i[A->rmap->n];
228:     /* malloc space and  add 1 to i and j indices */
229:     PetscMalloc1(A->rmap->n+1,&tia);
230:     for (i=0; i<A->rmap->n+1; i++) tia[i] = a->i[i] + 1;
231:     *ia = tia;
232:     if (ja) {
233:       PetscInt *tja;
234:       PetscMalloc1(nz+1,&tja);
235:       for (i=0; i<nz; i++) tja[i] = a->j[i] + 1;
236:       *ja = tja;
237:     }
238:   } else {
239:     *ia = a->i;
240:     if (ja) *ja = a->j;
241:   }
242:   return(0);
243: }

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

250:   if (!ia) return(0);
251:   if ((symmetric && !A->structurally_symmetric) || oshift == 1) {
252:     PetscFree(*ia);
253:     if (ja) {PetscFree(*ja);}
254:   }
255:   return(0);
256: }

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

266:   *nn = n;
267:   if (!ia) return(0);
268:   if (symmetric) {
269:     MatToSymmetricIJ_SeqAIJ(A->rmap->n,a->i,a->j,PETSC_TRUE,0,oshift,(PetscInt**)ia,(PetscInt**)ja);
270:   } else {
271:     PetscCalloc1(n,&collengths);
272:     PetscMalloc1(n+1,&cia);
273:     PetscMalloc1(nz,&cja);
274:     jj   = a->j;
275:     for (i=0; i<nz; i++) {
276:       collengths[jj[i]]++;
277:     }
278:     cia[0] = oshift;
279:     for (i=0; i<n; i++) {
280:       cia[i+1] = cia[i] + collengths[i];
281:     }
282:     PetscArrayzero(collengths,n);
283:     jj   = a->j;
284:     for (row=0; row<m; row++) {
285:       mr = a->i[row+1] - a->i[row];
286:       for (i=0; i<mr; i++) {
287:         col = *jj++;

289:         cja[cia[col] + collengths[col]++ - oshift] = row + oshift;
290:       }
291:     }
292:     PetscFree(collengths);
293:     *ia  = cia; *ja = cja;
294:   }
295:   return(0);
296: }

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

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

305:   PetscFree(*ia);
306:   PetscFree(*ja);
307:   return(0);
308: }

310: /*
311:  MatGetColumnIJ_SeqAIJ_Color() and MatRestoreColumnIJ_SeqAIJ_Color() are customized from
312:  MatGetColumnIJ_SeqAIJ() and MatRestoreColumnIJ_SeqAIJ() by adding an output
313:  spidx[], index of a->a, to be used in MatTransposeColoringCreate_SeqAIJ() and MatFDColoringCreate_SeqXAIJ()
314: */
315: PetscErrorCode MatGetColumnIJ_SeqAIJ_Color(Mat A,PetscInt oshift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *nn,const PetscInt *ia[],const PetscInt *ja[],PetscInt *spidx[],PetscBool  *done)
316: {
317:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
319:   PetscInt       i,*collengths,*cia,*cja,n = A->cmap->n,m = A->rmap->n;
320:   PetscInt       nz = a->i[m],row,mr,col,tmp;
321:   PetscInt       *cspidx;
322:   const PetscInt *jj;

325:   *nn = n;
326:   if (!ia) return(0);

328:   PetscCalloc1(n,&collengths);
329:   PetscMalloc1(n+1,&cia);
330:   PetscMalloc1(nz,&cja);
331:   PetscMalloc1(nz,&cspidx);
332:   jj   = a->j;
333:   for (i=0; i<nz; i++) {
334:     collengths[jj[i]]++;
335:   }
336:   cia[0] = oshift;
337:   for (i=0; i<n; i++) {
338:     cia[i+1] = cia[i] + collengths[i];
339:   }
340:   PetscArrayzero(collengths,n);
341:   jj   = a->j;
342:   for (row=0; row<m; row++) {
343:     mr = a->i[row+1] - a->i[row];
344:     for (i=0; i<mr; i++) {
345:       col         = *jj++;
346:       tmp         = cia[col] + collengths[col]++ - oshift;
347:       cspidx[tmp] = a->i[row] + i; /* index of a->j */
348:       cja[tmp]    = row + oshift;
349:     }
350:   }
351:   PetscFree(collengths);
352:   *ia    = cia;
353:   *ja    = cja;
354:   *spidx = cspidx;
355:   return(0);
356: }

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

363:   MatRestoreColumnIJ_SeqAIJ(A,oshift,symmetric,inodecompressed,n,ia,ja,done);
364:   PetscFree(*spidx);
365:   return(0);
366: }

368: PetscErrorCode MatSetValuesRow_SeqAIJ(Mat A,PetscInt row,const PetscScalar v[])
369: {
370:   Mat_SeqAIJ     *a  = (Mat_SeqAIJ*)A->data;
371:   PetscInt       *ai = a->i;

375:   PetscArraycpy(a->a+ai[row],v,ai[row+1]-ai[row]);
376: #if defined(PETSC_HAVE_DEVICE)
377:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED && ai[row+1]-ai[row]) A->offloadmask = PETSC_OFFLOAD_CPU;
378: #endif
379:   return(0);
380: }

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

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

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

392: */

394: #include <petsc/private/isimpl.h>
395: PetscErrorCode MatSeqAIJSetValuesLocalFast(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode is)
396: {
397:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
398:   PetscInt       low,high,t,row,nrow,i,col,l;
399:   const PetscInt *rp,*ai = a->i,*ailen = a->ilen,*aj = a->j;
400:   PetscInt       lastcol = -1;
401:   MatScalar      *ap,value,*aa = a->a;
402:   const PetscInt *ridx = A->rmap->mapping->indices,*cidx = A->cmap->mapping->indices;

404:   row  = ridx[im[0]];
405:   rp   = aj + ai[row];
406:   ap   = aa + ai[row];
407:   nrow = ailen[row];
408:   low  = 0;
409:   high = nrow;
410:   for (l=0; l<n; l++) { /* loop over added columns */
411:     col = cidx[in[l]];
412:     value = v[l];

414:     if (col <= lastcol) low = 0;
415:     else high = nrow;
416:     lastcol = col;
417:     while (high-low > 5) {
418:       t = (low+high)/2;
419:       if (rp[t] > col) high = t;
420:       else low = t;
421:     }
422:     for (i=low; i<high; i++) {
423:       if (rp[i] == col) {
424:         ap[i] += value;
425:         low = i + 1;
426:         break;
427:       }
428:     }
429:   }
430: #if defined(PETSC_HAVE_DEVICE)
431:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED && m && n) A->offloadmask = PETSC_OFFLOAD_CPU;
432: #endif
433:   return 0;
434: }

436: PetscErrorCode MatSetValues_SeqAIJ(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode is)
437: {
438:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
439:   PetscInt       *rp,k,low,high,t,ii,row,nrow,i,col,l,rmax,N;
440:   PetscInt       *imax = a->imax,*ai = a->i,*ailen = a->ilen;
442:   PetscInt       *aj = a->j,nonew = a->nonew,lastcol = -1;
443:   MatScalar      *ap=NULL,value=0.0,*aa = a->a;
444:   PetscBool      ignorezeroentries = a->ignorezeroentries;
445:   PetscBool      roworiented       = a->roworiented;
446: #if defined(PETSC_HAVE_DEVICE)
447:   PetscBool      inserted          = PETSC_FALSE;
448: #endif

451:   for (k=0; k<m; k++) { /* loop over added rows */
452:     row = im[k];
453:     if (row < 0) continue;
454:     if (PetscUnlikelyDebug(row >= A->rmap->n)) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",row,A->rmap->n-1);
455:     rp   = aj + ai[row];
456:     if (!A->structure_only) ap = aa + ai[row];
457:     rmax = imax[row]; nrow = ailen[row];
458:     low  = 0;
459:     high = nrow;
460:     for (l=0; l<n; l++) { /* loop over added columns */
461:       if (in[l] < 0) continue;
462:       if (PetscUnlikelyDebug(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);
463:       col = in[l];
464:       if (v && !A->structure_only) value = roworiented ? v[l + k*n] : v[k + l*m];
465:       if (!A->structure_only && value == 0.0 && ignorezeroentries && is == ADD_VALUES && row != col) continue;

467:       if (col <= lastcol) low = 0;
468:       else high = nrow;
469:       lastcol = col;
470:       while (high-low > 5) {
471:         t = (low+high)/2;
472:         if (rp[t] > col) high = t;
473:         else low = t;
474:       }
475:       for (i=low; i<high; i++) {
476:         if (rp[i] > col) break;
477:         if (rp[i] == col) {
478:           if (!A->structure_only) {
479:             if (is == ADD_VALUES) {
480:               ap[i] += value;
481:               (void)PetscLogFlops(1.0);
482:             }
483:             else ap[i] = value;
484: #if defined(PETSC_HAVE_DEVICE)
485:             inserted = PETSC_TRUE;
486: #endif
487:           }
488:           low = i + 1;
489:           goto noinsert;
490:         }
491:       }
492:       if (value == 0.0 && ignorezeroentries && row != col) goto noinsert;
493:       if (nonew == 1) goto noinsert;
494:       if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero at (%D,%D) in the matrix",row,col);
495:       if (A->structure_only) {
496:         MatSeqXAIJReallocateAIJ_structure_only(A,A->rmap->n,1,nrow,row,col,rmax,ai,aj,rp,imax,nonew,MatScalar);
497:       } else {
498:         MatSeqXAIJReallocateAIJ(A,A->rmap->n,1,nrow,row,col,rmax,aa,ai,aj,rp,ap,imax,nonew,MatScalar);
499:       }
500:       N = nrow++ - 1; a->nz++; high++;
501:       /* shift up all the later entries in this row */
502:       PetscArraymove(rp+i+1,rp+i,N-i+1);
503:       rp[i] = col;
504:       if (!A->structure_only){
505:         PetscArraymove(ap+i+1,ap+i,N-i+1);
506:         ap[i] = value;
507:       }
508:       low = i + 1;
509:       A->nonzerostate++;
510: #if defined(PETSC_HAVE_DEVICE)
511:       inserted = PETSC_TRUE;
512: #endif
513: noinsert:;
514:     }
515:     ailen[row] = nrow;
516:   }
517: #if defined(PETSC_HAVE_DEVICE)
518:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED && inserted) A->offloadmask = PETSC_OFFLOAD_CPU;
519: #endif
520:   return(0);
521: }


524: PetscErrorCode MatSetValues_SeqAIJ_SortedFullNoPreallocation(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode is)
525: {
526:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
527:   PetscInt       *rp,k,row;
528:   PetscInt       *ai = a->i;
530:   PetscInt       *aj = a->j;
531:   MatScalar      *aa = a->a,*ap;

534:   if (A->was_assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot call on assembled matrix.");
535:   if (m*n+a->nz > a->maxnz) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Number of entries in matrix will be larger than maximum nonzeros allocated for %D in MatSeqAIJSetTotalPreallocation()",a->maxnz);
536:   for (k=0; k<m; k++) { /* loop over added rows */
537:     row  = im[k];
538:     rp   = aj + ai[row];
539:     ap   = aa + ai[row];

541:     PetscMemcpy(rp,in,n*sizeof(PetscInt));
542:     if (!A->structure_only) {
543:       if (v) {
544:         PetscMemcpy(ap,v,n*sizeof(PetscScalar));
545:         v   += n;
546:       } else {
547:         PetscMemzero(ap,n*sizeof(PetscScalar));
548:       }
549:     }
550:     a->ilen[row] = n;
551:     a->imax[row] = n;
552:     a->i[row+1]  = a->i[row]+n;
553:     a->nz       += n;
554:   }
555: #if defined(PETSC_HAVE_DEVICE)
556:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED && m && n) A->offloadmask = PETSC_OFFLOAD_CPU;
557: #endif
558:   return(0);
559: }

561: /*@
562:     MatSeqAIJSetTotalPreallocation - Sets an upper bound on the total number of expected nonzeros in the matrix.

564:   Input Parameters:
565: +  A - the SeqAIJ matrix
566: -  nztotal - bound on the number of nonzeros

568:   Level: advanced

570:   Notes:
571:     This can be called if you will be provided the matrix row by row (from row zero) with sorted column indices for each row.
572:     Simply call MatSetValues() after this call to provide the matrix entries in the usual manner. This matrix may be used
573:     as always with multiple matrix assemblies.

575: .seealso: MatSetOption(), MAT_SORTED_FULL, MatSetValues(), MatSeqAIJSetPreallocation()
576: @*/

578: PetscErrorCode MatSeqAIJSetTotalPreallocation(Mat A,PetscInt nztotal)
579: {
581:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

584:   PetscLayoutSetUp(A->rmap);
585:   PetscLayoutSetUp(A->cmap);
586:   a->maxnz  = nztotal;
587:   if (!a->imax) {
588:     PetscMalloc1(A->rmap->n,&a->imax);
589:     PetscLogObjectMemory((PetscObject)A,A->rmap->n*sizeof(PetscInt));
590:   }
591:   if (!a->ilen) {
592:     PetscMalloc1(A->rmap->n,&a->ilen);
593:     PetscLogObjectMemory((PetscObject)A,A->rmap->n*sizeof(PetscInt));
594:   } else {
595:     PetscMemzero(a->ilen,A->rmap->n*sizeof(PetscInt));
596:   }

598:   /* allocate the matrix space */
599:   if (A->structure_only) {
600:     PetscMalloc1(nztotal,&a->j);
601:     PetscMalloc1(A->rmap->n+1,&a->i);
602:     PetscLogObjectMemory((PetscObject)A,(A->rmap->n+1)*sizeof(PetscInt)+nztotal*sizeof(PetscInt));
603:   } else {
604:     PetscMalloc3(nztotal,&a->a,nztotal,&a->j,A->rmap->n+1,&a->i);
605:     PetscLogObjectMemory((PetscObject)A,(A->rmap->n+1)*sizeof(PetscInt)+nztotal*(sizeof(PetscScalar)+sizeof(PetscInt)));
606:   }
607:   a->i[0] = 0;
608:   if (A->structure_only) {
609:     a->singlemalloc = PETSC_FALSE;
610:     a->free_a       = PETSC_FALSE;
611:   } else {
612:     a->singlemalloc = PETSC_TRUE;
613:     a->free_a       = PETSC_TRUE;
614:   }
615:   a->free_ij         = PETSC_TRUE;
616:   A->ops->setvalues = MatSetValues_SeqAIJ_SortedFullNoPreallocation;
617:   A->preallocated   = PETSC_TRUE;
618:   return(0);
619: }

621: PetscErrorCode MatSetValues_SeqAIJ_SortedFull(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode is)
622: {
623:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
624:   PetscInt       *rp,k,row;
625:   PetscInt       *ai = a->i,*ailen = a->ilen;
627:   PetscInt       *aj = a->j;
628:   MatScalar      *aa = a->a,*ap;

631:   for (k=0; k<m; k++) { /* loop over added rows */
632:     row  = im[k];
633:     if (PetscUnlikelyDebug(n > a->imax[row])) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Preallocation for row %D does not match number of columns provided",n);
634:     rp   = aj + ai[row];
635:     ap   = aa + ai[row];
636:     if (!A->was_assembled) {
637:       PetscMemcpy(rp,in,n*sizeof(PetscInt));
638:     }
639:     if (!A->structure_only) {
640:       if (v) {
641:         PetscMemcpy(ap,v,n*sizeof(PetscScalar));
642:         v   += n;
643:       } else {
644:         PetscMemzero(ap,n*sizeof(PetscScalar));
645:       }
646:     }
647:     ailen[row] = n;
648:     a->nz      += n;
649:   }
650: #if defined(PETSC_HAVE_DEVICE)
651:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED && m && n) A->offloadmask = PETSC_OFFLOAD_CPU;
652: #endif
653:   return(0);
654: }


657: PetscErrorCode MatGetValues_SeqAIJ(Mat A,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],PetscScalar v[])
658: {
659:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
660:   PetscInt   *rp,k,low,high,t,row,nrow,i,col,l,*aj = a->j;
661:   PetscInt   *ai = a->i,*ailen = a->ilen;
662:   MatScalar  *ap,*aa = a->a;

665:   for (k=0; k<m; k++) { /* loop over rows */
666:     row = im[k];
667:     if (row < 0) {v += n; continue;} /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",row); */
668:     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);
669:     rp   = aj + ai[row]; ap = aa + ai[row];
670:     nrow = ailen[row];
671:     for (l=0; l<n; l++) { /* loop over columns */
672:       if (in[l] < 0) {v++; continue;} /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",in[l]); */
673:       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);
674:       col  = in[l];
675:       high = nrow; low = 0; /* assume unsorted */
676:       while (high-low > 5) {
677:         t = (low+high)/2;
678:         if (rp[t] > col) high = t;
679:         else low = t;
680:       }
681:       for (i=low; i<high; i++) {
682:         if (rp[i] > col) break;
683:         if (rp[i] == col) {
684:           *v++ = ap[i];
685:           goto finished;
686:         }
687:       }
688:       *v++ = 0.0;
689: finished:;
690:     }
691:   }
692:   return(0);
693: }

695: PetscErrorCode MatView_SeqAIJ_Binary(Mat mat,PetscViewer viewer)
696: {
697:   Mat_SeqAIJ     *A = (Mat_SeqAIJ*)mat->data;
698:   PetscInt       header[4],M,N,m,nz,i;
699:   PetscInt       *rowlens;

703:   PetscViewerSetUp(viewer);

705:   M  = mat->rmap->N;
706:   N  = mat->cmap->N;
707:   m  = mat->rmap->n;
708:   nz = A->nz;

710:   /* write matrix header */
711:   header[0] = MAT_FILE_CLASSID;
712:   header[1] = M; header[2] = N; header[3] = nz;
713:   PetscViewerBinaryWrite(viewer,header,4,PETSC_INT);

715:   /* fill in and store row lengths */
716:   PetscMalloc1(m,&rowlens);
717:   for (i=0; i<m; i++) rowlens[i] = A->i[i+1] - A->i[i];
718:   PetscViewerBinaryWrite(viewer,rowlens,m,PETSC_INT);
719:   PetscFree(rowlens);
720:   /* store column indices */
721:   PetscViewerBinaryWrite(viewer,A->j,nz,PETSC_INT);
722:   /* store nonzero values */
723:   PetscViewerBinaryWrite(viewer,A->a,nz,PETSC_SCALAR);

725:   /* write block size option to the viewer's .info file */
726:   MatView_Binary_BlockSizes(mat,viewer);
727:   return(0);
728: }

730: static PetscErrorCode MatView_SeqAIJ_ASCII_structonly(Mat A,PetscViewer viewer)
731: {
733:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
734:   PetscInt       i,k,m=A->rmap->N;

737:   PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
738:   for (i=0; i<m; i++) {
739:     PetscViewerASCIIPrintf(viewer,"row %D:",i);
740:     for (k=a->i[i]; k<a->i[i+1]; k++) {
741:       PetscViewerASCIIPrintf(viewer," (%D) ",a->j[k]);
742:     }
743:     PetscViewerASCIIPrintf(viewer,"\n");
744:   }
745:   PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
746:   return(0);
747: }

749: extern PetscErrorCode MatSeqAIJFactorInfo_Matlab(Mat,PetscViewer);

751: PetscErrorCode MatView_SeqAIJ_ASCII(Mat A,PetscViewer viewer)
752: {
753:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
754:   PetscErrorCode    ierr;
755:   PetscInt          i,j,m = A->rmap->n;
756:   const char        *name;
757:   PetscViewerFormat format;

760:   if (A->structure_only) {
761:     MatView_SeqAIJ_ASCII_structonly(A,viewer);
762:     return(0);
763:   }

765:   PetscViewerGetFormat(viewer,&format);
766:   if (format == PETSC_VIEWER_ASCII_MATLAB) {
767:     PetscInt nofinalvalue = 0;
768:     if (m && ((a->i[m] == a->i[m-1]) || (a->j[a->nz-1] != A->cmap->n-1))) {
769:       /* Need a dummy value to ensure the dimension of the matrix. */
770:       nofinalvalue = 1;
771:     }
772:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
773:     PetscViewerASCIIPrintf(viewer,"%% Size = %D %D \n",m,A->cmap->n);
774:     PetscViewerASCIIPrintf(viewer,"%% Nonzeros = %D \n",a->nz);
775: #if defined(PETSC_USE_COMPLEX)
776:     PetscViewerASCIIPrintf(viewer,"zzz = zeros(%D,4);\n",a->nz+nofinalvalue);
777: #else
778:     PetscViewerASCIIPrintf(viewer,"zzz = zeros(%D,3);\n",a->nz+nofinalvalue);
779: #endif
780:     PetscViewerASCIIPrintf(viewer,"zzz = [\n");

782:     for (i=0; i<m; i++) {
783:       for (j=a->i[i]; j<a->i[i+1]; j++) {
784: #if defined(PETSC_USE_COMPLEX)
785:         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]));
786: #else
787:         PetscViewerASCIIPrintf(viewer,"%D %D  %18.16e\n",i+1,a->j[j]+1,(double)a->a[j]);
788: #endif
789:       }
790:     }
791:     if (nofinalvalue) {
792: #if defined(PETSC_USE_COMPLEX)
793:       PetscViewerASCIIPrintf(viewer,"%D %D  %18.16e %18.16e\n",m,A->cmap->n,0.,0.);
794: #else
795:       PetscViewerASCIIPrintf(viewer,"%D %D  %18.16e\n",m,A->cmap->n,0.0);
796: #endif
797:     }
798:     PetscObjectGetName((PetscObject)A,&name);
799:     PetscViewerASCIIPrintf(viewer,"];\n %s = spconvert(zzz);\n",name);
800:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
801:   } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO || format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
802:     return(0);
803:   } else if (format == PETSC_VIEWER_ASCII_COMMON) {
804:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
805:     for (i=0; i<m; i++) {
806:       PetscViewerASCIIPrintf(viewer,"row %D:",i);
807:       for (j=a->i[i]; j<a->i[i+1]; j++) {
808: #if defined(PETSC_USE_COMPLEX)
809:         if (PetscImaginaryPart(a->a[j]) > 0.0 && PetscRealPart(a->a[j]) != 0.0) {
810:           PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
811:         } else if (PetscImaginaryPart(a->a[j]) < 0.0 && PetscRealPart(a->a[j]) != 0.0) {
812:           PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)-PetscImaginaryPart(a->a[j]));
813:         } else if (PetscRealPart(a->a[j]) != 0.0) {
814:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
815:         }
816: #else
817:         if (a->a[j] != 0.0) {PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);}
818: #endif
819:       }
820:       PetscViewerASCIIPrintf(viewer,"\n");
821:     }
822:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
823:   } else if (format == PETSC_VIEWER_ASCII_SYMMODU) {
824:     PetscInt nzd=0,fshift=1,*sptr;
825:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
826:     PetscMalloc1(m+1,&sptr);
827:     for (i=0; i<m; i++) {
828:       sptr[i] = nzd+1;
829:       for (j=a->i[i]; j<a->i[i+1]; j++) {
830:         if (a->j[j] >= i) {
831: #if defined(PETSC_USE_COMPLEX)
832:           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) nzd++;
833: #else
834:           if (a->a[j] != 0.0) nzd++;
835: #endif
836:         }
837:       }
838:     }
839:     sptr[m] = nzd+1;
840:     PetscViewerASCIIPrintf(viewer," %D %D\n\n",m,nzd);
841:     for (i=0; i<m+1; i+=6) {
842:       if (i+4<m) {
843:         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]);
844:       } else if (i+3<m) {
845:         PetscViewerASCIIPrintf(viewer," %D %D %D %D %D\n",sptr[i],sptr[i+1],sptr[i+2],sptr[i+3],sptr[i+4]);
846:       } else if (i+2<m) {
847:         PetscViewerASCIIPrintf(viewer," %D %D %D %D\n",sptr[i],sptr[i+1],sptr[i+2],sptr[i+3]);
848:       } else if (i+1<m) {
849:         PetscViewerASCIIPrintf(viewer," %D %D %D\n",sptr[i],sptr[i+1],sptr[i+2]);
850:       } else if (i<m) {
851:         PetscViewerASCIIPrintf(viewer," %D %D\n",sptr[i],sptr[i+1]);
852:       } else {
853:         PetscViewerASCIIPrintf(viewer," %D\n",sptr[i]);
854:       }
855:     }
856:     PetscViewerASCIIPrintf(viewer,"\n");
857:     PetscFree(sptr);
858:     for (i=0; i<m; i++) {
859:       for (j=a->i[i]; j<a->i[i+1]; j++) {
860:         if (a->j[j] >= i) {PetscViewerASCIIPrintf(viewer," %D ",a->j[j]+fshift);}
861:       }
862:       PetscViewerASCIIPrintf(viewer,"\n");
863:     }
864:     PetscViewerASCIIPrintf(viewer,"\n");
865:     for (i=0; i<m; i++) {
866:       for (j=a->i[i]; j<a->i[i+1]; j++) {
867:         if (a->j[j] >= i) {
868: #if defined(PETSC_USE_COMPLEX)
869:           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) {
870:             PetscViewerASCIIPrintf(viewer," %18.16e %18.16e ",(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
871:           }
872: #else
873:           if (a->a[j] != 0.0) {PetscViewerASCIIPrintf(viewer," %18.16e ",(double)a->a[j]);}
874: #endif
875:         }
876:       }
877:       PetscViewerASCIIPrintf(viewer,"\n");
878:     }
879:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
880:   } else if (format == PETSC_VIEWER_ASCII_DENSE) {
881:     PetscInt    cnt = 0,jcnt;
882:     PetscScalar value;
883: #if defined(PETSC_USE_COMPLEX)
884:     PetscBool   realonly = PETSC_TRUE;

886:     for (i=0; i<a->i[m]; i++) {
887:       if (PetscImaginaryPart(a->a[i]) != 0.0) {
888:         realonly = PETSC_FALSE;
889:         break;
890:       }
891:     }
892: #endif

894:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
895:     for (i=0; i<m; i++) {
896:       jcnt = 0;
897:       for (j=0; j<A->cmap->n; j++) {
898:         if (jcnt < a->i[i+1]-a->i[i] && j == a->j[cnt]) {
899:           value = a->a[cnt++];
900:           jcnt++;
901:         } else {
902:           value = 0.0;
903:         }
904: #if defined(PETSC_USE_COMPLEX)
905:         if (realonly) {
906:           PetscViewerASCIIPrintf(viewer," %7.5e ",(double)PetscRealPart(value));
907:         } else {
908:           PetscViewerASCIIPrintf(viewer," %7.5e+%7.5e i ",(double)PetscRealPart(value),(double)PetscImaginaryPart(value));
909:         }
910: #else
911:         PetscViewerASCIIPrintf(viewer," %7.5e ",(double)value);
912: #endif
913:       }
914:       PetscViewerASCIIPrintf(viewer,"\n");
915:     }
916:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
917:   } else if (format == PETSC_VIEWER_ASCII_MATRIXMARKET) {
918:     PetscInt fshift=1;
919:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
920: #if defined(PETSC_USE_COMPLEX)
921:     PetscViewerASCIIPrintf(viewer,"%%%%MatrixMarket matrix coordinate complex general\n");
922: #else
923:     PetscViewerASCIIPrintf(viewer,"%%%%MatrixMarket matrix coordinate real general\n");
924: #endif
925:     PetscViewerASCIIPrintf(viewer,"%D %D %D\n", m, A->cmap->n, a->nz);
926:     for (i=0; i<m; i++) {
927:       for (j=a->i[i]; j<a->i[i+1]; j++) {
928: #if defined(PETSC_USE_COMPLEX)
929:         PetscViewerASCIIPrintf(viewer,"%D %D %g %g\n", i+fshift,a->j[j]+fshift,(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
930: #else
931:         PetscViewerASCIIPrintf(viewer,"%D %D %g\n", i+fshift, a->j[j]+fshift, (double)a->a[j]);
932: #endif
933:       }
934:     }
935:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
936:   } else {
937:     PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
938:     if (A->factortype) {
939:       for (i=0; i<m; i++) {
940:         PetscViewerASCIIPrintf(viewer,"row %D:",i);
941:         /* L part */
942:         for (j=a->i[i]; j<a->i[i+1]; j++) {
943: #if defined(PETSC_USE_COMPLEX)
944:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
945:             PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
946:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
947:             PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)(-PetscImaginaryPart(a->a[j])));
948:           } else {
949:             PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
950:           }
951: #else
952:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);
953: #endif
954:         }
955:         /* diagonal */
956:         j = a->diag[i];
957: #if defined(PETSC_USE_COMPLEX)
958:         if (PetscImaginaryPart(a->a[j]) > 0.0) {
959:           PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(1.0/a->a[j]),(double)PetscImaginaryPart(1.0/a->a[j]));
960:         } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
961:           PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(1.0/a->a[j]),(double)(-PetscImaginaryPart(1.0/a->a[j])));
962:         } else {
963:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(1.0/a->a[j]));
964:         }
965: #else
966:         PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)(1.0/a->a[j]));
967: #endif

969:         /* U part */
970:         for (j=a->diag[i+1]+1; j<a->diag[i]; j++) {
971: #if defined(PETSC_USE_COMPLEX)
972:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
973:             PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
974:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
975:             PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)(-PetscImaginaryPart(a->a[j])));
976:           } else {
977:             PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
978:           }
979: #else
980:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);
981: #endif
982:         }
983:         PetscViewerASCIIPrintf(viewer,"\n");
984:       }
985:     } else {
986:       for (i=0; i<m; i++) {
987:         PetscViewerASCIIPrintf(viewer,"row %D:",i);
988:         for (j=a->i[i]; j<a->i[i+1]; j++) {
989: #if defined(PETSC_USE_COMPLEX)
990:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
991:             PetscViewerASCIIPrintf(viewer," (%D, %g + %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)PetscImaginaryPart(a->a[j]));
992:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
993:             PetscViewerASCIIPrintf(viewer," (%D, %g - %g i)",a->j[j],(double)PetscRealPart(a->a[j]),(double)-PetscImaginaryPart(a->a[j]));
994:           } else {
995:             PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)PetscRealPart(a->a[j]));
996:           }
997: #else
998:           PetscViewerASCIIPrintf(viewer," (%D, %g) ",a->j[j],(double)a->a[j]);
999: #endif
1000:         }
1001:         PetscViewerASCIIPrintf(viewer,"\n");
1002:       }
1003:     }
1004:     PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
1005:   }
1006:   PetscViewerFlush(viewer);
1007:   return(0);
1008: }

1010: #include <petscdraw.h>
1011: PetscErrorCode MatView_SeqAIJ_Draw_Zoom(PetscDraw draw,void *Aa)
1012: {
1013:   Mat               A  = (Mat) Aa;
1014:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1015:   PetscErrorCode    ierr;
1016:   PetscInt          i,j,m = A->rmap->n;
1017:   int               color;
1018:   PetscReal         xl,yl,xr,yr,x_l,x_r,y_l,y_r;
1019:   PetscViewer       viewer;
1020:   PetscViewerFormat format;

1023:   PetscObjectQuery((PetscObject)A,"Zoomviewer",(PetscObject*)&viewer);
1024:   PetscViewerGetFormat(viewer,&format);
1025:   PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);

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

1029:   if (format != PETSC_VIEWER_DRAW_CONTOUR) {
1030:     PetscDrawCollectiveBegin(draw);
1031:     /* Blue for negative, Cyan for zero and  Red for positive */
1032:     color = PETSC_DRAW_BLUE;
1033:     for (i=0; i<m; i++) {
1034:       y_l = m - i - 1.0; y_r = y_l + 1.0;
1035:       for (j=a->i[i]; j<a->i[i+1]; j++) {
1036:         x_l = a->j[j]; x_r = x_l + 1.0;
1037:         if (PetscRealPart(a->a[j]) >=  0.) continue;
1038:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
1039:       }
1040:     }
1041:     color = PETSC_DRAW_CYAN;
1042:     for (i=0; i<m; i++) {
1043:       y_l = m - i - 1.0; y_r = y_l + 1.0;
1044:       for (j=a->i[i]; j<a->i[i+1]; j++) {
1045:         x_l = a->j[j]; x_r = x_l + 1.0;
1046:         if (a->a[j] !=  0.) continue;
1047:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
1048:       }
1049:     }
1050:     color = PETSC_DRAW_RED;
1051:     for (i=0; i<m; i++) {
1052:       y_l = m - i - 1.0; y_r = y_l + 1.0;
1053:       for (j=a->i[i]; j<a->i[i+1]; j++) {
1054:         x_l = a->j[j]; x_r = x_l + 1.0;
1055:         if (PetscRealPart(a->a[j]) <=  0.) continue;
1056:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
1057:       }
1058:     }
1059:     PetscDrawCollectiveEnd(draw);
1060:   } else {
1061:     /* use contour shading to indicate magnitude of values */
1062:     /* first determine max of all nonzero values */
1063:     PetscReal minv = 0.0, maxv = 0.0;
1064:     PetscInt  nz = a->nz, count = 0;
1065:     PetscDraw popup;

1067:     for (i=0; i<nz; i++) {
1068:       if (PetscAbsScalar(a->a[i]) > maxv) maxv = PetscAbsScalar(a->a[i]);
1069:     }
1070:     if (minv >= maxv) maxv = minv + PETSC_SMALL;
1071:     PetscDrawGetPopup(draw,&popup);
1072:     PetscDrawScalePopup(popup,minv,maxv);

1074:     PetscDrawCollectiveBegin(draw);
1075:     for (i=0; i<m; i++) {
1076:       y_l = m - i - 1.0;
1077:       y_r = y_l + 1.0;
1078:       for (j=a->i[i]; j<a->i[i+1]; j++) {
1079:         x_l = a->j[j];
1080:         x_r = x_l + 1.0;
1081:         color = PetscDrawRealToColor(PetscAbsScalar(a->a[count]),minv,maxv);
1082:         PetscDrawRectangle(draw,x_l,y_l,x_r,y_r,color,color,color,color);
1083:         count++;
1084:       }
1085:     }
1086:     PetscDrawCollectiveEnd(draw);
1087:   }
1088:   return(0);
1089: }

1091: #include <petscdraw.h>
1092: PetscErrorCode MatView_SeqAIJ_Draw(Mat A,PetscViewer viewer)
1093: {
1095:   PetscDraw      draw;
1096:   PetscReal      xr,yr,xl,yl,h,w;
1097:   PetscBool      isnull;

1100:   PetscViewerDrawGetDraw(viewer,0,&draw);
1101:   PetscDrawIsNull(draw,&isnull);
1102:   if (isnull) return(0);

1104:   xr   = A->cmap->n; yr  = A->rmap->n; h = yr/10.0; w = xr/10.0;
1105:   xr  += w;          yr += h;         xl = -w;     yl = -h;
1106:   PetscDrawSetCoordinates(draw,xl,yl,xr,yr);
1107:   PetscObjectCompose((PetscObject)A,"Zoomviewer",(PetscObject)viewer);
1108:   PetscDrawZoom(draw,MatView_SeqAIJ_Draw_Zoom,A);
1109:   PetscObjectCompose((PetscObject)A,"Zoomviewer",NULL);
1110:   PetscDrawSave(draw);
1111:   return(0);
1112: }

1114: PetscErrorCode MatView_SeqAIJ(Mat A,PetscViewer viewer)
1115: {
1117:   PetscBool      iascii,isbinary,isdraw;

1120:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1121:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1122:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1123:   if (iascii) {
1124:     MatView_SeqAIJ_ASCII(A,viewer);
1125:   } else if (isbinary) {
1126:     MatView_SeqAIJ_Binary(A,viewer);
1127:   } else if (isdraw) {
1128:     MatView_SeqAIJ_Draw(A,viewer);
1129:   }
1130:   MatView_SeqAIJ_Inode(A,viewer);
1131:   return(0);
1132: }

1134: PetscErrorCode MatAssemblyEnd_SeqAIJ(Mat A,MatAssemblyType mode)
1135: {
1136:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1138:   PetscInt       fshift = 0,i,*ai = a->i,*aj = a->j,*imax = a->imax;
1139:   PetscInt       m      = A->rmap->n,*ip,N,*ailen = a->ilen,rmax = 0;
1140:   MatScalar      *aa    = a->a,*ap;
1141:   PetscReal      ratio  = 0.6;

1144:   if (mode == MAT_FLUSH_ASSEMBLY) return(0);
1145:   MatSeqAIJInvalidateDiagonal(A);
1146:   if (A->was_assembled && A->ass_nonzerostate == A->nonzerostate) {
1147:     /* we need to respect users asking to use or not the inodes routine in between matrix assemblies */
1148:     MatAssemblyEnd_SeqAIJ_Inode(A,mode);
1149:     return(0);
1150:   }

1152:   if (m) rmax = ailen[0]; /* determine row with most nonzeros */
1153:   for (i=1; i<m; i++) {
1154:     /* move each row back by the amount of empty slots (fshift) before it*/
1155:     fshift += imax[i-1] - ailen[i-1];
1156:     rmax    = PetscMax(rmax,ailen[i]);
1157:     if (fshift) {
1158:       ip = aj + ai[i];
1159:       ap = aa + ai[i];
1160:       N  = ailen[i];
1161:       PetscArraymove(ip-fshift,ip,N);
1162:       if (!A->structure_only) {
1163:         PetscArraymove(ap-fshift,ap,N);
1164:       }
1165:     }
1166:     ai[i] = ai[i-1] + ailen[i-1];
1167:   }
1168:   if (m) {
1169:     fshift += imax[m-1] - ailen[m-1];
1170:     ai[m]   = ai[m-1] + ailen[m-1];
1171:   }

1173:   /* reset ilen and imax for each row */
1174:   a->nonzerorowcnt = 0;
1175:   if (A->structure_only) {
1176:     PetscFree(a->imax);
1177:     PetscFree(a->ilen);
1178:   } else { /* !A->structure_only */
1179:     for (i=0; i<m; i++) {
1180:       ailen[i] = imax[i] = ai[i+1] - ai[i];
1181:       a->nonzerorowcnt += ((ai[i+1] - ai[i]) > 0);
1182:     }
1183:   }
1184:   a->nz = ai[m];
1185:   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);

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

1192:   A->info.mallocs    += a->reallocs;
1193:   a->reallocs         = 0;
1194:   A->info.nz_unneeded = (PetscReal)fshift;
1195:   a->rmax             = rmax;

1197:   if (!A->structure_only) {
1198:     MatCheckCompressedRow(A,a->nonzerorowcnt,&a->compressedrow,a->i,m,ratio);
1199:   }
1200:   MatAssemblyEnd_SeqAIJ_Inode(A,mode);
1201:   return(0);
1202: }

1204: PetscErrorCode MatRealPart_SeqAIJ(Mat A)
1205: {
1206:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1207:   PetscInt       i,nz = a->nz;
1208:   MatScalar      *aa = a->a;

1212:   for (i=0; i<nz; i++) aa[i] = PetscRealPart(aa[i]);
1213:   MatSeqAIJInvalidateDiagonal(A);
1214: #if defined(PETSC_HAVE_DEVICE)
1215:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) A->offloadmask = PETSC_OFFLOAD_CPU;
1216: #endif
1217:   return(0);
1218: }

1220: PetscErrorCode MatImaginaryPart_SeqAIJ(Mat A)
1221: {
1222:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1223:   PetscInt       i,nz = a->nz;
1224:   MatScalar      *aa = a->a;

1228:   for (i=0; i<nz; i++) aa[i] = PetscImaginaryPart(aa[i]);
1229:   MatSeqAIJInvalidateDiagonal(A);
1230: #if defined(PETSC_HAVE_DEVICE)
1231:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) A->offloadmask = PETSC_OFFLOAD_CPU;
1232: #endif
1233:   return(0);
1234: }

1236: PetscErrorCode MatZeroEntries_SeqAIJ(Mat A)
1237: {
1238:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

1242:   PetscArrayzero(a->a,a->i[A->rmap->n]);
1243:   MatSeqAIJInvalidateDiagonal(A);
1244: #if defined(PETSC_HAVE_DEVICE)
1245:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) A->offloadmask = PETSC_OFFLOAD_CPU;
1246: #endif
1247:   return(0);
1248: }

1250: PetscErrorCode MatDestroy_SeqAIJ(Mat A)
1251: {
1252:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

1256: #if defined(PETSC_USE_LOG)
1257:   PetscLogObjectState((PetscObject)A,"Rows=%D, Cols=%D, NZ=%D",A->rmap->n,A->cmap->n,a->nz);
1258: #endif
1259:   MatSeqXAIJFreeAIJ(A,&a->a,&a->j,&a->i);
1260:   ISDestroy(&a->row);
1261:   ISDestroy(&a->col);
1262:   PetscFree(a->diag);
1263:   PetscFree(a->ibdiag);
1264:   PetscFree(a->imax);
1265:   PetscFree(a->ilen);
1266:   PetscFree(a->ipre);
1267:   PetscFree3(a->idiag,a->mdiag,a->ssor_work);
1268:   PetscFree(a->solve_work);
1269:   ISDestroy(&a->icol);
1270:   PetscFree(a->saved_values);
1271:   PetscFree2(a->compressedrow.i,a->compressedrow.rindex);

1273:   MatDestroy_SeqAIJ_Inode(A);
1274:   PetscFree(A->data);

1276:   /* MatMatMultNumeric_SeqAIJ_SeqAIJ_Sorted may allocate this.
1277:      That function is so heavily used (sometimes in an hidden way through multnumeric function pointers)
1278:      that is hard to properly add this data to the MatProduct data. We free it here to avoid
1279:      users reusing the matrix object with different data to incur in obscure segmentation faults
1280:      due to different matrix sizes */
1281:   PetscObjectCompose((PetscObject)A,"__PETSc__ab_dense",NULL);

1283:   PetscObjectChangeTypeName((PetscObject)A,NULL);
1284:   PetscObjectComposeFunction((PetscObject)A,"MatSeqAIJSetColumnIndices_C",NULL);
1285:   PetscObjectComposeFunction((PetscObject)A,"MatStoreValues_C",NULL);
1286:   PetscObjectComposeFunction((PetscObject)A,"MatRetrieveValues_C",NULL);
1287:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqsbaij_C",NULL);
1288:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqbaij_C",NULL);
1289:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqaijperm_C",NULL);
1290: #if defined(PETSC_HAVE_CUDA)
1291:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqaijcusparse_C",NULL);
1292:   PetscObjectComposeFunction((PetscObject)A,"MatProductSetFromOptions_seqaijcusparse_seqaij_C",NULL);
1293: #endif
1294: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
1295:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqaijkokkos_C",NULL);
1296: #endif
1297:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqaijcrl_C",NULL);
1298: #if defined(PETSC_HAVE_ELEMENTAL)
1299:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_elemental_C",NULL);
1300: #endif
1301: #if defined(PETSC_HAVE_SCALAPACK)
1302:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_scalapack_C",NULL);
1303: #endif
1304: #if defined(PETSC_HAVE_HYPRE)
1305:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_hypre_C",NULL);
1306:   PetscObjectComposeFunction((PetscObject)A,"MatProductSetFromOptions_transpose_seqaij_seqaij_C",NULL);
1307: #endif
1308:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqdense_C",NULL);
1309:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_seqsell_C",NULL);
1310:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_seqaij_is_C",NULL);
1311:   PetscObjectComposeFunction((PetscObject)A,"MatIsTranspose_C",NULL);
1312:   PetscObjectComposeFunction((PetscObject)A,"MatSeqAIJSetPreallocation_C",NULL);
1313:   PetscObjectComposeFunction((PetscObject)A,"MatResetPreallocation_C",NULL);
1314:   PetscObjectComposeFunction((PetscObject)A,"MatSeqAIJSetPreallocationCSR_C",NULL);
1315:   PetscObjectComposeFunction((PetscObject)A,"MatReorderForNonzeroDiagonal_C",NULL);
1316:   PetscObjectComposeFunction((PetscObject)A,"MatProductSetFromOptions_is_seqaij_C",NULL);
1317:   PetscObjectComposeFunction((PetscObject)A,"MatProductSetFromOptions_seqdense_seqaij_C",NULL);
1318:   PetscObjectComposeFunction((PetscObject)A,"MatProductSetFromOptions_seqaij_seqaij_C",NULL);
1319:   return(0);
1320: }

1322: PetscErrorCode MatSetOption_SeqAIJ(Mat A,MatOption op,PetscBool flg)
1323: {
1324:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;

1328:   switch (op) {
1329:   case MAT_ROW_ORIENTED:
1330:     a->roworiented = flg;
1331:     break;
1332:   case MAT_KEEP_NONZERO_PATTERN:
1333:     a->keepnonzeropattern = flg;
1334:     break;
1335:   case MAT_NEW_NONZERO_LOCATIONS:
1336:     a->nonew = (flg ? 0 : 1);
1337:     break;
1338:   case MAT_NEW_NONZERO_LOCATION_ERR:
1339:     a->nonew = (flg ? -1 : 0);
1340:     break;
1341:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1342:     a->nonew = (flg ? -2 : 0);
1343:     break;
1344:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1345:     a->nounused = (flg ? -1 : 0);
1346:     break;
1347:   case MAT_IGNORE_ZERO_ENTRIES:
1348:     a->ignorezeroentries = flg;
1349:     break;
1350:   case MAT_SPD:
1351:   case MAT_SYMMETRIC:
1352:   case MAT_STRUCTURALLY_SYMMETRIC:
1353:   case MAT_HERMITIAN:
1354:   case MAT_SYMMETRY_ETERNAL:
1355:   case MAT_STRUCTURE_ONLY:
1356:     /* These options are handled directly by MatSetOption() */
1357:     break;
1358:   case MAT_NEW_DIAGONALS:
1359:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1360:   case MAT_USE_HASH_TABLE:
1361:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1362:     break;
1363:   case MAT_USE_INODES:
1364:     MatSetOption_SeqAIJ_Inode(A,MAT_USE_INODES,flg);
1365:     break;
1366:   case MAT_SUBMAT_SINGLEIS:
1367:     A->submat_singleis = flg;
1368:     break;
1369:   case MAT_SORTED_FULL:
1370:     if (flg) A->ops->setvalues = MatSetValues_SeqAIJ_SortedFull;
1371:     else     A->ops->setvalues = MatSetValues_SeqAIJ;
1372:     break;
1373:   default:
1374:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unknown option %d",op);
1375:   }
1376:   return(0);
1377: }

1379: PetscErrorCode MatGetDiagonal_SeqAIJ(Mat A,Vec v)
1380: {
1381:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1383:   PetscInt       i,j,n,*ai=a->i,*aj=a->j;
1384:   PetscScalar    *aa=a->a,*x;

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

1390:   if (A->factortype == MAT_FACTOR_ILU || A->factortype == MAT_FACTOR_LU) {
1391:     PetscInt *diag=a->diag;
1392:     VecGetArrayWrite(v,&x);
1393:     for (i=0; i<n; i++) x[i] = 1.0/aa[diag[i]];
1394:     VecRestoreArrayWrite(v,&x);
1395:     return(0);
1396:   }

1398:   VecGetArrayWrite(v,&x);
1399:   for (i=0; i<n; i++) {
1400:     x[i] = 0.0;
1401:     for (j=ai[i]; j<ai[i+1]; j++) {
1402:       if (aj[j] == i) {
1403:         x[i] = aa[j];
1404:         break;
1405:       }
1406:     }
1407:   }
1408:   VecRestoreArrayWrite(v,&x);
1409:   return(0);
1410: }

1412: #include <../src/mat/impls/aij/seq/ftn-kernels/fmult.h>
1413: PetscErrorCode MatMultTransposeAdd_SeqAIJ(Mat A,Vec xx,Vec zz,Vec yy)
1414: {
1415:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1416:   PetscScalar       *y;
1417:   const PetscScalar *x;
1418:   PetscErrorCode    ierr;
1419:   PetscInt          m = A->rmap->n;
1420: #if !defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1421:   const MatScalar   *v;
1422:   PetscScalar       alpha;
1423:   PetscInt          n,i,j;
1424:   const PetscInt    *idx,*ii,*ridx=NULL;
1425:   Mat_CompressedRow cprow    = a->compressedrow;
1426:   PetscBool         usecprow = cprow.use;
1427: #endif

1430:   if (zz != yy) {VecCopy(zz,yy);}
1431:   VecGetArrayRead(xx,&x);
1432:   VecGetArray(yy,&y);

1434: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1435:   fortranmulttransposeaddaij_(&m,x,a->i,a->j,a->a,y);
1436: #else
1437:   if (usecprow) {
1438:     m    = cprow.nrows;
1439:     ii   = cprow.i;
1440:     ridx = cprow.rindex;
1441:   } else {
1442:     ii = a->i;
1443:   }
1444:   for (i=0; i<m; i++) {
1445:     idx = a->j + ii[i];
1446:     v   = a->a + ii[i];
1447:     n   = ii[i+1] - ii[i];
1448:     if (usecprow) {
1449:       alpha = x[ridx[i]];
1450:     } else {
1451:       alpha = x[i];
1452:     }
1453:     for (j=0; j<n; j++) y[idx[j]] += alpha*v[j];
1454:   }
1455: #endif
1456:   PetscLogFlops(2.0*a->nz);
1457:   VecRestoreArrayRead(xx,&x);
1458:   VecRestoreArray(yy,&y);
1459:   return(0);
1460: }

1462: PetscErrorCode MatMultTranspose_SeqAIJ(Mat A,Vec xx,Vec yy)
1463: {

1467:   VecSet(yy,0.0);
1468:   MatMultTransposeAdd_SeqAIJ(A,xx,yy,yy);
1469:   return(0);
1470: }

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

1474: PetscErrorCode MatMult_SeqAIJ(Mat A,Vec xx,Vec yy)
1475: {
1476:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1477:   PetscScalar       *y;
1478:   const PetscScalar *x;
1479:   const MatScalar   *aa;
1480:   PetscErrorCode    ierr;
1481:   PetscInt          m=A->rmap->n;
1482:   const PetscInt    *aj,*ii,*ridx=NULL;
1483:   PetscInt          n,i;
1484:   PetscScalar       sum;
1485:   PetscBool         usecprow=a->compressedrow.use;

1487: #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1488: #pragma disjoint(*x,*y,*aa)
1489: #endif

1492:   if (a->inode.use && a->inode.checked) {
1493:     MatMult_SeqAIJ_Inode(A,xx,yy);
1494:     return(0);
1495:   }
1496:   VecGetArrayRead(xx,&x);
1497:   VecGetArray(yy,&y);
1498:   ii   = a->i;
1499:   if (usecprow) { /* use compressed row format */
1500:     PetscArrayzero(y,m);
1501:     m    = a->compressedrow.nrows;
1502:     ii   = a->compressedrow.i;
1503:     ridx = a->compressedrow.rindex;
1504:     for (i=0; i<m; i++) {
1505:       n           = ii[i+1] - ii[i];
1506:       aj          = a->j + ii[i];
1507:       aa          = a->a + ii[i];
1508:       sum         = 0.0;
1509:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1510:       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1511:       y[*ridx++] = sum;
1512:     }
1513:   } else { /* do not use compressed row format */
1514: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTAIJ)
1515:     aj   = a->j;
1516:     aa   = a->a;
1517:     fortranmultaij_(&m,x,ii,aj,aa,y);
1518: #else
1519:     for (i=0; i<m; i++) {
1520:       n           = ii[i+1] - ii[i];
1521:       aj          = a->j + ii[i];
1522:       aa          = a->a + ii[i];
1523:       sum         = 0.0;
1524:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1525:       y[i] = sum;
1526:     }
1527: #endif
1528:   }
1529:   PetscLogFlops(2.0*a->nz - a->nonzerorowcnt);
1530:   VecRestoreArrayRead(xx,&x);
1531:   VecRestoreArray(yy,&y);
1532:   return(0);
1533: }

1535: PetscErrorCode MatMultMax_SeqAIJ(Mat A,Vec xx,Vec yy)
1536: {
1537:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1538:   PetscScalar       *y;
1539:   const PetscScalar *x;
1540:   const MatScalar   *aa;
1541:   PetscErrorCode    ierr;
1542:   PetscInt          m=A->rmap->n;
1543:   const PetscInt    *aj,*ii,*ridx=NULL;
1544:   PetscInt          n,i,nonzerorow=0;
1545:   PetscScalar       sum;
1546:   PetscBool         usecprow=a->compressedrow.use;

1548: #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1549: #pragma disjoint(*x,*y,*aa)
1550: #endif

1553:   VecGetArrayRead(xx,&x);
1554:   VecGetArray(yy,&y);
1555:   if (usecprow) { /* use compressed row format */
1556:     m    = a->compressedrow.nrows;
1557:     ii   = a->compressedrow.i;
1558:     ridx = a->compressedrow.rindex;
1559:     for (i=0; i<m; i++) {
1560:       n           = ii[i+1] - ii[i];
1561:       aj          = a->j + ii[i];
1562:       aa          = a->a + ii[i];
1563:       sum         = 0.0;
1564:       nonzerorow += (n>0);
1565:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1566:       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1567:       y[*ridx++] = sum;
1568:     }
1569:   } else { /* do not use compressed row format */
1570:     ii = a->i;
1571:     for (i=0; i<m; i++) {
1572:       n           = ii[i+1] - ii[i];
1573:       aj          = a->j + ii[i];
1574:       aa          = a->a + ii[i];
1575:       sum         = 0.0;
1576:       nonzerorow += (n>0);
1577:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1578:       y[i] = sum;
1579:     }
1580:   }
1581:   PetscLogFlops(2.0*a->nz - nonzerorow);
1582:   VecRestoreArrayRead(xx,&x);
1583:   VecRestoreArray(yy,&y);
1584:   return(0);
1585: }

1587: PetscErrorCode MatMultAddMax_SeqAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1588: {
1589:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1590:   PetscScalar       *y,*z;
1591:   const PetscScalar *x;
1592:   const MatScalar   *aa;
1593:   PetscErrorCode    ierr;
1594:   PetscInt          m = A->rmap->n,*aj,*ii;
1595:   PetscInt          n,i,*ridx=NULL;
1596:   PetscScalar       sum;
1597:   PetscBool         usecprow=a->compressedrow.use;

1600:   VecGetArrayRead(xx,&x);
1601:   VecGetArrayPair(yy,zz,&y,&z);
1602:   if (usecprow) { /* use compressed row format */
1603:     if (zz != yy) {
1604:       PetscArraycpy(z,y,m);
1605:     }
1606:     m    = a->compressedrow.nrows;
1607:     ii   = a->compressedrow.i;
1608:     ridx = a->compressedrow.rindex;
1609:     for (i=0; i<m; i++) {
1610:       n   = ii[i+1] - ii[i];
1611:       aj  = a->j + ii[i];
1612:       aa  = a->a + ii[i];
1613:       sum = y[*ridx];
1614:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1615:       z[*ridx++] = sum;
1616:     }
1617:   } else { /* do not use compressed row format */
1618:     ii = a->i;
1619:     for (i=0; i<m; i++) {
1620:       n   = ii[i+1] - ii[i];
1621:       aj  = a->j + ii[i];
1622:       aa  = a->a + ii[i];
1623:       sum = y[i];
1624:       PetscSparseDenseMaxDot(sum,x,aa,aj,n);
1625:       z[i] = sum;
1626:     }
1627:   }
1628:   PetscLogFlops(2.0*a->nz);
1629:   VecRestoreArrayRead(xx,&x);
1630:   VecRestoreArrayPair(yy,zz,&y,&z);
1631:   return(0);
1632: }

1634: #include <../src/mat/impls/aij/seq/ftn-kernels/fmultadd.h>
1635: PetscErrorCode MatMultAdd_SeqAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1636: {
1637:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1638:   PetscScalar       *y,*z;
1639:   const PetscScalar *x;
1640:   const MatScalar   *aa;
1641:   PetscErrorCode    ierr;
1642:   const PetscInt    *aj,*ii,*ridx=NULL;
1643:   PetscInt          m = A->rmap->n,n,i;
1644:   PetscScalar       sum;
1645:   PetscBool         usecprow=a->compressedrow.use;

1648:   if (a->inode.use && a->inode.checked) {
1649:     MatMultAdd_SeqAIJ_Inode(A,xx,yy,zz);
1650:     return(0);
1651:   }
1652:   VecGetArrayRead(xx,&x);
1653:   VecGetArrayPair(yy,zz,&y,&z);
1654:   if (usecprow) { /* use compressed row format */
1655:     if (zz != yy) {
1656:       PetscArraycpy(z,y,m);
1657:     }
1658:     m    = a->compressedrow.nrows;
1659:     ii   = a->compressedrow.i;
1660:     ridx = a->compressedrow.rindex;
1661:     for (i=0; i<m; i++) {
1662:       n   = ii[i+1] - ii[i];
1663:       aj  = a->j + ii[i];
1664:       aa  = a->a + ii[i];
1665:       sum = y[*ridx];
1666:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1667:       z[*ridx++] = sum;
1668:     }
1669:   } else { /* do not use compressed row format */
1670:     ii = a->i;
1671: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTADDAIJ)
1672:     aj = a->j;
1673:     aa = a->a;
1674:     fortranmultaddaij_(&m,x,ii,aj,aa,y,z);
1675: #else
1676:     for (i=0; i<m; i++) {
1677:       n   = ii[i+1] - ii[i];
1678:       aj  = a->j + ii[i];
1679:       aa  = a->a + ii[i];
1680:       sum = y[i];
1681:       PetscSparseDensePlusDot(sum,x,aa,aj,n);
1682:       z[i] = sum;
1683:     }
1684: #endif
1685:   }
1686:   PetscLogFlops(2.0*a->nz);
1687:   VecRestoreArrayRead(xx,&x);
1688:   VecRestoreArrayPair(yy,zz,&y,&z);
1689:   return(0);
1690: }

1692: /*
1693:      Adds diagonal pointers to sparse matrix structure.
1694: */
1695: PetscErrorCode MatMarkDiagonal_SeqAIJ(Mat A)
1696: {
1697:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1699:   PetscInt       i,j,m = A->rmap->n;

1702:   if (!a->diag) {
1703:     PetscMalloc1(m,&a->diag);
1704:     PetscLogObjectMemory((PetscObject)A, m*sizeof(PetscInt));
1705:   }
1706:   for (i=0; i<A->rmap->n; i++) {
1707:     a->diag[i] = a->i[i+1];
1708:     for (j=a->i[i]; j<a->i[i+1]; j++) {
1709:       if (a->j[j] == i) {
1710:         a->diag[i] = j;
1711:         break;
1712:       }
1713:     }
1714:   }
1715:   return(0);
1716: }

1718: PetscErrorCode MatShift_SeqAIJ(Mat A,PetscScalar v)
1719: {
1720:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1721:   const PetscInt    *diag = (const PetscInt*)a->diag;
1722:   const PetscInt    *ii = (const PetscInt*) a->i;
1723:   PetscInt          i,*mdiag = NULL;
1724:   PetscErrorCode    ierr;
1725:   PetscInt          cnt = 0; /* how many diagonals are missing */

1728:   if (!A->preallocated || !a->nz) {
1729:     MatSeqAIJSetPreallocation(A,1,NULL);
1730:     MatShift_Basic(A,v);
1731:     return(0);
1732:   }

1734:   if (a->diagonaldense) {
1735:     cnt = 0;
1736:   } else {
1737:     PetscCalloc1(A->rmap->n,&mdiag);
1738:     for (i=0; i<A->rmap->n; i++) {
1739:       if (diag[i] >= ii[i+1]) {
1740:         cnt++;
1741:         mdiag[i] = 1;
1742:       }
1743:     }
1744:   }
1745:   if (!cnt) {
1746:     MatShift_Basic(A,v);
1747:   } else {
1748:     PetscScalar *olda = a->a;  /* preserve pointers to current matrix nonzeros structure and values */
1749:     PetscInt    *oldj = a->j, *oldi = a->i;
1750:     PetscBool   singlemalloc = a->singlemalloc,free_a = a->free_a,free_ij = a->free_ij;

1752:     a->a = NULL;
1753:     a->j = NULL;
1754:     a->i = NULL;
1755:     /* increase the values in imax for each row where a diagonal is being inserted then reallocate the matrix data structures */
1756:     for (i=0; i<A->rmap->n; i++) {
1757:       a->imax[i] += mdiag[i];
1758:       a->imax[i] = PetscMin(a->imax[i],A->cmap->n);
1759:     }
1760:     MatSeqAIJSetPreallocation_SeqAIJ(A,0,a->imax);

1762:     /* copy old values into new matrix data structure */
1763:     for (i=0; i<A->rmap->n; i++) {
1764:       MatSetValues(A,1,&i,a->imax[i] - mdiag[i],&oldj[oldi[i]],&olda[oldi[i]],ADD_VALUES);
1765:       if (i < A->cmap->n) {
1766:         MatSetValue(A,i,i,v,ADD_VALUES);
1767:       }
1768:     }
1769:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1770:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1771:     if (singlemalloc) {
1772:       PetscFree3(olda,oldj,oldi);
1773:     } else {
1774:       if (free_a)  {PetscFree(olda);}
1775:       if (free_ij) {PetscFree(oldj);}
1776:       if (free_ij) {PetscFree(oldi);}
1777:     }
1778:   }
1779:   PetscFree(mdiag);
1780:   a->diagonaldense = PETSC_TRUE;
1781:   return(0);
1782: }

1784: /*
1785:      Checks for missing diagonals
1786: */
1787: PetscErrorCode MatMissingDiagonal_SeqAIJ(Mat A,PetscBool  *missing,PetscInt *d)
1788: {
1789:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
1790:   PetscInt       *diag,*ii = a->i,i;

1794:   *missing = PETSC_FALSE;
1795:   if (A->rmap->n > 0 && !ii) {
1796:     *missing = PETSC_TRUE;
1797:     if (d) *d = 0;
1798:     PetscInfo(A,"Matrix has no entries therefore is missing diagonal\n");
1799:   } else {
1800:     PetscInt n;
1801:     n = PetscMin(A->rmap->n, A->cmap->n);
1802:     diag = a->diag;
1803:     for (i=0; i<n; i++) {
1804:       if (diag[i] >= ii[i+1]) {
1805:         *missing = PETSC_TRUE;
1806:         if (d) *d = i;
1807:         PetscInfo1(A,"Matrix is missing diagonal number %D\n",i);
1808:         break;
1809:       }
1810:     }
1811:   }
1812:   return(0);
1813: }

1815: #include <petscblaslapack.h>
1816: #include <petsc/private/kernels/blockinvert.h>

1818: /*
1819:     Note that values is allocated externally by the PC and then passed into this routine
1820: */
1821: PetscErrorCode MatInvertVariableBlockDiagonal_SeqAIJ(Mat A,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *diag)
1822: {
1823:   PetscErrorCode  ierr;
1824:   PetscInt        n = A->rmap->n, i, ncnt = 0, *indx,j,bsizemax = 0,*v_pivots;
1825:   PetscBool       allowzeropivot,zeropivotdetected=PETSC_FALSE;
1826:   const PetscReal shift = 0.0;
1827:   PetscInt        ipvt[5];
1828:   PetscScalar     work[25],*v_work;

1831:   allowzeropivot = PetscNot(A->erroriffailure);
1832:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
1833:   if (ncnt != n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Total blocksizes %D doesn't match number matrix rows %D",ncnt,n);
1834:   for (i=0; i<nblocks; i++) {
1835:     bsizemax = PetscMax(bsizemax,bsizes[i]);
1836:   }
1837:   PetscMalloc1(bsizemax,&indx);
1838:   if (bsizemax > 7) {
1839:     PetscMalloc2(bsizemax,&v_work,bsizemax,&v_pivots);
1840:   }
1841:   ncnt = 0;
1842:   for (i=0; i<nblocks; i++) {
1843:     for (j=0; j<bsizes[i]; j++) indx[j] = ncnt+j;
1844:     MatGetValues(A,bsizes[i],indx,bsizes[i],indx,diag);
1845:     switch (bsizes[i]) {
1846:     case 1:
1847:       *diag = 1.0/(*diag);
1848:       break;
1849:     case 2:
1850:       PetscKernel_A_gets_inverse_A_2(diag,shift,allowzeropivot,&zeropivotdetected);
1851:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1852:       PetscKernel_A_gets_transpose_A_2(diag);
1853:       break;
1854:     case 3:
1855:       PetscKernel_A_gets_inverse_A_3(diag,shift,allowzeropivot,&zeropivotdetected);
1856:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1857:       PetscKernel_A_gets_transpose_A_3(diag);
1858:       break;
1859:     case 4:
1860:       PetscKernel_A_gets_inverse_A_4(diag,shift,allowzeropivot,&zeropivotdetected);
1861:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1862:       PetscKernel_A_gets_transpose_A_4(diag);
1863:       break;
1864:     case 5:
1865:       PetscKernel_A_gets_inverse_A_5(diag,ipvt,work,shift,allowzeropivot,&zeropivotdetected);
1866:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1867:       PetscKernel_A_gets_transpose_A_5(diag);
1868:       break;
1869:     case 6:
1870:       PetscKernel_A_gets_inverse_A_6(diag,shift,allowzeropivot,&zeropivotdetected);
1871:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1872:       PetscKernel_A_gets_transpose_A_6(diag);
1873:       break;
1874:     case 7:
1875:       PetscKernel_A_gets_inverse_A_7(diag,shift,allowzeropivot,&zeropivotdetected);
1876:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1877:       PetscKernel_A_gets_transpose_A_7(diag);
1878:       break;
1879:     default:
1880:       PetscKernel_A_gets_inverse_A(bsizes[i],diag,v_pivots,v_work,allowzeropivot,&zeropivotdetected);
1881:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1882:       PetscKernel_A_gets_transpose_A_N(diag,bsizes[i]);
1883:     }
1884:     ncnt   += bsizes[i];
1885:     diag += bsizes[i]*bsizes[i];
1886:   }
1887:   if (bsizemax > 7) {
1888:     PetscFree2(v_work,v_pivots);
1889:   }
1890:   PetscFree(indx);
1891:   return(0);
1892: }

1894: /*
1895:    Negative shift indicates do not generate an error if there is a zero diagonal, just invert it anyways
1896: */
1897: PetscErrorCode  MatInvertDiagonal_SeqAIJ(Mat A,PetscScalar omega,PetscScalar fshift)
1898: {
1899:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*) A->data;
1901:   PetscInt       i,*diag,m = A->rmap->n;
1902:   MatScalar      *v = a->a;
1903:   PetscScalar    *idiag,*mdiag;

1906:   if (a->idiagvalid) return(0);
1907:   MatMarkDiagonal_SeqAIJ(A);
1908:   diag = a->diag;
1909:   if (!a->idiag) {
1910:     PetscMalloc3(m,&a->idiag,m,&a->mdiag,m,&a->ssor_work);
1911:     PetscLogObjectMemory((PetscObject)A, 3*m*sizeof(PetscScalar));
1912:     v    = a->a;
1913:   }
1914:   mdiag = a->mdiag;
1915:   idiag = a->idiag;

1917:   if (omega == 1.0 && PetscRealPart(fshift) <= 0.0) {
1918:     for (i=0; i<m; i++) {
1919:       mdiag[i] = v[diag[i]];
1920:       if (!PetscAbsScalar(mdiag[i])) { /* zero diagonal */
1921:         if (PetscRealPart(fshift)) {
1922:           PetscInfo1(A,"Zero diagonal on row %D\n",i);
1923:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1924:           A->factorerror_zeropivot_value = 0.0;
1925:           A->factorerror_zeropivot_row   = i;
1926:         } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Zero diagonal on row %D",i);
1927:       }
1928:       idiag[i] = 1.0/v[diag[i]];
1929:     }
1930:     PetscLogFlops(m);
1931:   } else {
1932:     for (i=0; i<m; i++) {
1933:       mdiag[i] = v[diag[i]];
1934:       idiag[i] = omega/(fshift + v[diag[i]]);
1935:     }
1936:     PetscLogFlops(2.0*m);
1937:   }
1938:   a->idiagvalid = PETSC_TRUE;
1939:   return(0);
1940: }

1942: #include <../src/mat/impls/aij/seq/ftn-kernels/frelax.h>
1943: PetscErrorCode MatSOR_SeqAIJ(Mat A,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
1944: {
1945:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
1946:   PetscScalar       *x,d,sum,*t,scale;
1947:   const MatScalar   *v,*idiag=NULL,*mdiag;
1948:   const PetscScalar *b, *bs,*xb, *ts;
1949:   PetscErrorCode    ierr;
1950:   PetscInt          n,m = A->rmap->n,i;
1951:   const PetscInt    *idx,*diag;

1954:   if (a->inode.use && a->inode.checked && omega == 1.0 && fshift == 0.0) {
1955:     MatSOR_SeqAIJ_Inode(A,bb,omega,flag,fshift,its,lits,xx);
1956:     return(0);
1957:   }
1958:   its = its*lits;

1960:   if (fshift != a->fshift || omega != a->omega) a->idiagvalid = PETSC_FALSE; /* must recompute idiag[] */
1961:   if (!a->idiagvalid) {MatInvertDiagonal_SeqAIJ(A,omega,fshift);}
1962:   a->fshift = fshift;
1963:   a->omega  = omega;

1965:   diag  = a->diag;
1966:   t     = a->ssor_work;
1967:   idiag = a->idiag;
1968:   mdiag = a->mdiag;

1970:   VecGetArray(xx,&x);
1971:   VecGetArrayRead(bb,&b);
1972:   /* We count flops by assuming the upper triangular and lower triangular parts have the same number of nonzeros */
1973:   if (flag == SOR_APPLY_UPPER) {
1974:     /* apply (U + D/omega) to the vector */
1975:     bs = b;
1976:     for (i=0; i<m; i++) {
1977:       d   = fshift + mdiag[i];
1978:       n   = a->i[i+1] - diag[i] - 1;
1979:       idx = a->j + diag[i] + 1;
1980:       v   = a->a + diag[i] + 1;
1981:       sum = b[i]*d/omega;
1982:       PetscSparseDensePlusDot(sum,bs,v,idx,n);
1983:       x[i] = sum;
1984:     }
1985:     VecRestoreArray(xx,&x);
1986:     VecRestoreArrayRead(bb,&b);
1987:     PetscLogFlops(a->nz);
1988:     return(0);
1989:   }

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

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

1998:     to a vector efficiently using Eisenstat's trick.
1999:     */
2000:     scale = (2.0/omega) - 1.0;

2002:     /*  x = (E + U)^{-1} b */
2003:     for (i=m-1; i>=0; i--) {
2004:       n   = a->i[i+1] - diag[i] - 1;
2005:       idx = a->j + diag[i] + 1;
2006:       v   = a->a + diag[i] + 1;
2007:       sum = b[i];
2008:       PetscSparseDenseMinusDot(sum,x,v,idx,n);
2009:       x[i] = sum*idiag[i];
2010:     }

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

2016:     /*  t = (E + L)^{-1}t */
2017:     ts   = t;
2018:     diag = a->diag;
2019:     for (i=0; i<m; i++) {
2020:       n   = diag[i] - a->i[i];
2021:       idx = a->j + a->i[i];
2022:       v   = a->a + a->i[i];
2023:       sum = t[i];
2024:       PetscSparseDenseMinusDot(sum,ts,v,idx,n);
2025:       t[i] = sum*idiag[i];
2026:       /*  x = x + t */
2027:       x[i] += t[i];
2028:     }

2030:     PetscLogFlops(6.0*m-1 + 2.0*a->nz);
2031:     VecRestoreArray(xx,&x);
2032:     VecRestoreArrayRead(bb,&b);
2033:     return(0);
2034:   }
2035:   if (flag & SOR_ZERO_INITIAL_GUESS) {
2036:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
2037:       for (i=0; i<m; i++) {
2038:         n   = diag[i] - a->i[i];
2039:         idx = a->j + a->i[i];
2040:         v   = a->a + a->i[i];
2041:         sum = b[i];
2042:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
2043:         t[i] = sum;
2044:         x[i] = sum*idiag[i];
2045:       }
2046:       xb   = t;
2047:       PetscLogFlops(a->nz);
2048:     } else xb = b;
2049:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
2050:       for (i=m-1; i>=0; i--) {
2051:         n   = a->i[i+1] - diag[i] - 1;
2052:         idx = a->j + diag[i] + 1;
2053:         v   = a->a + diag[i] + 1;
2054:         sum = xb[i];
2055:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
2056:         if (xb == b) {
2057:           x[i] = sum*idiag[i];
2058:         } else {
2059:           x[i] = (1-omega)*x[i] + sum*idiag[i];  /* omega in idiag */
2060:         }
2061:       }
2062:       PetscLogFlops(a->nz); /* assumes 1/2 in upper */
2063:     }
2064:     its--;
2065:   }
2066:   while (its--) {
2067:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
2068:       for (i=0; i<m; i++) {
2069:         /* lower */
2070:         n   = diag[i] - a->i[i];
2071:         idx = a->j + a->i[i];
2072:         v   = a->a + a->i[i];
2073:         sum = b[i];
2074:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
2075:         t[i] = sum;             /* save application of the lower-triangular part */
2076:         /* upper */
2077:         n   = a->i[i+1] - diag[i] - 1;
2078:         idx = a->j + diag[i] + 1;
2079:         v   = a->a + diag[i] + 1;
2080:         PetscSparseDenseMinusDot(sum,x,v,idx,n);
2081:         x[i] = (1. - omega)*x[i] + sum*idiag[i]; /* omega in idiag */
2082:       }
2083:       xb   = t;
2084:       PetscLogFlops(2.0*a->nz);
2085:     } else xb = b;
2086:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
2087:       for (i=m-1; i>=0; i--) {
2088:         sum = xb[i];
2089:         if (xb == b) {
2090:           /* whole matrix (no checkpointing available) */
2091:           n   = a->i[i+1] - a->i[i];
2092:           idx = a->j + a->i[i];
2093:           v   = a->a + a->i[i];
2094:           PetscSparseDenseMinusDot(sum,x,v,idx,n);
2095:           x[i] = (1. - omega)*x[i] + (sum + mdiag[i]*x[i])*idiag[i];
2096:         } else { /* lower-triangular part has been saved, so only apply upper-triangular */
2097:           n   = a->i[i+1] - diag[i] - 1;
2098:           idx = a->j + diag[i] + 1;
2099:           v   = a->a + diag[i] + 1;
2100:           PetscSparseDenseMinusDot(sum,x,v,idx,n);
2101:           x[i] = (1. - omega)*x[i] + sum*idiag[i];  /* omega in idiag */
2102:         }
2103:       }
2104:       if (xb == b) {
2105:         PetscLogFlops(2.0*a->nz);
2106:       } else {
2107:         PetscLogFlops(a->nz); /* assumes 1/2 in upper */
2108:       }
2109:     }
2110:   }
2111:   VecRestoreArray(xx,&x);
2112:   VecRestoreArrayRead(bb,&b);
2113:   return(0);
2114: }


2117: PetscErrorCode MatGetInfo_SeqAIJ(Mat A,MatInfoType flag,MatInfo *info)
2118: {
2119:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;

2122:   info->block_size   = 1.0;
2123:   info->nz_allocated = a->maxnz;
2124:   info->nz_used      = a->nz;
2125:   info->nz_unneeded  = (a->maxnz - a->nz);
2126:   info->assemblies   = A->num_ass;
2127:   info->mallocs      = A->info.mallocs;
2128:   info->memory       = ((PetscObject)A)->mem;
2129:   if (A->factortype) {
2130:     info->fill_ratio_given  = A->info.fill_ratio_given;
2131:     info->fill_ratio_needed = A->info.fill_ratio_needed;
2132:     info->factor_mallocs    = A->info.factor_mallocs;
2133:   } else {
2134:     info->fill_ratio_given  = 0;
2135:     info->fill_ratio_needed = 0;
2136:     info->factor_mallocs    = 0;
2137:   }
2138:   return(0);
2139: }

2141: PetscErrorCode MatZeroRows_SeqAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
2142: {
2143:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
2144:   PetscInt          i,m = A->rmap->n - 1;
2145:   PetscErrorCode    ierr;
2146:   const PetscScalar *xx;
2147:   PetscScalar       *bb;
2148:   PetscInt          d = 0;

2151:   if (x && b) {
2152:     VecGetArrayRead(x,&xx);
2153:     VecGetArray(b,&bb);
2154:     for (i=0; i<N; i++) {
2155:       if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
2156:       if (rows[i] >= A->cmap->n) continue;
2157:       bb[rows[i]] = diag*xx[rows[i]];
2158:     }
2159:     VecRestoreArrayRead(x,&xx);
2160:     VecRestoreArray(b,&bb);
2161:   }

2163:   if (a->keepnonzeropattern) {
2164:     for (i=0; i<N; i++) {
2165:       if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
2166:       PetscArrayzero(&a->a[a->i[rows[i]]],a->ilen[rows[i]]);
2167:     }
2168:     if (diag != 0.0) {
2169:       for (i=0; i<N; i++) {
2170:         d = rows[i];
2171:         if (rows[i] >= A->cmap->n) continue;
2172:         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);
2173:       }
2174:       for (i=0; i<N; i++) {
2175:         if (rows[i] >= A->cmap->n) continue;
2176:         a->a[a->diag[rows[i]]] = diag;
2177:       }
2178:     }
2179:   } else {
2180:     if (diag != 0.0) {
2181:       for (i=0; i<N; i++) {
2182:         if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
2183:         if (a->ilen[rows[i]] > 0) {
2184:           if (rows[i] >= A->cmap->n) {
2185:             a->ilen[rows[i]] = 0;
2186:           } else {
2187:             a->ilen[rows[i]]    = 1;
2188:             a->a[a->i[rows[i]]] = diag;
2189:             a->j[a->i[rows[i]]] = rows[i];
2190:           }
2191:         } else if (rows[i] < A->cmap->n) { /* in case row was completely empty */
2192:           MatSetValues_SeqAIJ(A,1,&rows[i],1,&rows[i],&diag,INSERT_VALUES);
2193:         }
2194:       }
2195:     } else {
2196:       for (i=0; i<N; i++) {
2197:         if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
2198:         a->ilen[rows[i]] = 0;
2199:       }
2200:     }
2201:     A->nonzerostate++;
2202:   }
2203: #if defined(PETSC_HAVE_DEVICE)
2204:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) A->offloadmask = PETSC_OFFLOAD_CPU;
2205: #endif
2206:   (*A->ops->assemblyend)(A,MAT_FINAL_ASSEMBLY);
2207:   return(0);
2208: }

2210: PetscErrorCode MatZeroRowsColumns_SeqAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
2211: {
2212:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
2213:   PetscInt          i,j,m = A->rmap->n - 1,d = 0;
2214:   PetscErrorCode    ierr;
2215:   PetscBool         missing,*zeroed,vecs = PETSC_FALSE;
2216:   const PetscScalar *xx;
2217:   PetscScalar       *bb;

2220:   if (x && b) {
2221:     VecGetArrayRead(x,&xx);
2222:     VecGetArray(b,&bb);
2223:     vecs = PETSC_TRUE;
2224:   }
2225:   PetscCalloc1(A->rmap->n,&zeroed);
2226:   for (i=0; i<N; i++) {
2227:     if (rows[i] < 0 || rows[i] > m) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"row %D out of range", rows[i]);
2228:     PetscArrayzero(&a->a[a->i[rows[i]]],a->ilen[rows[i]]);

2230:     zeroed[rows[i]] = PETSC_TRUE;
2231:   }
2232:   for (i=0; i<A->rmap->n; i++) {
2233:     if (!zeroed[i]) {
2234:       for (j=a->i[i]; j<a->i[i+1]; j++) {
2235:         if (a->j[j] < A->rmap->n && zeroed[a->j[j]]) {
2236:           if (vecs) bb[i] -= a->a[j]*xx[a->j[j]];
2237:           a->a[j] = 0.0;
2238:         }
2239:       }
2240:     } else if (vecs && i < A->cmap->N) bb[i] = diag*xx[i];
2241:   }
2242:   if (x && b) {
2243:     VecRestoreArrayRead(x,&xx);
2244:     VecRestoreArray(b,&bb);
2245:   }
2246:   PetscFree(zeroed);
2247:   if (diag != 0.0) {
2248:     MatMissingDiagonal_SeqAIJ(A,&missing,&d);
2249:     if (missing) {
2250:       for (i=0; i<N; i++) {
2251:         if (rows[i] >= A->cmap->N) continue;
2252:         if (a->nonew && rows[i] >= d) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Matrix is missing diagonal entry in row %D (%D)",d,rows[i]);
2253:         MatSetValues_SeqAIJ(A,1,&rows[i],1,&rows[i],&diag,INSERT_VALUES);
2254:       }
2255:     } else {
2256:       for (i=0; i<N; i++) {
2257:         a->a[a->diag[rows[i]]] = diag;
2258:       }
2259:     }
2260:   }
2261: #if defined(PETSC_HAVE_DEVICE)
2262:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) A->offloadmask = PETSC_OFFLOAD_CPU;
2263: #endif
2264:   (*A->ops->assemblyend)(A,MAT_FINAL_ASSEMBLY);
2265:   return(0);
2266: }

2268: PetscErrorCode MatGetRow_SeqAIJ(Mat A,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
2269: {
2270:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;
2271:   PetscInt   *itmp;

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

2276:   *nz = a->i[row+1] - a->i[row];
2277:   if (v) *v = a->a + a->i[row];
2278:   if (idx) {
2279:     itmp = a->j + a->i[row];
2280:     if (*nz) *idx = itmp;
2281:     else *idx = NULL;
2282:   }
2283:   return(0);
2284: }

2286: /* remove this function? */
2287: PetscErrorCode MatRestoreRow_SeqAIJ(Mat A,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
2288: {
2290:   return(0);
2291: }

2293: PetscErrorCode MatNorm_SeqAIJ(Mat A,NormType type,PetscReal *nrm)
2294: {
2295:   Mat_SeqAIJ     *a  = (Mat_SeqAIJ*)A->data;
2296:   MatScalar      *v  = a->a;
2297:   PetscReal      sum = 0.0;
2299:   PetscInt       i,j;

2302:   if (type == NORM_FROBENIUS) {
2303: #if defined(PETSC_USE_REAL___FP16)
2304:     PetscBLASInt one = 1,nz = a->nz;
2305:     *nrm = BLASnrm2_(&nz,v,&one);
2306: #else
2307:     for (i=0; i<a->nz; i++) {
2308:       sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
2309:     }
2310:     *nrm = PetscSqrtReal(sum);
2311: #endif
2312:     PetscLogFlops(2.0*a->nz);
2313:   } else if (type == NORM_1) {
2314:     PetscReal *tmp;
2315:     PetscInt  *jj = a->j;
2316:     PetscCalloc1(A->cmap->n+1,&tmp);
2317:     *nrm = 0.0;
2318:     for (j=0; j<a->nz; j++) {
2319:       tmp[*jj++] += PetscAbsScalar(*v);  v++;
2320:     }
2321:     for (j=0; j<A->cmap->n; j++) {
2322:       if (tmp[j] > *nrm) *nrm = tmp[j];
2323:     }
2324:     PetscFree(tmp);
2325:     PetscLogFlops(PetscMax(a->nz-1,0));
2326:   } else if (type == NORM_INFINITY) {
2327:     *nrm = 0.0;
2328:     for (j=0; j<A->rmap->n; j++) {
2329:       v   = a->a + a->i[j];
2330:       sum = 0.0;
2331:       for (i=0; i<a->i[j+1]-a->i[j]; i++) {
2332:         sum += PetscAbsScalar(*v); v++;
2333:       }
2334:       if (sum > *nrm) *nrm = sum;
2335:     }
2336:     PetscLogFlops(PetscMax(a->nz-1,0));
2337:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for two norm");
2338:   return(0);
2339: }

2341: /* Merged from MatGetSymbolicTranspose_SeqAIJ() - replace MatGetSymbolicTranspose_SeqAIJ()? */
2342: PetscErrorCode MatTransposeSymbolic_SeqAIJ(Mat A,Mat *B)
2343: {
2345:   PetscInt       i,j,anzj;
2346:   Mat_SeqAIJ     *a=(Mat_SeqAIJ*)A->data,*b;
2347:   PetscInt       an=A->cmap->N,am=A->rmap->N;
2348:   PetscInt       *ati,*atj,*atfill,*ai=a->i,*aj=a->j;

2351:   /* Allocate space for symbolic transpose info and work array */
2352:   PetscCalloc1(an+1,&ati);
2353:   PetscMalloc1(ai[am],&atj);
2354:   PetscMalloc1(an,&atfill);

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

2362:   /* Copy ati into atfill so we have locations of the next free space in atj */
2363:   PetscArraycpy(atfill,ati,an);

2365:   /* Walk through A row-wise and mark nonzero entries of A^T. */
2366:   for (i=0;i<am;i++) {
2367:     anzj = ai[i+1] - ai[i];
2368:     for (j=0;j<anzj;j++) {
2369:       atj[atfill[*aj]] = i;
2370:       atfill[*aj++]   += 1;
2371:     }
2372:   }

2374:   /* Clean up temporary space and complete requests. */
2375:   PetscFree(atfill);
2376:   MatCreateSeqAIJWithArrays(PetscObjectComm((PetscObject)A),an,am,ati,atj,NULL,B);
2377:   MatSetBlockSizes(*B,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
2378:   MatSetType(*B,((PetscObject)A)->type_name);

2380:   b          = (Mat_SeqAIJ*)((*B)->data);
2381:   b->free_a  = PETSC_FALSE;
2382:   b->free_ij = PETSC_TRUE;
2383:   b->nonew   = 0;
2384:   return(0);
2385: }

2387: PetscErrorCode  MatIsTranspose_SeqAIJ(Mat A,Mat B,PetscReal tol,PetscBool  *f)
2388: {
2389:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*) A->data,*bij = (Mat_SeqAIJ*) B->data;
2390:   PetscInt       *adx,*bdx,*aii,*bii,*aptr,*bptr;
2391:   MatScalar      *va,*vb;
2393:   PetscInt       ma,na,mb,nb, i;

2396:   MatGetSize(A,&ma,&na);
2397:   MatGetSize(B,&mb,&nb);
2398:   if (ma!=nb || na!=mb) {
2399:     *f = PETSC_FALSE;
2400:     return(0);
2401:   }
2402:   aii  = aij->i; bii = bij->i;
2403:   adx  = aij->j; bdx = bij->j;
2404:   va   = aij->a; vb = bij->a;
2405:   PetscMalloc1(ma,&aptr);
2406:   PetscMalloc1(mb,&bptr);
2407:   for (i=0; i<ma; i++) aptr[i] = aii[i];
2408:   for (i=0; i<mb; i++) bptr[i] = bii[i];

2410:   *f = PETSC_TRUE;
2411:   for (i=0; i<ma; i++) {
2412:     while (aptr[i]<aii[i+1]) {
2413:       PetscInt    idc,idr;
2414:       PetscScalar vc,vr;
2415:       /* column/row index/value */
2416:       idc = adx[aptr[i]];
2417:       idr = bdx[bptr[idc]];
2418:       vc  = va[aptr[i]];
2419:       vr  = vb[bptr[idc]];
2420:       if (i!=idr || PetscAbsScalar(vc-vr) > tol) {
2421:         *f = PETSC_FALSE;
2422:         goto done;
2423:       } else {
2424:         aptr[i]++;
2425:         if (B || i!=idc) bptr[idc]++;
2426:       }
2427:     }
2428:   }
2429: done:
2430:   PetscFree(aptr);
2431:   PetscFree(bptr);
2432:   return(0);
2433: }

2435: PetscErrorCode  MatIsHermitianTranspose_SeqAIJ(Mat A,Mat B,PetscReal tol,PetscBool  *f)
2436: {
2437:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*) A->data,*bij = (Mat_SeqAIJ*) B->data;
2438:   PetscInt       *adx,*bdx,*aii,*bii,*aptr,*bptr;
2439:   MatScalar      *va,*vb;
2441:   PetscInt       ma,na,mb,nb, i;

2444:   MatGetSize(A,&ma,&na);
2445:   MatGetSize(B,&mb,&nb);
2446:   if (ma!=nb || na!=mb) {
2447:     *f = PETSC_FALSE;
2448:     return(0);
2449:   }
2450:   aii  = aij->i; bii = bij->i;
2451:   adx  = aij->j; bdx = bij->j;
2452:   va   = aij->a; vb = bij->a;
2453:   PetscMalloc1(ma,&aptr);
2454:   PetscMalloc1(mb,&bptr);
2455:   for (i=0; i<ma; i++) aptr[i] = aii[i];
2456:   for (i=0; i<mb; i++) bptr[i] = bii[i];

2458:   *f = PETSC_TRUE;
2459:   for (i=0; i<ma; i++) {
2460:     while (aptr[i]<aii[i+1]) {
2461:       PetscInt    idc,idr;
2462:       PetscScalar vc,vr;
2463:       /* column/row index/value */
2464:       idc = adx[aptr[i]];
2465:       idr = bdx[bptr[idc]];
2466:       vc  = va[aptr[i]];
2467:       vr  = vb[bptr[idc]];
2468:       if (i!=idr || PetscAbsScalar(vc-PetscConj(vr)) > tol) {
2469:         *f = PETSC_FALSE;
2470:         goto done;
2471:       } else {
2472:         aptr[i]++;
2473:         if (B || i!=idc) bptr[idc]++;
2474:       }
2475:     }
2476:   }
2477: done:
2478:   PetscFree(aptr);
2479:   PetscFree(bptr);
2480:   return(0);
2481: }

2483: PetscErrorCode MatIsSymmetric_SeqAIJ(Mat A,PetscReal tol,PetscBool  *f)
2484: {

2488:   MatIsTranspose_SeqAIJ(A,A,tol,f);
2489:   return(0);
2490: }

2492: PetscErrorCode MatIsHermitian_SeqAIJ(Mat A,PetscReal tol,PetscBool  *f)
2493: {

2497:   MatIsHermitianTranspose_SeqAIJ(A,A,tol,f);
2498:   return(0);
2499: }

2501: PetscErrorCode MatDiagonalScale_SeqAIJ(Mat A,Vec ll,Vec rr)
2502: {
2503:   Mat_SeqAIJ        *a = (Mat_SeqAIJ*)A->data;
2504:   const PetscScalar *l,*r;
2505:   PetscScalar       x;
2506:   MatScalar         *v;
2507:   PetscErrorCode    ierr;
2508:   PetscInt          i,j,m = A->rmap->n,n = A->cmap->n,M,nz = a->nz;
2509:   const PetscInt    *jj;

2512:   if (ll) {
2513:     /* The local size is used so that VecMPI can be passed to this routine
2514:        by MatDiagonalScale_MPIAIJ */
2515:     VecGetLocalSize(ll,&m);
2516:     if (m != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Left scaling vector wrong length");
2517:     VecGetArrayRead(ll,&l);
2518:     v    = a->a;
2519:     for (i=0; i<m; i++) {
2520:       x = l[i];
2521:       M = a->i[i+1] - a->i[i];
2522:       for (j=0; j<M; j++) (*v++) *= x;
2523:     }
2524:     VecRestoreArrayRead(ll,&l);
2525:     PetscLogFlops(nz);
2526:   }
2527:   if (rr) {
2528:     VecGetLocalSize(rr,&n);
2529:     if (n != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Right scaling vector wrong length");
2530:     VecGetArrayRead(rr,&r);
2531:     v    = a->a; jj = a->j;
2532:     for (i=0; i<nz; i++) (*v++) *= r[*jj++];
2533:     VecRestoreArrayRead(rr,&r);
2534:     PetscLogFlops(nz);
2535:   }
2536:   MatSeqAIJInvalidateDiagonal(A);
2537: #if defined(PETSC_HAVE_DEVICE)
2538:   if (A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) A->offloadmask = PETSC_OFFLOAD_CPU;
2539: #endif
2540:   return(0);
2541: }

2543: PetscErrorCode MatCreateSubMatrix_SeqAIJ(Mat A,IS isrow,IS iscol,PetscInt csize,MatReuse scall,Mat *B)
2544: {
2545:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*c;
2547:   PetscInt       *smap,i,k,kstart,kend,oldcols = A->cmap->n,*lens;
2548:   PetscInt       row,mat_i,*mat_j,tcol,first,step,*mat_ilen,sum,lensi;
2549:   const PetscInt *irow,*icol;
2550:   PetscInt       nrows,ncols;
2551:   PetscInt       *starts,*j_new,*i_new,*aj = a->j,*ai = a->i,ii,*ailen = a->ilen;
2552:   MatScalar      *a_new,*mat_a;
2553:   Mat            C;
2554:   PetscBool      stride;


2558:   ISGetIndices(isrow,&irow);
2559:   ISGetLocalSize(isrow,&nrows);
2560:   ISGetLocalSize(iscol,&ncols);

2562:   PetscObjectTypeCompare((PetscObject)iscol,ISSTRIDE,&stride);
2563:   if (stride) {
2564:     ISStrideGetInfo(iscol,&first,&step);
2565:   } else {
2566:     first = 0;
2567:     step  = 0;
2568:   }
2569:   if (stride && step == 1) {
2570:     /* special case of contiguous rows */
2571:     PetscMalloc2(nrows,&lens,nrows,&starts);
2572:     /* loop over new rows determining lens and starting points */
2573:     for (i=0; i<nrows; i++) {
2574:       kstart = ai[irow[i]];
2575:       kend   = kstart + ailen[irow[i]];
2576:       starts[i] = kstart;
2577:       for (k=kstart; k<kend; k++) {
2578:         if (aj[k] >= first) {
2579:           starts[i] = k;
2580:           break;
2581:         }
2582:       }
2583:       sum = 0;
2584:       while (k < kend) {
2585:         if (aj[k++] >= first+ncols) break;
2586:         sum++;
2587:       }
2588:       lens[i] = sum;
2589:     }
2590:     /* create submatrix */
2591:     if (scall == MAT_REUSE_MATRIX) {
2592:       PetscInt n_cols,n_rows;
2593:       MatGetSize(*B,&n_rows,&n_cols);
2594:       if (n_rows != nrows || n_cols != ncols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Reused submatrix wrong size");
2595:       MatZeroEntries(*B);
2596:       C    = *B;
2597:     } else {
2598:       PetscInt rbs,cbs;
2599:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2600:       MatSetSizes(C,nrows,ncols,PETSC_DETERMINE,PETSC_DETERMINE);
2601:       ISGetBlockSize(isrow,&rbs);
2602:       ISGetBlockSize(iscol,&cbs);
2603:       MatSetBlockSizes(C,rbs,cbs);
2604:       MatSetType(C,((PetscObject)A)->type_name);
2605:       MatSeqAIJSetPreallocation_SeqAIJ(C,0,lens);
2606:     }
2607:     c = (Mat_SeqAIJ*)C->data;

2609:     /* loop over rows inserting into submatrix */
2610:     a_new = c->a;
2611:     j_new = c->j;
2612:     i_new = c->i;

2614:     for (i=0; i<nrows; i++) {
2615:       ii    = starts[i];
2616:       lensi = lens[i];
2617:       for (k=0; k<lensi; k++) {
2618:         *j_new++ = aj[ii+k] - first;
2619:       }
2620:       PetscArraycpy(a_new,a->a + starts[i],lensi);
2621:       a_new     += lensi;
2622:       i_new[i+1] = i_new[i] + lensi;
2623:       c->ilen[i] = lensi;
2624:     }
2625:     PetscFree2(lens,starts);
2626:   } else {
2627:     ISGetIndices(iscol,&icol);
2628:     PetscCalloc1(oldcols,&smap);
2629:     PetscMalloc1(1+nrows,&lens);
2630:     for (i=0; i<ncols; i++) {
2631:       if (PetscUnlikelyDebug(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);
2632:       smap[icol[i]] = i+1;
2633:     }

2635:     /* determine lens of each row */
2636:     for (i=0; i<nrows; i++) {
2637:       kstart  = ai[irow[i]];
2638:       kend    = kstart + a->ilen[irow[i]];
2639:       lens[i] = 0;
2640:       for (k=kstart; k<kend; k++) {
2641:         if (smap[aj[k]]) {
2642:           lens[i]++;
2643:         }
2644:       }
2645:     }
2646:     /* Create and fill new matrix */
2647:     if (scall == MAT_REUSE_MATRIX) {
2648:       PetscBool equal;

2650:       c = (Mat_SeqAIJ*)((*B)->data);
2651:       if ((*B)->rmap->n  != nrows || (*B)->cmap->n != ncols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. wrong size");
2652:       PetscArraycmp(c->ilen,lens,(*B)->rmap->n,&equal);
2653:       if (!equal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. wrong no of nonzeros");
2654:       PetscArrayzero(c->ilen,(*B)->rmap->n);
2655:       C    = *B;
2656:     } else {
2657:       PetscInt rbs,cbs;
2658:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2659:       MatSetSizes(C,nrows,ncols,PETSC_DETERMINE,PETSC_DETERMINE);
2660:       ISGetBlockSize(isrow,&rbs);
2661:       ISGetBlockSize(iscol,&cbs);
2662:       MatSetBlockSizes(C,rbs,cbs);
2663:       MatSetType(C,((PetscObject)A)->type_name);
2664:       MatSeqAIJSetPreallocation_SeqAIJ(C,0,lens);
2665:     }
2666:     c = (Mat_SeqAIJ*)(C->data);
2667:     for (i=0; i<nrows; i++) {
2668:       row      = irow[i];
2669:       kstart   = ai[row];
2670:       kend     = kstart + a->ilen[row];
2671:       mat_i    = c->i[i];
2672:       mat_j    = c->j + mat_i;
2673:       mat_a    = c->a + mat_i;
2674:       mat_ilen = c->ilen + i;
2675:       for (k=kstart; k<kend; k++) {
2676:         if ((tcol=smap[a->j[k]])) {
2677:           *mat_j++ = tcol - 1;
2678:           *mat_a++ = a->a[k];
2679:           (*mat_ilen)++;

2681:         }
2682:       }
2683:     }
2684:     /* Free work space */
2685:     ISRestoreIndices(iscol,&icol);
2686:     PetscFree(smap);
2687:     PetscFree(lens);
2688:     /* sort */
2689:     for (i = 0; i < nrows; i++) {
2690:       PetscInt ilen;

2692:       mat_i = c->i[i];
2693:       mat_j = c->j + mat_i;
2694:       mat_a = c->a + mat_i;
2695:       ilen  = c->ilen[i];
2696:       PetscSortIntWithScalarArray(ilen,mat_j,mat_a);
2697:     }
2698:   }
2699: #if defined(PETSC_HAVE_DEVICE)
2700:   MatBindToCPU(C,A->boundtocpu);
2701: #endif
2702:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2703:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

2705:   ISRestoreIndices(isrow,&irow);
2706:   *B   = C;
2707:   return(0);
2708: }

2710: PetscErrorCode  MatGetMultiProcBlock_SeqAIJ(Mat mat,MPI_Comm subComm,MatReuse scall,Mat *subMat)
2711: {
2713:   Mat            B;

2716:   if (scall == MAT_INITIAL_MATRIX) {
2717:     MatCreate(subComm,&B);
2718:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->n,mat->cmap->n);
2719:     MatSetBlockSizesFromMats(B,mat,mat);
2720:     MatSetType(B,MATSEQAIJ);
2721:     MatDuplicateNoCreate_SeqAIJ(B,mat,MAT_COPY_VALUES,PETSC_TRUE);
2722:     *subMat = B;
2723:   } else {
2724:     MatCopy_SeqAIJ(mat,*subMat,SAME_NONZERO_PATTERN);
2725:   }
2726:   return(0);
2727: }

2729: PetscErrorCode MatILUFactor_SeqAIJ(Mat inA,IS row,IS col,const MatFactorInfo *info)
2730: {
2731:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)inA->data;
2733:   Mat            outA;
2734:   PetscBool      row_identity,col_identity;

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

2739:   ISIdentity(row,&row_identity);
2740:   ISIdentity(col,&col_identity);

2742:   outA             = inA;
2743:   outA->factortype = MAT_FACTOR_LU;
2744:   PetscFree(inA->solvertype);
2745:   PetscStrallocpy(MATSOLVERPETSC,&inA->solvertype);

2747:   PetscObjectReference((PetscObject)row);
2748:   ISDestroy(&a->row);

2750:   a->row = row;

2752:   PetscObjectReference((PetscObject)col);
2753:   ISDestroy(&a->col);

2755:   a->col = col;

2757:   /* Create the inverse permutation so that it can be used in MatLUFactorNumeric() */
2758:   ISDestroy(&a->icol);
2759:   ISInvertPermutation(col,PETSC_DECIDE,&a->icol);
2760:   PetscLogObjectParent((PetscObject)inA,(PetscObject)a->icol);

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

2767:   MatMarkDiagonal_SeqAIJ(inA);
2768:   if (row_identity && col_identity) {
2769:     MatLUFactorNumeric_SeqAIJ_inplace(outA,inA,info);
2770:   } else {
2771:     MatLUFactorNumeric_SeqAIJ_InplaceWithPerm(outA,inA,info);
2772:   }
2773:   return(0);
2774: }

2776: PetscErrorCode MatScale_SeqAIJ(Mat inA,PetscScalar alpha)
2777: {
2778:   Mat_SeqAIJ     *a     = (Mat_SeqAIJ*)inA->data;
2779:   PetscScalar    oalpha = alpha;
2781:   PetscBLASInt   one = 1,bnz;

2784:   PetscBLASIntCast(a->nz,&bnz);
2785:   PetscStackCallBLAS("BLASscal",BLASscal_(&bnz,&oalpha,a->a,&one));
2786:   PetscLogFlops(a->nz);
2787:   MatSeqAIJInvalidateDiagonal(inA);
2788: #if defined(PETSC_HAVE_DEVICE)
2789:   if (inA->offloadmask != PETSC_OFFLOAD_UNALLOCATED) inA->offloadmask = PETSC_OFFLOAD_CPU;
2790: #endif
2791:   return(0);
2792: }

2794: PetscErrorCode MatDestroySubMatrix_Private(Mat_SubSppt *submatj)
2795: {
2797:   PetscInt       i;

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

2803:     for (i=0; i<submatj->nrqr; ++i) {
2804:       PetscFree(submatj->sbuf2[i]);
2805:     }
2806:     PetscFree3(submatj->sbuf2,submatj->req_size,submatj->req_source1);

2808:     if (submatj->rbuf1) {
2809:       PetscFree(submatj->rbuf1[0]);
2810:       PetscFree(submatj->rbuf1);
2811:     }

2813:     for (i=0; i<submatj->nrqs; ++i) {
2814:       PetscFree(submatj->rbuf3[i]);
2815:     }
2816:     PetscFree3(submatj->req_source2,submatj->rbuf2,submatj->rbuf3);
2817:     PetscFree(submatj->pa);
2818:   }

2820: #if defined(PETSC_USE_CTABLE)
2821:   PetscTableDestroy((PetscTable*)&submatj->rmap);
2822:   if (submatj->cmap_loc) {PetscFree(submatj->cmap_loc);}
2823:   PetscFree(submatj->rmap_loc);
2824: #else
2825:   PetscFree(submatj->rmap);
2826: #endif

2828:   if (!submatj->allcolumns) {
2829: #if defined(PETSC_USE_CTABLE)
2830:     PetscTableDestroy((PetscTable*)&submatj->cmap);
2831: #else
2832:     PetscFree(submatj->cmap);
2833: #endif
2834:   }
2835:   PetscFree(submatj->row2proc);

2837:   PetscFree(submatj);
2838:   return(0);
2839: }

2841: PetscErrorCode MatDestroySubMatrix_SeqAIJ(Mat C)
2842: {
2844:   Mat_SeqAIJ     *c = (Mat_SeqAIJ*)C->data;
2845:   Mat_SubSppt    *submatj = c->submatis1;

2848:   (*submatj->destroy)(C);
2849:   MatDestroySubMatrix_Private(submatj);
2850:   return(0);
2851: }

2853: PetscErrorCode MatDestroySubMatrices_SeqAIJ(PetscInt n,Mat *mat[])
2854: {
2856:   PetscInt       i;
2857:   Mat            C;
2858:   Mat_SeqAIJ     *c;
2859:   Mat_SubSppt    *submatj;

2862:   for (i=0; i<n; i++) {
2863:     C       = (*mat)[i];
2864:     c       = (Mat_SeqAIJ*)C->data;
2865:     submatj = c->submatis1;
2866:     if (submatj) {
2867:       if (--((PetscObject)C)->refct <= 0) {
2868:         (*submatj->destroy)(C);
2869:         MatDestroySubMatrix_Private(submatj);
2870:         PetscFree(C->defaultvectype);
2871:         PetscLayoutDestroy(&C->rmap);
2872:         PetscLayoutDestroy(&C->cmap);
2873:         PetscHeaderDestroy(&C);
2874:       }
2875:     } else {
2876:       MatDestroy(&C);
2877:     }
2878:   }

2880:   /* Destroy Dummy submatrices created for reuse */
2881:   MatDestroySubMatrices_Dummy(n,mat);

2883:   PetscFree(*mat);
2884:   return(0);
2885: }

2887: PetscErrorCode MatCreateSubMatrices_SeqAIJ(Mat A,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *B[])
2888: {
2890:   PetscInt       i;

2893:   if (scall == MAT_INITIAL_MATRIX) {
2894:     PetscCalloc1(n+1,B);
2895:   }

2897:   for (i=0; i<n; i++) {
2898:     MatCreateSubMatrix_SeqAIJ(A,irow[i],icol[i],PETSC_DECIDE,scall,&(*B)[i]);
2899:   }
2900:   return(0);
2901: }

2903: PetscErrorCode MatIncreaseOverlap_SeqAIJ(Mat A,PetscInt is_max,IS is[],PetscInt ov)
2904: {
2905:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2907:   PetscInt       row,i,j,k,l,m,n,*nidx,isz,val;
2908:   const PetscInt *idx;
2909:   PetscInt       start,end,*ai,*aj;
2910:   PetscBT        table;

2913:   m  = A->rmap->n;
2914:   ai = a->i;
2915:   aj = a->j;

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

2919:   PetscMalloc1(m+1,&nidx);
2920:   PetscBTCreate(m,&table);

2922:   for (i=0; i<is_max; i++) {
2923:     /* Initialize the two local arrays */
2924:     isz  = 0;
2925:     PetscBTMemzero(m,table);

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

2931:     /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2932:     for (j=0; j<n; ++j) {
2933:       if (!PetscBTLookupSet(table,idx[j])) nidx[isz++] = idx[j];
2934:     }
2935:     ISRestoreIndices(is[i],&idx);
2936:     ISDestroy(&is[i]);

2938:     k = 0;
2939:     for (j=0; j<ov; j++) { /* for each overlap */
2940:       n = isz;
2941:       for (; k<n; k++) { /* do only those rows in nidx[k], which are not done yet */
2942:         row   = nidx[k];
2943:         start = ai[row];
2944:         end   = ai[row+1];
2945:         for (l = start; l<end; l++) {
2946:           val = aj[l];
2947:           if (!PetscBTLookupSet(table,val)) nidx[isz++] = val;
2948:         }
2949:       }
2950:     }
2951:     ISCreateGeneral(PETSC_COMM_SELF,isz,nidx,PETSC_COPY_VALUES,(is+i));
2952:   }
2953:   PetscBTDestroy(&table);
2954:   PetscFree(nidx);
2955:   return(0);
2956: }

2958: /* -------------------------------------------------------------- */
2959: PetscErrorCode MatPermute_SeqAIJ(Mat A,IS rowp,IS colp,Mat *B)
2960: {
2961:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
2963:   PetscInt       i,nz = 0,m = A->rmap->n,n = A->cmap->n;
2964:   const PetscInt *row,*col;
2965:   PetscInt       *cnew,j,*lens;
2966:   IS             icolp,irowp;
2967:   PetscInt       *cwork = NULL;
2968:   PetscScalar    *vwork = NULL;

2971:   ISInvertPermutation(rowp,PETSC_DECIDE,&irowp);
2972:   ISGetIndices(irowp,&row);
2973:   ISInvertPermutation(colp,PETSC_DECIDE,&icolp);
2974:   ISGetIndices(icolp,&col);

2976:   /* determine lengths of permuted rows */
2977:   PetscMalloc1(m+1,&lens);
2978:   for (i=0; i<m; i++) lens[row[i]] = a->i[i+1] - a->i[i];
2979:   MatCreate(PetscObjectComm((PetscObject)A),B);
2980:   MatSetSizes(*B,m,n,m,n);
2981:   MatSetBlockSizesFromMats(*B,A,A);
2982:   MatSetType(*B,((PetscObject)A)->type_name);
2983:   MatSeqAIJSetPreallocation_SeqAIJ(*B,0,lens);
2984:   PetscFree(lens);

2986:   PetscMalloc1(n,&cnew);
2987:   for (i=0; i<m; i++) {
2988:     MatGetRow_SeqAIJ(A,i,&nz,&cwork,&vwork);
2989:     for (j=0; j<nz; j++) cnew[j] = col[cwork[j]];
2990:     MatSetValues_SeqAIJ(*B,1,&row[i],nz,cnew,vwork,INSERT_VALUES);
2991:     MatRestoreRow_SeqAIJ(A,i,&nz,&cwork,&vwork);
2992:   }
2993:   PetscFree(cnew);

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

2997: #if defined(PETSC_HAVE_DEVICE)
2998:   MatBindToCPU(*B,A->boundtocpu);
2999: #endif
3000:   MatAssemblyBegin(*B,MAT_FINAL_ASSEMBLY);
3001:   MatAssemblyEnd(*B,MAT_FINAL_ASSEMBLY);
3002:   ISRestoreIndices(irowp,&row);
3003:   ISRestoreIndices(icolp,&col);
3004:   ISDestroy(&irowp);
3005:   ISDestroy(&icolp);
3006:   if (rowp == colp) {
3007:     if (A->symmetric) {
3008:       MatSetOption(*B,MAT_SYMMETRIC,PETSC_TRUE);
3009:     }
3010:     if (A->hermitian) {
3011:       MatSetOption(*B,MAT_HERMITIAN,PETSC_TRUE);
3012:     }
3013:   }
3014:   return(0);
3015: }

3017: PetscErrorCode MatCopy_SeqAIJ(Mat A,Mat B,MatStructure str)
3018: {

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

3027:     if (a->i[A->rmap->n] != b->i[B->rmap->n]) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Number of nonzeros in two matrices are different %D != %D",a->i[A->rmap->n],b->i[B->rmap->n]);
3028:     PetscArraycpy(b->a,a->a,a->i[A->rmap->n]);
3029:     PetscObjectStateIncrease((PetscObject)B);
3030:   } else {
3031:     MatCopy_Basic(A,B,str);
3032:   }
3033:   return(0);
3034: }

3036: PetscErrorCode MatSetUp_SeqAIJ(Mat A)
3037: {

3041:   MatSeqAIJSetPreallocation_SeqAIJ(A,PETSC_DEFAULT,NULL);
3042:   return(0);
3043: }

3045: PETSC_INTERN PetscErrorCode MatSeqAIJGetArray_SeqAIJ(Mat A,PetscScalar *array[])
3046: {
3047:   Mat_SeqAIJ *a = (Mat_SeqAIJ*)A->data;

3050:   *array = a->a;
3051:   return(0);
3052: }

3054: PETSC_INTERN PetscErrorCode MatSeqAIJRestoreArray_SeqAIJ(Mat A,PetscScalar *array[])
3055: {
3057:   *array = NULL;
3058:   return(0);
3059: }

3061: /*
3062:    Computes the number of nonzeros per row needed for preallocation when X and Y
3063:    have different nonzero structure.
3064: */
3065: PetscErrorCode MatAXPYGetPreallocation_SeqX_private(PetscInt m,const PetscInt *xi,const PetscInt *xj,const PetscInt *yi,const PetscInt *yj,PetscInt *nnz)
3066: {
3067:   PetscInt       i,j,k,nzx,nzy;

3070:   /* Set the number of nonzeros in the new matrix */
3071:   for (i=0; i<m; i++) {
3072:     const PetscInt *xjj = xj+xi[i],*yjj = yj+yi[i];
3073:     nzx = xi[i+1] - xi[i];
3074:     nzy = yi[i+1] - yi[i];
3075:     nnz[i] = 0;
3076:     for (j=0,k=0; j<nzx; j++) {                   /* Point in X */
3077:       for (; k<nzy && yjj[k]<xjj[j]; k++) nnz[i]++; /* Catch up to X */
3078:       if (k<nzy && yjj[k]==xjj[j]) k++;             /* Skip duplicate */
3079:       nnz[i]++;
3080:     }
3081:     for (; k<nzy; k++) nnz[i]++;
3082:   }
3083:   return(0);
3084: }

3086: PetscErrorCode MatAXPYGetPreallocation_SeqAIJ(Mat Y,Mat X,PetscInt *nnz)
3087: {
3088:   PetscInt       m = Y->rmap->N;
3089:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data;
3090:   Mat_SeqAIJ     *y = (Mat_SeqAIJ*)Y->data;

3094:   /* Set the number of nonzeros in the new matrix */
3095:   MatAXPYGetPreallocation_SeqX_private(m,x->i,x->j,y->i,y->j,nnz);
3096:   return(0);
3097: }

3099: PetscErrorCode MatAXPY_SeqAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
3100: {
3102:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data,*y = (Mat_SeqAIJ*)Y->data;

3105:   if (str == DIFFERENT_NONZERO_PATTERN) {
3106:     if (x->nz == y->nz) {
3107:       PetscBool e;
3108:       PetscArraycmp(x->i,y->i,Y->rmap->n+1,&e);
3109:       if (e) {
3110:         PetscArraycmp(x->j,y->j,y->nz,&e);
3111:         if (e) {
3112:           str = SAME_NONZERO_PATTERN;
3113:         }
3114:       }
3115:     }
3116:   }
3117:   if (str == SAME_NONZERO_PATTERN) {
3118:     PetscScalar  alpha = a;
3119:     PetscBLASInt one = 1,bnz;

3121:     PetscBLASIntCast(x->nz,&bnz);
3122:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
3123:     MatSeqAIJInvalidateDiagonal(Y);
3124:     PetscObjectStateIncrease((PetscObject)Y);
3125:     /* the MatAXPY_Basic* subroutines calls MatAssembly, so the matrix on the GPU will be updated */
3126: #if defined(PETSC_HAVE_DEVICE)
3127:     if (Y->offloadmask != PETSC_OFFLOAD_UNALLOCATED) {
3128:       Y->offloadmask = PETSC_OFFLOAD_CPU;
3129:     }
3130: #endif
3131:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
3132:     MatAXPY_Basic(Y,a,X,str);
3133:   } else {
3134:     Mat      B;
3135:     PetscInt *nnz;
3136:     PetscMalloc1(Y->rmap->N,&nnz);
3137:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
3138:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
3139:     MatSetLayouts(B,Y->rmap,Y->cmap);
3140:     MatSetType(B,(MatType) ((PetscObject)Y)->type_name);
3141:     MatAXPYGetPreallocation_SeqAIJ(Y,X,nnz);
3142:     MatSeqAIJSetPreallocation(B,0,nnz);
3143:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
3144:     MatHeaderReplace(Y,&B);
3145:     PetscFree(nnz);
3146:   }
3147:   return(0);
3148: }

3150: PetscErrorCode  MatConjugate_SeqAIJ(Mat mat)
3151: {
3152: #if defined(PETSC_USE_COMPLEX)
3153:   Mat_SeqAIJ  *aij = (Mat_SeqAIJ*)mat->data;
3154:   PetscInt    i,nz;
3155:   PetscScalar *a;

3158:   nz = aij->nz;
3159:   a  = aij->a;
3160:   for (i=0; i<nz; i++) a[i] = PetscConj(a[i]);
3161: #if defined(PETSC_HAVE_DEVICE)
3162:   if (mat->offloadmask != PETSC_OFFLOAD_UNALLOCATED) mat->offloadmask = PETSC_OFFLOAD_CPU;
3163: #endif
3164: #else
3166: #endif
3167:   return(0);
3168: }

3170: PetscErrorCode MatGetRowMaxAbs_SeqAIJ(Mat A,Vec v,PetscInt idx[])
3171: {
3172:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
3174:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
3175:   PetscReal      atmp;
3176:   PetscScalar    *x;
3177:   MatScalar      *aa;

3180:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3181:   aa = a->a;
3182:   ai = a->i;
3183:   aj = a->j;

3185:   VecSet(v,0.0);
3186:   VecGetArrayWrite(v,&x);
3187:   VecGetLocalSize(v,&n);
3188:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
3189:   for (i=0; i<m; i++) {
3190:     ncols = ai[1] - ai[0]; ai++;
3191:     for (j=0; j<ncols; j++) {
3192:       atmp = PetscAbsScalar(*aa);
3193:       if (PetscAbsScalar(x[i]) < atmp) {x[i] = atmp; if (idx) idx[i] = *aj;}
3194:       aa++; aj++;
3195:     }
3196:   }
3197:   VecRestoreArrayWrite(v,&x);
3198:   return(0);
3199: }

3201: PetscErrorCode MatGetRowMax_SeqAIJ(Mat A,Vec v,PetscInt idx[])
3202: {
3203:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
3205:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
3206:   PetscScalar    *x;
3207:   MatScalar      *aa;

3210:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3211:   aa = a->a;
3212:   ai = a->i;
3213:   aj = a->j;

3215:   VecSet(v,0.0);
3216:   VecGetArrayWrite(v,&x);
3217:   VecGetLocalSize(v,&n);
3218:   if (n != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
3219:   for (i=0; i<m; i++) {
3220:     ncols = ai[1] - ai[0]; ai++;
3221:     if (ncols == A->cmap->n) { /* row is dense */
3222:       x[i] = *aa; if (idx) idx[i] = 0;
3223:     } else {  /* row is sparse so already KNOW maximum is 0.0 or higher */
3224:       x[i] = 0.0;
3225:       if (idx) {
3226:         for (j=0; j<ncols; j++) { /* find first implicit 0.0 in the row */
3227:           if (aj[j] > j) {
3228:             idx[i] = j;
3229:             break;
3230:           }
3231:         }
3232:         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3233:         if (j==ncols && j < A->cmap->n) idx[i] = j;
3234:       }
3235:     }
3236:     for (j=0; j<ncols; j++) {
3237:       if (PetscRealPart(x[i]) < PetscRealPart(*aa)) {x[i] = *aa; if (idx) idx[i] = *aj;}
3238:       aa++; aj++;
3239:     }
3240:   }
3241:   VecRestoreArrayWrite(v,&x);
3242:   return(0);
3243: }

3245: PetscErrorCode MatGetRowMinAbs_SeqAIJ(Mat A,Vec v,PetscInt idx[])
3246: {
3247:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
3249:   PetscInt       i,j,m = A->rmap->n,*ai,*aj,ncols,n;
3250:   PetscScalar    *x,*aa;

3253:   aa = a->a;
3254:   ai = a->i;
3255:   aj = a->j;

3257:   VecSet(v,0.0);
3258:   VecGetArrayWrite(v,&x);
3259:   VecGetLocalSize(v,&n);
3260:   if (n != m) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector, %D vs. %D rows", m, n);
3261:   for (i=0; i<m; i++) {
3262:     ncols = ai[1] - ai[0]; ai++;
3263:     if (ncols == A->cmap->n) { /* row is dense */
3264:       x[i] = *aa; if (idx) idx[i] = 0;
3265:     } else {  /* row is sparse so already KNOW minimum is 0.0 or higher */
3266:       x[i] = 0.0;
3267:       if (idx) {   /* find first implicit 0.0 in the row */
3268:         for (j=0; j<ncols; j++) {
3269:           if (aj[j] > j) {
3270:             idx[i] = j;
3271:             break;
3272:           }
3273:         }
3274:         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3275:         if (j==ncols && j < A->cmap->n) idx[i] = j;
3276:       }
3277:     }
3278:     for (j=0; j<ncols; j++) {
3279:       if (PetscAbsScalar(x[i]) > PetscAbsScalar(*aa)) {x[i] = *aa; if (idx) idx[i] = *aj;}
3280:       aa++; aj++;
3281:     }
3282:   }
3283:   VecRestoreArrayWrite(v,&x);
3284:   return(0);
3285: }

3287: PetscErrorCode MatGetRowMin_SeqAIJ(Mat A,Vec v,PetscInt idx[])
3288: {
3289:   Mat_SeqAIJ      *a = (Mat_SeqAIJ*)A->data;
3290:   PetscErrorCode  ierr;
3291:   PetscInt        i,j,m = A->rmap->n,ncols,n;
3292:   const PetscInt  *ai,*aj;
3293:   PetscScalar     *x;
3294:   const MatScalar *aa;

3297:   if (A->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3298:   aa = a->a;
3299:   ai = a->i;
3300:   aj = a->j;

3302:   VecSet(v,0.0);
3303:   VecGetArrayWrite(v,&x);
3304:   VecGetLocalSize(v,&n);
3305:   if (n != m) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Nonconforming matrix and vector");
3306:   for (i=0; i<m; i++) {
3307:     ncols = ai[1] - ai[0]; ai++;
3308:     if (ncols == A->cmap->n) { /* row is dense */
3309:       x[i] = *aa; if (idx) idx[i] = 0;
3310:     } else {  /* row is sparse so already KNOW minimum is 0.0 or lower */
3311:       x[i] = 0.0;
3312:       if (idx) {   /* find first implicit 0.0 in the row */
3313:         for (j=0; j<ncols; j++) {
3314:           if (aj[j] > j) {
3315:             idx[i] = j;
3316:             break;
3317:           }
3318:         }
3319:         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3320:         if (j==ncols && j < A->cmap->n) idx[i] = j;
3321:       }
3322:     }
3323:     for (j=0; j<ncols; j++) {
3324:       if (PetscRealPart(x[i]) > PetscRealPart(*aa)) {x[i] = *aa; if (idx) idx[i] = *aj;}
3325:       aa++; aj++;
3326:     }
3327:   }
3328:   VecRestoreArrayWrite(v,&x);
3329:   return(0);
3330: }

3332: PetscErrorCode MatInvertBlockDiagonal_SeqAIJ(Mat A,const PetscScalar **values)
3333: {
3334:   Mat_SeqAIJ      *a = (Mat_SeqAIJ*) A->data;
3335:   PetscErrorCode  ierr;
3336:   PetscInt        i,bs = PetscAbs(A->rmap->bs),mbs = A->rmap->n/bs,ipvt[5],bs2 = bs*bs,*v_pivots,ij[7],*IJ,j;
3337:   MatScalar       *diag,work[25],*v_work;
3338:   const PetscReal shift = 0.0;
3339:   PetscBool       allowzeropivot,zeropivotdetected=PETSC_FALSE;

3342:   allowzeropivot = PetscNot(A->erroriffailure);
3343:   if (a->ibdiagvalid) {
3344:     if (values) *values = a->ibdiag;
3345:     return(0);
3346:   }
3347:   MatMarkDiagonal_SeqAIJ(A);
3348:   if (!a->ibdiag) {
3349:     PetscMalloc1(bs2*mbs,&a->ibdiag);
3350:     PetscLogObjectMemory((PetscObject)A,bs2*mbs*sizeof(PetscScalar));
3351:   }
3352:   diag = a->ibdiag;
3353:   if (values) *values = a->ibdiag;
3354:   /* factor and invert each block */
3355:   switch (bs) {
3356:   case 1:
3357:     for (i=0; i<mbs; i++) {
3358:       MatGetValues(A,1,&i,1,&i,diag+i);
3359:       if (PetscAbsScalar(diag[i] + shift) < PETSC_MACHINE_EPSILON) {
3360:         if (allowzeropivot) {
3361:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3362:           A->factorerror_zeropivot_value = PetscAbsScalar(diag[i]);
3363:           A->factorerror_zeropivot_row   = i;
3364:           PetscInfo3(A,"Zero pivot, row %D pivot %g tolerance %g\n",i,(double)PetscAbsScalar(diag[i]),(double)PETSC_MACHINE_EPSILON);
3365:         } 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);
3366:       }
3367:       diag[i] = (PetscScalar)1.0 / (diag[i] + shift);
3368:     }
3369:     break;
3370:   case 2:
3371:     for (i=0; i<mbs; i++) {
3372:       ij[0] = 2*i; ij[1] = 2*i + 1;
3373:       MatGetValues(A,2,ij,2,ij,diag);
3374:       PetscKernel_A_gets_inverse_A_2(diag,shift,allowzeropivot,&zeropivotdetected);
3375:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3376:       PetscKernel_A_gets_transpose_A_2(diag);
3377:       diag += 4;
3378:     }
3379:     break;
3380:   case 3:
3381:     for (i=0; i<mbs; i++) {
3382:       ij[0] = 3*i; ij[1] = 3*i + 1; ij[2] = 3*i + 2;
3383:       MatGetValues(A,3,ij,3,ij,diag);
3384:       PetscKernel_A_gets_inverse_A_3(diag,shift,allowzeropivot,&zeropivotdetected);
3385:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3386:       PetscKernel_A_gets_transpose_A_3(diag);
3387:       diag += 9;
3388:     }
3389:     break;
3390:   case 4:
3391:     for (i=0; i<mbs; i++) {
3392:       ij[0] = 4*i; ij[1] = 4*i + 1; ij[2] = 4*i + 2; ij[3] = 4*i + 3;
3393:       MatGetValues(A,4,ij,4,ij,diag);
3394:       PetscKernel_A_gets_inverse_A_4(diag,shift,allowzeropivot,&zeropivotdetected);
3395:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3396:       PetscKernel_A_gets_transpose_A_4(diag);
3397:       diag += 16;
3398:     }
3399:     break;
3400:   case 5:
3401:     for (i=0; i<mbs; i++) {
3402:       ij[0] = 5*i; ij[1] = 5*i + 1; ij[2] = 5*i + 2; ij[3] = 5*i + 3; ij[4] = 5*i + 4;
3403:       MatGetValues(A,5,ij,5,ij,diag);
3404:       PetscKernel_A_gets_inverse_A_5(diag,ipvt,work,shift,allowzeropivot,&zeropivotdetected);
3405:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3406:       PetscKernel_A_gets_transpose_A_5(diag);
3407:       diag += 25;
3408:     }
3409:     break;
3410:   case 6:
3411:     for (i=0; i<mbs; i++) {
3412:       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;
3413:       MatGetValues(A,6,ij,6,ij,diag);
3414:       PetscKernel_A_gets_inverse_A_6(diag,shift,allowzeropivot,&zeropivotdetected);
3415:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3416:       PetscKernel_A_gets_transpose_A_6(diag);
3417:       diag += 36;
3418:     }
3419:     break;
3420:   case 7:
3421:     for (i=0; i<mbs; i++) {
3422:       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;
3423:       MatGetValues(A,7,ij,7,ij,diag);
3424:       PetscKernel_A_gets_inverse_A_7(diag,shift,allowzeropivot,&zeropivotdetected);
3425:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3426:       PetscKernel_A_gets_transpose_A_7(diag);
3427:       diag += 49;
3428:     }
3429:     break;
3430:   default:
3431:     PetscMalloc3(bs,&v_work,bs,&v_pivots,bs,&IJ);
3432:     for (i=0; i<mbs; i++) {
3433:       for (j=0; j<bs; j++) {
3434:         IJ[j] = bs*i + j;
3435:       }
3436:       MatGetValues(A,bs,IJ,bs,IJ,diag);
3437:       PetscKernel_A_gets_inverse_A(bs,diag,v_pivots,v_work,allowzeropivot,&zeropivotdetected);
3438:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3439:       PetscKernel_A_gets_transpose_A_N(diag,bs);
3440:       diag += bs2;
3441:     }
3442:     PetscFree3(v_work,v_pivots,IJ);
3443:   }
3444:   a->ibdiagvalid = PETSC_TRUE;
3445:   return(0);
3446: }

3448: static PetscErrorCode  MatSetRandom_SeqAIJ(Mat x,PetscRandom rctx)
3449: {
3451:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)x->data;
3452:   PetscScalar    a;
3453:   PetscInt       m,n,i,j,col;

3456:   if (!x->assembled) {
3457:     MatGetSize(x,&m,&n);
3458:     for (i=0; i<m; i++) {
3459:       for (j=0; j<aij->imax[i]; j++) {
3460:         PetscRandomGetValue(rctx,&a);
3461:         col  = (PetscInt)(n*PetscRealPart(a));
3462:         MatSetValues(x,1,&i,1,&col,&a,ADD_VALUES);
3463:       }
3464:     }
3465:   } else {
3466:     for (i=0; i<aij->nz; i++) {PetscRandomGetValue(rctx,aij->a+i);}
3467:   }
3468:   MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);
3469:   MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);
3470:   return(0);
3471: }

3473: /* Like MatSetRandom_SeqAIJ, but do not set values on columns in range of [low, high) */
3474: PetscErrorCode  MatSetRandomSkipColumnRange_SeqAIJ_Private(Mat x,PetscInt low,PetscInt high,PetscRandom rctx)
3475: {
3477:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)x->data;
3478:   PetscScalar    a;
3479:   PetscInt       m,n,i,j,col,nskip;

3482:   nskip = high - low;
3483:   MatGetSize(x,&m,&n);
3484:   n    -= nskip; /* shrink number of columns where nonzeros can be set */
3485:   for (i=0; i<m; i++) {
3486:     for (j=0; j<aij->imax[i]; j++) {
3487:       PetscRandomGetValue(rctx,&a);
3488:       col  = (PetscInt)(n*PetscRealPart(a));
3489:       if (col >= low) col += nskip; /* shift col rightward to skip the hole */
3490:       MatSetValues(x,1,&i,1,&col,&a,ADD_VALUES);
3491:     }
3492:   }
3493:   MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);
3494:   MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);
3495:   return(0);
3496: }


3499: /* -------------------------------------------------------------------*/
3500: static struct _MatOps MatOps_Values = { MatSetValues_SeqAIJ,
3501:                                         MatGetRow_SeqAIJ,
3502:                                         MatRestoreRow_SeqAIJ,
3503:                                         MatMult_SeqAIJ,
3504:                                 /*  4*/ MatMultAdd_SeqAIJ,
3505:                                         MatMultTranspose_SeqAIJ,
3506:                                         MatMultTransposeAdd_SeqAIJ,
3507:                                         NULL,
3508:                                         NULL,
3509:                                         NULL,
3510:                                 /* 10*/ NULL,
3511:                                         MatLUFactor_SeqAIJ,
3512:                                         NULL,
3513:                                         MatSOR_SeqAIJ,
3514:                                         MatTranspose_SeqAIJ,
3515:                                 /*1 5*/ MatGetInfo_SeqAIJ,
3516:                                         MatEqual_SeqAIJ,
3517:                                         MatGetDiagonal_SeqAIJ,
3518:                                         MatDiagonalScale_SeqAIJ,
3519:                                         MatNorm_SeqAIJ,
3520:                                 /* 20*/ NULL,
3521:                                         MatAssemblyEnd_SeqAIJ,
3522:                                         MatSetOption_SeqAIJ,
3523:                                         MatZeroEntries_SeqAIJ,
3524:                                 /* 24*/ MatZeroRows_SeqAIJ,
3525:                                         NULL,
3526:                                         NULL,
3527:                                         NULL,
3528:                                         NULL,
3529:                                 /* 29*/ MatSetUp_SeqAIJ,
3530:                                         NULL,
3531:                                         NULL,
3532:                                         NULL,
3533:                                         NULL,
3534:                                 /* 34*/ MatDuplicate_SeqAIJ,
3535:                                         NULL,
3536:                                         NULL,
3537:                                         MatILUFactor_SeqAIJ,
3538:                                         NULL,
3539:                                 /* 39*/ MatAXPY_SeqAIJ,
3540:                                         MatCreateSubMatrices_SeqAIJ,
3541:                                         MatIncreaseOverlap_SeqAIJ,
3542:                                         MatGetValues_SeqAIJ,
3543:                                         MatCopy_SeqAIJ,
3544:                                 /* 44*/ MatGetRowMax_SeqAIJ,
3545:                                         MatScale_SeqAIJ,
3546:                                         MatShift_SeqAIJ,
3547:                                         MatDiagonalSet_SeqAIJ,
3548:                                         MatZeroRowsColumns_SeqAIJ,
3549:                                 /* 49*/ MatSetRandom_SeqAIJ,
3550:                                         MatGetRowIJ_SeqAIJ,
3551:                                         MatRestoreRowIJ_SeqAIJ,
3552:                                         MatGetColumnIJ_SeqAIJ,
3553:                                         MatRestoreColumnIJ_SeqAIJ,
3554:                                 /* 54*/ MatFDColoringCreate_SeqXAIJ,
3555:                                         NULL,
3556:                                         NULL,
3557:                                         MatPermute_SeqAIJ,
3558:                                         NULL,
3559:                                 /* 59*/ NULL,
3560:                                         MatDestroy_SeqAIJ,
3561:                                         MatView_SeqAIJ,
3562:                                         NULL,
3563:                                         NULL,
3564:                                 /* 64*/ NULL,
3565:                                         MatMatMatMultNumeric_SeqAIJ_SeqAIJ_SeqAIJ,
3566:                                         NULL,
3567:                                         NULL,
3568:                                         NULL,
3569:                                 /* 69*/ MatGetRowMaxAbs_SeqAIJ,
3570:                                         MatGetRowMinAbs_SeqAIJ,
3571:                                         NULL,
3572:                                         NULL,
3573:                                         NULL,
3574:                                 /* 74*/ NULL,
3575:                                         MatFDColoringApply_AIJ,
3576:                                         NULL,
3577:                                         NULL,
3578:                                         NULL,
3579:                                 /* 79*/ MatFindZeroDiagonals_SeqAIJ,
3580:                                         NULL,
3581:                                         NULL,
3582:                                         NULL,
3583:                                         MatLoad_SeqAIJ,
3584:                                 /* 84*/ MatIsSymmetric_SeqAIJ,
3585:                                         MatIsHermitian_SeqAIJ,
3586:                                         NULL,
3587:                                         NULL,
3588:                                         NULL,
3589:                                 /* 89*/ NULL,
3590:                                         NULL,
3591:                                         MatMatMultNumeric_SeqAIJ_SeqAIJ,
3592:                                         NULL,
3593:                                         NULL,
3594:                                 /* 94*/ MatPtAPNumeric_SeqAIJ_SeqAIJ_SparseAxpy,
3595:                                         NULL,
3596:                                         NULL,
3597:                                         MatMatTransposeMultNumeric_SeqAIJ_SeqAIJ,
3598:                                         NULL,
3599:                                 /* 99*/ MatProductSetFromOptions_SeqAIJ,
3600:                                         NULL,
3601:                                         NULL,
3602:                                         MatConjugate_SeqAIJ,
3603:                                         NULL,
3604:                                 /*104*/ MatSetValuesRow_SeqAIJ,
3605:                                         MatRealPart_SeqAIJ,
3606:                                         MatImaginaryPart_SeqAIJ,
3607:                                         NULL,
3608:                                         NULL,
3609:                                 /*109*/ MatMatSolve_SeqAIJ,
3610:                                         NULL,
3611:                                         MatGetRowMin_SeqAIJ,
3612:                                         NULL,
3613:                                         MatMissingDiagonal_SeqAIJ,
3614:                                 /*114*/ NULL,
3615:                                         NULL,
3616:                                         NULL,
3617:                                         NULL,
3618:                                         NULL,
3619:                                 /*119*/ NULL,
3620:                                         NULL,
3621:                                         NULL,
3622:                                         NULL,
3623:                                         MatGetMultiProcBlock_SeqAIJ,
3624:                                 /*124*/ MatFindNonzeroRows_SeqAIJ,
3625:                                         MatGetColumnNorms_SeqAIJ,
3626:                                         MatInvertBlockDiagonal_SeqAIJ,
3627:                                         MatInvertVariableBlockDiagonal_SeqAIJ,
3628:                                         NULL,
3629:                                 /*129*/ NULL,
3630:                                         NULL,
3631:                                         NULL,
3632:                                         MatTransposeMatMultNumeric_SeqAIJ_SeqAIJ,
3633:                                         MatTransposeColoringCreate_SeqAIJ,
3634:                                 /*134*/ MatTransColoringApplySpToDen_SeqAIJ,
3635:                                         MatTransColoringApplyDenToSp_SeqAIJ,
3636:                                         NULL,
3637:                                         NULL,
3638:                                         MatRARtNumeric_SeqAIJ_SeqAIJ,
3639:                                  /*139*/NULL,
3640:                                         NULL,
3641:                                         NULL,
3642:                                         MatFDColoringSetUp_SeqXAIJ,
3643:                                         MatFindOffBlockDiagonalEntries_SeqAIJ,
3644:                                         MatCreateMPIMatConcatenateSeqMat_SeqAIJ,
3645:                                  /*145*/MatDestroySubMatrices_SeqAIJ,
3646:                                         NULL,
3647:                                         NULL
3648: };

3650: PetscErrorCode  MatSeqAIJSetColumnIndices_SeqAIJ(Mat mat,PetscInt *indices)
3651: {
3652:   Mat_SeqAIJ *aij = (Mat_SeqAIJ*)mat->data;
3653:   PetscInt   i,nz,n;

3656:   nz = aij->maxnz;
3657:   n  = mat->rmap->n;
3658:   for (i=0; i<nz; i++) {
3659:     aij->j[i] = indices[i];
3660:   }
3661:   aij->nz = nz;
3662:   for (i=0; i<n; i++) {
3663:     aij->ilen[i] = aij->imax[i];
3664:   }
3665:   return(0);
3666: }

3668: /*
3669:  * When a sparse matrix has many zero columns, we should compact them out to save the space
3670:  * This happens in MatPtAPSymbolic_MPIAIJ_MPIAIJ_scalable()
3671:  * */
3672: PetscErrorCode  MatSeqAIJCompactOutExtraColumns_SeqAIJ(Mat mat, ISLocalToGlobalMapping *mapping)
3673: {
3674:   Mat_SeqAIJ *aij = (Mat_SeqAIJ*)mat->data;
3675:   PetscTable         gid1_lid1;
3676:   PetscTablePosition tpos;
3677:   PetscInt           gid,lid,i,j,ncols,ec;
3678:   PetscInt           *garray;
3679:   PetscErrorCode  ierr;

3684:   /* use a table */
3685:   PetscTableCreate(mat->rmap->n,mat->cmap->N+1,&gid1_lid1);
3686:   ec = 0;
3687:   for (i=0; i<mat->rmap->n; i++) {
3688:     ncols = aij->i[i+1] - aij->i[i];
3689:     for (j=0; j<ncols; j++) {
3690:       PetscInt data,gid1 = aij->j[aij->i[i] + j] + 1;
3691:       PetscTableFind(gid1_lid1,gid1,&data);
3692:       if (!data) {
3693:         /* one based table */
3694:         PetscTableAdd(gid1_lid1,gid1,++ec,INSERT_VALUES);
3695:       }
3696:     }
3697:   }
3698:   /* form array of columns we need */
3699:   PetscMalloc1(ec+1,&garray);
3700:   PetscTableGetHeadPosition(gid1_lid1,&tpos);
3701:   while (tpos) {
3702:     PetscTableGetNext(gid1_lid1,&tpos,&gid,&lid);
3703:     gid--;
3704:     lid--;
3705:     garray[lid] = gid;
3706:   }
3707:   PetscSortInt(ec,garray); /* sort, and rebuild */
3708:   PetscTableRemoveAll(gid1_lid1);
3709:   for (i=0; i<ec; i++) {
3710:     PetscTableAdd(gid1_lid1,garray[i]+1,i+1,INSERT_VALUES);
3711:   }
3712:   /* compact out the extra columns in B */
3713:   for (i=0; i<mat->rmap->n; i++) {
3714:         ncols = aij->i[i+1] - aij->i[i];
3715:     for (j=0; j<ncols; j++) {
3716:       PetscInt gid1 = aij->j[aij->i[i] + j] + 1;
3717:       PetscTableFind(gid1_lid1,gid1,&lid);
3718:       lid--;
3719:       aij->j[aij->i[i] + j] = lid;
3720:     }
3721:   }
3722:   PetscLayoutDestroy(&mat->cmap);
3723:   PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)mat),ec,ec,1,&mat->cmap);
3724:   PetscTableDestroy(&gid1_lid1);
3725:   ISLocalToGlobalMappingCreate(PETSC_COMM_SELF,mat->cmap->bs,mat->cmap->n,garray,PETSC_OWN_POINTER,mapping);
3726:   ISLocalToGlobalMappingSetType(*mapping,ISLOCALTOGLOBALMAPPINGHASH);
3727:   return(0);
3728: }

3730: /*@
3731:     MatSeqAIJSetColumnIndices - Set the column indices for all the rows
3732:        in the matrix.

3734:   Input Parameters:
3735: +  mat - the SeqAIJ matrix
3736: -  indices - the column indices

3738:   Level: advanced

3740:   Notes:
3741:     This can be called if you have precomputed the nonzero structure of the
3742:   matrix and want to provide it to the matrix object to improve the performance
3743:   of the MatSetValues() operation.

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

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

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

3752: @*/
3753: PetscErrorCode  MatSeqAIJSetColumnIndices(Mat mat,PetscInt *indices)
3754: {

3760:   PetscUseMethod(mat,"MatSeqAIJSetColumnIndices_C",(Mat,PetscInt*),(mat,indices));
3761:   return(0);
3762: }

3764: /* ----------------------------------------------------------------------------------------*/

3766: PetscErrorCode  MatStoreValues_SeqAIJ(Mat mat)
3767: {
3768:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)mat->data;
3770:   size_t         nz = aij->i[mat->rmap->n];

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

3775:   /* allocate space for values if not already there */
3776:   if (!aij->saved_values) {
3777:     PetscMalloc1(nz+1,&aij->saved_values);
3778:     PetscLogObjectMemory((PetscObject)mat,(nz+1)*sizeof(PetscScalar));
3779:   }

3781:   /* copy values over */
3782:   PetscArraycpy(aij->saved_values,aij->a,nz);
3783:   return(0);
3784: }

3786: /*@
3787:     MatStoreValues - Stashes a copy of the matrix values; this allows, for
3788:        example, reuse of the linear part of a Jacobian, while recomputing the
3789:        nonlinear portion.

3791:    Collect on Mat

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

3796:   Level: advanced

3798:   Common Usage, with SNESSolve():
3799: $    Create Jacobian matrix
3800: $    Set linear terms into matrix
3801: $    Apply boundary conditions to matrix, at this time matrix must have
3802: $      final nonzero structure (i.e. setting the nonlinear terms and applying
3803: $      boundary conditions again will not change the nonzero structure
3804: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3805: $    MatStoreValues(mat);
3806: $    Call SNESSetJacobian() with matrix
3807: $    In your Jacobian routine
3808: $      MatRetrieveValues(mat);
3809: $      Set nonlinear terms in matrix

3811:   Common Usage without SNESSolve(), i.e. when you handle nonlinear solve yourself:
3812: $    // build linear portion of Jacobian
3813: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3814: $    MatStoreValues(mat);
3815: $    loop over nonlinear iterations
3816: $       MatRetrieveValues(mat);
3817: $       // call MatSetValues(mat,...) to set nonliner portion of Jacobian
3818: $       // call MatAssemblyBegin/End() on matrix
3819: $       Solve linear system with Jacobian
3820: $    endloop

3822:   Notes:
3823:     Matrix must already be assemblied before calling this routine
3824:     Must set the matrix option MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE); before
3825:     calling this routine.

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

3830: .seealso: MatRetrieveValues()

3832: @*/
3833: PetscErrorCode  MatStoreValues(Mat mat)
3834: {

3839:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3840:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3841:   PetscUseMethod(mat,"MatStoreValues_C",(Mat),(mat));
3842:   return(0);
3843: }

3845: PetscErrorCode  MatRetrieveValues_SeqAIJ(Mat mat)
3846: {
3847:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)mat->data;
3849:   PetscInt       nz = aij->i[mat->rmap->n];

3852:   if (!aij->nonew) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");
3853:   if (!aij->saved_values) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ORDER,"Must call MatStoreValues(A);first");
3854:   /* copy values over */
3855:   PetscArraycpy(aij->a,aij->saved_values,nz);
3856:   return(0);
3857: }

3859: /*@
3860:     MatRetrieveValues - Retrieves the copy of the matrix values; this allows, for
3861:        example, reuse of the linear part of a Jacobian, while recomputing the
3862:        nonlinear portion.

3864:    Collect on Mat

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

3869:   Level: advanced

3871: .seealso: MatStoreValues()

3873: @*/
3874: PetscErrorCode  MatRetrieveValues(Mat mat)
3875: {

3880:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3881:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3882:   PetscUseMethod(mat,"MatRetrieveValues_C",(Mat),(mat));
3883:   return(0);
3884: }


3887: /* --------------------------------------------------------------------------------*/
3888: /*@C
3889:    MatCreateSeqAIJ - Creates a sparse matrix in AIJ (compressed row) format
3890:    (the default parallel PETSc format).  For good matrix assembly performance
3891:    the user should preallocate the matrix storage by setting the parameter nz
3892:    (or the array nnz).  By setting these parameters accurately, performance
3893:    during matrix assembly can be increased by more than a factor of 50.

3895:    Collective

3897:    Input Parameters:
3898: +  comm - MPI communicator, set to PETSC_COMM_SELF
3899: .  m - number of rows
3900: .  n - number of columns
3901: .  nz - number of nonzeros per row (same for all rows)
3902: -  nnz - array containing the number of nonzeros in the various rows
3903:          (possibly different for each row) or NULL

3905:    Output Parameter:
3906: .  A - the matrix

3908:    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
3909:    MatXXXXSetPreallocation() paradigm instead of this routine directly.
3910:    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]

3912:    Notes:
3913:    If nnz is given then nz is ignored

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

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

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

3930:    Options Database Keys:
3931: +  -mat_no_inode  - Do not use inodes
3932: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3934:    Level: intermediate

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

3938: @*/
3939: PetscErrorCode  MatCreateSeqAIJ(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt nz,const PetscInt nnz[],Mat *A)
3940: {

3944:   MatCreate(comm,A);
3945:   MatSetSizes(*A,m,n,m,n);
3946:   MatSetType(*A,MATSEQAIJ);
3947:   MatSeqAIJSetPreallocation_SeqAIJ(*A,nz,nnz);
3948:   return(0);
3949: }

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

3957:    Collective

3959:    Input Parameters:
3960: +  B - The matrix
3961: .  nz - number of nonzeros per row (same for all rows)
3962: -  nnz - array containing the number of nonzeros in the various rows
3963:          (possibly different for each row) or NULL

3965:    Notes:
3966:      If nnz is given then nz is ignored

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

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

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

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

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

3991:    Options Database Keys:
3992: +  -mat_no_inode  - Do not use inodes
3993: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3995:    Level: intermediate

3997: .seealso: MatCreate(), MatCreateAIJ(), MatSetValues(), MatSeqAIJSetColumnIndices(), MatCreateSeqAIJWithArrays(), MatGetInfo(),
3998:           MatSeqAIJSetTotalPreallocation()

4000: @*/
4001: PetscErrorCode  MatSeqAIJSetPreallocation(Mat B,PetscInt nz,const PetscInt nnz[])
4002: {

4008:   PetscTryMethod(B,"MatSeqAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[]),(B,nz,nnz));
4009:   return(0);
4010: }

4012: PetscErrorCode  MatSeqAIJSetPreallocation_SeqAIJ(Mat B,PetscInt nz,const PetscInt *nnz)
4013: {
4014:   Mat_SeqAIJ     *b;
4015:   PetscBool      skipallocation = PETSC_FALSE,realalloc = PETSC_FALSE;
4017:   PetscInt       i;

4020:   if (nz >= 0 || nnz) realalloc = PETSC_TRUE;
4021:   if (nz == MAT_SKIP_ALLOCATION) {
4022:     skipallocation = PETSC_TRUE;
4023:     nz             = 0;
4024:   }
4025:   PetscLayoutSetUp(B->rmap);
4026:   PetscLayoutSetUp(B->cmap);

4028:   if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 5;
4029:   if (nz < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"nz cannot be less than 0: value %D",nz);
4030:   if (PetscUnlikelyDebug(nnz)) {
4031:     for (i=0; i<B->rmap->n; i++) {
4032:       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]);
4033:       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);
4034:     }
4035:   }

4037:   B->preallocated = PETSC_TRUE;

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

4041:   if (!skipallocation) {
4042:     if (!b->imax) {
4043:       PetscMalloc1(B->rmap->n,&b->imax);
4044:       PetscLogObjectMemory((PetscObject)B,B->rmap->n*sizeof(PetscInt));
4045:     }
4046:     if (!b->ilen) {
4047:       /* b->ilen will count nonzeros in each row so far. */
4048:       PetscCalloc1(B->rmap->n,&b->ilen);
4049:       PetscLogObjectMemory((PetscObject)B,B->rmap->n*sizeof(PetscInt));
4050:     } else {
4051:       PetscMemzero(b->ilen,B->rmap->n*sizeof(PetscInt));
4052:     }
4053:     if (!b->ipre) {
4054:       PetscMalloc1(B->rmap->n,&b->ipre);
4055:       PetscLogObjectMemory((PetscObject)B,B->rmap->n*sizeof(PetscInt));
4056:     }
4057:     if (!nnz) {
4058:       if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 10;
4059:       else if (nz < 0) nz = 1;
4060:       nz = PetscMin(nz,B->cmap->n);
4061:       for (i=0; i<B->rmap->n; i++) b->imax[i] = nz;
4062:       nz = nz*B->rmap->n;
4063:     } else {
4064:       PetscInt64 nz64 = 0;
4065:       for (i=0; i<B->rmap->n; i++) {b->imax[i] = nnz[i]; nz64 += nnz[i];}
4066:       PetscIntCast(nz64,&nz);
4067:     }

4069:     /* allocate the matrix space */
4070:     /* FIXME: should B's old memory be unlogged? */
4071:     MatSeqXAIJFreeAIJ(B,&b->a,&b->j,&b->i);
4072:     if (B->structure_only) {
4073:       PetscMalloc1(nz,&b->j);
4074:       PetscMalloc1(B->rmap->n+1,&b->i);
4075:       PetscLogObjectMemory((PetscObject)B,(B->rmap->n+1)*sizeof(PetscInt)+nz*sizeof(PetscInt));
4076:     } else {
4077:       PetscMalloc3(nz,&b->a,nz,&b->j,B->rmap->n+1,&b->i);
4078:       PetscLogObjectMemory((PetscObject)B,(B->rmap->n+1)*sizeof(PetscInt)+nz*(sizeof(PetscScalar)+sizeof(PetscInt)));
4079:     }
4080:     b->i[0] = 0;
4081:     for (i=1; i<B->rmap->n+1; i++) {
4082:       b->i[i] = b->i[i-1] + b->imax[i-1];
4083:     }
4084:     if (B->structure_only) {
4085:       b->singlemalloc = PETSC_FALSE;
4086:       b->free_a       = PETSC_FALSE;
4087:     } else {
4088:       b->singlemalloc = PETSC_TRUE;
4089:       b->free_a       = PETSC_TRUE;
4090:     }
4091:     b->free_ij      = PETSC_TRUE;
4092:   } else {
4093:     b->free_a  = PETSC_FALSE;
4094:     b->free_ij = PETSC_FALSE;
4095:   }

4097:   if (b->ipre && nnz != b->ipre  && b->imax) {
4098:     /* reserve user-requested sparsity */
4099:     PetscArraycpy(b->ipre,b->imax,B->rmap->n);
4100:   }


4103:   b->nz               = 0;
4104:   b->maxnz            = nz;
4105:   B->info.nz_unneeded = (double)b->maxnz;
4106:   if (realalloc) {
4107:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
4108:   }
4109:   B->was_assembled = PETSC_FALSE;
4110:   B->assembled     = PETSC_FALSE;
4111:   return(0);
4112: }


4115: PetscErrorCode MatResetPreallocation_SeqAIJ(Mat A)
4116: {
4117:   Mat_SeqAIJ     *a;
4118:   PetscInt       i;


4124:   /* Check local size. If zero, then return */
4125:   if (!A->rmap->n) return(0);

4127:   a = (Mat_SeqAIJ*)A->data;
4128:   /* if no saved info, we error out */
4129:   if (!a->ipre) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"No saved preallocation info \n");

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

4133:   PetscArraycpy(a->imax,a->ipre,A->rmap->n);
4134:   PetscArrayzero(a->ilen,A->rmap->n);
4135:   a->i[0] = 0;
4136:   for (i=1; i<A->rmap->n+1; i++) {
4137:     a->i[i] = a->i[i-1] + a->imax[i-1];
4138:   }
4139:   A->preallocated     = PETSC_TRUE;
4140:   a->nz               = 0;
4141:   a->maxnz            = a->i[A->rmap->n];
4142:   A->info.nz_unneeded = (double)a->maxnz;
4143:   A->was_assembled    = PETSC_FALSE;
4144:   A->assembled        = PETSC_FALSE;
4145:   return(0);
4146: }

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

4151:    Input Parameters:
4152: +  B - the matrix
4153: .  i - the indices into j for the start of each row (starts with zero)
4154: .  j - the column indices for each row (starts with zero) these must be sorted for each row
4155: -  v - optional values in the matrix

4157:    Level: developer

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

4162:       This routine may be called multiple times with different nonzero patterns (or the same nonzero pattern). The nonzero
4163:       structure will be the union of all the previous nonzero structures.

4165:     Developer Notes:
4166:       An optimization could be added to the implementation where it checks if the i, and j are identical to the current i and j and
4167:       then just copies the v values directly with PetscMemcpy().

4169:       This routine could also take a PetscCopyMode argument to allow sharing the values instead of always copying them.

4171: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatSeqAIJSetPreallocation(), MatCreateSeqAIJ(), MATSEQAIJ, MatResetPreallocation()
4172: @*/
4173: PetscErrorCode MatSeqAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[],const PetscScalar v[])
4174: {

4180:   PetscTryMethod(B,"MatSeqAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));
4181:   return(0);
4182: }

4184: PetscErrorCode  MatSeqAIJSetPreallocationCSR_SeqAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
4185: {
4186:   PetscInt       i;
4187:   PetscInt       m,n;
4188:   PetscInt       nz;
4189:   PetscInt       *nnz;

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

4195:   PetscLayoutSetUp(B->rmap);
4196:   PetscLayoutSetUp(B->cmap);

4198:   MatGetSize(B, &m, &n);
4199:   PetscMalloc1(m+1, &nnz);
4200:   for (i = 0; i < m; i++) {
4201:     nz     = Ii[i+1]- Ii[i];
4202:     if (nz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Local row %D has a negative number of columns %D", i, nnz);
4203:     nnz[i] = nz;
4204:   }
4205:   MatSeqAIJSetPreallocation(B, 0, nnz);
4206:   PetscFree(nnz);

4208:   for (i = 0; i < m; i++) {
4209:     MatSetValues_SeqAIJ(B, 1, &i, Ii[i+1] - Ii[i], J+Ii[i], v ? v + Ii[i] : NULL, INSERT_VALUES);
4210:   }

4212:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4213:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

4215:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
4216:   return(0);
4217: }

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

4222: /*
4223:     Computes (B'*A')' since computing B*A directly is untenable

4225:                n                       p                          p
4226:         [             ]       [             ]         [                 ]
4227:       m [      A      ]  *  n [       B     ]   =   m [         C       ]
4228:         [             ]       [             ]         [                 ]

4230: */
4231: PetscErrorCode MatMatMultNumeric_SeqDense_SeqAIJ(Mat A,Mat B,Mat C)
4232: {
4233:   PetscErrorCode    ierr;
4234:   Mat_SeqDense      *sub_a = (Mat_SeqDense*)A->data;
4235:   Mat_SeqAIJ        *sub_b = (Mat_SeqAIJ*)B->data;
4236:   Mat_SeqDense      *sub_c = (Mat_SeqDense*)C->data;
4237:   PetscInt          i,j,n,m,q,p;
4238:   const PetscInt    *ii,*idx;
4239:   const PetscScalar *b,*a,*a_q;
4240:   PetscScalar       *c,*c_q;
4241:   PetscInt          clda = sub_c->lda;
4242:   PetscInt          alda = sub_a->lda;

4245:   m    = A->rmap->n;
4246:   n    = A->cmap->n;
4247:   p    = B->cmap->n;
4248:   a    = sub_a->v;
4249:   b    = sub_b->a;
4250:   c    = sub_c->v;
4251:   if (clda == m) {
4252:     PetscArrayzero(c,m*p);
4253:   } else {
4254:     for (j=0;j<p;j++)
4255:       for (i=0;i<m;i++)
4256:         c[j*clda + i] = 0.0;
4257:   }
4258:   ii  = sub_b->i;
4259:   idx = sub_b->j;
4260:   for (i=0; i<n; i++) {
4261:     q = ii[i+1] - ii[i];
4262:     while (q-->0) {
4263:       c_q = c + clda*(*idx);
4264:       a_q = a + alda*i;
4265:       PetscKernelAXPY(c_q,*b,a_q,m);
4266:       idx++;
4267:       b++;
4268:     }
4269:   }
4270:   return(0);
4271: }

4273: PetscErrorCode MatMatMultSymbolic_SeqDense_SeqAIJ(Mat A,Mat B,PetscReal fill,Mat C)
4274: {
4276:   PetscInt       m=A->rmap->n,n=B->cmap->n;
4277:   PetscBool      cisdense;

4280:   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);
4281:   MatSetSizes(C,m,n,m,n);
4282:   MatSetBlockSizesFromMats(C,A,B);
4283:   PetscObjectTypeCompareAny((PetscObject)C,&cisdense,MATSEQDENSE,MATSEQDENSECUDA,"");
4284:   if (!cisdense) {
4285:     MatSetType(C,MATDENSE);
4286:   }
4287:   MatSetUp(C);

4289:   C->ops->matmultnumeric = MatMatMultNumeric_SeqDense_SeqAIJ;
4290:   return(0);
4291: }

4293: /* ----------------------------------------------------------------*/
4294: /*MC
4295:    MATSEQAIJ - MATSEQAIJ = "seqaij" - A matrix type to be used for sequential sparse matrices,
4296:    based on compressed sparse row format.

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

4301:    Level: beginner

4303:    Notes:
4304:     MatSetValues() may be called for this matrix type with a NULL argument for the numerical values,
4305:     in this case the values associated with the rows and columns one passes in are set to zero
4306:     in the matrix

4308:     MatSetOptions(,MAT_STRUCTURE_ONLY,PETSC_TRUE) may be called for this matrix type. In this no
4309:     space is allocated for the nonzero entries and any entries passed with MatSetValues() are ignored

4311:   Developer Notes:
4312:     It would be nice if all matrix formats supported passing NULL in for the numerical values

4314: .seealso: MatCreateSeqAIJ(), MatSetFromOptions(), MatSetType(), MatCreate(), MatType
4315: M*/

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

4320:    This matrix type is identical to MATSEQAIJ when constructed with a single process communicator,
4321:    and MATMPIAIJ otherwise.  As a result, for single process communicators,
4322:   MatSeqAIJSetPreallocation is supported, and similarly MatMPIAIJSetPreallocation() is supported
4323:   for communicators controlling multiple processes.  It is recommended that you call both of
4324:   the above preallocation routines for simplicity.

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

4329:   Developer Notes:
4330:     Subclasses include MATAIJCUSPARSE, MATAIJPERM, MATAIJSELL, MATAIJMKL, MATAIJCRL, and also automatically switches over to use inodes when
4331:    enough exist.

4333:   Level: beginner

4335: .seealso: MatCreateAIJ(), MatCreateSeqAIJ(), MATSEQAIJ,MATMPIAIJ
4336: M*/

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

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

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

4350:   Level: beginner

4352: .seealso: MatCreateMPIAIJCRL,MATSEQAIJCRL,MATMPIAIJCRL, MATSEQAIJCRL, MATMPIAIJCRL
4353: M*/

4355: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCRL(Mat,MatType,MatReuse,Mat*);
4356: #if defined(PETSC_HAVE_ELEMENTAL)
4357: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_Elemental(Mat,MatType,MatReuse,Mat*);
4358: #endif
4359: #if defined(PETSC_HAVE_SCALAPACK)
4360: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat,MatType,MatReuse,Mat*);
4361: #endif
4362: #if defined(PETSC_HAVE_HYPRE)
4363: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat A,MatType,MatReuse,Mat*);
4364: #endif
4365: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqDense(Mat,MatType,MatReuse,Mat*);

4367: PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqSELL(Mat,MatType,MatReuse,Mat*);
4368: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat,MatType,MatReuse,Mat*);
4369: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);

4371: /*@C
4372:    MatSeqAIJGetArray - gives read/write access to the array where the data for a MATSEQAIJ matrix is stored

4374:    Not Collective

4376:    Input Parameter:
4377: .  mat - a MATSEQAIJ matrix

4379:    Output Parameter:
4380: .   array - pointer to the data

4382:    Level: intermediate

4384: .seealso: MatSeqAIJRestoreArray(), MatSeqAIJGetArrayF90()
4385: @*/
4386: PetscErrorCode  MatSeqAIJGetArray(Mat A,PetscScalar **array)
4387: {

4391:   PetscUseMethod(A,"MatSeqAIJGetArray_C",(Mat,PetscScalar**),(A,array));
4392:   return(0);
4393: }

4395: /*@C
4396:    MatSeqAIJGetArrayRead - gives read-only access to the array where the data for a MATSEQAIJ matrix is stored

4398:    Not Collective

4400:    Input Parameter:
4401: .  mat - a MATSEQAIJ matrix

4403:    Output Parameter:
4404: .   array - pointer to the data

4406:    Level: intermediate

4408: .seealso: MatSeqAIJGetArray(), MatSeqAIJRestoreArrayRead()
4409: @*/
4410: PetscErrorCode  MatSeqAIJGetArrayRead(Mat A,const PetscScalar **array)
4411: {
4412: #if defined(PETSC_HAVE_DEVICE)
4413:   PetscOffloadMask oval;
4414: #endif

4418: #if defined(PETSC_HAVE_DEVICE)
4419:   oval = A->offloadmask;
4420: #endif
4421:   MatSeqAIJGetArray(A,(PetscScalar**)array);
4422: #if defined(PETSC_HAVE_DEVICE)
4423:   if (oval == PETSC_OFFLOAD_GPU || oval == PETSC_OFFLOAD_BOTH) A->offloadmask = PETSC_OFFLOAD_BOTH;
4424: #endif
4425:   return(0);
4426: }

4428: /*@C
4429:    MatSeqAIJRestoreArrayRead - restore the read-only access array obtained from MatSeqAIJGetArrayRead

4431:    Not Collective

4433:    Input Parameter:
4434: .  mat - a MATSEQAIJ matrix

4436:    Output Parameter:
4437: .   array - pointer to the data

4439:    Level: intermediate

4441: .seealso: MatSeqAIJGetArray(), MatSeqAIJGetArrayRead()
4442: @*/
4443: PetscErrorCode  MatSeqAIJRestoreArrayRead(Mat A,const PetscScalar **array)
4444: {
4445: #if defined(PETSC_HAVE_DEVICE)
4446:   PetscOffloadMask oval;
4447: #endif

4451: #if defined(PETSC_HAVE_DEVICE)
4452:   oval = A->offloadmask;
4453: #endif
4454:   MatSeqAIJRestoreArray(A,(PetscScalar**)array);
4455: #if defined(PETSC_HAVE_DEVICE)
4456:   A->offloadmask = oval;
4457: #endif
4458:   return(0);
4459: }

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

4464:    Not Collective

4466:    Input Parameter:
4467: .  mat - a MATSEQAIJ matrix

4469:    Output Parameter:
4470: .   nz - the maximum number of nonzeros in any row

4472:    Level: intermediate

4474: .seealso: MatSeqAIJRestoreArray(), MatSeqAIJGetArrayF90()
4475: @*/
4476: PetscErrorCode  MatSeqAIJGetMaxRowNonzeros(Mat A,PetscInt *nz)
4477: {
4478:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)A->data;

4481:   *nz = aij->rmax;
4482:   return(0);
4483: }

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

4488:    Not Collective

4490:    Input Parameters:
4491: +  mat - a MATSEQAIJ matrix
4492: -  array - pointer to the data

4494:    Level: intermediate

4496: .seealso: MatSeqAIJGetArray(), MatSeqAIJRestoreArrayF90()
4497: @*/
4498: PetscErrorCode  MatSeqAIJRestoreArray(Mat A,PetscScalar **array)
4499: {

4503:   PetscUseMethod(A,"MatSeqAIJRestoreArray_C",(Mat,PetscScalar**),(A,array));
4504:   return(0);
4505: }

4507: #if defined(PETSC_HAVE_CUDA)
4508: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat);
4509: #endif
4510: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
4511: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJKokkos(Mat);
4512: #endif

4514: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJ(Mat B)
4515: {
4516:   Mat_SeqAIJ     *b;
4518:   PetscMPIInt    size;

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

4524:   PetscNewLog(B,&b);

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

4528:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));
4529:   if (B->sortedfull) B->ops->setvalues = MatSetValues_SeqAIJ_SortedFull;

4531:   b->row                = NULL;
4532:   b->col                = NULL;
4533:   b->icol               = NULL;
4534:   b->reallocs           = 0;
4535:   b->ignorezeroentries  = PETSC_FALSE;
4536:   b->roworiented        = PETSC_TRUE;
4537:   b->nonew              = 0;
4538:   b->diag               = NULL;
4539:   b->solve_work         = NULL;
4540:   B->spptr              = NULL;
4541:   b->saved_values       = NULL;
4542:   b->idiag              = NULL;
4543:   b->mdiag              = NULL;
4544:   b->ssor_work          = NULL;
4545:   b->omega              = 1.0;
4546:   b->fshift             = 0.0;
4547:   b->idiagvalid         = PETSC_FALSE;
4548:   b->ibdiagvalid        = PETSC_FALSE;
4549:   b->keepnonzeropattern = PETSC_FALSE;

4551:   PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJ);
4552:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJGetArray_C",MatSeqAIJGetArray_SeqAIJ);
4553:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJRestoreArray_C",MatSeqAIJRestoreArray_SeqAIJ);

4555: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4556:   PetscObjectComposeFunction((PetscObject)B,"PetscMatlabEnginePut_C",MatlabEnginePut_SeqAIJ);
4557:   PetscObjectComposeFunction((PetscObject)B,"PetscMatlabEngineGet_C",MatlabEngineGet_SeqAIJ);
4558: #endif

4560:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetColumnIndices_C",MatSeqAIJSetColumnIndices_SeqAIJ);
4561:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_SeqAIJ);
4562:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_SeqAIJ);
4563:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqsbaij_C",MatConvert_SeqAIJ_SeqSBAIJ);
4564:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqbaij_C",MatConvert_SeqAIJ_SeqBAIJ);
4565:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijperm_C",MatConvert_SeqAIJ_SeqAIJPERM);
4566:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijsell_C",MatConvert_SeqAIJ_SeqAIJSELL);
4567: #if defined(PETSC_HAVE_MKL_SPARSE)
4568:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijmkl_C",MatConvert_SeqAIJ_SeqAIJMKL);
4569: #endif
4570: #if defined(PETSC_HAVE_CUDA)
4571:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijcusparse_C",MatConvert_SeqAIJ_SeqAIJCUSPARSE);
4572:   PetscObjectComposeFunction((PetscObject)B,"MatProductSetFromOptions_seqaijcusparse_seqaij_C",MatProductSetFromOptions_SeqAIJ);
4573: #endif
4574: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
4575:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijkokkos_C",MatConvert_SeqAIJ_SeqAIJKokkos);
4576: #endif
4577:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqaijcrl_C",MatConvert_SeqAIJ_SeqAIJCRL);
4578: #if defined(PETSC_HAVE_ELEMENTAL)
4579:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_elemental_C",MatConvert_SeqAIJ_Elemental);
4580: #endif
4581: #if defined(PETSC_HAVE_SCALAPACK)
4582:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_scalapack_C",MatConvert_AIJ_ScaLAPACK);
4583: #endif
4584: #if defined(PETSC_HAVE_HYPRE)
4585:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_hypre_C",MatConvert_AIJ_HYPRE);
4586:   PetscObjectComposeFunction((PetscObject)B,"MatProductSetFromOptions_transpose_seqaij_seqaij_C",MatProductSetFromOptions_Transpose_AIJ_AIJ);
4587: #endif
4588:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqdense_C",MatConvert_SeqAIJ_SeqDense);
4589:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_seqsell_C",MatConvert_SeqAIJ_SeqSELL);
4590:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_seqaij_is_C",MatConvert_XAIJ_IS);
4591:   PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_SeqAIJ);
4592:   PetscObjectComposeFunction((PetscObject)B,"MatIsHermitianTranspose_C",MatIsTranspose_SeqAIJ);
4593:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetPreallocation_C",MatSeqAIJSetPreallocation_SeqAIJ);
4594:   PetscObjectComposeFunction((PetscObject)B,"MatResetPreallocation_C",MatResetPreallocation_SeqAIJ);
4595:   PetscObjectComposeFunction((PetscObject)B,"MatSeqAIJSetPreallocationCSR_C",MatSeqAIJSetPreallocationCSR_SeqAIJ);
4596:   PetscObjectComposeFunction((PetscObject)B,"MatReorderForNonzeroDiagonal_C",MatReorderForNonzeroDiagonal_SeqAIJ);
4597:   PetscObjectComposeFunction((PetscObject)B,"MatProductSetFromOptions_is_seqaij_C",MatProductSetFromOptions_IS_XAIJ);
4598:   PetscObjectComposeFunction((PetscObject)B,"MatProductSetFromOptions_seqdense_seqaij_C",MatProductSetFromOptions_SeqDense_SeqAIJ);
4599:   PetscObjectComposeFunction((PetscObject)B,"MatProductSetFromOptions_seqaij_seqaij_C",MatProductSetFromOptions_SeqAIJ);
4600:   MatCreate_SeqAIJ_Inode(B);
4601:   PetscObjectChangeTypeName((PetscObject)B,MATSEQAIJ);
4602:   MatSeqAIJSetTypeFromOptions(B);  /* this allows changing the matrix subtype to say MATSEQAIJPERM */
4603:   return(0);
4604: }

4606: /*
4607:     Given a matrix generated with MatGetFactor() duplicates all the information in A into B
4608: */
4609: PetscErrorCode MatDuplicateNoCreate_SeqAIJ(Mat C,Mat A,MatDuplicateOption cpvalues,PetscBool mallocmatspace)
4610: {
4611:   Mat_SeqAIJ     *c = (Mat_SeqAIJ*)C->data,*a = (Mat_SeqAIJ*)A->data;
4613:   PetscInt       m = A->rmap->n,i;

4616:   if (!A->assembled && cpvalues!=MAT_DO_NOT_COPY_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot duplicate unassembled matrix");

4618:   C->factortype = A->factortype;
4619:   c->row        = NULL;
4620:   c->col        = NULL;
4621:   c->icol       = NULL;
4622:   c->reallocs   = 0;

4624:   C->assembled = PETSC_TRUE;

4626:   PetscLayoutReference(A->rmap,&C->rmap);
4627:   PetscLayoutReference(A->cmap,&C->cmap);

4629:   PetscMalloc1(m,&c->imax);
4630:   PetscMemcpy(c->imax,a->imax,m*sizeof(PetscInt));
4631:   PetscMalloc1(m,&c->ilen);
4632:   PetscMemcpy(c->ilen,a->ilen,m*sizeof(PetscInt));
4633:   PetscLogObjectMemory((PetscObject)C, 2*m*sizeof(PetscInt));

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

4640:     c->singlemalloc = PETSC_TRUE;

4642:     PetscArraycpy(c->i,a->i,m+1);
4643:     if (m > 0) {
4644:       PetscArraycpy(c->j,a->j,a->i[m]);
4645:       if (cpvalues == MAT_COPY_VALUES) {
4646:         PetscArraycpy(c->a,a->a,a->i[m]);
4647:       } else {
4648:         PetscArrayzero(c->a,a->i[m]);
4649:       }
4650:     }
4651:   }

4653:   c->ignorezeroentries = a->ignorezeroentries;
4654:   c->roworiented       = a->roworiented;
4655:   c->nonew             = a->nonew;
4656:   if (a->diag) {
4657:     PetscMalloc1(m+1,&c->diag);
4658:     PetscMemcpy(c->diag,a->diag,m*sizeof(PetscInt));
4659:     PetscLogObjectMemory((PetscObject)C,(m+1)*sizeof(PetscInt));
4660:   } else c->diag = NULL;

4662:   c->solve_work         = NULL;
4663:   c->saved_values       = NULL;
4664:   c->idiag              = NULL;
4665:   c->ssor_work          = NULL;
4666:   c->keepnonzeropattern = a->keepnonzeropattern;
4667:   c->free_a             = PETSC_TRUE;
4668:   c->free_ij            = PETSC_TRUE;

4670:   c->rmax         = a->rmax;
4671:   c->nz           = a->nz;
4672:   c->maxnz        = a->nz;       /* Since we allocate exactly the right amount */
4673:   C->preallocated = PETSC_TRUE;

4675:   c->compressedrow.use   = a->compressedrow.use;
4676:   c->compressedrow.nrows = a->compressedrow.nrows;
4677:   if (a->compressedrow.use) {
4678:     i    = a->compressedrow.nrows;
4679:     PetscMalloc2(i+1,&c->compressedrow.i,i,&c->compressedrow.rindex);
4680:     PetscArraycpy(c->compressedrow.i,a->compressedrow.i,i+1);
4681:     PetscArraycpy(c->compressedrow.rindex,a->compressedrow.rindex,i);
4682:   } else {
4683:     c->compressedrow.use    = PETSC_FALSE;
4684:     c->compressedrow.i      = NULL;
4685:     c->compressedrow.rindex = NULL;
4686:   }
4687:   c->nonzerorowcnt = a->nonzerorowcnt;
4688:   C->nonzerostate  = A->nonzerostate;

4690:   MatDuplicate_SeqAIJ_Inode(A,cpvalues,&C);
4691:   PetscFunctionListDuplicate(((PetscObject)A)->qlist,&((PetscObject)C)->qlist);
4692:   return(0);
4693: }

4695: PetscErrorCode MatDuplicate_SeqAIJ(Mat A,MatDuplicateOption cpvalues,Mat *B)
4696: {

4700:   MatCreate(PetscObjectComm((PetscObject)A),B);
4701:   MatSetSizes(*B,A->rmap->n,A->cmap->n,A->rmap->n,A->cmap->n);
4702:   if (!(A->rmap->n % A->rmap->bs) && !(A->cmap->n % A->cmap->bs)) {
4703:     MatSetBlockSizesFromMats(*B,A,A);
4704:   }
4705:   MatSetType(*B,((PetscObject)A)->type_name);
4706:   MatDuplicateNoCreate_SeqAIJ(*B,A,cpvalues,PETSC_TRUE);
4707:   return(0);
4708: }

4710: PetscErrorCode MatLoad_SeqAIJ(Mat newMat, PetscViewer viewer)
4711: {
4712:   PetscBool      isbinary, ishdf5;

4718:   /* force binary viewer to load .info file if it has not yet done so */
4719:   PetscViewerSetUp(viewer);
4720:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
4721:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERHDF5,  &ishdf5);
4722:   if (isbinary) {
4723:     MatLoad_SeqAIJ_Binary(newMat,viewer);
4724:   } else if (ishdf5) {
4725: #if defined(PETSC_HAVE_HDF5)
4726:     MatLoad_AIJ_HDF5(newMat,viewer);
4727: #else
4728:     SETERRQ(PetscObjectComm((PetscObject)newMat),PETSC_ERR_SUP,"HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
4729: #endif
4730:   } else {
4731:     SETERRQ2(PetscObjectComm((PetscObject)newMat),PETSC_ERR_SUP,"Viewer type %s not yet supported for reading %s matrices",((PetscObject)viewer)->type_name,((PetscObject)newMat)->type_name);
4732:   }
4733:   return(0);
4734: }

4736: PetscErrorCode MatLoad_SeqAIJ_Binary(Mat mat, PetscViewer viewer)
4737: {
4738:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)mat->data;
4740:   PetscInt       header[4],*rowlens,M,N,nz,sum,rows,cols,i;

4743:   PetscViewerSetUp(viewer);

4745:   /* read in matrix header */
4746:   PetscViewerBinaryRead(viewer,header,4,NULL,PETSC_INT);
4747:   if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"Not a matrix object in file");
4748:   M = header[1]; N = header[2]; nz = header[3];
4749:   if (M < 0) SETERRQ1(PetscObjectComm((PetscObject)viewer),PETSC_ERR_FILE_UNEXPECTED,"Matrix row size (%D) in file is negative",M);
4750:   if (N < 0) SETERRQ1(PetscObjectComm((PetscObject)viewer),PETSC_ERR_FILE_UNEXPECTED,"Matrix column size (%D) in file is negative",N);
4751:   if (nz < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"Matrix stored in special format on disk, cannot load as SeqAIJ");

4753:   /* set block sizes from the viewer's .info file */
4754:   MatLoad_Binary_BlockSizes(mat,viewer);
4755:   /* set local and global sizes if not set already */
4756:   if (mat->rmap->n < 0) mat->rmap->n = M;
4757:   if (mat->cmap->n < 0) mat->cmap->n = N;
4758:   if (mat->rmap->N < 0) mat->rmap->N = M;
4759:   if (mat->cmap->N < 0) mat->cmap->N = N;
4760:   PetscLayoutSetUp(mat->rmap);
4761:   PetscLayoutSetUp(mat->cmap);

4763:   /* check if the matrix sizes are correct */
4764:   MatGetSize(mat,&rows,&cols);
4765:   if (M != rows || N != cols) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Matrix in file of different sizes (%D, %D) than the input matrix (%D, %D)",M,N,rows,cols);

4767:   /* read in row lengths */
4768:   PetscMalloc1(M,&rowlens);
4769:   PetscViewerBinaryRead(viewer,rowlens,M,NULL,PETSC_INT);
4770:   /* check if sum(rowlens) is same as nz */
4771:   sum = 0; for (i=0; i<M; i++) sum += rowlens[i];
4772:   if (sum != nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"Inconsistent matrix data in file: nonzeros = %D, sum-row-lengths = %D\n",nz,sum);
4773:   /* preallocate and check sizes */
4774:   MatSeqAIJSetPreallocation_SeqAIJ(mat,0,rowlens);
4775:   MatGetSize(mat,&rows,&cols);
4776:   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);
4777:   /* store row lengths */
4778:   PetscArraycpy(a->ilen,rowlens,M);
4779:   PetscFree(rowlens);

4781:   /* fill in "i" row pointers */
4782:   a->i[0] = 0; for (i=0; i<M; i++) a->i[i+1] = a->i[i] + a->ilen[i];
4783:   /* read in "j" column indices */
4784:   PetscViewerBinaryRead(viewer,a->j,nz,NULL,PETSC_INT);
4785:   /* read in "a" nonzero values */
4786:   PetscViewerBinaryRead(viewer,a->a,nz,NULL,PETSC_SCALAR);

4788:   MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
4789:   MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
4790:   return(0);
4791: }

4793: PetscErrorCode MatEqual_SeqAIJ(Mat A,Mat B,PetscBool * flg)
4794: {
4795:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*b = (Mat_SeqAIJ*)B->data;
4797: #if defined(PETSC_USE_COMPLEX)
4798:   PetscInt k;
4799: #endif

4802:   /* If the  matrix dimensions are not equal,or no of nonzeros */
4803:   if ((A->rmap->n != B->rmap->n) || (A->cmap->n != B->cmap->n) ||(a->nz != b->nz)) {
4804:     *flg = PETSC_FALSE;
4805:     return(0);
4806:   }

4808:   /* if the a->i are the same */
4809:   PetscArraycmp(a->i,b->i,A->rmap->n+1,flg);
4810:   if (!*flg) return(0);

4812:   /* if a->j are the same */
4813:   PetscArraycmp(a->j,b->j,a->nz,flg);
4814:   if (!*flg) return(0);

4816:   /* if a->a are the same */
4817: #if defined(PETSC_USE_COMPLEX)
4818:   for (k=0; k<a->nz; k++) {
4819:     if (PetscRealPart(a->a[k]) != PetscRealPart(b->a[k]) || PetscImaginaryPart(a->a[k]) != PetscImaginaryPart(b->a[k])) {
4820:       *flg = PETSC_FALSE;
4821:       return(0);
4822:     }
4823:   }
4824: #else
4825:   PetscArraycmp(a->a,b->a,a->nz,flg);
4826: #endif
4827:   return(0);
4828: }

4830: /*@
4831:      MatCreateSeqAIJWithArrays - Creates an sequential AIJ matrix using matrix elements (in CSR format)
4832:               provided by the user.

4834:       Collective

4836:    Input Parameters:
4837: +   comm - must be an MPI communicator of size 1
4838: .   m - number of rows
4839: .   n - number of columns
4840: .   i - row indices; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
4841: .   j - column indices
4842: -   a - matrix values

4844:    Output Parameter:
4845: .   mat - the matrix

4847:    Level: intermediate

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

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

4855:        The i and j indices are 0 based

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

4861: $        1 0 0
4862: $        2 0 3
4863: $        4 5 6
4864: $
4865: $        i =  {0,1,3,6}  [size = nrow+1  = 3+1]
4866: $        j =  {0,0,2,0,1,2}  [size = 6]; values must be sorted for each row
4867: $        v =  {1,2,3,4,5,6}  [size = 6]


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

4872: @*/
4873: PetscErrorCode  MatCreateSeqAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt i[],PetscInt j[],PetscScalar a[],Mat *mat)
4874: {
4876:   PetscInt       ii;
4877:   Mat_SeqAIJ     *aij;
4878:   PetscInt jj;

4881:   if (m > 0 && i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4882:   MatCreate(comm,mat);
4883:   MatSetSizes(*mat,m,n,m,n);
4884:   /* MatSetBlockSizes(*mat,,); */
4885:   MatSetType(*mat,MATSEQAIJ);
4886:   MatSeqAIJSetPreallocation_SeqAIJ(*mat,MAT_SKIP_ALLOCATION,NULL);
4887:   aij  = (Mat_SeqAIJ*)(*mat)->data;
4888:   PetscMalloc1(m,&aij->imax);
4889:   PetscMalloc1(m,&aij->ilen);

4891:   aij->i            = i;
4892:   aij->j            = j;
4893:   aij->a            = a;
4894:   aij->singlemalloc = PETSC_FALSE;
4895:   aij->nonew        = -1;             /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
4896:   aij->free_a       = PETSC_FALSE;
4897:   aij->free_ij      = PETSC_FALSE;

4899:   for (ii=0; ii<m; ii++) {
4900:     aij->ilen[ii] = aij->imax[ii] = i[ii+1] - i[ii];
4901:     if (PetscDefined(USE_DEBUG)) {
4902:       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]);
4903:       for (jj=i[ii]+1; jj<i[ii+1]; jj++) {
4904:         if (j[jj] < j[jj-1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column entry number %D (actual column %D) in row %D is not sorted",jj-i[ii],j[jj],ii);
4905:         if (j[jj] == j[jj-1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column entry number %D (actual column %D) in row %D is identical to previous entry",jj-i[ii],j[jj],ii);
4906:       }
4907:     }
4908:   }
4909:   if (PetscDefined(USE_DEBUG)) {
4910:     for (ii=0; ii<aij->i[m]; ii++) {
4911:       if (j[ii] < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column index at location = %D index = %D",ii,j[ii]);
4912:       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]);
4913:     }
4914:   }

4916:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
4917:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
4918:   return(0);
4919: }
4920: /*@C
4921:      MatCreateSeqAIJFromTriple - Creates an sequential AIJ matrix using matrix elements (in COO format)
4922:               provided by the user.

4924:       Collective

4926:    Input Parameters:
4927: +   comm - must be an MPI communicator of size 1
4928: .   m   - number of rows
4929: .   n   - number of columns
4930: .   i   - row indices
4931: .   j   - column indices
4932: .   a   - matrix values
4933: .   nz  - number of nonzeros
4934: -   idx - 0 or 1 based

4936:    Output Parameter:
4937: .   mat - the matrix

4939:    Level: intermediate

4941:    Notes:
4942:        The i and j indices are 0 based

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

4948:         1 0 0
4949:         2 0 3
4950:         4 5 6

4952:         i =  {0,1,1,2,2,2}
4953:         j =  {0,0,2,0,1,2}
4954:         v =  {1,2,3,4,5,6}


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

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


4967:   PetscCalloc1(m,&nnz);
4968:   for (ii = 0; ii < nz; ii++) {
4969:     nnz[i[ii] - !!idx] += 1;
4970:   }
4971:   MatCreate(comm,mat);
4972:   MatSetSizes(*mat,m,n,m,n);
4973:   MatSetType(*mat,MATSEQAIJ);
4974:   MatSeqAIJSetPreallocation_SeqAIJ(*mat,0,nnz);
4975:   for (ii = 0; ii < nz; ii++) {
4976:     if (idx) {
4977:       row = i[ii] - 1;
4978:       col = j[ii] - 1;
4979:     } else {
4980:       row = i[ii];
4981:       col = j[ii];
4982:     }
4983:     MatSetValues(*mat,one,&row,one,&col,&a[ii],ADD_VALUES);
4984:   }
4985:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
4986:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
4987:   PetscFree(nnz);
4988:   return(0);
4989: }

4991: PetscErrorCode MatSeqAIJInvalidateDiagonal(Mat A)
4992: {
4993:   Mat_SeqAIJ     *a=(Mat_SeqAIJ*)A->data;

4997:   a->idiagvalid  = PETSC_FALSE;
4998:   a->ibdiagvalid = PETSC_FALSE;

5000:   MatSeqAIJInvalidateDiagonal_Inode(A);
5001:   return(0);
5002: }

5004: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
5005: {
5007:   PetscMPIInt    size;

5010:   MPI_Comm_size(comm,&size);
5011:   if (size == 1) {
5012:     if (scall == MAT_INITIAL_MATRIX) {
5013:       MatDuplicate(inmat,MAT_COPY_VALUES,outmat);
5014:     } else {
5015:       MatCopy(inmat,*outmat,SAME_NONZERO_PATTERN);
5016:     }
5017:   } else {
5018:     MatCreateMPIMatConcatenateSeqMat_MPIAIJ(comm,inmat,n,scall,outmat);
5019:   }
5020:   return(0);
5021: }

5023: /*
5024:  Permute A into C's *local* index space using rowemb,colemb.
5025:  The embedding are supposed to be injections and the above implies that the range of rowemb is a subset
5026:  of [0,m), colemb is in [0,n).
5027:  If pattern == DIFFERENT_NONZERO_PATTERN, C is preallocated according to A.
5028:  */
5029: PetscErrorCode MatSetSeqMat_SeqAIJ(Mat C,IS rowemb,IS colemb,MatStructure pattern,Mat B)
5030: {
5031:   /* If making this function public, change the error returned in this function away from _PLIB. */
5033:   Mat_SeqAIJ     *Baij;
5034:   PetscBool      seqaij;
5035:   PetscInt       m,n,*nz,i,j,count;
5036:   PetscScalar    v;
5037:   const PetscInt *rowindices,*colindices;

5040:   if (!B) return(0);
5041:   /* Check to make sure the target matrix (and embeddings) are compatible with C and each other. */
5042:   PetscObjectBaseTypeCompare((PetscObject)B,MATSEQAIJ,&seqaij);
5043:   if (!seqaij) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is of wrong type");
5044:   if (rowemb) {
5045:     ISGetLocalSize(rowemb,&m);
5046:     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);
5047:   } else {
5048:     if (C->rmap->n != B->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is row-incompatible with the target matrix");
5049:   }
5050:   if (colemb) {
5051:     ISGetLocalSize(colemb,&n);
5052:     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);
5053:   } else {
5054:     if (C->cmap->n != B->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Input matrix is col-incompatible with the target matrix");
5055:   }

5057:   Baij = (Mat_SeqAIJ*)(B->data);
5058:   if (pattern == DIFFERENT_NONZERO_PATTERN) {
5059:     PetscMalloc1(B->rmap->n,&nz);
5060:     for (i=0; i<B->rmap->n; i++) {
5061:       nz[i] = Baij->i[i+1] - Baij->i[i];
5062:     }
5063:     MatSeqAIJSetPreallocation(C,0,nz);
5064:     PetscFree(nz);
5065:   }
5066:   if (pattern == SUBSET_NONZERO_PATTERN) {
5067:     MatZeroEntries(C);
5068:   }
5069:   count = 0;
5070:   rowindices = NULL;
5071:   colindices = NULL;
5072:   if (rowemb) {
5073:     ISGetIndices(rowemb,&rowindices);
5074:   }
5075:   if (colemb) {
5076:     ISGetIndices(colemb,&colindices);
5077:   }
5078:   for (i=0; i<B->rmap->n; i++) {
5079:     PetscInt row;
5080:     row = i;
5081:     if (rowindices) row = rowindices[i];
5082:     for (j=Baij->i[i]; j<Baij->i[i+1]; j++) {
5083:       PetscInt col;
5084:       col  = Baij->j[count];
5085:       if (colindices) col = colindices[col];
5086:       v    = Baij->a[count];
5087:       MatSetValues(C,1,&row,1,&col,&v,INSERT_VALUES);
5088:       ++count;
5089:     }
5090:   }
5091:   /* FIXME: set C's nonzerostate correctly. */
5092:   /* Assembly for C is necessary. */
5093:   C->preallocated = PETSC_TRUE;
5094:   C->assembled     = PETSC_TRUE;
5095:   C->was_assembled = PETSC_FALSE;
5096:   return(0);
5097: }

5099: PetscFunctionList MatSeqAIJList = NULL;

5101: /*@C
5102:    MatSeqAIJSetType - Converts a MATSEQAIJ matrix to a subtype

5104:    Collective on Mat

5106:    Input Parameters:
5107: +  mat      - the matrix object
5108: -  matype   - matrix type

5110:    Options Database Key:
5111: .  -mat_seqai_type  <method> - for example seqaijcrl


5114:   Level: intermediate

5116: .seealso: PCSetType(), VecSetType(), MatCreate(), MatType, Mat
5117: @*/
5118: PetscErrorCode  MatSeqAIJSetType(Mat mat, MatType matype)
5119: {
5120:   PetscErrorCode ierr,(*r)(Mat,MatType,MatReuse,Mat*);
5121:   PetscBool      sametype;

5125:   PetscObjectTypeCompare((PetscObject)mat,matype,&sametype);
5126:   if (sametype) return(0);

5128:    PetscFunctionListFind(MatSeqAIJList,matype,&r);
5129:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unknown Mat type given: %s",matype);
5130:   (*r)(mat,matype,MAT_INPLACE_MATRIX,&mat);
5131:   return(0);
5132: }


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

5138:    Not Collective

5140:    Input Parameters:
5141: +  name - name of a new user-defined matrix type, for example MATSEQAIJCRL
5142: -  function - routine to convert to subtype

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


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

5151:    Level: advanced

5153: .seealso: MatSeqAIJRegisterAll()


5156:   Level: advanced
5157: @*/
5158: PetscErrorCode  MatSeqAIJRegister(const char sname[],PetscErrorCode (*function)(Mat,MatType,MatReuse,Mat *))
5159: {

5163:   MatInitializePackage();
5164:   PetscFunctionListAdd(&MatSeqAIJList,sname,function);
5165:   return(0);
5166: }

5168: PetscBool MatSeqAIJRegisterAllCalled = PETSC_FALSE;

5170: /*@C
5171:   MatSeqAIJRegisterAll - Registers all of the matrix subtypes of SeqAIJ

5173:   Not Collective

5175:   Level: advanced

5177:   Developers Note: CUSPARSE does not yet support the MatConvert_SeqAIJ..() paradigm and thus cannot be registered here

5179: .seealso:  MatRegisterAll(), MatSeqAIJRegister()
5180: @*/
5181: PetscErrorCode  MatSeqAIJRegisterAll(void)
5182: {

5186:   if (MatSeqAIJRegisterAllCalled) return(0);
5187:   MatSeqAIJRegisterAllCalled = PETSC_TRUE;

5189:   MatSeqAIJRegister(MATSEQAIJCRL,      MatConvert_SeqAIJ_SeqAIJCRL);
5190:   MatSeqAIJRegister(MATSEQAIJPERM,     MatConvert_SeqAIJ_SeqAIJPERM);
5191:   MatSeqAIJRegister(MATSEQAIJSELL,     MatConvert_SeqAIJ_SeqAIJSELL);
5192: #if defined(PETSC_HAVE_MKL_SPARSE)
5193:   MatSeqAIJRegister(MATSEQAIJMKL,      MatConvert_SeqAIJ_SeqAIJMKL);
5194: #endif
5195: #if defined(PETSC_HAVE_VIENNACL) && defined(PETSC_HAVE_VIENNACL_NO_CUDA)
5196:   MatSeqAIJRegister(MATMPIAIJVIENNACL, MatConvert_SeqAIJ_SeqAIJViennaCL);
5197: #endif
5198:   return(0);
5199: }

5201: /*
5202:     Special version for direct calls from Fortran
5203: */
5204: #include <petsc/private/fortranimpl.h>
5205: #if defined(PETSC_HAVE_FORTRAN_CAPS)
5206: #define matsetvaluesseqaij_ MATSETVALUESSEQAIJ
5207: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
5208: #define matsetvaluesseqaij_ matsetvaluesseqaij
5209: #endif

5211: /* Change these macros so can be used in void function */
5212: #undef CHKERRQ
5213: #define CHKERRQ(ierr) CHKERRABORT(PetscObjectComm((PetscObject)A),ierr)
5214: #undef SETERRQ2
5215: #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
5216: #undef SETERRQ3
5217: #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)

5219: PETSC_EXTERN void matsetvaluesseqaij_(Mat *AA,PetscInt *mm,const PetscInt im[],PetscInt *nn,const PetscInt in[],const PetscScalar v[],InsertMode *isis, PetscErrorCode *_ierr)
5220: {
5221:   Mat            A  = *AA;
5222:   PetscInt       m  = *mm, n = *nn;
5223:   InsertMode     is = *isis;
5224:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data;
5225:   PetscInt       *rp,k,low,high,t,ii,row,nrow,i,col,l,rmax,N;
5226:   PetscInt       *imax,*ai,*ailen;
5228:   PetscInt       *aj,nonew = a->nonew,lastcol = -1;
5229:   MatScalar      *ap,value,*aa;
5230:   PetscBool      ignorezeroentries = a->ignorezeroentries;
5231:   PetscBool      roworiented       = a->roworiented;

5234:   MatCheckPreallocated(A,1);
5235:   imax  = a->imax;
5236:   ai    = a->i;
5237:   ailen = a->ilen;
5238:   aj    = a->j;
5239:   aa    = a->a;

5241:   for (k=0; k<m; k++) { /* loop over added rows */
5242:     row = im[k];
5243:     if (row < 0) continue;
5244:     if (PetscUnlikelyDebug(row >= A->rmap->n)) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Row too large");
5245:     rp   = aj + ai[row]; ap = aa + ai[row];
5246:     rmax = imax[row]; nrow = ailen[row];
5247:     low  = 0;
5248:     high = nrow;
5249:     for (l=0; l<n; l++) { /* loop over added columns */
5250:       if (in[l] < 0) continue;
5251:       if (PetscUnlikelyDebug(in[l] >= A->cmap->n)) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Column too large");
5252:       col = in[l];
5253:       if (roworiented) value = v[l + k*n];
5254:       else value = v[k + l*m];

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

5258:       if (col <= lastcol) low = 0;
5259:       else high = nrow;
5260:       lastcol = col;
5261:       while (high-low > 5) {
5262:         t = (low+high)/2;
5263:         if (rp[t] > col) high = t;
5264:         else             low  = t;
5265:       }
5266:       for (i=low; i<high; i++) {
5267:         if (rp[i] > col) break;
5268:         if (rp[i] == col) {
5269:           if (is == ADD_VALUES) ap[i] += value;
5270:           else                  ap[i] = value;
5271:           goto noinsert;
5272:         }
5273:       }
5274:       if (value == 0.0 && ignorezeroentries) goto noinsert;
5275:       if (nonew == 1) goto noinsert;
5276:       if (nonew == -1) SETERRABORT(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero in the matrix");
5277:       MatSeqXAIJReallocateAIJ(A,A->rmap->n,1,nrow,row,col,rmax,aa,ai,aj,rp,ap,imax,nonew,MatScalar);
5278:       N = nrow++ - 1; a->nz++; high++;
5279:       /* shift up all the later entries in this row */
5280:       for (ii=N; ii>=i; ii--) {
5281:         rp[ii+1] = rp[ii];
5282:         ap[ii+1] = ap[ii];
5283:       }
5284:       rp[i] = col;
5285:       ap[i] = value;
5286:       A->nonzerostate++;
5287: noinsert:;
5288:       low = i + 1;
5289:     }
5290:     ailen[row] = nrow;
5291:   }
5292:   PetscFunctionReturnVoid();
5293: }