Actual source code: aij.c

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

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

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

 16:   PetscObjectOptionsBegin((PetscObject)A);
 17:   PetscOptionsFList("-mat_seqaij_type", "Matrix SeqAIJ type", "MatSeqAIJSetType", MatSeqAIJList, "seqaij", type, 256, &flg);
 18:   if (flg) MatSeqAIJSetType(A, type);
 19:   PetscOptionsEnd();
 20:   return 0;
 21: }

 23: PetscErrorCode MatGetColumnReductions_SeqAIJ(Mat A, PetscInt type, PetscReal *reductions)
 24: {
 25:   PetscInt    i, m, n;
 26:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

 28:   MatGetSize(A, &m, &n);
 29:   PetscArrayzero(reductions, n);
 30:   if (type == NORM_2) {
 31:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscAbsScalar(aij->a[i] * aij->a[i]);
 32:   } else if (type == NORM_1) {
 33:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscAbsScalar(aij->a[i]);
 34:   } else if (type == NORM_INFINITY) {
 35:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] = PetscMax(PetscAbsScalar(aij->a[i]), reductions[aij->j[i]]);
 36:   } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
 37:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscRealPart(aij->a[i]);
 38:   } else if (type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART) {
 39:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscImaginaryPart(aij->a[i]);
 40:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unknown reduction type");

 42:   if (type == NORM_2) {
 43:     for (i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
 44:   } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
 45:     for (i = 0; i < n; i++) reductions[i] /= m;
 46:   }
 47:   return 0;
 48: }

 50: PetscErrorCode MatFindOffBlockDiagonalEntries_SeqAIJ(Mat A, IS *is)
 51: {
 52:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
 53:   PetscInt        i, m = A->rmap->n, cnt = 0, bs = A->rmap->bs;
 54:   const PetscInt *jj = a->j, *ii = a->i;
 55:   PetscInt       *rows;

 57:   for (i = 0; i < m; i++) {
 58:     if ((ii[i] != ii[i + 1]) && ((jj[ii[i]] < bs * (i / bs)) || (jj[ii[i + 1] - 1] > bs * ((i + bs) / bs) - 1))) cnt++;
 59:   }
 60:   PetscMalloc1(cnt, &rows);
 61:   cnt = 0;
 62:   for (i = 0; i < m; i++) {
 63:     if ((ii[i] != ii[i + 1]) && ((jj[ii[i]] < bs * (i / bs)) || (jj[ii[i + 1] - 1] > bs * ((i + bs) / bs) - 1))) {
 64:       rows[cnt] = i;
 65:       cnt++;
 66:     }
 67:   }
 68:   ISCreateGeneral(PETSC_COMM_SELF, cnt, rows, PETSC_OWN_POINTER, is);
 69:   return 0;
 70: }

 72: PetscErrorCode MatFindZeroDiagonals_SeqAIJ_Private(Mat A, PetscInt *nrows, PetscInt **zrows)
 73: {
 74:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
 75:   const MatScalar *aa;
 76:   PetscInt         i, m = A->rmap->n, cnt = 0;
 77:   const PetscInt  *ii = a->i, *jj = a->j, *diag;
 78:   PetscInt        *rows;

 80:   MatSeqAIJGetArrayRead(A, &aa);
 81:   MatMarkDiagonal_SeqAIJ(A);
 82:   diag = a->diag;
 83:   for (i = 0; i < m; i++) {
 84:     if ((diag[i] >= ii[i + 1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) cnt++;
 85:   }
 86:   PetscMalloc1(cnt, &rows);
 87:   cnt = 0;
 88:   for (i = 0; i < m; i++) {
 89:     if ((diag[i] >= ii[i + 1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) rows[cnt++] = i;
 90:   }
 91:   *nrows = cnt;
 92:   *zrows = rows;
 93:   MatSeqAIJRestoreArrayRead(A, &aa);
 94:   return 0;
 95: }

 97: PetscErrorCode MatFindZeroDiagonals_SeqAIJ(Mat A, IS *zrows)
 98: {
 99:   PetscInt nrows, *rows;

101:   *zrows = NULL;
102:   MatFindZeroDiagonals_SeqAIJ_Private(A, &nrows, &rows);
103:   ISCreateGeneral(PetscObjectComm((PetscObject)A), nrows, rows, PETSC_OWN_POINTER, zrows);
104:   return 0;
105: }

107: PetscErrorCode MatFindNonzeroRows_SeqAIJ(Mat A, IS *keptrows)
108: {
109:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
110:   const MatScalar *aa;
111:   PetscInt         m = A->rmap->n, cnt = 0;
112:   const PetscInt  *ii;
113:   PetscInt         n, i, j, *rows;

115:   MatSeqAIJGetArrayRead(A, &aa);
116:   *keptrows = NULL;
117:   ii        = a->i;
118:   for (i = 0; i < m; i++) {
119:     n = ii[i + 1] - ii[i];
120:     if (!n) {
121:       cnt++;
122:       goto ok1;
123:     }
124:     for (j = ii[i]; j < ii[i + 1]; j++) {
125:       if (aa[j] != 0.0) goto ok1;
126:     }
127:     cnt++;
128:   ok1:;
129:   }
130:   if (!cnt) {
131:     MatSeqAIJRestoreArrayRead(A, &aa);
132:     return 0;
133:   }
134:   PetscMalloc1(A->rmap->n - cnt, &rows);
135:   cnt = 0;
136:   for (i = 0; i < m; i++) {
137:     n = ii[i + 1] - ii[i];
138:     if (!n) continue;
139:     for (j = ii[i]; j < ii[i + 1]; j++) {
140:       if (aa[j] != 0.0) {
141:         rows[cnt++] = i;
142:         break;
143:       }
144:     }
145:   }
146:   MatSeqAIJRestoreArrayRead(A, &aa);
147:   ISCreateGeneral(PETSC_COMM_SELF, cnt, rows, PETSC_OWN_POINTER, keptrows);
148:   return 0;
149: }

151: PetscErrorCode MatDiagonalSet_SeqAIJ(Mat Y, Vec D, InsertMode is)
152: {
153:   Mat_SeqAIJ        *aij = (Mat_SeqAIJ *)Y->data;
154:   PetscInt           i, m = Y->rmap->n;
155:   const PetscInt    *diag;
156:   MatScalar         *aa;
157:   const PetscScalar *v;
158:   PetscBool          missing;

160:   if (Y->assembled) {
161:     MatMissingDiagonal_SeqAIJ(Y, &missing, NULL);
162:     if (!missing) {
163:       diag = aij->diag;
164:       VecGetArrayRead(D, &v);
165:       MatSeqAIJGetArray(Y, &aa);
166:       if (is == INSERT_VALUES) {
167:         for (i = 0; i < m; i++) aa[diag[i]] = v[i];
168:       } else {
169:         for (i = 0; i < m; i++) aa[diag[i]] += v[i];
170:       }
171:       MatSeqAIJRestoreArray(Y, &aa);
172:       VecRestoreArrayRead(D, &v);
173:       return 0;
174:     }
175:     MatSeqAIJInvalidateDiagonal(Y);
176:   }
177:   MatDiagonalSet_Default(Y, D, is);
178:   return 0;
179: }

181: PetscErrorCode MatGetRowIJ_SeqAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
182: {
183:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
184:   PetscInt    i, ishift;

186:   if (m) *m = A->rmap->n;
187:   if (!ia) return 0;
188:   ishift = 0;
189:   if (symmetric && A->structurally_symmetric != PETSC_BOOL3_TRUE) {
190:     MatToSymmetricIJ_SeqAIJ(A->rmap->n, a->i, a->j, PETSC_TRUE, ishift, oshift, (PetscInt **)ia, (PetscInt **)ja);
191:   } else if (oshift == 1) {
192:     PetscInt *tia;
193:     PetscInt  nz = a->i[A->rmap->n];
194:     /* malloc space and  add 1 to i and j indices */
195:     PetscMalloc1(A->rmap->n + 1, &tia);
196:     for (i = 0; i < A->rmap->n + 1; i++) tia[i] = a->i[i] + 1;
197:     *ia = tia;
198:     if (ja) {
199:       PetscInt *tja;
200:       PetscMalloc1(nz + 1, &tja);
201:       for (i = 0; i < nz; i++) tja[i] = a->j[i] + 1;
202:       *ja = tja;
203:     }
204:   } else {
205:     *ia = a->i;
206:     if (ja) *ja = a->j;
207:   }
208:   return 0;
209: }

211: PetscErrorCode MatRestoreRowIJ_SeqAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
212: {
213:   if (!ia) return 0;
214:   if ((symmetric && A->structurally_symmetric != PETSC_BOOL3_TRUE) || oshift == 1) {
215:     PetscFree(*ia);
216:     if (ja) PetscFree(*ja);
217:   }
218:   return 0;
219: }

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

227:   *nn = n;
228:   if (!ia) return 0;
229:   if (symmetric) {
230:     MatToSymmetricIJ_SeqAIJ(A->rmap->n, a->i, a->j, PETSC_TRUE, 0, oshift, (PetscInt **)ia, (PetscInt **)ja);
231:   } else {
232:     PetscCalloc1(n, &collengths);
233:     PetscMalloc1(n + 1, &cia);
234:     PetscMalloc1(nz, &cja);
235:     jj = a->j;
236:     for (i = 0; i < nz; i++) collengths[jj[i]]++;
237:     cia[0] = oshift;
238:     for (i = 0; i < n; i++) cia[i + 1] = cia[i] + collengths[i];
239:     PetscArrayzero(collengths, n);
240:     jj = a->j;
241:     for (row = 0; row < m; row++) {
242:       mr = a->i[row + 1] - a->i[row];
243:       for (i = 0; i < mr; i++) {
244:         col = *jj++;

246:         cja[cia[col] + collengths[col]++ - oshift] = row + oshift;
247:       }
248:     }
249:     PetscFree(collengths);
250:     *ia = cia;
251:     *ja = cja;
252:   }
253:   return 0;
254: }

256: PetscErrorCode MatRestoreColumnIJ_SeqAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
257: {
258:   if (!ia) return 0;

260:   PetscFree(*ia);
261:   PetscFree(*ja);
262:   return 0;
263: }

265: /*
266:  MatGetColumnIJ_SeqAIJ_Color() and MatRestoreColumnIJ_SeqAIJ_Color() are customized from
267:  MatGetColumnIJ_SeqAIJ() and MatRestoreColumnIJ_SeqAIJ() by adding an output
268:  spidx[], index of a->a, to be used in MatTransposeColoringCreate_SeqAIJ() and MatFDColoringCreate_SeqXAIJ()
269: */
270: PetscErrorCode MatGetColumnIJ_SeqAIJ_Color(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *nn, const PetscInt *ia[], const PetscInt *ja[], PetscInt *spidx[], PetscBool *done)
271: {
272:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
273:   PetscInt        i, *collengths, *cia, *cja, n = A->cmap->n, m = A->rmap->n;
274:   PetscInt        nz = a->i[m], row, mr, col, tmp;
275:   PetscInt       *cspidx;
276:   const PetscInt *jj;

278:   *nn = n;
279:   if (!ia) return 0;

281:   PetscCalloc1(n, &collengths);
282:   PetscMalloc1(n + 1, &cia);
283:   PetscMalloc1(nz, &cja);
284:   PetscMalloc1(nz, &cspidx);
285:   jj = a->j;
286:   for (i = 0; i < nz; i++) collengths[jj[i]]++;
287:   cia[0] = oshift;
288:   for (i = 0; i < n; i++) cia[i + 1] = cia[i] + collengths[i];
289:   PetscArrayzero(collengths, n);
290:   jj = a->j;
291:   for (row = 0; row < m; row++) {
292:     mr = a->i[row + 1] - a->i[row];
293:     for (i = 0; i < mr; i++) {
294:       col         = *jj++;
295:       tmp         = cia[col] + collengths[col]++ - oshift;
296:       cspidx[tmp] = a->i[row] + i; /* index of a->j */
297:       cja[tmp]    = row + oshift;
298:     }
299:   }
300:   PetscFree(collengths);
301:   *ia    = cia;
302:   *ja    = cja;
303:   *spidx = cspidx;
304:   return 0;
305: }

307: PetscErrorCode MatRestoreColumnIJ_SeqAIJ_Color(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscInt *spidx[], PetscBool *done)
308: {
309:   MatRestoreColumnIJ_SeqAIJ(A, oshift, symmetric, inodecompressed, n, ia, ja, done);
310:   PetscFree(*spidx);
311:   return 0;
312: }

314: PetscErrorCode MatSetValuesRow_SeqAIJ(Mat A, PetscInt row, const PetscScalar v[])
315: {
316:   Mat_SeqAIJ  *a  = (Mat_SeqAIJ *)A->data;
317:   PetscInt    *ai = a->i;
318:   PetscScalar *aa;

320:   MatSeqAIJGetArray(A, &aa);
321:   PetscArraycpy(aa + ai[row], v, ai[row + 1] - ai[row]);
322:   MatSeqAIJRestoreArray(A, &aa);
323:   return 0;
324: }

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

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

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

336: */

338: #include <petsc/private/isimpl.h>
339: PetscErrorCode MatSeqAIJSetValuesLocalFast(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
340: {
341:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
342:   PetscInt        low, high, t, row, nrow, i, col, l;
343:   const PetscInt *rp, *ai = a->i, *ailen = a->ilen, *aj = a->j;
344:   PetscInt        lastcol = -1;
345:   MatScalar      *ap, value, *aa;
346:   const PetscInt *ridx = A->rmap->mapping->indices, *cidx = A->cmap->mapping->indices;

348:   MatSeqAIJGetArray(A, &aa);
349:   row  = ridx[im[0]];
350:   rp   = aj + ai[row];
351:   ap   = aa + ai[row];
352:   nrow = ailen[row];
353:   low  = 0;
354:   high = nrow;
355:   for (l = 0; l < n; l++) { /* loop over added columns */
356:     col   = cidx[in[l]];
357:     value = v[l];

359:     if (col <= lastcol) low = 0;
360:     else high = nrow;
361:     lastcol = col;
362:     while (high - low > 5) {
363:       t = (low + high) / 2;
364:       if (rp[t] > col) high = t;
365:       else low = t;
366:     }
367:     for (i = low; i < high; i++) {
368:       if (rp[i] == col) {
369:         ap[i] += value;
370:         low = i + 1;
371:         break;
372:       }
373:     }
374:   }
375:   MatSeqAIJRestoreArray(A, &aa);
376:   return 0;
377: }

379: PetscErrorCode MatSetValues_SeqAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
380: {
381:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
382:   PetscInt   *rp, k, low, high, t, ii, row, nrow, i, col, l, rmax, N;
383:   PetscInt   *imax = a->imax, *ai = a->i, *ailen = a->ilen;
384:   PetscInt   *aj = a->j, nonew = a->nonew, lastcol = -1;
385:   MatScalar  *ap = NULL, value = 0.0, *aa;
386:   PetscBool   ignorezeroentries = a->ignorezeroentries;
387:   PetscBool   roworiented       = a->roworiented;

389:   MatSeqAIJGetArray(A, &aa);
390:   for (k = 0; k < m; k++) { /* loop over added rows */
391:     row = im[k];
392:     if (row < 0) continue;
394:     rp = aj + ai[row];
395:     if (!A->structure_only) ap = aa + ai[row];
396:     rmax = imax[row];
397:     nrow = ailen[row];
398:     low  = 0;
399:     high = nrow;
400:     for (l = 0; l < n; l++) { /* loop over added columns */
401:       if (in[l] < 0) continue;
403:       col = in[l];
404:       if (v && !A->structure_only) value = roworiented ? v[l + k * n] : v[k + l * m];
405:       if (!A->structure_only && value == 0.0 && ignorezeroentries && is == ADD_VALUES && row != col) continue;

407:       if (col <= lastcol) low = 0;
408:       else high = nrow;
409:       lastcol = col;
410:       while (high - low > 5) {
411:         t = (low + high) / 2;
412:         if (rp[t] > col) high = t;
413:         else low = t;
414:       }
415:       for (i = low; i < high; i++) {
416:         if (rp[i] > col) break;
417:         if (rp[i] == col) {
418:           if (!A->structure_only) {
419:             if (is == ADD_VALUES) {
420:               ap[i] += value;
421:               (void)PetscLogFlops(1.0);
422:             } else ap[i] = value;
423:           }
424:           low = i + 1;
425:           goto noinsert;
426:         }
427:       }
428:       if (value == 0.0 && ignorezeroentries && row != col) goto noinsert;
429:       if (nonew == 1) goto noinsert;
431:       if (A->structure_only) {
432:         MatSeqXAIJReallocateAIJ_structure_only(A, A->rmap->n, 1, nrow, row, col, rmax, ai, aj, rp, imax, nonew, MatScalar);
433:       } else {
434:         MatSeqXAIJReallocateAIJ(A, A->rmap->n, 1, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
435:       }
436:       N = nrow++ - 1;
437:       a->nz++;
438:       high++;
439:       /* shift up all the later entries in this row */
440:       PetscArraymove(rp + i + 1, rp + i, N - i + 1);
441:       rp[i] = col;
442:       if (!A->structure_only) {
443:         PetscArraymove(ap + i + 1, ap + i, N - i + 1);
444:         ap[i] = value;
445:       }
446:       low = i + 1;
447:       A->nonzerostate++;
448:     noinsert:;
449:     }
450:     ailen[row] = nrow;
451:   }
452:   MatSeqAIJRestoreArray(A, &aa);
453:   return 0;
454: }

456: PetscErrorCode MatSetValues_SeqAIJ_SortedFullNoPreallocation(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
457: {
458:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
459:   PetscInt   *rp, k, row;
460:   PetscInt   *ai = a->i;
461:   PetscInt   *aj = a->j;
462:   MatScalar  *aa, *ap;


467:   MatSeqAIJGetArray(A, &aa);
468:   for (k = 0; k < m; k++) { /* loop over added rows */
469:     row = im[k];
470:     rp  = aj + ai[row];
471:     ap  = aa + ai[row];

473:     PetscMemcpy(rp, in, n * sizeof(PetscInt));
474:     if (!A->structure_only) {
475:       if (v) {
476:         PetscMemcpy(ap, v, n * sizeof(PetscScalar));
477:         v += n;
478:       } else {
479:         PetscMemzero(ap, n * sizeof(PetscScalar));
480:       }
481:     }
482:     a->ilen[row]  = n;
483:     a->imax[row]  = n;
484:     a->i[row + 1] = a->i[row] + n;
485:     a->nz += n;
486:   }
487:   MatSeqAIJRestoreArray(A, &aa);
488:   return 0;
489: }

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

494:   Input Parameters:
495: +  A - the `MATSEQAIJ` matrix
496: -  nztotal - bound on the number of nonzeros

498:   Level: advanced

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

505: .seealso: `MatSetOption()`, `MAT_SORTED_FULL`, `MatSetValues()`, `MatSeqAIJSetPreallocation()`
506: @*/

508: PetscErrorCode MatSeqAIJSetTotalPreallocation(Mat A, PetscInt nztotal)
509: {
510:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

512:   PetscLayoutSetUp(A->rmap);
513:   PetscLayoutSetUp(A->cmap);
514:   a->maxnz = nztotal;
515:   if (!a->imax) { PetscMalloc1(A->rmap->n, &a->imax); }
516:   if (!a->ilen) {
517:     PetscMalloc1(A->rmap->n, &a->ilen);
518:   } else {
519:     PetscMemzero(a->ilen, A->rmap->n * sizeof(PetscInt));
520:   }

522:   /* allocate the matrix space */
523:   if (A->structure_only) {
524:     PetscMalloc1(nztotal, &a->j);
525:     PetscMalloc1(A->rmap->n + 1, &a->i);
526:   } else {
527:     PetscMalloc3(nztotal, &a->a, nztotal, &a->j, A->rmap->n + 1, &a->i);
528:   }
529:   a->i[0] = 0;
530:   if (A->structure_only) {
531:     a->singlemalloc = PETSC_FALSE;
532:     a->free_a       = PETSC_FALSE;
533:   } else {
534:     a->singlemalloc = PETSC_TRUE;
535:     a->free_a       = PETSC_TRUE;
536:   }
537:   a->free_ij        = PETSC_TRUE;
538:   A->ops->setvalues = MatSetValues_SeqAIJ_SortedFullNoPreallocation;
539:   A->preallocated   = PETSC_TRUE;
540:   return 0;
541: }

543: PetscErrorCode MatSetValues_SeqAIJ_SortedFull(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
544: {
545:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
546:   PetscInt   *rp, k, row;
547:   PetscInt   *ai = a->i, *ailen = a->ilen;
548:   PetscInt   *aj = a->j;
549:   MatScalar  *aa, *ap;

551:   MatSeqAIJGetArray(A, &aa);
552:   for (k = 0; k < m; k++) { /* loop over added rows */
553:     row = im[k];
555:     rp = aj + ai[row];
556:     ap = aa + ai[row];
557:     if (!A->was_assembled) PetscMemcpy(rp, in, n * sizeof(PetscInt));
558:     if (!A->structure_only) {
559:       if (v) {
560:         PetscMemcpy(ap, v, n * sizeof(PetscScalar));
561:         v += n;
562:       } else {
563:         PetscMemzero(ap, n * sizeof(PetscScalar));
564:       }
565:     }
566:     ailen[row] = n;
567:     a->nz += n;
568:   }
569:   MatSeqAIJRestoreArray(A, &aa);
570:   return 0;
571: }

573: PetscErrorCode MatGetValues_SeqAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], PetscScalar v[])
574: {
575:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
576:   PetscInt        *rp, k, low, high, t, row, nrow, i, col, l, *aj = a->j;
577:   PetscInt        *ai = a->i, *ailen = a->ilen;
578:   const MatScalar *ap, *aa;

580:   MatSeqAIJGetArrayRead(A, &aa);
581:   for (k = 0; k < m; k++) { /* loop over rows */
582:     row = im[k];
583:     if (row < 0) {
584:       v += n;
585:       continue;
586:     } /* negative row */
588:     rp   = aj + ai[row];
589:     ap   = aa + ai[row];
590:     nrow = ailen[row];
591:     for (l = 0; l < n; l++) { /* loop over columns */
592:       if (in[l] < 0) {
593:         v++;
594:         continue;
595:       } /* negative column */
597:       col  = in[l];
598:       high = nrow;
599:       low  = 0; /* assume unsorted */
600:       while (high - low > 5) {
601:         t = (low + high) / 2;
602:         if (rp[t] > col) high = t;
603:         else low = t;
604:       }
605:       for (i = low; i < high; i++) {
606:         if (rp[i] > col) break;
607:         if (rp[i] == col) {
608:           *v++ = ap[i];
609:           goto finished;
610:         }
611:       }
612:       *v++ = 0.0;
613:     finished:;
614:     }
615:   }
616:   MatSeqAIJRestoreArrayRead(A, &aa);
617:   return 0;
618: }

620: PetscErrorCode MatView_SeqAIJ_Binary(Mat mat, PetscViewer viewer)
621: {
622:   Mat_SeqAIJ        *A = (Mat_SeqAIJ *)mat->data;
623:   const PetscScalar *av;
624:   PetscInt           header[4], M, N, m, nz, i;
625:   PetscInt          *rowlens;

627:   PetscViewerSetUp(viewer);

629:   M  = mat->rmap->N;
630:   N  = mat->cmap->N;
631:   m  = mat->rmap->n;
632:   nz = A->nz;

634:   /* write matrix header */
635:   header[0] = MAT_FILE_CLASSID;
636:   header[1] = M;
637:   header[2] = N;
638:   header[3] = nz;
639:   PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT);

641:   /* fill in and store row lengths */
642:   PetscMalloc1(m, &rowlens);
643:   for (i = 0; i < m; i++) rowlens[i] = A->i[i + 1] - A->i[i];
644:   PetscViewerBinaryWrite(viewer, rowlens, m, PETSC_INT);
645:   PetscFree(rowlens);
646:   /* store column indices */
647:   PetscViewerBinaryWrite(viewer, A->j, nz, PETSC_INT);
648:   /* store nonzero values */
649:   MatSeqAIJGetArrayRead(mat, &av);
650:   PetscViewerBinaryWrite(viewer, av, nz, PETSC_SCALAR);
651:   MatSeqAIJRestoreArrayRead(mat, &av);

653:   /* write block size option to the viewer's .info file */
654:   MatView_Binary_BlockSizes(mat, viewer);
655:   return 0;
656: }

658: static PetscErrorCode MatView_SeqAIJ_ASCII_structonly(Mat A, PetscViewer viewer)
659: {
660:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
661:   PetscInt    i, k, m = A->rmap->N;

663:   PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
664:   for (i = 0; i < m; i++) {
665:     PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i);
666:     for (k = a->i[i]; k < a->i[i + 1]; k++) PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ") ", a->j[k]);
667:     PetscViewerASCIIPrintf(viewer, "\n");
668:   }
669:   PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
670:   return 0;
671: }

673: extern PetscErrorCode MatSeqAIJFactorInfo_Matlab(Mat, PetscViewer);

675: PetscErrorCode MatView_SeqAIJ_ASCII(Mat A, PetscViewer viewer)
676: {
677:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
678:   const PetscScalar *av;
679:   PetscInt           i, j, m = A->rmap->n;
680:   const char        *name;
681:   PetscViewerFormat  format;

683:   if (A->structure_only) {
684:     MatView_SeqAIJ_ASCII_structonly(A, viewer);
685:     return 0;
686:   }

688:   PetscViewerGetFormat(viewer, &format);
689:   if (format == PETSC_VIEWER_ASCII_FACTOR_INFO || format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) return 0;

691:   /* trigger copy to CPU if needed */
692:   MatSeqAIJGetArrayRead(A, &av);
693:   MatSeqAIJRestoreArrayRead(A, &av);
694:   if (format == PETSC_VIEWER_ASCII_MATLAB) {
695:     PetscInt nofinalvalue = 0;
696:     if (m && ((a->i[m] == a->i[m - 1]) || (a->j[a->nz - 1] != A->cmap->n - 1))) {
697:       /* Need a dummy value to ensure the dimension of the matrix. */
698:       nofinalvalue = 1;
699:     }
700:     PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
701:     PetscViewerASCIIPrintf(viewer, "%% Size = %" PetscInt_FMT " %" PetscInt_FMT " \n", m, A->cmap->n);
702:     PetscViewerASCIIPrintf(viewer, "%% Nonzeros = %" PetscInt_FMT " \n", a->nz);
703: #if defined(PETSC_USE_COMPLEX)
704:     PetscViewerASCIIPrintf(viewer, "zzz = zeros(%" PetscInt_FMT ",4);\n", a->nz + nofinalvalue);
705: #else
706:     PetscViewerASCIIPrintf(viewer, "zzz = zeros(%" PetscInt_FMT ",3);\n", a->nz + nofinalvalue);
707: #endif
708:     PetscViewerASCIIPrintf(viewer, "zzz = [\n");

710:     for (i = 0; i < m; i++) {
711:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
712: #if defined(PETSC_USE_COMPLEX)
713:         PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e %18.16e\n", i + 1, a->j[j] + 1, (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j]));
714: #else
715:         PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e\n", i + 1, a->j[j] + 1, (double)a->a[j]);
716: #endif
717:       }
718:     }
719:     if (nofinalvalue) {
720: #if defined(PETSC_USE_COMPLEX)
721:       PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e %18.16e\n", m, A->cmap->n, 0., 0.);
722: #else
723:       PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e\n", m, A->cmap->n, 0.0);
724: #endif
725:     }
726:     PetscObjectGetName((PetscObject)A, &name);
727:     PetscViewerASCIIPrintf(viewer, "];\n %s = spconvert(zzz);\n", name);
728:     PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
729:   } else if (format == PETSC_VIEWER_ASCII_COMMON) {
730:     PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
731:     for (i = 0; i < m; i++) {
732:       PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i);
733:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
734: #if defined(PETSC_USE_COMPLEX)
735:         if (PetscImaginaryPart(a->a[j]) > 0.0 && PetscRealPart(a->a[j]) != 0.0) {
736:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j]));
737:         } else if (PetscImaginaryPart(a->a[j]) < 0.0 && PetscRealPart(a->a[j]) != 0.0) {
738:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)-PetscImaginaryPart(a->a[j]));
739:         } else if (PetscRealPart(a->a[j]) != 0.0) {
740:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j]));
741:         }
742: #else
743:         if (a->a[j] != 0.0) PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]);
744: #endif
745:       }
746:       PetscViewerASCIIPrintf(viewer, "\n");
747:     }
748:     PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
749:   } else if (format == PETSC_VIEWER_ASCII_SYMMODU) {
750:     PetscInt nzd = 0, fshift = 1, *sptr;
751:     PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
752:     PetscMalloc1(m + 1, &sptr);
753:     for (i = 0; i < m; i++) {
754:       sptr[i] = nzd + 1;
755:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
756:         if (a->j[j] >= i) {
757: #if defined(PETSC_USE_COMPLEX)
758:           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) nzd++;
759: #else
760:           if (a->a[j] != 0.0) nzd++;
761: #endif
762:         }
763:       }
764:     }
765:     sptr[m] = nzd + 1;
766:     PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT "\n\n", m, nzd);
767:     for (i = 0; i < m + 1; i += 6) {
768:       if (i + 4 < m) {
769:         PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2], sptr[i + 3], sptr[i + 4], sptr[i + 5]);
770:       } else if (i + 3 < m) {
771:         PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2], sptr[i + 3], sptr[i + 4]);
772:       } else if (i + 2 < m) {
773:         PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2], sptr[i + 3]);
774:       } else if (i + 1 < m) {
775:         PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2]);
776:       } else if (i < m) {
777:         PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1]);
778:       } else {
779:         PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT "\n", sptr[i]);
780:       }
781:     }
782:     PetscViewerASCIIPrintf(viewer, "\n");
783:     PetscFree(sptr);
784:     for (i = 0; i < m; i++) {
785:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
786:         if (a->j[j] >= i) PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " ", a->j[j] + fshift);
787:       }
788:       PetscViewerASCIIPrintf(viewer, "\n");
789:     }
790:     PetscViewerASCIIPrintf(viewer, "\n");
791:     for (i = 0; i < m; i++) {
792:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
793:         if (a->j[j] >= i) {
794: #if defined(PETSC_USE_COMPLEX)
795:           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) PetscViewerASCIIPrintf(viewer, " %18.16e %18.16e ", (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j]));
796: #else
797:           if (a->a[j] != 0.0) PetscViewerASCIIPrintf(viewer, " %18.16e ", (double)a->a[j]);
798: #endif
799:         }
800:       }
801:       PetscViewerASCIIPrintf(viewer, "\n");
802:     }
803:     PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
804:   } else if (format == PETSC_VIEWER_ASCII_DENSE) {
805:     PetscInt    cnt = 0, jcnt;
806:     PetscScalar value;
807: #if defined(PETSC_USE_COMPLEX)
808:     PetscBool realonly = PETSC_TRUE;

810:     for (i = 0; i < a->i[m]; i++) {
811:       if (PetscImaginaryPart(a->a[i]) != 0.0) {
812:         realonly = PETSC_FALSE;
813:         break;
814:       }
815:     }
816: #endif

818:     PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
819:     for (i = 0; i < m; i++) {
820:       jcnt = 0;
821:       for (j = 0; j < A->cmap->n; j++) {
822:         if (jcnt < a->i[i + 1] - a->i[i] && j == a->j[cnt]) {
823:           value = a->a[cnt++];
824:           jcnt++;
825:         } else {
826:           value = 0.0;
827:         }
828: #if defined(PETSC_USE_COMPLEX)
829:         if (realonly) {
830:           PetscViewerASCIIPrintf(viewer, " %7.5e ", (double)PetscRealPart(value));
831:         } else {
832:           PetscViewerASCIIPrintf(viewer, " %7.5e+%7.5e i ", (double)PetscRealPart(value), (double)PetscImaginaryPart(value));
833:         }
834: #else
835:         PetscViewerASCIIPrintf(viewer, " %7.5e ", (double)value);
836: #endif
837:       }
838:       PetscViewerASCIIPrintf(viewer, "\n");
839:     }
840:     PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
841:   } else if (format == PETSC_VIEWER_ASCII_MATRIXMARKET) {
842:     PetscInt fshift = 1;
843:     PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
844: #if defined(PETSC_USE_COMPLEX)
845:     PetscViewerASCIIPrintf(viewer, "%%%%MatrixMarket matrix coordinate complex general\n");
846: #else
847:     PetscViewerASCIIPrintf(viewer, "%%%%MatrixMarket matrix coordinate real general\n");
848: #endif
849:     PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", m, A->cmap->n, a->nz);
850:     for (i = 0; i < m; i++) {
851:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
852: #if defined(PETSC_USE_COMPLEX)
853:         PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT " %g %g\n", i + fshift, a->j[j] + fshift, (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j]));
854: #else
855:         PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT " %g\n", i + fshift, a->j[j] + fshift, (double)a->a[j]);
856: #endif
857:       }
858:     }
859:     PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
860:   } else {
861:     PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
862:     if (A->factortype) {
863:       for (i = 0; i < m; i++) {
864:         PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i);
865:         /* L part */
866:         for (j = a->i[i]; j < a->i[i + 1]; j++) {
867: #if defined(PETSC_USE_COMPLEX)
868:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
869:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j]));
870:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
871:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)(-PetscImaginaryPart(a->a[j])));
872:           } else {
873:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j]));
874:           }
875: #else
876:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]);
877: #endif
878:         }
879:         /* diagonal */
880:         j = a->diag[i];
881: #if defined(PETSC_USE_COMPLEX)
882:         if (PetscImaginaryPart(a->a[j]) > 0.0) {
883:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(1.0 / a->a[j]), (double)PetscImaginaryPart(1.0 / a->a[j]));
884:         } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
885:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(1.0 / a->a[j]), (double)(-PetscImaginaryPart(1.0 / a->a[j])));
886:         } else {
887:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(1.0 / a->a[j]));
888:         }
889: #else
890:         PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)(1.0 / a->a[j]));
891: #endif

893:         /* U part */
894:         for (j = a->diag[i + 1] + 1; j < a->diag[i]; j++) {
895: #if defined(PETSC_USE_COMPLEX)
896:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
897:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j]));
898:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
899:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)(-PetscImaginaryPart(a->a[j])));
900:           } else {
901:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j]));
902:           }
903: #else
904:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]);
905: #endif
906:         }
907:         PetscViewerASCIIPrintf(viewer, "\n");
908:       }
909:     } else {
910:       for (i = 0; i < m; i++) {
911:         PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i);
912:         for (j = a->i[i]; j < a->i[i + 1]; j++) {
913: #if defined(PETSC_USE_COMPLEX)
914:           if (PetscImaginaryPart(a->a[j]) > 0.0) {
915:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j]));
916:           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
917:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)-PetscImaginaryPart(a->a[j]));
918:           } else {
919:             PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j]));
920:           }
921: #else
922:           PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]);
923: #endif
924:         }
925:         PetscViewerASCIIPrintf(viewer, "\n");
926:       }
927:     }
928:     PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
929:   }
930:   PetscViewerFlush(viewer);
931:   return 0;
932: }

934: #include <petscdraw.h>
935: PetscErrorCode MatView_SeqAIJ_Draw_Zoom(PetscDraw draw, void *Aa)
936: {
937:   Mat                A = (Mat)Aa;
938:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
939:   PetscInt           i, j, m = A->rmap->n;
940:   int                color;
941:   PetscReal          xl, yl, xr, yr, x_l, x_r, y_l, y_r;
942:   PetscViewer        viewer;
943:   PetscViewerFormat  format;
944:   const PetscScalar *aa;

946:   PetscObjectQuery((PetscObject)A, "Zoomviewer", (PetscObject *)&viewer);
947:   PetscViewerGetFormat(viewer, &format);
948:   PetscDrawGetCoordinates(draw, &xl, &yl, &xr, &yr);

950:   /* loop over matrix elements drawing boxes */
951:   MatSeqAIJGetArrayRead(A, &aa);
952:   if (format != PETSC_VIEWER_DRAW_CONTOUR) {
953:     PetscDrawCollectiveBegin(draw);
954:     /* Blue for negative, Cyan for zero and  Red for positive */
955:     color = PETSC_DRAW_BLUE;
956:     for (i = 0; i < m; i++) {
957:       y_l = m - i - 1.0;
958:       y_r = y_l + 1.0;
959:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
960:         x_l = a->j[j];
961:         x_r = x_l + 1.0;
962:         if (PetscRealPart(aa[j]) >= 0.) continue;
963:         PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color);
964:       }
965:     }
966:     color = PETSC_DRAW_CYAN;
967:     for (i = 0; i < m; i++) {
968:       y_l = m - i - 1.0;
969:       y_r = y_l + 1.0;
970:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
971:         x_l = a->j[j];
972:         x_r = x_l + 1.0;
973:         if (aa[j] != 0.) continue;
974:         PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color);
975:       }
976:     }
977:     color = PETSC_DRAW_RED;
978:     for (i = 0; i < m; i++) {
979:       y_l = m - i - 1.0;
980:       y_r = y_l + 1.0;
981:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
982:         x_l = a->j[j];
983:         x_r = x_l + 1.0;
984:         if (PetscRealPart(aa[j]) <= 0.) continue;
985:         PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color);
986:       }
987:     }
988:     PetscDrawCollectiveEnd(draw);
989:   } else {
990:     /* use contour shading to indicate magnitude of values */
991:     /* first determine max of all nonzero values */
992:     PetscReal minv = 0.0, maxv = 0.0;
993:     PetscInt  nz = a->nz, count = 0;
994:     PetscDraw popup;

996:     for (i = 0; i < nz; i++) {
997:       if (PetscAbsScalar(aa[i]) > maxv) maxv = PetscAbsScalar(aa[i]);
998:     }
999:     if (minv >= maxv) maxv = minv + PETSC_SMALL;
1000:     PetscDrawGetPopup(draw, &popup);
1001:     PetscDrawScalePopup(popup, minv, maxv);

1003:     PetscDrawCollectiveBegin(draw);
1004:     for (i = 0; i < m; i++) {
1005:       y_l = m - i - 1.0;
1006:       y_r = y_l + 1.0;
1007:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
1008:         x_l   = a->j[j];
1009:         x_r   = x_l + 1.0;
1010:         color = PetscDrawRealToColor(PetscAbsScalar(aa[count]), minv, maxv);
1011:         PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color);
1012:         count++;
1013:       }
1014:     }
1015:     PetscDrawCollectiveEnd(draw);
1016:   }
1017:   MatSeqAIJRestoreArrayRead(A, &aa);
1018:   return 0;
1019: }

1021: #include <petscdraw.h>
1022: PetscErrorCode MatView_SeqAIJ_Draw(Mat A, PetscViewer viewer)
1023: {
1024:   PetscDraw draw;
1025:   PetscReal xr, yr, xl, yl, h, w;
1026:   PetscBool isnull;

1028:   PetscViewerDrawGetDraw(viewer, 0, &draw);
1029:   PetscDrawIsNull(draw, &isnull);
1030:   if (isnull) return 0;

1032:   xr = A->cmap->n;
1033:   yr = A->rmap->n;
1034:   h  = yr / 10.0;
1035:   w  = xr / 10.0;
1036:   xr += w;
1037:   yr += h;
1038:   xl = -w;
1039:   yl = -h;
1040:   PetscDrawSetCoordinates(draw, xl, yl, xr, yr);
1041:   PetscObjectCompose((PetscObject)A, "Zoomviewer", (PetscObject)viewer);
1042:   PetscDrawZoom(draw, MatView_SeqAIJ_Draw_Zoom, A);
1043:   PetscObjectCompose((PetscObject)A, "Zoomviewer", NULL);
1044:   PetscDrawSave(draw);
1045:   return 0;
1046: }

1048: PetscErrorCode MatView_SeqAIJ(Mat A, PetscViewer viewer)
1049: {
1050:   PetscBool iascii, isbinary, isdraw;

1052:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii);
1053:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary);
1054:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw);
1055:   if (iascii) MatView_SeqAIJ_ASCII(A, viewer);
1056:   else if (isbinary) MatView_SeqAIJ_Binary(A, viewer);
1057:   else if (isdraw) MatView_SeqAIJ_Draw(A, viewer);
1058:   MatView_SeqAIJ_Inode(A, viewer);
1059:   return 0;
1060: }

1062: PetscErrorCode MatAssemblyEnd_SeqAIJ(Mat A, MatAssemblyType mode)
1063: {
1064:   Mat_SeqAIJ *a      = (Mat_SeqAIJ *)A->data;
1065:   PetscInt    fshift = 0, i, *ai = a->i, *aj = a->j, *imax = a->imax;
1066:   PetscInt    m = A->rmap->n, *ip, N, *ailen = a->ilen, rmax = 0;
1067:   MatScalar  *aa    = a->a, *ap;
1068:   PetscReal   ratio = 0.6;

1070:   if (mode == MAT_FLUSH_ASSEMBLY) return 0;
1071:   MatSeqAIJInvalidateDiagonal(A);
1072:   if (A->was_assembled && A->ass_nonzerostate == A->nonzerostate) {
1073:     /* we need to respect users asking to use or not the inodes routine in between matrix assemblies */
1074:     MatAssemblyEnd_SeqAIJ_Inode(A, mode);
1075:     return 0;
1076:   }

1078:   if (m) rmax = ailen[0]; /* determine row with most nonzeros */
1079:   for (i = 1; i < m; i++) {
1080:     /* move each row back by the amount of empty slots (fshift) before it*/
1081:     fshift += imax[i - 1] - ailen[i - 1];
1082:     rmax = PetscMax(rmax, ailen[i]);
1083:     if (fshift) {
1084:       ip = aj + ai[i];
1085:       ap = aa + ai[i];
1086:       N  = ailen[i];
1087:       PetscArraymove(ip - fshift, ip, N);
1088:       if (!A->structure_only) PetscArraymove(ap - fshift, ap, N);
1089:     }
1090:     ai[i] = ai[i - 1] + ailen[i - 1];
1091:   }
1092:   if (m) {
1093:     fshift += imax[m - 1] - ailen[m - 1];
1094:     ai[m] = ai[m - 1] + ailen[m - 1];
1095:   }

1097:   /* reset ilen and imax for each row */
1098:   a->nonzerorowcnt = 0;
1099:   if (A->structure_only) {
1100:     PetscFree(a->imax);
1101:     PetscFree(a->ilen);
1102:   } else { /* !A->structure_only */
1103:     for (i = 0; i < m; i++) {
1104:       ailen[i] = imax[i] = ai[i + 1] - ai[i];
1105:       a->nonzerorowcnt += ((ai[i + 1] - ai[i]) > 0);
1106:     }
1107:   }
1108:   a->nz = ai[m];

1111:   MatMarkDiagonal_SeqAIJ(A);
1112:   PetscInfo(A, "Matrix size: %" PetscInt_FMT " X %" PetscInt_FMT "; storage space: %" PetscInt_FMT " unneeded,%" PetscInt_FMT " used\n", m, A->cmap->n, fshift, a->nz);
1113:   PetscInfo(A, "Number of mallocs during MatSetValues() is %" PetscInt_FMT "\n", a->reallocs);
1114:   PetscInfo(A, "Maximum nonzeros in any row is %" PetscInt_FMT "\n", rmax);

1116:   A->info.mallocs += a->reallocs;
1117:   a->reallocs         = 0;
1118:   A->info.nz_unneeded = (PetscReal)fshift;
1119:   a->rmax             = rmax;

1121:   if (!A->structure_only) MatCheckCompressedRow(A, a->nonzerorowcnt, &a->compressedrow, a->i, m, ratio);
1122:   MatAssemblyEnd_SeqAIJ_Inode(A, mode);
1123:   return 0;
1124: }

1126: PetscErrorCode MatRealPart_SeqAIJ(Mat A)
1127: {
1128:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1129:   PetscInt    i, nz = a->nz;
1130:   MatScalar  *aa;

1132:   MatSeqAIJGetArray(A, &aa);
1133:   for (i = 0; i < nz; i++) aa[i] = PetscRealPart(aa[i]);
1134:   MatSeqAIJRestoreArray(A, &aa);
1135:   MatSeqAIJInvalidateDiagonal(A);
1136:   return 0;
1137: }

1139: PetscErrorCode MatImaginaryPart_SeqAIJ(Mat A)
1140: {
1141:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1142:   PetscInt    i, nz = a->nz;
1143:   MatScalar  *aa;

1145:   MatSeqAIJGetArray(A, &aa);
1146:   for (i = 0; i < nz; i++) aa[i] = PetscImaginaryPart(aa[i]);
1147:   MatSeqAIJRestoreArray(A, &aa);
1148:   MatSeqAIJInvalidateDiagonal(A);
1149:   return 0;
1150: }

1152: PetscErrorCode MatZeroEntries_SeqAIJ(Mat A)
1153: {
1154:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1155:   MatScalar  *aa;

1157:   MatSeqAIJGetArrayWrite(A, &aa);
1158:   PetscArrayzero(aa, a->i[A->rmap->n]);
1159:   MatSeqAIJRestoreArrayWrite(A, &aa);
1160:   MatSeqAIJInvalidateDiagonal(A);
1161:   return 0;
1162: }

1164: PETSC_INTERN PetscErrorCode MatResetPreallocationCOO_SeqAIJ(Mat A)
1165: {
1166:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

1168:   PetscFree(a->perm);
1169:   PetscFree(a->jmap);
1170:   return 0;
1171: }

1173: PetscErrorCode MatDestroy_SeqAIJ(Mat A)
1174: {
1175:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

1177: #if defined(PETSC_USE_LOG)
1178:   PetscLogObjectState((PetscObject)A, "Rows=%" PetscInt_FMT ", Cols=%" PetscInt_FMT ", NZ=%" PetscInt_FMT, A->rmap->n, A->cmap->n, a->nz);
1179: #endif
1180:   MatSeqXAIJFreeAIJ(A, &a->a, &a->j, &a->i);
1181:   MatResetPreallocationCOO_SeqAIJ(A);
1182:   ISDestroy(&a->row);
1183:   ISDestroy(&a->col);
1184:   PetscFree(a->diag);
1185:   PetscFree(a->ibdiag);
1186:   PetscFree(a->imax);
1187:   PetscFree(a->ilen);
1188:   PetscFree(a->ipre);
1189:   PetscFree3(a->idiag, a->mdiag, a->ssor_work);
1190:   PetscFree(a->solve_work);
1191:   ISDestroy(&a->icol);
1192:   PetscFree(a->saved_values);
1193:   PetscFree2(a->compressedrow.i, a->compressedrow.rindex);
1194:   MatDestroy_SeqAIJ_Inode(A);
1195:   PetscFree(A->data);

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

1204:   PetscObjectChangeTypeName((PetscObject)A, NULL);
1205:   PetscObjectComposeFunction((PetscObject)A, "PetscMatlabEnginePut_C", NULL);
1206:   PetscObjectComposeFunction((PetscObject)A, "PetscMatlabEngineGet_C", NULL);
1207:   PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetColumnIndices_C", NULL);
1208:   PetscObjectComposeFunction((PetscObject)A, "MatStoreValues_C", NULL);
1209:   PetscObjectComposeFunction((PetscObject)A, "MatRetrieveValues_C", NULL);
1210:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqsbaij_C", NULL);
1211:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqbaij_C", NULL);
1212:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijperm_C", NULL);
1213:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijsell_C", NULL);
1214: #if defined(PETSC_HAVE_MKL_SPARSE)
1215:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijmkl_C", NULL);
1216: #endif
1217: #if defined(PETSC_HAVE_CUDA)
1218:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijcusparse_C", NULL);
1219:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijcusparse_seqaij_C", NULL);
1220:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaijcusparse_C", NULL);
1221: #endif
1222: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
1223:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijkokkos_C", NULL);
1224: #endif
1225:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijcrl_C", NULL);
1226: #if defined(PETSC_HAVE_ELEMENTAL)
1227:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_elemental_C", NULL);
1228: #endif
1229: #if defined(PETSC_HAVE_SCALAPACK)
1230:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_scalapack_C", NULL);
1231: #endif
1232: #if defined(PETSC_HAVE_HYPRE)
1233:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_hypre_C", NULL);
1234:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_transpose_seqaij_seqaij_C", NULL);
1235: #endif
1236:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqdense_C", NULL);
1237:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqsell_C", NULL);
1238:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_is_C", NULL);
1239:   PetscObjectComposeFunction((PetscObject)A, "MatIsTranspose_C", NULL);
1240:   PetscObjectComposeFunction((PetscObject)A, "MatIsHermitianTranspose_C", NULL);
1241:   PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetPreallocation_C", NULL);
1242:   PetscObjectComposeFunction((PetscObject)A, "MatResetPreallocation_C", NULL);
1243:   PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetPreallocationCSR_C", NULL);
1244:   PetscObjectComposeFunction((PetscObject)A, "MatReorderForNonzeroDiagonal_C", NULL);
1245:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_is_seqaij_C", NULL);
1246:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqdense_seqaij_C", NULL);
1247:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaij_C", NULL);
1248:   PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJKron_C", NULL);
1249:   PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL);
1250:   PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL);
1251:   PetscObjectComposeFunction((PetscObject)A, "MatFactorGetSolverType_C", NULL);
1252:   /* these calls do not belong here: the subclasses Duplicate/Destroy are wrong */
1253:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijsell_seqaij_C", NULL);
1254:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijperm_seqaij_C", NULL);
1255:   PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijviennacl_C", NULL);
1256:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijviennacl_seqdense_C", NULL);
1257:   PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijviennacl_seqaij_C", NULL);
1258:   return 0;
1259: }

1261: PetscErrorCode MatSetOption_SeqAIJ(Mat A, MatOption op, PetscBool flg)
1262: {
1263:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

1265:   switch (op) {
1266:   case MAT_ROW_ORIENTED:
1267:     a->roworiented = flg;
1268:     break;
1269:   case MAT_KEEP_NONZERO_PATTERN:
1270:     a->keepnonzeropattern = flg;
1271:     break;
1272:   case MAT_NEW_NONZERO_LOCATIONS:
1273:     a->nonew = (flg ? 0 : 1);
1274:     break;
1275:   case MAT_NEW_NONZERO_LOCATION_ERR:
1276:     a->nonew = (flg ? -1 : 0);
1277:     break;
1278:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1279:     a->nonew = (flg ? -2 : 0);
1280:     break;
1281:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1282:     a->nounused = (flg ? -1 : 0);
1283:     break;
1284:   case MAT_IGNORE_ZERO_ENTRIES:
1285:     a->ignorezeroentries = flg;
1286:     break;
1287:   case MAT_SPD:
1288:   case MAT_SYMMETRIC:
1289:   case MAT_STRUCTURALLY_SYMMETRIC:
1290:   case MAT_HERMITIAN:
1291:   case MAT_SYMMETRY_ETERNAL:
1292:   case MAT_STRUCTURE_ONLY:
1293:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
1294:   case MAT_SPD_ETERNAL:
1295:     /* if the diagonal matrix is square it inherits some of the properties above */
1296:     break;
1297:   case MAT_FORCE_DIAGONAL_ENTRIES:
1298:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1299:   case MAT_USE_HASH_TABLE:
1300:     PetscInfo(A, "Option %s ignored\n", MatOptions[op]);
1301:     break;
1302:   case MAT_USE_INODES:
1303:     MatSetOption_SeqAIJ_Inode(A, MAT_USE_INODES, flg);
1304:     break;
1305:   case MAT_SUBMAT_SINGLEIS:
1306:     A->submat_singleis = flg;
1307:     break;
1308:   case MAT_SORTED_FULL:
1309:     if (flg) A->ops->setvalues = MatSetValues_SeqAIJ_SortedFull;
1310:     else A->ops->setvalues = MatSetValues_SeqAIJ;
1311:     break;
1312:   case MAT_FORM_EXPLICIT_TRANSPOSE:
1313:     A->form_explicit_transpose = flg;
1314:     break;
1315:   default:
1316:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "unknown option %d", op);
1317:   }
1318:   return 0;
1319: }

1321: PetscErrorCode MatGetDiagonal_SeqAIJ(Mat A, Vec v)
1322: {
1323:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1324:   PetscInt           i, j, n, *ai = a->i, *aj = a->j;
1325:   PetscScalar       *x;
1326:   const PetscScalar *aa;

1328:   VecGetLocalSize(v, &n);
1330:   MatSeqAIJGetArrayRead(A, &aa);
1331:   if (A->factortype == MAT_FACTOR_ILU || A->factortype == MAT_FACTOR_LU) {
1332:     PetscInt *diag = a->diag;
1333:     VecGetArrayWrite(v, &x);
1334:     for (i = 0; i < n; i++) x[i] = 1.0 / aa[diag[i]];
1335:     VecRestoreArrayWrite(v, &x);
1336:     MatSeqAIJRestoreArrayRead(A, &aa);
1337:     return 0;
1338:   }

1340:   VecGetArrayWrite(v, &x);
1341:   for (i = 0; i < n; i++) {
1342:     x[i] = 0.0;
1343:     for (j = ai[i]; j < ai[i + 1]; j++) {
1344:       if (aj[j] == i) {
1345:         x[i] = aa[j];
1346:         break;
1347:       }
1348:     }
1349:   }
1350:   VecRestoreArrayWrite(v, &x);
1351:   MatSeqAIJRestoreArrayRead(A, &aa);
1352:   return 0;
1353: }

1355: #include <../src/mat/impls/aij/seq/ftn-kernels/fmult.h>
1356: PetscErrorCode MatMultTransposeAdd_SeqAIJ(Mat A, Vec xx, Vec zz, Vec yy)
1357: {
1358:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1359:   const MatScalar   *aa;
1360:   PetscScalar       *y;
1361:   const PetscScalar *x;
1362:   PetscInt           m = A->rmap->n;
1363: #if !defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1364:   const MatScalar  *v;
1365:   PetscScalar       alpha;
1366:   PetscInt          n, i, j;
1367:   const PetscInt   *idx, *ii, *ridx = NULL;
1368:   Mat_CompressedRow cprow    = a->compressedrow;
1369:   PetscBool         usecprow = cprow.use;
1370: #endif

1372:   if (zz != yy) VecCopy(zz, yy);
1373:   VecGetArrayRead(xx, &x);
1374:   VecGetArray(yy, &y);
1375:   MatSeqAIJGetArrayRead(A, &aa);

1377: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1378:   fortranmulttransposeaddaij_(&m, x, a->i, a->j, aa, y);
1379: #else
1380:   if (usecprow) {
1381:     m = cprow.nrows;
1382:     ii = cprow.i;
1383:     ridx = cprow.rindex;
1384:   } else {
1385:     ii = a->i;
1386:   }
1387:   for (i = 0; i < m; i++) {
1388:     idx = a->j + ii[i];
1389:     v = aa + ii[i];
1390:     n = ii[i + 1] - ii[i];
1391:     if (usecprow) {
1392:       alpha = x[ridx[i]];
1393:     } else {
1394:       alpha = x[i];
1395:     }
1396:     for (j = 0; j < n; j++) y[idx[j]] += alpha * v[j];
1397:   }
1398: #endif
1399:   PetscLogFlops(2.0 * a->nz);
1400:   VecRestoreArrayRead(xx, &x);
1401:   VecRestoreArray(yy, &y);
1402:   MatSeqAIJRestoreArrayRead(A, &aa);
1403:   return 0;
1404: }

1406: PetscErrorCode MatMultTranspose_SeqAIJ(Mat A, Vec xx, Vec yy)
1407: {
1408:   VecSet(yy, 0.0);
1409:   MatMultTransposeAdd_SeqAIJ(A, xx, yy, yy);
1410:   return 0;
1411: }

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

1415: PetscErrorCode MatMult_SeqAIJ(Mat A, Vec xx, Vec yy)
1416: {
1417:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1418:   PetscScalar       *y;
1419:   const PetscScalar *x;
1420:   const MatScalar   *aa, *a_a;
1421:   PetscInt           m = A->rmap->n;
1422:   const PetscInt    *aj, *ii, *ridx = NULL;
1423:   PetscInt           n, i;
1424:   PetscScalar        sum;
1425:   PetscBool          usecprow = a->compressedrow.use;

1427: #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1428:   #pragma disjoint(*x, *y, *aa)
1429: #endif

1431:   if (a->inode.use && a->inode.checked) {
1432:     MatMult_SeqAIJ_Inode(A, xx, yy);
1433:     return 0;
1434:   }
1435:   MatSeqAIJGetArrayRead(A, &a_a);
1436:   VecGetArrayRead(xx, &x);
1437:   VecGetArray(yy, &y);
1438:   ii = a->i;
1439:   if (usecprow) { /* use compressed row format */
1440:     PetscArrayzero(y, m);
1441:     m    = a->compressedrow.nrows;
1442:     ii   = a->compressedrow.i;
1443:     ridx = a->compressedrow.rindex;
1444:     for (i = 0; i < m; i++) {
1445:       n   = ii[i + 1] - ii[i];
1446:       aj  = a->j + ii[i];
1447:       aa  = a_a + ii[i];
1448:       sum = 0.0;
1449:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1450:       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1451:       y[*ridx++] = sum;
1452:     }
1453:   } else { /* do not use compressed row format */
1454: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTAIJ)
1455:     aj = a->j;
1456:     aa = a_a;
1457:     fortranmultaij_(&m, x, ii, aj, aa, y);
1458: #else
1459:     for (i = 0; i < m; i++) {
1460:       n = ii[i + 1] - ii[i];
1461:       aj = a->j + ii[i];
1462:       aa = a_a + ii[i];
1463:       sum = 0.0;
1464:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1465:       y[i] = sum;
1466:     }
1467: #endif
1468:   }
1469:   PetscLogFlops(2.0 * a->nz - a->nonzerorowcnt);
1470:   VecRestoreArrayRead(xx, &x);
1471:   VecRestoreArray(yy, &y);
1472:   MatSeqAIJRestoreArrayRead(A, &a_a);
1473:   return 0;
1474: }

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

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

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

1528: PetscErrorCode MatMultAddMax_SeqAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1529: {
1530:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1531:   PetscScalar       *y, *z;
1532:   const PetscScalar *x;
1533:   const MatScalar   *aa, *a_a;
1534:   PetscInt           m = A->rmap->n, *aj, *ii;
1535:   PetscInt           n, i, *ridx = NULL;
1536:   PetscScalar        sum;
1537:   PetscBool          usecprow = a->compressedrow.use;

1539:   MatSeqAIJGetArrayRead(A, &a_a);
1540:   VecGetArrayRead(xx, &x);
1541:   VecGetArrayPair(yy, zz, &y, &z);
1542:   if (usecprow) { /* use compressed row format */
1543:     if (zz != yy) PetscArraycpy(z, y, m);
1544:     m    = a->compressedrow.nrows;
1545:     ii   = a->compressedrow.i;
1546:     ridx = a->compressedrow.rindex;
1547:     for (i = 0; i < m; i++) {
1548:       n   = ii[i + 1] - ii[i];
1549:       aj  = a->j + ii[i];
1550:       aa  = a_a + ii[i];
1551:       sum = y[*ridx];
1552:       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1553:       z[*ridx++] = sum;
1554:     }
1555:   } else { /* do not use compressed row format */
1556:     ii = a->i;
1557:     for (i = 0; i < m; i++) {
1558:       n   = ii[i + 1] - ii[i];
1559:       aj  = a->j + ii[i];
1560:       aa  = a_a + ii[i];
1561:       sum = y[i];
1562:       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1563:       z[i] = sum;
1564:     }
1565:   }
1566:   PetscLogFlops(2.0 * a->nz);
1567:   VecRestoreArrayRead(xx, &x);
1568:   VecRestoreArrayPair(yy, zz, &y, &z);
1569:   MatSeqAIJRestoreArrayRead(A, &a_a);
1570:   return 0;
1571: }

1573: #include <../src/mat/impls/aij/seq/ftn-kernels/fmultadd.h>
1574: PetscErrorCode MatMultAdd_SeqAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1575: {
1576:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1577:   PetscScalar       *y, *z;
1578:   const PetscScalar *x;
1579:   const MatScalar   *aa, *a_a;
1580:   const PetscInt    *aj, *ii, *ridx = NULL;
1581:   PetscInt           m = A->rmap->n, n, i;
1582:   PetscScalar        sum;
1583:   PetscBool          usecprow = a->compressedrow.use;

1585:   if (a->inode.use && a->inode.checked) {
1586:     MatMultAdd_SeqAIJ_Inode(A, xx, yy, zz);
1587:     return 0;
1588:   }
1589:   MatSeqAIJGetArrayRead(A, &a_a);
1590:   VecGetArrayRead(xx, &x);
1591:   VecGetArrayPair(yy, zz, &y, &z);
1592:   if (usecprow) { /* use compressed row format */
1593:     if (zz != yy) PetscArraycpy(z, y, m);
1594:     m    = a->compressedrow.nrows;
1595:     ii   = a->compressedrow.i;
1596:     ridx = a->compressedrow.rindex;
1597:     for (i = 0; i < m; i++) {
1598:       n   = ii[i + 1] - ii[i];
1599:       aj  = a->j + ii[i];
1600:       aa  = a_a + ii[i];
1601:       sum = y[*ridx];
1602:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1603:       z[*ridx++] = sum;
1604:     }
1605:   } else { /* do not use compressed row format */
1606:     ii = a->i;
1607: #if defined(PETSC_USE_FORTRAN_KERNEL_MULTADDAIJ)
1608:     aj = a->j;
1609:     aa = a_a;
1610:     fortranmultaddaij_(&m, x, ii, aj, aa, y, z);
1611: #else
1612:     for (i = 0; i < m; i++) {
1613:       n = ii[i + 1] - ii[i];
1614:       aj = a->j + ii[i];
1615:       aa = a_a + ii[i];
1616:       sum = y[i];
1617:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1618:       z[i] = sum;
1619:     }
1620: #endif
1621:   }
1622:   PetscLogFlops(2.0 * a->nz);
1623:   VecRestoreArrayRead(xx, &x);
1624:   VecRestoreArrayPair(yy, zz, &y, &z);
1625:   MatSeqAIJRestoreArrayRead(A, &a_a);
1626:   return 0;
1627: }

1629: /*
1630:      Adds diagonal pointers to sparse matrix structure.
1631: */
1632: PetscErrorCode MatMarkDiagonal_SeqAIJ(Mat A)
1633: {
1634:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1635:   PetscInt    i, j, m = A->rmap->n;
1636:   PetscBool   alreadySet = PETSC_TRUE;

1638:   if (!a->diag) {
1639:     PetscMalloc1(m, &a->diag);
1640:     alreadySet = PETSC_FALSE;
1641:   }
1642:   for (i = 0; i < A->rmap->n; i++) {
1643:     /* If A's diagonal is already correctly set, this fast track enables cheap and repeated MatMarkDiagonal_SeqAIJ() calls */
1644:     if (alreadySet) {
1645:       PetscInt pos = a->diag[i];
1646:       if (pos >= a->i[i] && pos < a->i[i + 1] && a->j[pos] == i) continue;
1647:     }

1649:     a->diag[i] = a->i[i + 1];
1650:     for (j = a->i[i]; j < a->i[i + 1]; j++) {
1651:       if (a->j[j] == i) {
1652:         a->diag[i] = j;
1653:         break;
1654:       }
1655:     }
1656:   }
1657:   return 0;
1658: }

1660: PetscErrorCode MatShift_SeqAIJ(Mat A, PetscScalar v)
1661: {
1662:   Mat_SeqAIJ     *a    = (Mat_SeqAIJ *)A->data;
1663:   const PetscInt *diag = (const PetscInt *)a->diag;
1664:   const PetscInt *ii   = (const PetscInt *)a->i;
1665:   PetscInt        i, *mdiag = NULL;
1666:   PetscInt        cnt = 0; /* how many diagonals are missing */

1668:   if (!A->preallocated || !a->nz) {
1669:     MatSeqAIJSetPreallocation(A, 1, NULL);
1670:     MatShift_Basic(A, v);
1671:     return 0;
1672:   }

1674:   if (a->diagonaldense) {
1675:     cnt = 0;
1676:   } else {
1677:     PetscCalloc1(A->rmap->n, &mdiag);
1678:     for (i = 0; i < A->rmap->n; i++) {
1679:       if (i < A->cmap->n && diag[i] >= ii[i + 1]) { /* 'out of range' rows never have diagonals */
1680:         cnt++;
1681:         mdiag[i] = 1;
1682:       }
1683:     }
1684:   }
1685:   if (!cnt) {
1686:     MatShift_Basic(A, v);
1687:   } else {
1688:     PetscScalar *olda = a->a; /* preserve pointers to current matrix nonzeros structure and values */
1689:     PetscInt    *oldj = a->j, *oldi = a->i;
1690:     PetscBool    singlemalloc = a->singlemalloc, free_a = a->free_a, free_ij = a->free_ij;

1692:     a->a = NULL;
1693:     a->j = NULL;
1694:     a->i = NULL;
1695:     /* increase the values in imax for each row where a diagonal is being inserted then reallocate the matrix data structures */
1696:     for (i = 0; i < PetscMin(A->rmap->n, A->cmap->n); i++) a->imax[i] += mdiag[i];
1697:     MatSeqAIJSetPreallocation_SeqAIJ(A, 0, a->imax);

1699:     /* copy old values into new matrix data structure */
1700:     for (i = 0; i < A->rmap->n; i++) {
1701:       MatSetValues(A, 1, &i, a->imax[i] - mdiag[i], &oldj[oldi[i]], &olda[oldi[i]], ADD_VALUES);
1702:       if (i < A->cmap->n) MatSetValue(A, i, i, v, ADD_VALUES);
1703:     }
1704:     MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
1705:     MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY);
1706:     if (singlemalloc) {
1707:       PetscFree3(olda, oldj, oldi);
1708:     } else {
1709:       if (free_a) PetscFree(olda);
1710:       if (free_ij) PetscFree(oldj);
1711:       if (free_ij) PetscFree(oldi);
1712:     }
1713:   }
1714:   PetscFree(mdiag);
1715:   a->diagonaldense = PETSC_TRUE;
1716:   return 0;
1717: }

1719: /*
1720:      Checks for missing diagonals
1721: */
1722: PetscErrorCode MatMissingDiagonal_SeqAIJ(Mat A, PetscBool *missing, PetscInt *d)
1723: {
1724:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1725:   PetscInt   *diag, *ii = a->i, i;

1727:   *missing = PETSC_FALSE;
1728:   if (A->rmap->n > 0 && !ii) {
1729:     *missing = PETSC_TRUE;
1730:     if (d) *d = 0;
1731:     PetscInfo(A, "Matrix has no entries therefore is missing diagonal\n");
1732:   } else {
1733:     PetscInt n;
1734:     n    = PetscMin(A->rmap->n, A->cmap->n);
1735:     diag = a->diag;
1736:     for (i = 0; i < n; i++) {
1737:       if (diag[i] >= ii[i + 1]) {
1738:         *missing = PETSC_TRUE;
1739:         if (d) *d = i;
1740:         PetscInfo(A, "Matrix is missing diagonal number %" PetscInt_FMT "\n", i);
1741:         break;
1742:       }
1743:     }
1744:   }
1745:   return 0;
1746: }

1748: #include <petscblaslapack.h>
1749: #include <petsc/private/kernels/blockinvert.h>

1751: /*
1752:     Note that values is allocated externally by the PC and then passed into this routine
1753: */
1754: PetscErrorCode MatInvertVariableBlockDiagonal_SeqAIJ(Mat A, PetscInt nblocks, const PetscInt *bsizes, PetscScalar *diag)
1755: {
1756:   PetscInt        n = A->rmap->n, i, ncnt = 0, *indx, j, bsizemax = 0, *v_pivots;
1757:   PetscBool       allowzeropivot, zeropivotdetected = PETSC_FALSE;
1758:   const PetscReal shift = 0.0;
1759:   PetscInt        ipvt[5];
1760:   PetscCount      flops = 0;
1761:   PetscScalar     work[25], *v_work;

1763:   allowzeropivot = PetscNot(A->erroriffailure);
1764:   for (i = 0; i < nblocks; i++) ncnt += bsizes[i];
1766:   for (i = 0; i < nblocks; i++) bsizemax = PetscMax(bsizemax, bsizes[i]);
1767:   PetscMalloc1(bsizemax, &indx);
1768:   if (bsizemax > 7) PetscMalloc2(bsizemax, &v_work, bsizemax, &v_pivots);
1769:   ncnt = 0;
1770:   for (i = 0; i < nblocks; i++) {
1771:     for (j = 0; j < bsizes[i]; j++) indx[j] = ncnt + j;
1772:     MatGetValues(A, bsizes[i], indx, bsizes[i], indx, diag);
1773:     switch (bsizes[i]) {
1774:     case 1:
1775:       *diag = 1.0 / (*diag);
1776:       break;
1777:     case 2:
1778:       PetscKernel_A_gets_inverse_A_2(diag, shift, allowzeropivot, &zeropivotdetected);
1779:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1780:       PetscKernel_A_gets_transpose_A_2(diag);
1781:       break;
1782:     case 3:
1783:       PetscKernel_A_gets_inverse_A_3(diag, shift, allowzeropivot, &zeropivotdetected);
1784:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1785:       PetscKernel_A_gets_transpose_A_3(diag);
1786:       break;
1787:     case 4:
1788:       PetscKernel_A_gets_inverse_A_4(diag, shift, allowzeropivot, &zeropivotdetected);
1789:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1790:       PetscKernel_A_gets_transpose_A_4(diag);
1791:       break;
1792:     case 5:
1793:       PetscKernel_A_gets_inverse_A_5(diag, ipvt, work, shift, allowzeropivot, &zeropivotdetected);
1794:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1795:       PetscKernel_A_gets_transpose_A_5(diag);
1796:       break;
1797:     case 6:
1798:       PetscKernel_A_gets_inverse_A_6(diag, shift, allowzeropivot, &zeropivotdetected);
1799:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1800:       PetscKernel_A_gets_transpose_A_6(diag);
1801:       break;
1802:     case 7:
1803:       PetscKernel_A_gets_inverse_A_7(diag, shift, allowzeropivot, &zeropivotdetected);
1804:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1805:       PetscKernel_A_gets_transpose_A_7(diag);
1806:       break;
1807:     default:
1808:       PetscKernel_A_gets_inverse_A(bsizes[i], diag, v_pivots, v_work, allowzeropivot, &zeropivotdetected);
1809:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1810:       PetscKernel_A_gets_transpose_A_N(diag, bsizes[i]);
1811:     }
1812:     ncnt += bsizes[i];
1813:     diag += bsizes[i] * bsizes[i];
1814:     flops += 2 * PetscPowInt(bsizes[i], 3) / 3;
1815:   }
1816:   PetscLogFlops(flops);
1817:   if (bsizemax > 7) PetscFree2(v_work, v_pivots);
1818:   PetscFree(indx);
1819:   return 0;
1820: }

1822: /*
1823:    Negative shift indicates do not generate an error if there is a zero diagonal, just invert it anyways
1824: */
1825: PetscErrorCode MatInvertDiagonal_SeqAIJ(Mat A, PetscScalar omega, PetscScalar fshift)
1826: {
1827:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
1828:   PetscInt         i, *diag, m = A->rmap->n;
1829:   const MatScalar *v;
1830:   PetscScalar     *idiag, *mdiag;

1832:   if (a->idiagvalid) return 0;
1833:   MatMarkDiagonal_SeqAIJ(A);
1834:   diag = a->diag;
1835:   if (!a->idiag) { PetscMalloc3(m, &a->idiag, m, &a->mdiag, m, &a->ssor_work); }

1837:   mdiag = a->mdiag;
1838:   idiag = a->idiag;
1839:   MatSeqAIJGetArrayRead(A, &v);
1840:   if (omega == 1.0 && PetscRealPart(fshift) <= 0.0) {
1841:     for (i = 0; i < m; i++) {
1842:       mdiag[i] = v[diag[i]];
1843:       if (!PetscAbsScalar(mdiag[i])) { /* zero diagonal */
1844:         if (PetscRealPart(fshift)) {
1845:           PetscInfo(A, "Zero diagonal on row %" PetscInt_FMT "\n", i);
1846:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1847:           A->factorerror_zeropivot_value = 0.0;
1848:           A->factorerror_zeropivot_row   = i;
1849:         } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Zero diagonal on row %" PetscInt_FMT, i);
1850:       }
1851:       idiag[i] = 1.0 / v[diag[i]];
1852:     }
1853:     PetscLogFlops(m);
1854:   } else {
1855:     for (i = 0; i < m; i++) {
1856:       mdiag[i] = v[diag[i]];
1857:       idiag[i] = omega / (fshift + v[diag[i]]);
1858:     }
1859:     PetscLogFlops(2.0 * m);
1860:   }
1861:   a->idiagvalid = PETSC_TRUE;
1862:   MatSeqAIJRestoreArrayRead(A, &v);
1863:   return 0;
1864: }

1866: #include <../src/mat/impls/aij/seq/ftn-kernels/frelax.h>
1867: PetscErrorCode MatSOR_SeqAIJ(Mat A, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1868: {
1869:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1870:   PetscScalar       *x, d, sum, *t, scale;
1871:   const MatScalar   *v, *idiag = NULL, *mdiag, *aa;
1872:   const PetscScalar *b, *bs, *xb, *ts;
1873:   PetscInt           n, m = A->rmap->n, i;
1874:   const PetscInt    *idx, *diag;

1876:   if (a->inode.use && a->inode.checked && omega == 1.0 && fshift == 0.0) {
1877:     MatSOR_SeqAIJ_Inode(A, bb, omega, flag, fshift, its, lits, xx);
1878:     return 0;
1879:   }
1880:   its = its * lits;

1882:   if (fshift != a->fshift || omega != a->omega) a->idiagvalid = PETSC_FALSE; /* must recompute idiag[] */
1883:   if (!a->idiagvalid) MatInvertDiagonal_SeqAIJ(A, omega, fshift);
1884:   a->fshift = fshift;
1885:   a->omega  = omega;

1887:   diag  = a->diag;
1888:   t     = a->ssor_work;
1889:   idiag = a->idiag;
1890:   mdiag = a->mdiag;

1892:   MatSeqAIJGetArrayRead(A, &aa);
1893:   VecGetArray(xx, &x);
1894:   VecGetArrayRead(bb, &b);
1895:   /* We count flops by assuming the upper triangular and lower triangular parts have the same number of nonzeros */
1896:   if (flag == SOR_APPLY_UPPER) {
1897:     /* apply (U + D/omega) to the vector */
1898:     bs = b;
1899:     for (i = 0; i < m; i++) {
1900:       d   = fshift + mdiag[i];
1901:       n   = a->i[i + 1] - diag[i] - 1;
1902:       idx = a->j + diag[i] + 1;
1903:       v   = aa + diag[i] + 1;
1904:       sum = b[i] * d / omega;
1905:       PetscSparseDensePlusDot(sum, bs, v, idx, n);
1906:       x[i] = sum;
1907:     }
1908:     VecRestoreArray(xx, &x);
1909:     VecRestoreArrayRead(bb, &b);
1910:     MatSeqAIJRestoreArrayRead(A, &aa);
1911:     PetscLogFlops(a->nz);
1912:     return 0;
1913:   }

1916:   if (flag & SOR_EISENSTAT) {
1917:     /* Let  A = L + U + D; where L is lower triangular,
1918:     U is upper triangular, E = D/omega; This routine applies

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

1922:     to a vector efficiently using Eisenstat's trick.
1923:     */
1924:     scale = (2.0 / omega) - 1.0;

1926:     /*  x = (E + U)^{-1} b */
1927:     for (i = m - 1; i >= 0; i--) {
1928:       n   = a->i[i + 1] - diag[i] - 1;
1929:       idx = a->j + diag[i] + 1;
1930:       v   = aa + diag[i] + 1;
1931:       sum = b[i];
1932:       PetscSparseDenseMinusDot(sum, x, v, idx, n);
1933:       x[i] = sum * idiag[i];
1934:     }

1936:     /*  t = b - (2*E - D)x */
1937:     v = aa;
1938:     for (i = 0; i < m; i++) t[i] = b[i] - scale * (v[*diag++]) * x[i];

1940:     /*  t = (E + L)^{-1}t */
1941:     ts   = t;
1942:     diag = a->diag;
1943:     for (i = 0; i < m; i++) {
1944:       n   = diag[i] - a->i[i];
1945:       idx = a->j + a->i[i];
1946:       v   = aa + a->i[i];
1947:       sum = t[i];
1948:       PetscSparseDenseMinusDot(sum, ts, v, idx, n);
1949:       t[i] = sum * idiag[i];
1950:       /*  x = x + t */
1951:       x[i] += t[i];
1952:     }

1954:     PetscLogFlops(6.0 * m - 1 + 2.0 * a->nz);
1955:     VecRestoreArray(xx, &x);
1956:     VecRestoreArrayRead(bb, &b);
1957:     return 0;
1958:   }
1959:   if (flag & SOR_ZERO_INITIAL_GUESS) {
1960:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1961:       for (i = 0; i < m; i++) {
1962:         n   = diag[i] - a->i[i];
1963:         idx = a->j + a->i[i];
1964:         v   = aa + a->i[i];
1965:         sum = b[i];
1966:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
1967:         t[i] = sum;
1968:         x[i] = sum * idiag[i];
1969:       }
1970:       xb = t;
1971:       PetscLogFlops(a->nz);
1972:     } else xb = b;
1973:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1974:       for (i = m - 1; i >= 0; i--) {
1975:         n   = a->i[i + 1] - diag[i] - 1;
1976:         idx = a->j + diag[i] + 1;
1977:         v   = aa + diag[i] + 1;
1978:         sum = xb[i];
1979:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
1980:         if (xb == b) {
1981:           x[i] = sum * idiag[i];
1982:         } else {
1983:           x[i] = (1 - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
1984:         }
1985:       }
1986:       PetscLogFlops(a->nz); /* assumes 1/2 in upper */
1987:     }
1988:     its--;
1989:   }
1990:   while (its--) {
1991:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1992:       for (i = 0; i < m; i++) {
1993:         /* lower */
1994:         n   = diag[i] - a->i[i];
1995:         idx = a->j + a->i[i];
1996:         v   = aa + a->i[i];
1997:         sum = b[i];
1998:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
1999:         t[i] = sum; /* save application of the lower-triangular part */
2000:         /* upper */
2001:         n   = a->i[i + 1] - diag[i] - 1;
2002:         idx = a->j + diag[i] + 1;
2003:         v   = aa + diag[i] + 1;
2004:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
2005:         x[i] = (1. - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
2006:       }
2007:       xb = t;
2008:       PetscLogFlops(2.0 * a->nz);
2009:     } else xb = b;
2010:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
2011:       for (i = m - 1; i >= 0; i--) {
2012:         sum = xb[i];
2013:         if (xb == b) {
2014:           /* whole matrix (no checkpointing available) */
2015:           n   = a->i[i + 1] - a->i[i];
2016:           idx = a->j + a->i[i];
2017:           v   = aa + a->i[i];
2018:           PetscSparseDenseMinusDot(sum, x, v, idx, n);
2019:           x[i] = (1. - omega) * x[i] + (sum + mdiag[i] * x[i]) * idiag[i];
2020:         } else { /* lower-triangular part has been saved, so only apply upper-triangular */
2021:           n   = a->i[i + 1] - diag[i] - 1;
2022:           idx = a->j + diag[i] + 1;
2023:           v   = aa + diag[i] + 1;
2024:           PetscSparseDenseMinusDot(sum, x, v, idx, n);
2025:           x[i] = (1. - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
2026:         }
2027:       }
2028:       if (xb == b) {
2029:         PetscLogFlops(2.0 * a->nz);
2030:       } else {
2031:         PetscLogFlops(a->nz); /* assumes 1/2 in upper */
2032:       }
2033:     }
2034:   }
2035:   MatSeqAIJRestoreArrayRead(A, &aa);
2036:   VecRestoreArray(xx, &x);
2037:   VecRestoreArrayRead(bb, &b);
2038:   return 0;
2039: }

2041: PetscErrorCode MatGetInfo_SeqAIJ(Mat A, MatInfoType flag, MatInfo *info)
2042: {
2043:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

2045:   info->block_size   = 1.0;
2046:   info->nz_allocated = a->maxnz;
2047:   info->nz_used      = a->nz;
2048:   info->nz_unneeded  = (a->maxnz - a->nz);
2049:   info->assemblies   = A->num_ass;
2050:   info->mallocs      = A->info.mallocs;
2051:   info->memory       = 0; /* REVIEW ME */
2052:   if (A->factortype) {
2053:     info->fill_ratio_given  = A->info.fill_ratio_given;
2054:     info->fill_ratio_needed = A->info.fill_ratio_needed;
2055:     info->factor_mallocs    = A->info.factor_mallocs;
2056:   } else {
2057:     info->fill_ratio_given  = 0;
2058:     info->fill_ratio_needed = 0;
2059:     info->factor_mallocs    = 0;
2060:   }
2061:   return 0;
2062: }

2064: PetscErrorCode MatZeroRows_SeqAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
2065: {
2066:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2067:   PetscInt           i, m = A->rmap->n - 1;
2068:   const PetscScalar *xx;
2069:   PetscScalar       *bb, *aa;
2070:   PetscInt           d = 0;

2072:   if (x && b) {
2073:     VecGetArrayRead(x, &xx);
2074:     VecGetArray(b, &bb);
2075:     for (i = 0; i < N; i++) {
2077:       if (rows[i] >= A->cmap->n) continue;
2078:       bb[rows[i]] = diag * xx[rows[i]];
2079:     }
2080:     VecRestoreArrayRead(x, &xx);
2081:     VecRestoreArray(b, &bb);
2082:   }

2084:   MatSeqAIJGetArray(A, &aa);
2085:   if (a->keepnonzeropattern) {
2086:     for (i = 0; i < N; i++) {
2088:       PetscArrayzero(&aa[a->i[rows[i]]], a->ilen[rows[i]]);
2089:     }
2090:     if (diag != 0.0) {
2091:       for (i = 0; i < N; i++) {
2092:         d = rows[i];
2093:         if (rows[i] >= A->cmap->n) continue;
2095:       }
2096:       for (i = 0; i < N; i++) {
2097:         if (rows[i] >= A->cmap->n) continue;
2098:         aa[a->diag[rows[i]]] = diag;
2099:       }
2100:     }
2101:   } else {
2102:     if (diag != 0.0) {
2103:       for (i = 0; i < N; i++) {
2105:         if (a->ilen[rows[i]] > 0) {
2106:           if (rows[i] >= A->cmap->n) {
2107:             a->ilen[rows[i]] = 0;
2108:           } else {
2109:             a->ilen[rows[i]]    = 1;
2110:             aa[a->i[rows[i]]]   = diag;
2111:             a->j[a->i[rows[i]]] = rows[i];
2112:           }
2113:         } else if (rows[i] < A->cmap->n) { /* in case row was completely empty */
2114:           MatSetValues_SeqAIJ(A, 1, &rows[i], 1, &rows[i], &diag, INSERT_VALUES);
2115:         }
2116:       }
2117:     } else {
2118:       for (i = 0; i < N; i++) {
2120:         a->ilen[rows[i]] = 0;
2121:       }
2122:     }
2123:     A->nonzerostate++;
2124:   }
2125:   MatSeqAIJRestoreArray(A, &aa);
2126:   PetscUseTypeMethod(A, assemblyend, MAT_FINAL_ASSEMBLY);
2127:   return 0;
2128: }

2130: PetscErrorCode MatZeroRowsColumns_SeqAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
2131: {
2132:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2133:   PetscInt           i, j, m = A->rmap->n - 1, d = 0;
2134:   PetscBool          missing, *zeroed, vecs = PETSC_FALSE;
2135:   const PetscScalar *xx;
2136:   PetscScalar       *bb, *aa;

2138:   if (!N) return 0;
2139:   MatSeqAIJGetArray(A, &aa);
2140:   if (x && b) {
2141:     VecGetArrayRead(x, &xx);
2142:     VecGetArray(b, &bb);
2143:     vecs = PETSC_TRUE;
2144:   }
2145:   PetscCalloc1(A->rmap->n, &zeroed);
2146:   for (i = 0; i < N; i++) {
2148:     PetscArrayzero(&aa[a->i[rows[i]]], a->ilen[rows[i]]);

2150:     zeroed[rows[i]] = PETSC_TRUE;
2151:   }
2152:   for (i = 0; i < A->rmap->n; i++) {
2153:     if (!zeroed[i]) {
2154:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
2155:         if (a->j[j] < A->rmap->n && zeroed[a->j[j]]) {
2156:           if (vecs) bb[i] -= aa[j] * xx[a->j[j]];
2157:           aa[j] = 0.0;
2158:         }
2159:       }
2160:     } else if (vecs && i < A->cmap->N) bb[i] = diag * xx[i];
2161:   }
2162:   if (x && b) {
2163:     VecRestoreArrayRead(x, &xx);
2164:     VecRestoreArray(b, &bb);
2165:   }
2166:   PetscFree(zeroed);
2167:   if (diag != 0.0) {
2168:     MatMissingDiagonal_SeqAIJ(A, &missing, &d);
2169:     if (missing) {
2170:       for (i = 0; i < N; i++) {
2171:         if (rows[i] >= A->cmap->N) continue;
2173:         MatSetValues_SeqAIJ(A, 1, &rows[i], 1, &rows[i], &diag, INSERT_VALUES);
2174:       }
2175:     } else {
2176:       for (i = 0; i < N; i++) aa[a->diag[rows[i]]] = diag;
2177:     }
2178:   }
2179:   MatSeqAIJRestoreArray(A, &aa);
2180:   PetscUseTypeMethod(A, assemblyend, MAT_FINAL_ASSEMBLY);
2181:   return 0;
2182: }

2184: PetscErrorCode MatGetRow_SeqAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
2185: {
2186:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2187:   const PetscScalar *aa;
2188:   PetscInt          *itmp;

2190:   MatSeqAIJGetArrayRead(A, &aa);
2191:   *nz = a->i[row + 1] - a->i[row];
2192:   if (v) *v = (PetscScalar *)(aa + a->i[row]);
2193:   if (idx) {
2194:     itmp = a->j + a->i[row];
2195:     if (*nz) *idx = itmp;
2196:     else *idx = NULL;
2197:   }
2198:   MatSeqAIJRestoreArrayRead(A, &aa);
2199:   return 0;
2200: }

2202: PetscErrorCode MatRestoreRow_SeqAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
2203: {
2204:   if (nz) *nz = 0;
2205:   if (idx) *idx = NULL;
2206:   if (v) *v = NULL;
2207:   return 0;
2208: }

2210: PetscErrorCode MatNorm_SeqAIJ(Mat A, NormType type, PetscReal *nrm)
2211: {
2212:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
2213:   const MatScalar *v;
2214:   PetscReal        sum = 0.0;
2215:   PetscInt         i, j;

2217:   MatSeqAIJGetArrayRead(A, &v);
2218:   if (type == NORM_FROBENIUS) {
2219: #if defined(PETSC_USE_REAL___FP16)
2220:     PetscBLASInt one = 1, nz = a->nz;
2221:     PetscCallBLAS("BLASnrm2", *nrm = BLASnrm2_(&nz, v, &one));
2222: #else
2223:     for (i = 0; i < a->nz; i++) {
2224:       sum += PetscRealPart(PetscConj(*v) * (*v));
2225:       v++;
2226:     }
2227:     *nrm = PetscSqrtReal(sum);
2228: #endif
2229:     PetscLogFlops(2.0 * a->nz);
2230:   } else if (type == NORM_1) {
2231:     PetscReal *tmp;
2232:     PetscInt  *jj = a->j;
2233:     PetscCalloc1(A->cmap->n + 1, &tmp);
2234:     *nrm = 0.0;
2235:     for (j = 0; j < a->nz; j++) {
2236:       tmp[*jj++] += PetscAbsScalar(*v);
2237:       v++;
2238:     }
2239:     for (j = 0; j < A->cmap->n; j++) {
2240:       if (tmp[j] > *nrm) *nrm = tmp[j];
2241:     }
2242:     PetscFree(tmp);
2243:     PetscLogFlops(PetscMax(a->nz - 1, 0));
2244:   } else if (type == NORM_INFINITY) {
2245:     *nrm = 0.0;
2246:     for (j = 0; j < A->rmap->n; j++) {
2247:       const PetscScalar *v2 = v + a->i[j];
2248:       sum                   = 0.0;
2249:       for (i = 0; i < a->i[j + 1] - a->i[j]; i++) {
2250:         sum += PetscAbsScalar(*v2);
2251:         v2++;
2252:       }
2253:       if (sum > *nrm) *nrm = sum;
2254:     }
2255:     PetscLogFlops(PetscMax(a->nz - 1, 0));
2256:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for two norm");
2257:   MatSeqAIJRestoreArrayRead(A, &v);
2258:   return 0;
2259: }

2261: PetscErrorCode MatIsTranspose_SeqAIJ(Mat A, Mat B, PetscReal tol, PetscBool *f)
2262: {
2263:   Mat_SeqAIJ      *aij = (Mat_SeqAIJ *)A->data, *bij = (Mat_SeqAIJ *)B->data;
2264:   PetscInt        *adx, *bdx, *aii, *bii, *aptr, *bptr;
2265:   const MatScalar *va, *vb;
2266:   PetscInt         ma, na, mb, nb, i;

2268:   MatGetSize(A, &ma, &na);
2269:   MatGetSize(B, &mb, &nb);
2270:   if (ma != nb || na != mb) {
2271:     *f = PETSC_FALSE;
2272:     return 0;
2273:   }
2274:   MatSeqAIJGetArrayRead(A, &va);
2275:   MatSeqAIJGetArrayRead(B, &vb);
2276:   aii = aij->i;
2277:   bii = bij->i;
2278:   adx = aij->j;
2279:   bdx = bij->j;
2280:   PetscMalloc1(ma, &aptr);
2281:   PetscMalloc1(mb, &bptr);
2282:   for (i = 0; i < ma; i++) aptr[i] = aii[i];
2283:   for (i = 0; i < mb; i++) bptr[i] = bii[i];

2285:   *f = PETSC_TRUE;
2286:   for (i = 0; i < ma; i++) {
2287:     while (aptr[i] < aii[i + 1]) {
2288:       PetscInt    idc, idr;
2289:       PetscScalar vc, vr;
2290:       /* column/row index/value */
2291:       idc = adx[aptr[i]];
2292:       idr = bdx[bptr[idc]];
2293:       vc  = va[aptr[i]];
2294:       vr  = vb[bptr[idc]];
2295:       if (i != idr || PetscAbsScalar(vc - vr) > tol) {
2296:         *f = PETSC_FALSE;
2297:         goto done;
2298:       } else {
2299:         aptr[i]++;
2300:         if (B || i != idc) bptr[idc]++;
2301:       }
2302:     }
2303:   }
2304: done:
2305:   PetscFree(aptr);
2306:   PetscFree(bptr);
2307:   MatSeqAIJRestoreArrayRead(A, &va);
2308:   MatSeqAIJRestoreArrayRead(B, &vb);
2309:   return 0;
2310: }

2312: PetscErrorCode MatIsHermitianTranspose_SeqAIJ(Mat A, Mat B, PetscReal tol, PetscBool *f)
2313: {
2314:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data, *bij = (Mat_SeqAIJ *)B->data;
2315:   PetscInt   *adx, *bdx, *aii, *bii, *aptr, *bptr;
2316:   MatScalar  *va, *vb;
2317:   PetscInt    ma, na, mb, nb, i;

2319:   MatGetSize(A, &ma, &na);
2320:   MatGetSize(B, &mb, &nb);
2321:   if (ma != nb || na != mb) {
2322:     *f = PETSC_FALSE;
2323:     return 0;
2324:   }
2325:   aii = aij->i;
2326:   bii = bij->i;
2327:   adx = aij->j;
2328:   bdx = bij->j;
2329:   va  = aij->a;
2330:   vb  = bij->a;
2331:   PetscMalloc1(ma, &aptr);
2332:   PetscMalloc1(mb, &bptr);
2333:   for (i = 0; i < ma; i++) aptr[i] = aii[i];
2334:   for (i = 0; i < mb; i++) bptr[i] = bii[i];

2336:   *f = PETSC_TRUE;
2337:   for (i = 0; i < ma; i++) {
2338:     while (aptr[i] < aii[i + 1]) {
2339:       PetscInt    idc, idr;
2340:       PetscScalar vc, vr;
2341:       /* column/row index/value */
2342:       idc = adx[aptr[i]];
2343:       idr = bdx[bptr[idc]];
2344:       vc  = va[aptr[i]];
2345:       vr  = vb[bptr[idc]];
2346:       if (i != idr || PetscAbsScalar(vc - PetscConj(vr)) > tol) {
2347:         *f = PETSC_FALSE;
2348:         goto done;
2349:       } else {
2350:         aptr[i]++;
2351:         if (B || i != idc) bptr[idc]++;
2352:       }
2353:     }
2354:   }
2355: done:
2356:   PetscFree(aptr);
2357:   PetscFree(bptr);
2358:   return 0;
2359: }

2361: PetscErrorCode MatIsSymmetric_SeqAIJ(Mat A, PetscReal tol, PetscBool *f)
2362: {
2363:   MatIsTranspose_SeqAIJ(A, A, tol, f);
2364:   return 0;
2365: }

2367: PetscErrorCode MatIsHermitian_SeqAIJ(Mat A, PetscReal tol, PetscBool *f)
2368: {
2369:   MatIsHermitianTranspose_SeqAIJ(A, A, tol, f);
2370:   return 0;
2371: }

2373: PetscErrorCode MatDiagonalScale_SeqAIJ(Mat A, Vec ll, Vec rr)
2374: {
2375:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2376:   const PetscScalar *l, *r;
2377:   PetscScalar        x;
2378:   MatScalar         *v;
2379:   PetscInt           i, j, m = A->rmap->n, n = A->cmap->n, M, nz = a->nz;
2380:   const PetscInt    *jj;

2382:   if (ll) {
2383:     /* The local size is used so that VecMPI can be passed to this routine
2384:        by MatDiagonalScale_MPIAIJ */
2385:     VecGetLocalSize(ll, &m);
2387:     VecGetArrayRead(ll, &l);
2388:     MatSeqAIJGetArray(A, &v);
2389:     for (i = 0; i < m; i++) {
2390:       x = l[i];
2391:       M = a->i[i + 1] - a->i[i];
2392:       for (j = 0; j < M; j++) (*v++) *= x;
2393:     }
2394:     VecRestoreArrayRead(ll, &l);
2395:     PetscLogFlops(nz);
2396:     MatSeqAIJRestoreArray(A, &v);
2397:   }
2398:   if (rr) {
2399:     VecGetLocalSize(rr, &n);
2401:     VecGetArrayRead(rr, &r);
2402:     MatSeqAIJGetArray(A, &v);
2403:     jj = a->j;
2404:     for (i = 0; i < nz; i++) (*v++) *= r[*jj++];
2405:     MatSeqAIJRestoreArray(A, &v);
2406:     VecRestoreArrayRead(rr, &r);
2407:     PetscLogFlops(nz);
2408:   }
2409:   MatSeqAIJInvalidateDiagonal(A);
2410:   return 0;
2411: }

2413: PetscErrorCode MatCreateSubMatrix_SeqAIJ(Mat A, IS isrow, IS iscol, PetscInt csize, MatReuse scall, Mat *B)
2414: {
2415:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data, *c;
2416:   PetscInt          *smap, i, k, kstart, kend, oldcols = A->cmap->n, *lens;
2417:   PetscInt           row, mat_i, *mat_j, tcol, first, step, *mat_ilen, sum, lensi;
2418:   const PetscInt    *irow, *icol;
2419:   const PetscScalar *aa;
2420:   PetscInt           nrows, ncols;
2421:   PetscInt          *starts, *j_new, *i_new, *aj = a->j, *ai = a->i, ii, *ailen = a->ilen;
2422:   MatScalar         *a_new, *mat_a;
2423:   Mat                C;
2424:   PetscBool          stride;

2426:   ISGetIndices(isrow, &irow);
2427:   ISGetLocalSize(isrow, &nrows);
2428:   ISGetLocalSize(iscol, &ncols);

2430:   PetscObjectTypeCompare((PetscObject)iscol, ISSTRIDE, &stride);
2431:   if (stride) {
2432:     ISStrideGetInfo(iscol, &first, &step);
2433:   } else {
2434:     first = 0;
2435:     step  = 0;
2436:   }
2437:   if (stride && step == 1) {
2438:     /* special case of contiguous rows */
2439:     PetscMalloc2(nrows, &lens, nrows, &starts);
2440:     /* loop over new rows determining lens and starting points */
2441:     for (i = 0; i < nrows; i++) {
2442:       kstart    = ai[irow[i]];
2443:       kend      = kstart + ailen[irow[i]];
2444:       starts[i] = kstart;
2445:       for (k = kstart; k < kend; k++) {
2446:         if (aj[k] >= first) {
2447:           starts[i] = k;
2448:           break;
2449:         }
2450:       }
2451:       sum = 0;
2452:       while (k < kend) {
2453:         if (aj[k++] >= first + ncols) break;
2454:         sum++;
2455:       }
2456:       lens[i] = sum;
2457:     }
2458:     /* create submatrix */
2459:     if (scall == MAT_REUSE_MATRIX) {
2460:       PetscInt n_cols, n_rows;
2461:       MatGetSize(*B, &n_rows, &n_cols);
2463:       MatZeroEntries(*B);
2464:       C = *B;
2465:     } else {
2466:       PetscInt rbs, cbs;
2467:       MatCreate(PetscObjectComm((PetscObject)A), &C);
2468:       MatSetSizes(C, nrows, ncols, PETSC_DETERMINE, PETSC_DETERMINE);
2469:       ISGetBlockSize(isrow, &rbs);
2470:       ISGetBlockSize(iscol, &cbs);
2471:       MatSetBlockSizes(C, rbs, cbs);
2472:       MatSetType(C, ((PetscObject)A)->type_name);
2473:       MatSeqAIJSetPreallocation_SeqAIJ(C, 0, lens);
2474:     }
2475:     c = (Mat_SeqAIJ *)C->data;

2477:     /* loop over rows inserting into submatrix */
2478:     a_new = c->a;
2479:     j_new = c->j;
2480:     i_new = c->i;
2481:     MatSeqAIJGetArrayRead(A, &aa);
2482:     for (i = 0; i < nrows; i++) {
2483:       ii    = starts[i];
2484:       lensi = lens[i];
2485:       for (k = 0; k < lensi; k++) *j_new++ = aj[ii + k] - first;
2486:       PetscArraycpy(a_new, aa + starts[i], lensi);
2487:       a_new += lensi;
2488:       i_new[i + 1] = i_new[i] + lensi;
2489:       c->ilen[i]   = lensi;
2490:     }
2491:     MatSeqAIJRestoreArrayRead(A, &aa);
2492:     PetscFree2(lens, starts);
2493:   } else {
2494:     ISGetIndices(iscol, &icol);
2495:     PetscCalloc1(oldcols, &smap);
2496:     PetscMalloc1(1 + nrows, &lens);
2497:     for (i = 0; i < ncols; i++) {
2499:       smap[icol[i]] = i + 1;
2500:     }

2502:     /* determine lens of each row */
2503:     for (i = 0; i < nrows; i++) {
2504:       kstart  = ai[irow[i]];
2505:       kend    = kstart + a->ilen[irow[i]];
2506:       lens[i] = 0;
2507:       for (k = kstart; k < kend; k++) {
2508:         if (smap[aj[k]]) lens[i]++;
2509:       }
2510:     }
2511:     /* Create and fill new matrix */
2512:     if (scall == MAT_REUSE_MATRIX) {
2513:       PetscBool equal;

2515:       c = (Mat_SeqAIJ *)((*B)->data);
2517:       PetscArraycmp(c->ilen, lens, (*B)->rmap->n, &equal);
2519:       PetscArrayzero(c->ilen, (*B)->rmap->n);
2520:       C = *B;
2521:     } else {
2522:       PetscInt rbs, cbs;
2523:       MatCreate(PetscObjectComm((PetscObject)A), &C);
2524:       MatSetSizes(C, nrows, ncols, PETSC_DETERMINE, PETSC_DETERMINE);
2525:       ISGetBlockSize(isrow, &rbs);
2526:       ISGetBlockSize(iscol, &cbs);
2527:       MatSetBlockSizes(C, rbs, cbs);
2528:       MatSetType(C, ((PetscObject)A)->type_name);
2529:       MatSeqAIJSetPreallocation_SeqAIJ(C, 0, lens);
2530:     }
2531:     MatSeqAIJGetArrayRead(A, &aa);
2532:     c = (Mat_SeqAIJ *)(C->data);
2533:     for (i = 0; i < nrows; i++) {
2534:       row      = irow[i];
2535:       kstart   = ai[row];
2536:       kend     = kstart + a->ilen[row];
2537:       mat_i    = c->i[i];
2538:       mat_j    = c->j + mat_i;
2539:       mat_a    = c->a + mat_i;
2540:       mat_ilen = c->ilen + i;
2541:       for (k = kstart; k < kend; k++) {
2542:         if ((tcol = smap[a->j[k]])) {
2543:           *mat_j++ = tcol - 1;
2544:           *mat_a++ = aa[k];
2545:           (*mat_ilen)++;
2546:         }
2547:       }
2548:     }
2549:     MatSeqAIJRestoreArrayRead(A, &aa);
2550:     /* Free work space */
2551:     ISRestoreIndices(iscol, &icol);
2552:     PetscFree(smap);
2553:     PetscFree(lens);
2554:     /* sort */
2555:     for (i = 0; i < nrows; i++) {
2556:       PetscInt ilen;

2558:       mat_i = c->i[i];
2559:       mat_j = c->j + mat_i;
2560:       mat_a = c->a + mat_i;
2561:       ilen  = c->ilen[i];
2562:       PetscSortIntWithScalarArray(ilen, mat_j, mat_a);
2563:     }
2564:   }
2565: #if defined(PETSC_HAVE_DEVICE)
2566:   MatBindToCPU(C, A->boundtocpu);
2567: #endif
2568:   MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY);
2569:   MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY);

2571:   ISRestoreIndices(isrow, &irow);
2572:   *B = C;
2573:   return 0;
2574: }

2576: PetscErrorCode MatGetMultiProcBlock_SeqAIJ(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
2577: {
2578:   Mat B;

2580:   if (scall == MAT_INITIAL_MATRIX) {
2581:     MatCreate(subComm, &B);
2582:     MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->n, mat->cmap->n);
2583:     MatSetBlockSizesFromMats(B, mat, mat);
2584:     MatSetType(B, MATSEQAIJ);
2585:     MatDuplicateNoCreate_SeqAIJ(B, mat, MAT_COPY_VALUES, PETSC_TRUE);
2586:     *subMat = B;
2587:   } else {
2588:     MatCopy_SeqAIJ(mat, *subMat, SAME_NONZERO_PATTERN);
2589:   }
2590:   return 0;
2591: }

2593: PetscErrorCode MatILUFactor_SeqAIJ(Mat inA, IS row, IS col, const MatFactorInfo *info)
2594: {
2595:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)inA->data;
2596:   Mat         outA;
2597:   PetscBool   row_identity, col_identity;


2601:   ISIdentity(row, &row_identity);
2602:   ISIdentity(col, &col_identity);

2604:   outA             = inA;
2605:   outA->factortype = MAT_FACTOR_LU;
2606:   PetscFree(inA->solvertype);
2607:   PetscStrallocpy(MATSOLVERPETSC, &inA->solvertype);

2609:   PetscObjectReference((PetscObject)row);
2610:   ISDestroy(&a->row);

2612:   a->row = row;

2614:   PetscObjectReference((PetscObject)col);
2615:   ISDestroy(&a->col);

2617:   a->col = col;

2619:   /* Create the inverse permutation so that it can be used in MatLUFactorNumeric() */
2620:   ISDestroy(&a->icol);
2621:   ISInvertPermutation(col, PETSC_DECIDE, &a->icol);

2623:   if (!a->solve_work) { /* this matrix may have been factored before */
2624:     PetscMalloc1(inA->rmap->n + 1, &a->solve_work);
2625:   }

2627:   MatMarkDiagonal_SeqAIJ(inA);
2628:   if (row_identity && col_identity) {
2629:     MatLUFactorNumeric_SeqAIJ_inplace(outA, inA, info);
2630:   } else {
2631:     MatLUFactorNumeric_SeqAIJ_InplaceWithPerm(outA, inA, info);
2632:   }
2633:   return 0;
2634: }

2636: PetscErrorCode MatScale_SeqAIJ(Mat inA, PetscScalar alpha)
2637: {
2638:   Mat_SeqAIJ  *a = (Mat_SeqAIJ *)inA->data;
2639:   PetscScalar *v;
2640:   PetscBLASInt one = 1, bnz;

2642:   MatSeqAIJGetArray(inA, &v);
2643:   PetscBLASIntCast(a->nz, &bnz);
2644:   PetscCallBLAS("BLASscal", BLASscal_(&bnz, &alpha, v, &one));
2645:   PetscLogFlops(a->nz);
2646:   MatSeqAIJRestoreArray(inA, &v);
2647:   MatSeqAIJInvalidateDiagonal(inA);
2648:   return 0;
2649: }

2651: PetscErrorCode MatDestroySubMatrix_Private(Mat_SubSppt *submatj)
2652: {
2653:   PetscInt i;

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

2658:     for (i = 0; i < submatj->nrqr; ++i) PetscFree(submatj->sbuf2[i]);
2659:     PetscFree3(submatj->sbuf2, submatj->req_size, submatj->req_source1);

2661:     if (submatj->rbuf1) {
2662:       PetscFree(submatj->rbuf1[0]);
2663:       PetscFree(submatj->rbuf1);
2664:     }

2666:     for (i = 0; i < submatj->nrqs; ++i) PetscFree(submatj->rbuf3[i]);
2667:     PetscFree3(submatj->req_source2, submatj->rbuf2, submatj->rbuf3);
2668:     PetscFree(submatj->pa);
2669:   }

2671: #if defined(PETSC_USE_CTABLE)
2672:   PetscTableDestroy((PetscTable *)&submatj->rmap);
2673:   if (submatj->cmap_loc) PetscFree(submatj->cmap_loc);
2674:   PetscFree(submatj->rmap_loc);
2675: #else
2676:   PetscFree(submatj->rmap);
2677: #endif

2679:   if (!submatj->allcolumns) {
2680: #if defined(PETSC_USE_CTABLE)
2681:     PetscTableDestroy((PetscTable *)&submatj->cmap);
2682: #else
2683:     PetscFree(submatj->cmap);
2684: #endif
2685:   }
2686:   PetscFree(submatj->row2proc);

2688:   PetscFree(submatj);
2689:   return 0;
2690: }

2692: PetscErrorCode MatDestroySubMatrix_SeqAIJ(Mat C)
2693: {
2694:   Mat_SeqAIJ  *c       = (Mat_SeqAIJ *)C->data;
2695:   Mat_SubSppt *submatj = c->submatis1;

2697:   (*submatj->destroy)(C);
2698:   MatDestroySubMatrix_Private(submatj);
2699:   return 0;
2700: }

2702: /* Note this has code duplication with MatDestroySubMatrices_SeqBAIJ() */
2703: PetscErrorCode MatDestroySubMatrices_SeqAIJ(PetscInt n, Mat *mat[])
2704: {
2705:   PetscInt     i;
2706:   Mat          C;
2707:   Mat_SeqAIJ  *c;
2708:   Mat_SubSppt *submatj;

2710:   for (i = 0; i < n; i++) {
2711:     C       = (*mat)[i];
2712:     c       = (Mat_SeqAIJ *)C->data;
2713:     submatj = c->submatis1;
2714:     if (submatj) {
2715:       if (--((PetscObject)C)->refct <= 0) {
2716:         PetscFree(C->factorprefix);
2717:         (*submatj->destroy)(C);
2718:         MatDestroySubMatrix_Private(submatj);
2719:         PetscFree(C->defaultvectype);
2720:         PetscFree(C->defaultrandtype);
2721:         PetscLayoutDestroy(&C->rmap);
2722:         PetscLayoutDestroy(&C->cmap);
2723:         PetscHeaderDestroy(&C);
2724:       }
2725:     } else {
2726:       MatDestroy(&C);
2727:     }
2728:   }

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

2733:   PetscFree(*mat);
2734:   return 0;
2735: }

2737: PetscErrorCode MatCreateSubMatrices_SeqAIJ(Mat A, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *B[])
2738: {
2739:   PetscInt i;

2741:   if (scall == MAT_INITIAL_MATRIX) PetscCalloc1(n + 1, B);

2743:   for (i = 0; i < n; i++) MatCreateSubMatrix_SeqAIJ(A, irow[i], icol[i], PETSC_DECIDE, scall, &(*B)[i]);
2744:   return 0;
2745: }

2747: PetscErrorCode MatIncreaseOverlap_SeqAIJ(Mat A, PetscInt is_max, IS is[], PetscInt ov)
2748: {
2749:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
2750:   PetscInt        row, i, j, k, l, ll, m, n, *nidx, isz, val;
2751:   const PetscInt *idx;
2752:   PetscInt        start, end, *ai, *aj, bs = (A->rmap->bs > 0 && A->rmap->bs == A->cmap->bs) ? A->rmap->bs : 1;
2753:   PetscBT         table;

2755:   m  = A->rmap->n / bs;
2756:   ai = a->i;
2757:   aj = a->j;


2761:   PetscMalloc1(m + 1, &nidx);
2762:   PetscBTCreate(m, &table);

2764:   for (i = 0; i < is_max; i++) {
2765:     /* Initialize the two local arrays */
2766:     isz = 0;
2767:     PetscBTMemzero(m, table);

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

2773:     if (bs > 1) {
2774:       /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2775:       for (j = 0; j < n; ++j) {
2776:         if (!PetscBTLookupSet(table, idx[j] / bs)) nidx[isz++] = idx[j] / bs;
2777:       }
2778:       ISRestoreIndices(is[i], &idx);
2779:       ISDestroy(&is[i]);

2781:       k = 0;
2782:       for (j = 0; j < ov; j++) { /* for each overlap */
2783:         n = isz;
2784:         for (; k < n; k++) { /* do only those rows in nidx[k], which are not done yet */
2785:           for (ll = 0; ll < bs; ll++) {
2786:             row   = bs * nidx[k] + ll;
2787:             start = ai[row];
2788:             end   = ai[row + 1];
2789:             for (l = start; l < end; l++) {
2790:               val = aj[l] / bs;
2791:               if (!PetscBTLookupSet(table, val)) nidx[isz++] = val;
2792:             }
2793:           }
2794:         }
2795:       }
2796:       ISCreateBlock(PETSC_COMM_SELF, bs, isz, nidx, PETSC_COPY_VALUES, (is + i));
2797:     } else {
2798:       /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2799:       for (j = 0; j < n; ++j) {
2800:         if (!PetscBTLookupSet(table, idx[j])) nidx[isz++] = idx[j];
2801:       }
2802:       ISRestoreIndices(is[i], &idx);
2803:       ISDestroy(&is[i]);

2805:       k = 0;
2806:       for (j = 0; j < ov; j++) { /* for each overlap */
2807:         n = isz;
2808:         for (; k < n; k++) { /* do only those rows in nidx[k], which are not done yet */
2809:           row   = nidx[k];
2810:           start = ai[row];
2811:           end   = ai[row + 1];
2812:           for (l = start; l < end; l++) {
2813:             val = aj[l];
2814:             if (!PetscBTLookupSet(table, val)) nidx[isz++] = val;
2815:           }
2816:         }
2817:       }
2818:       ISCreateGeneral(PETSC_COMM_SELF, isz, nidx, PETSC_COPY_VALUES, (is + i));
2819:     }
2820:   }
2821:   PetscBTDestroy(&table);
2822:   PetscFree(nidx);
2823:   return 0;
2824: }

2826: /* -------------------------------------------------------------- */
2827: PetscErrorCode MatPermute_SeqAIJ(Mat A, IS rowp, IS colp, Mat *B)
2828: {
2829:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
2830:   PetscInt        i, nz = 0, m = A->rmap->n, n = A->cmap->n;
2831:   const PetscInt *row, *col;
2832:   PetscInt       *cnew, j, *lens;
2833:   IS              icolp, irowp;
2834:   PetscInt       *cwork = NULL;
2835:   PetscScalar    *vwork = NULL;

2837:   ISInvertPermutation(rowp, PETSC_DECIDE, &irowp);
2838:   ISGetIndices(irowp, &row);
2839:   ISInvertPermutation(colp, PETSC_DECIDE, &icolp);
2840:   ISGetIndices(icolp, &col);

2842:   /* determine lengths of permuted rows */
2843:   PetscMalloc1(m + 1, &lens);
2844:   for (i = 0; i < m; i++) lens[row[i]] = a->i[i + 1] - a->i[i];
2845:   MatCreate(PetscObjectComm((PetscObject)A), B);
2846:   MatSetSizes(*B, m, n, m, n);
2847:   MatSetBlockSizesFromMats(*B, A, A);
2848:   MatSetType(*B, ((PetscObject)A)->type_name);
2849:   MatSeqAIJSetPreallocation_SeqAIJ(*B, 0, lens);
2850:   PetscFree(lens);

2852:   PetscMalloc1(n, &cnew);
2853:   for (i = 0; i < m; i++) {
2854:     MatGetRow_SeqAIJ(A, i, &nz, &cwork, &vwork);
2855:     for (j = 0; j < nz; j++) cnew[j] = col[cwork[j]];
2856:     MatSetValues_SeqAIJ(*B, 1, &row[i], nz, cnew, vwork, INSERT_VALUES);
2857:     MatRestoreRow_SeqAIJ(A, i, &nz, &cwork, &vwork);
2858:   }
2859:   PetscFree(cnew);

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

2863: #if defined(PETSC_HAVE_DEVICE)
2864:   MatBindToCPU(*B, A->boundtocpu);
2865: #endif
2866:   MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY);
2867:   MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY);
2868:   ISRestoreIndices(irowp, &row);
2869:   ISRestoreIndices(icolp, &col);
2870:   ISDestroy(&irowp);
2871:   ISDestroy(&icolp);
2872:   if (rowp == colp) MatPropagateSymmetryOptions(A, *B);
2873:   return 0;
2874: }

2876: PetscErrorCode MatCopy_SeqAIJ(Mat A, Mat B, MatStructure str)
2877: {
2878:   /* If the two matrices have the same copy implementation, use fast copy. */
2879:   if (str == SAME_NONZERO_PATTERN && (A->ops->copy == B->ops->copy)) {
2880:     Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2881:     Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;
2882:     const PetscScalar *aa;

2884:     MatSeqAIJGetArrayRead(A, &aa);
2886:     PetscArraycpy(b->a, aa, a->i[A->rmap->n]);
2887:     PetscObjectStateIncrease((PetscObject)B);
2888:     MatSeqAIJRestoreArrayRead(A, &aa);
2889:   } else {
2890:     MatCopy_Basic(A, B, str);
2891:   }
2892:   return 0;
2893: }

2895: PetscErrorCode MatSetUp_SeqAIJ(Mat A)
2896: {
2897:   MatSeqAIJSetPreallocation_SeqAIJ(A, PETSC_DEFAULT, NULL);
2898:   return 0;
2899: }

2901: PETSC_INTERN PetscErrorCode MatSeqAIJGetArray_SeqAIJ(Mat A, PetscScalar *array[])
2902: {
2903:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

2905:   *array = a->a;
2906:   return 0;
2907: }

2909: PETSC_INTERN PetscErrorCode MatSeqAIJRestoreArray_SeqAIJ(Mat A, PetscScalar *array[])
2910: {
2911:   *array = NULL;
2912:   return 0;
2913: }

2915: /*
2916:    Computes the number of nonzeros per row needed for preallocation when X and Y
2917:    have different nonzero structure.
2918: */
2919: PetscErrorCode MatAXPYGetPreallocation_SeqX_private(PetscInt m, const PetscInt *xi, const PetscInt *xj, const PetscInt *yi, const PetscInt *yj, PetscInt *nnz)
2920: {
2921:   PetscInt i, j, k, nzx, nzy;

2923:   /* Set the number of nonzeros in the new matrix */
2924:   for (i = 0; i < m; i++) {
2925:     const PetscInt *xjj = xj + xi[i], *yjj = yj + yi[i];
2926:     nzx    = xi[i + 1] - xi[i];
2927:     nzy    = yi[i + 1] - yi[i];
2928:     nnz[i] = 0;
2929:     for (j = 0, k = 0; j < nzx; j++) {                  /* Point in X */
2930:       for (; k < nzy && yjj[k] < xjj[j]; k++) nnz[i]++; /* Catch up to X */
2931:       if (k < nzy && yjj[k] == xjj[j]) k++;             /* Skip duplicate */
2932:       nnz[i]++;
2933:     }
2934:     for (; k < nzy; k++) nnz[i]++;
2935:   }
2936:   return 0;
2937: }

2939: PetscErrorCode MatAXPYGetPreallocation_SeqAIJ(Mat Y, Mat X, PetscInt *nnz)
2940: {
2941:   PetscInt    m = Y->rmap->N;
2942:   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data;
2943:   Mat_SeqAIJ *y = (Mat_SeqAIJ *)Y->data;

2945:   /* Set the number of nonzeros in the new matrix */
2946:   MatAXPYGetPreallocation_SeqX_private(m, x->i, x->j, y->i, y->j, nnz);
2947:   return 0;
2948: }

2950: PetscErrorCode MatAXPY_SeqAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
2951: {
2952:   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data, *y = (Mat_SeqAIJ *)Y->data;

2954:   if (str == UNKNOWN_NONZERO_PATTERN || (PetscDefined(USE_DEBUG) && str == SAME_NONZERO_PATTERN)) {
2955:     PetscBool e = x->nz == y->nz ? PETSC_TRUE : PETSC_FALSE;
2956:     if (e) {
2957:       PetscArraycmp(x->i, y->i, Y->rmap->n + 1, &e);
2958:       if (e) {
2959:         PetscArraycmp(x->j, y->j, y->nz, &e);
2960:         if (e) str = SAME_NONZERO_PATTERN;
2961:       }
2962:     }
2964:   }
2965:   if (str == SAME_NONZERO_PATTERN) {
2966:     const PetscScalar *xa;
2967:     PetscScalar       *ya, alpha = a;
2968:     PetscBLASInt       one = 1, bnz;

2970:     PetscBLASIntCast(x->nz, &bnz);
2971:     MatSeqAIJGetArray(Y, &ya);
2972:     MatSeqAIJGetArrayRead(X, &xa);
2973:     PetscCallBLAS("BLASaxpy", BLASaxpy_(&bnz, &alpha, xa, &one, ya, &one));
2974:     MatSeqAIJRestoreArrayRead(X, &xa);
2975:     MatSeqAIJRestoreArray(Y, &ya);
2976:     PetscLogFlops(2.0 * bnz);
2977:     MatSeqAIJInvalidateDiagonal(Y);
2978:     PetscObjectStateIncrease((PetscObject)Y);
2979:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2980:     MatAXPY_Basic(Y, a, X, str);
2981:   } else {
2982:     Mat       B;
2983:     PetscInt *nnz;
2984:     PetscMalloc1(Y->rmap->N, &nnz);
2985:     MatCreate(PetscObjectComm((PetscObject)Y), &B);
2986:     PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name);
2987:     MatSetLayouts(B, Y->rmap, Y->cmap);
2988:     MatSetType(B, ((PetscObject)Y)->type_name);
2989:     MatAXPYGetPreallocation_SeqAIJ(Y, X, nnz);
2990:     MatSeqAIJSetPreallocation(B, 0, nnz);
2991:     MatAXPY_BasicWithPreallocation(B, Y, a, X, str);
2992:     MatHeaderMerge(Y, &B);
2993:     MatSeqAIJCheckInode(Y);
2994:     PetscFree(nnz);
2995:   }
2996:   return 0;
2997: }

2999: PETSC_INTERN PetscErrorCode MatConjugate_SeqAIJ(Mat mat)
3000: {
3001: #if defined(PETSC_USE_COMPLEX)
3002:   Mat_SeqAIJ  *aij = (Mat_SeqAIJ *)mat->data;
3003:   PetscInt     i, nz;
3004:   PetscScalar *a;

3006:   nz = aij->nz;
3007:   MatSeqAIJGetArray(mat, &a);
3008:   for (i = 0; i < nz; i++) a[i] = PetscConj(a[i]);
3009:   MatSeqAIJRestoreArray(mat, &a);
3010: #else
3011: #endif
3012:   return 0;
3013: }

3015: PetscErrorCode MatGetRowMaxAbs_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3016: {
3017:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3018:   PetscInt         i, j, m = A->rmap->n, *ai, *aj, ncols, n;
3019:   PetscReal        atmp;
3020:   PetscScalar     *x;
3021:   const MatScalar *aa, *av;

3024:   MatSeqAIJGetArrayRead(A, &av);
3025:   aa = av;
3026:   ai = a->i;
3027:   aj = a->j;

3029:   VecSet(v, 0.0);
3030:   VecGetArrayWrite(v, &x);
3031:   VecGetLocalSize(v, &n);
3033:   for (i = 0; i < m; i++) {
3034:     ncols = ai[1] - ai[0];
3035:     ai++;
3036:     for (j = 0; j < ncols; j++) {
3037:       atmp = PetscAbsScalar(*aa);
3038:       if (PetscAbsScalar(x[i]) < atmp) {
3039:         x[i] = atmp;
3040:         if (idx) idx[i] = *aj;
3041:       }
3042:       aa++;
3043:       aj++;
3044:     }
3045:   }
3046:   VecRestoreArrayWrite(v, &x);
3047:   MatSeqAIJRestoreArrayRead(A, &av);
3048:   return 0;
3049: }

3051: PetscErrorCode MatGetRowMax_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3052: {
3053:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3054:   PetscInt         i, j, m = A->rmap->n, *ai, *aj, ncols, n;
3055:   PetscScalar     *x;
3056:   const MatScalar *aa, *av;

3059:   MatSeqAIJGetArrayRead(A, &av);
3060:   aa = av;
3061:   ai = a->i;
3062:   aj = a->j;

3064:   VecSet(v, 0.0);
3065:   VecGetArrayWrite(v, &x);
3066:   VecGetLocalSize(v, &n);
3068:   for (i = 0; i < m; i++) {
3069:     ncols = ai[1] - ai[0];
3070:     ai++;
3071:     if (ncols == A->cmap->n) { /* row is dense */
3072:       x[i] = *aa;
3073:       if (idx) idx[i] = 0;
3074:     } else { /* row is sparse so already KNOW maximum is 0.0 or higher */
3075:       x[i] = 0.0;
3076:       if (idx) {
3077:         for (j = 0; j < ncols; j++) { /* find first implicit 0.0 in the row */
3078:           if (aj[j] > j) {
3079:             idx[i] = j;
3080:             break;
3081:           }
3082:         }
3083:         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3084:         if (j == ncols && j < A->cmap->n) idx[i] = j;
3085:       }
3086:     }
3087:     for (j = 0; j < ncols; j++) {
3088:       if (PetscRealPart(x[i]) < PetscRealPart(*aa)) {
3089:         x[i] = *aa;
3090:         if (idx) idx[i] = *aj;
3091:       }
3092:       aa++;
3093:       aj++;
3094:     }
3095:   }
3096:   VecRestoreArrayWrite(v, &x);
3097:   MatSeqAIJRestoreArrayRead(A, &av);
3098:   return 0;
3099: }

3101: PetscErrorCode MatGetRowMinAbs_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3102: {
3103:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3104:   PetscInt         i, j, m = A->rmap->n, *ai, *aj, ncols, n;
3105:   PetscScalar     *x;
3106:   const MatScalar *aa, *av;

3108:   MatSeqAIJGetArrayRead(A, &av);
3109:   aa = av;
3110:   ai = a->i;
3111:   aj = a->j;

3113:   VecSet(v, 0.0);
3114:   VecGetArrayWrite(v, &x);
3115:   VecGetLocalSize(v, &n);
3117:   for (i = 0; i < m; i++) {
3118:     ncols = ai[1] - ai[0];
3119:     ai++;
3120:     if (ncols == A->cmap->n) { /* row is dense */
3121:       x[i] = *aa;
3122:       if (idx) idx[i] = 0;
3123:     } else { /* row is sparse so already KNOW minimum is 0.0 or higher */
3124:       x[i] = 0.0;
3125:       if (idx) { /* find first implicit 0.0 in the row */
3126:         for (j = 0; j < ncols; j++) {
3127:           if (aj[j] > j) {
3128:             idx[i] = j;
3129:             break;
3130:           }
3131:         }
3132:         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3133:         if (j == ncols && j < A->cmap->n) idx[i] = j;
3134:       }
3135:     }
3136:     for (j = 0; j < ncols; j++) {
3137:       if (PetscAbsScalar(x[i]) > PetscAbsScalar(*aa)) {
3138:         x[i] = *aa;
3139:         if (idx) idx[i] = *aj;
3140:       }
3141:       aa++;
3142:       aj++;
3143:     }
3144:   }
3145:   VecRestoreArrayWrite(v, &x);
3146:   MatSeqAIJRestoreArrayRead(A, &av);
3147:   return 0;
3148: }

3150: PetscErrorCode MatGetRowMin_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3151: {
3152:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3153:   PetscInt         i, j, m = A->rmap->n, ncols, n;
3154:   const PetscInt  *ai, *aj;
3155:   PetscScalar     *x;
3156:   const MatScalar *aa, *av;

3159:   MatSeqAIJGetArrayRead(A, &av);
3160:   aa = av;
3161:   ai = a->i;
3162:   aj = a->j;

3164:   VecSet(v, 0.0);
3165:   VecGetArrayWrite(v, &x);
3166:   VecGetLocalSize(v, &n);
3168:   for (i = 0; i < m; i++) {
3169:     ncols = ai[1] - ai[0];
3170:     ai++;
3171:     if (ncols == A->cmap->n) { /* row is dense */
3172:       x[i] = *aa;
3173:       if (idx) idx[i] = 0;
3174:     } else { /* row is sparse so already KNOW minimum is 0.0 or lower */
3175:       x[i] = 0.0;
3176:       if (idx) { /* find first implicit 0.0 in the row */
3177:         for (j = 0; j < ncols; j++) {
3178:           if (aj[j] > j) {
3179:             idx[i] = j;
3180:             break;
3181:           }
3182:         }
3183:         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3184:         if (j == ncols && j < A->cmap->n) idx[i] = j;
3185:       }
3186:     }
3187:     for (j = 0; j < ncols; j++) {
3188:       if (PetscRealPart(x[i]) > PetscRealPart(*aa)) {
3189:         x[i] = *aa;
3190:         if (idx) idx[i] = *aj;
3191:       }
3192:       aa++;
3193:       aj++;
3194:     }
3195:   }
3196:   VecRestoreArrayWrite(v, &x);
3197:   MatSeqAIJRestoreArrayRead(A, &av);
3198:   return 0;
3199: }

3201: PetscErrorCode MatInvertBlockDiagonal_SeqAIJ(Mat A, const PetscScalar **values)
3202: {
3203:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
3204:   PetscInt        i, bs = PetscAbs(A->rmap->bs), mbs = A->rmap->n / bs, ipvt[5], bs2 = bs * bs, *v_pivots, ij[7], *IJ, j;
3205:   MatScalar      *diag, work[25], *v_work;
3206:   const PetscReal shift = 0.0;
3207:   PetscBool       allowzeropivot, zeropivotdetected = PETSC_FALSE;

3209:   allowzeropivot = PetscNot(A->erroriffailure);
3210:   if (a->ibdiagvalid) {
3211:     if (values) *values = a->ibdiag;
3212:     return 0;
3213:   }
3214:   MatMarkDiagonal_SeqAIJ(A);
3215:   if (!a->ibdiag) { PetscMalloc1(bs2 * mbs, &a->ibdiag); }
3216:   diag = a->ibdiag;
3217:   if (values) *values = a->ibdiag;
3218:   /* factor and invert each block */
3219:   switch (bs) {
3220:   case 1:
3221:     for (i = 0; i < mbs; i++) {
3222:       MatGetValues(A, 1, &i, 1, &i, diag + i);
3223:       if (PetscAbsScalar(diag[i] + shift) < PETSC_MACHINE_EPSILON) {
3224:         if (allowzeropivot) {
3225:           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3226:           A->factorerror_zeropivot_value = PetscAbsScalar(diag[i]);
3227:           A->factorerror_zeropivot_row   = i;
3228:           PetscInfo(A, "Zero pivot, row %" PetscInt_FMT " pivot %g tolerance %g\n", i, (double)PetscAbsScalar(diag[i]), (double)PETSC_MACHINE_EPSILON);
3229:         } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_MAT_LU_ZRPVT, "Zero pivot, row %" PetscInt_FMT " pivot %g tolerance %g", i, (double)PetscAbsScalar(diag[i]), (double)PETSC_MACHINE_EPSILON);
3230:       }
3231:       diag[i] = (PetscScalar)1.0 / (diag[i] + shift);
3232:     }
3233:     break;
3234:   case 2:
3235:     for (i = 0; i < mbs; i++) {
3236:       ij[0] = 2 * i;
3237:       ij[1] = 2 * i + 1;
3238:       MatGetValues(A, 2, ij, 2, ij, diag);
3239:       PetscKernel_A_gets_inverse_A_2(diag, shift, allowzeropivot, &zeropivotdetected);
3240:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3241:       PetscKernel_A_gets_transpose_A_2(diag);
3242:       diag += 4;
3243:     }
3244:     break;
3245:   case 3:
3246:     for (i = 0; i < mbs; i++) {
3247:       ij[0] = 3 * i;
3248:       ij[1] = 3 * i + 1;
3249:       ij[2] = 3 * i + 2;
3250:       MatGetValues(A, 3, ij, 3, ij, diag);
3251:       PetscKernel_A_gets_inverse_A_3(diag, shift, allowzeropivot, &zeropivotdetected);
3252:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3253:       PetscKernel_A_gets_transpose_A_3(diag);
3254:       diag += 9;
3255:     }
3256:     break;
3257:   case 4:
3258:     for (i = 0; i < mbs; i++) {
3259:       ij[0] = 4 * i;
3260:       ij[1] = 4 * i + 1;
3261:       ij[2] = 4 * i + 2;
3262:       ij[3] = 4 * i + 3;
3263:       MatGetValues(A, 4, ij, 4, ij, diag);
3264:       PetscKernel_A_gets_inverse_A_4(diag, shift, allowzeropivot, &zeropivotdetected);
3265:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3266:       PetscKernel_A_gets_transpose_A_4(diag);
3267:       diag += 16;
3268:     }
3269:     break;
3270:   case 5:
3271:     for (i = 0; i < mbs; i++) {
3272:       ij[0] = 5 * i;
3273:       ij[1] = 5 * i + 1;
3274:       ij[2] = 5 * i + 2;
3275:       ij[3] = 5 * i + 3;
3276:       ij[4] = 5 * i + 4;
3277:       MatGetValues(A, 5, ij, 5, ij, diag);
3278:       PetscKernel_A_gets_inverse_A_5(diag, ipvt, work, shift, allowzeropivot, &zeropivotdetected);
3279:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3280:       PetscKernel_A_gets_transpose_A_5(diag);
3281:       diag += 25;
3282:     }
3283:     break;
3284:   case 6:
3285:     for (i = 0; i < mbs; i++) {
3286:       ij[0] = 6 * i;
3287:       ij[1] = 6 * i + 1;
3288:       ij[2] = 6 * i + 2;
3289:       ij[3] = 6 * i + 3;
3290:       ij[4] = 6 * i + 4;
3291:       ij[5] = 6 * i + 5;
3292:       MatGetValues(A, 6, ij, 6, ij, diag);
3293:       PetscKernel_A_gets_inverse_A_6(diag, shift, allowzeropivot, &zeropivotdetected);
3294:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3295:       PetscKernel_A_gets_transpose_A_6(diag);
3296:       diag += 36;
3297:     }
3298:     break;
3299:   case 7:
3300:     for (i = 0; i < mbs; i++) {
3301:       ij[0] = 7 * i;
3302:       ij[1] = 7 * i + 1;
3303:       ij[2] = 7 * i + 2;
3304:       ij[3] = 7 * i + 3;
3305:       ij[4] = 7 * i + 4;
3306:       ij[5] = 7 * i + 5;
3307:       ij[6] = 7 * i + 6;
3308:       MatGetValues(A, 7, ij, 7, ij, diag);
3309:       PetscKernel_A_gets_inverse_A_7(diag, shift, allowzeropivot, &zeropivotdetected);
3310:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3311:       PetscKernel_A_gets_transpose_A_7(diag);
3312:       diag += 49;
3313:     }
3314:     break;
3315:   default:
3316:     PetscMalloc3(bs, &v_work, bs, &v_pivots, bs, &IJ);
3317:     for (i = 0; i < mbs; i++) {
3318:       for (j = 0; j < bs; j++) IJ[j] = bs * i + j;
3319:       MatGetValues(A, bs, IJ, bs, IJ, diag);
3320:       PetscKernel_A_gets_inverse_A(bs, diag, v_pivots, v_work, allowzeropivot, &zeropivotdetected);
3321:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3322:       PetscKernel_A_gets_transpose_A_N(diag, bs);
3323:       diag += bs2;
3324:     }
3325:     PetscFree3(v_work, v_pivots, IJ);
3326:   }
3327:   a->ibdiagvalid = PETSC_TRUE;
3328:   return 0;
3329: }

3331: static PetscErrorCode MatSetRandom_SeqAIJ(Mat x, PetscRandom rctx)
3332: {
3333:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)x->data;
3334:   PetscScalar a, *aa;
3335:   PetscInt    m, n, i, j, col;

3337:   if (!x->assembled) {
3338:     MatGetSize(x, &m, &n);
3339:     for (i = 0; i < m; i++) {
3340:       for (j = 0; j < aij->imax[i]; j++) {
3341:         PetscRandomGetValue(rctx, &a);
3342:         col = (PetscInt)(n * PetscRealPart(a));
3343:         MatSetValues(x, 1, &i, 1, &col, &a, ADD_VALUES);
3344:       }
3345:     }
3346:   } else {
3347:     MatSeqAIJGetArrayWrite(x, &aa);
3348:     for (i = 0; i < aij->nz; i++) PetscRandomGetValue(rctx, aa + i);
3349:     MatSeqAIJRestoreArrayWrite(x, &aa);
3350:   }
3351:   MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);
3352:   MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);
3353:   return 0;
3354: }

3356: /* Like MatSetRandom_SeqAIJ, but do not set values on columns in range of [low, high) */
3357: PetscErrorCode MatSetRandomSkipColumnRange_SeqAIJ_Private(Mat x, PetscInt low, PetscInt high, PetscRandom rctx)
3358: {
3359:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)x->data;
3360:   PetscScalar a;
3361:   PetscInt    m, n, i, j, col, nskip;

3363:   nskip = high - low;
3364:   MatGetSize(x, &m, &n);
3365:   n -= nskip; /* shrink number of columns where nonzeros can be set */
3366:   for (i = 0; i < m; i++) {
3367:     for (j = 0; j < aij->imax[i]; j++) {
3368:       PetscRandomGetValue(rctx, &a);
3369:       col = (PetscInt)(n * PetscRealPart(a));
3370:       if (col >= low) col += nskip; /* shift col rightward to skip the hole */
3371:       MatSetValues(x, 1, &i, 1, &col, &a, ADD_VALUES);
3372:     }
3373:   }
3374:   MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);
3375:   MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);
3376:   return 0;
3377: }

3379: /* -------------------------------------------------------------------*/
3380: static struct _MatOps MatOps_Values = {MatSetValues_SeqAIJ,
3381:                                        MatGetRow_SeqAIJ,
3382:                                        MatRestoreRow_SeqAIJ,
3383:                                        MatMult_SeqAIJ,
3384:                                        /*  4*/ MatMultAdd_SeqAIJ,
3385:                                        MatMultTranspose_SeqAIJ,
3386:                                        MatMultTransposeAdd_SeqAIJ,
3387:                                        NULL,
3388:                                        NULL,
3389:                                        NULL,
3390:                                        /* 10*/ NULL,
3391:                                        MatLUFactor_SeqAIJ,
3392:                                        NULL,
3393:                                        MatSOR_SeqAIJ,
3394:                                        MatTranspose_SeqAIJ,
3395:                                        /*1 5*/ MatGetInfo_SeqAIJ,
3396:                                        MatEqual_SeqAIJ,
3397:                                        MatGetDiagonal_SeqAIJ,
3398:                                        MatDiagonalScale_SeqAIJ,
3399:                                        MatNorm_SeqAIJ,
3400:                                        /* 20*/ NULL,
3401:                                        MatAssemblyEnd_SeqAIJ,
3402:                                        MatSetOption_SeqAIJ,
3403:                                        MatZeroEntries_SeqAIJ,
3404:                                        /* 24*/ MatZeroRows_SeqAIJ,
3405:                                        NULL,
3406:                                        NULL,
3407:                                        NULL,
3408:                                        NULL,
3409:                                        /* 29*/ MatSetUp_SeqAIJ,
3410:                                        NULL,
3411:                                        NULL,
3412:                                        NULL,
3413:                                        NULL,
3414:                                        /* 34*/ MatDuplicate_SeqAIJ,
3415:                                        NULL,
3416:                                        NULL,
3417:                                        MatILUFactor_SeqAIJ,
3418:                                        NULL,
3419:                                        /* 39*/ MatAXPY_SeqAIJ,
3420:                                        MatCreateSubMatrices_SeqAIJ,
3421:                                        MatIncreaseOverlap_SeqAIJ,
3422:                                        MatGetValues_SeqAIJ,
3423:                                        MatCopy_SeqAIJ,
3424:                                        /* 44*/ MatGetRowMax_SeqAIJ,
3425:                                        MatScale_SeqAIJ,
3426:                                        MatShift_SeqAIJ,
3427:                                        MatDiagonalSet_SeqAIJ,
3428:                                        MatZeroRowsColumns_SeqAIJ,
3429:                                        /* 49*/ MatSetRandom_SeqAIJ,
3430:                                        MatGetRowIJ_SeqAIJ,
3431:                                        MatRestoreRowIJ_SeqAIJ,
3432:                                        MatGetColumnIJ_SeqAIJ,
3433:                                        MatRestoreColumnIJ_SeqAIJ,
3434:                                        /* 54*/ MatFDColoringCreate_SeqXAIJ,
3435:                                        NULL,
3436:                                        NULL,
3437:                                        MatPermute_SeqAIJ,
3438:                                        NULL,
3439:                                        /* 59*/ NULL,
3440:                                        MatDestroy_SeqAIJ,
3441:                                        MatView_SeqAIJ,
3442:                                        NULL,
3443:                                        NULL,
3444:                                        /* 64*/ NULL,
3445:                                        MatMatMatMultNumeric_SeqAIJ_SeqAIJ_SeqAIJ,
3446:                                        NULL,
3447:                                        NULL,
3448:                                        NULL,
3449:                                        /* 69*/ MatGetRowMaxAbs_SeqAIJ,
3450:                                        MatGetRowMinAbs_SeqAIJ,
3451:                                        NULL,
3452:                                        NULL,
3453:                                        NULL,
3454:                                        /* 74*/ NULL,
3455:                                        MatFDColoringApply_AIJ,
3456:                                        NULL,
3457:                                        NULL,
3458:                                        NULL,
3459:                                        /* 79*/ MatFindZeroDiagonals_SeqAIJ,
3460:                                        NULL,
3461:                                        NULL,
3462:                                        NULL,
3463:                                        MatLoad_SeqAIJ,
3464:                                        /* 84*/ MatIsSymmetric_SeqAIJ,
3465:                                        MatIsHermitian_SeqAIJ,
3466:                                        NULL,
3467:                                        NULL,
3468:                                        NULL,
3469:                                        /* 89*/ NULL,
3470:                                        NULL,
3471:                                        MatMatMultNumeric_SeqAIJ_SeqAIJ,
3472:                                        NULL,
3473:                                        NULL,
3474:                                        /* 94*/ MatPtAPNumeric_SeqAIJ_SeqAIJ_SparseAxpy,
3475:                                        NULL,
3476:                                        NULL,
3477:                                        MatMatTransposeMultNumeric_SeqAIJ_SeqAIJ,
3478:                                        NULL,
3479:                                        /* 99*/ MatProductSetFromOptions_SeqAIJ,
3480:                                        NULL,
3481:                                        NULL,
3482:                                        MatConjugate_SeqAIJ,
3483:                                        NULL,
3484:                                        /*104*/ MatSetValuesRow_SeqAIJ,
3485:                                        MatRealPart_SeqAIJ,
3486:                                        MatImaginaryPart_SeqAIJ,
3487:                                        NULL,
3488:                                        NULL,
3489:                                        /*109*/ MatMatSolve_SeqAIJ,
3490:                                        NULL,
3491:                                        MatGetRowMin_SeqAIJ,
3492:                                        NULL,
3493:                                        MatMissingDiagonal_SeqAIJ,
3494:                                        /*114*/ NULL,
3495:                                        NULL,
3496:                                        NULL,
3497:                                        NULL,
3498:                                        NULL,
3499:                                        /*119*/ NULL,
3500:                                        NULL,
3501:                                        NULL,
3502:                                        NULL,
3503:                                        MatGetMultiProcBlock_SeqAIJ,
3504:                                        /*124*/ MatFindNonzeroRows_SeqAIJ,
3505:                                        MatGetColumnReductions_SeqAIJ,
3506:                                        MatInvertBlockDiagonal_SeqAIJ,
3507:                                        MatInvertVariableBlockDiagonal_SeqAIJ,
3508:                                        NULL,
3509:                                        /*129*/ NULL,
3510:                                        NULL,
3511:                                        NULL,
3512:                                        MatTransposeMatMultNumeric_SeqAIJ_SeqAIJ,
3513:                                        MatTransposeColoringCreate_SeqAIJ,
3514:                                        /*134*/ MatTransColoringApplySpToDen_SeqAIJ,
3515:                                        MatTransColoringApplyDenToSp_SeqAIJ,
3516:                                        NULL,
3517:                                        NULL,
3518:                                        MatRARtNumeric_SeqAIJ_SeqAIJ,
3519:                                        /*139*/ NULL,
3520:                                        NULL,
3521:                                        NULL,
3522:                                        MatFDColoringSetUp_SeqXAIJ,
3523:                                        MatFindOffBlockDiagonalEntries_SeqAIJ,
3524:                                        MatCreateMPIMatConcatenateSeqMat_SeqAIJ,
3525:                                        /*145*/ MatDestroySubMatrices_SeqAIJ,
3526:                                        NULL,
3527:                                        NULL,
3528:                                        MatCreateGraph_Simple_AIJ,
3529:                                        NULL,
3530:                                        /*150*/ MatTransposeSymbolic_SeqAIJ};

3532: PetscErrorCode MatSeqAIJSetColumnIndices_SeqAIJ(Mat mat, PetscInt *indices)
3533: {
3534:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3535:   PetscInt    i, nz, n;

3537:   nz = aij->maxnz;
3538:   n  = mat->rmap->n;
3539:   for (i = 0; i < nz; i++) aij->j[i] = indices[i];
3540:   aij->nz = nz;
3541:   for (i = 0; i < n; i++) aij->ilen[i] = aij->imax[i];
3542:   return 0;
3543: }

3545: /*
3546:  * Given a sparse matrix with global column indices, compact it by using a local column space.
3547:  * The result matrix helps saving memory in other algorithms, such as MatPtAPSymbolic_MPIAIJ_MPIAIJ_scalable()
3548:  */
3549: PetscErrorCode MatSeqAIJCompactOutExtraColumns_SeqAIJ(Mat mat, ISLocalToGlobalMapping *mapping)
3550: {
3551:   Mat_SeqAIJ        *aij = (Mat_SeqAIJ *)mat->data;
3552:   PetscTable         gid1_lid1;
3553:   PetscTablePosition tpos;
3554:   PetscInt           gid, lid, i, ec, nz = aij->nz;
3555:   PetscInt          *garray, *jj = aij->j;

3559:   /* use a table */
3560:   PetscTableCreate(mat->rmap->n, mat->cmap->N + 1, &gid1_lid1);
3561:   ec = 0;
3562:   for (i = 0; i < nz; i++) {
3563:     PetscInt data, gid1 = jj[i] + 1;
3564:     PetscTableFind(gid1_lid1, gid1, &data);
3565:     if (!data) {
3566:       /* one based table */
3567:       PetscTableAdd(gid1_lid1, gid1, ++ec, INSERT_VALUES);
3568:     }
3569:   }
3570:   /* form array of columns we need */
3571:   PetscMalloc1(ec, &garray);
3572:   PetscTableGetHeadPosition(gid1_lid1, &tpos);
3573:   while (tpos) {
3574:     PetscTableGetNext(gid1_lid1, &tpos, &gid, &lid);
3575:     gid--;
3576:     lid--;
3577:     garray[lid] = gid;
3578:   }
3579:   PetscSortInt(ec, garray); /* sort, and rebuild */
3580:   PetscTableRemoveAll(gid1_lid1);
3581:   for (i = 0; i < ec; i++) PetscTableAdd(gid1_lid1, garray[i] + 1, i + 1, INSERT_VALUES);
3582:   /* compact out the extra columns in B */
3583:   for (i = 0; i < nz; i++) {
3584:     PetscInt gid1 = jj[i] + 1;
3585:     PetscTableFind(gid1_lid1, gid1, &lid);
3586:     lid--;
3587:     jj[i] = lid;
3588:   }
3589:   PetscLayoutDestroy(&mat->cmap);
3590:   PetscTableDestroy(&gid1_lid1);
3591:   PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)mat), ec, ec, 1, &mat->cmap);
3592:   ISLocalToGlobalMappingCreate(PETSC_COMM_SELF, mat->cmap->bs, mat->cmap->n, garray, PETSC_OWN_POINTER, mapping);
3593:   ISLocalToGlobalMappingSetType(*mapping, ISLOCALTOGLOBALMAPPINGHASH);
3594:   return 0;
3595: }

3597: /*@
3598:     MatSeqAIJSetColumnIndices - Set the column indices for all the rows
3599:        in the matrix.

3601:   Input Parameters:
3602: +  mat - the `MATSEQAIJ` matrix
3603: -  indices - the column indices

3605:   Level: advanced

3607:   Notes:
3608:     This can be called if you have precomputed the nonzero structure of the
3609:   matrix and want to provide it to the matrix object to improve the performance
3610:   of the `MatSetValues()` operation.

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

3615:     MUST be called before any calls to `MatSetValues()`

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

3619: @*/
3620: PetscErrorCode MatSeqAIJSetColumnIndices(Mat mat, PetscInt *indices)
3621: {
3624:   PetscUseMethod(mat, "MatSeqAIJSetColumnIndices_C", (Mat, PetscInt *), (mat, indices));
3625:   return 0;
3626: }

3628: /* ----------------------------------------------------------------------------------------*/

3630: PetscErrorCode MatStoreValues_SeqAIJ(Mat mat)
3631: {
3632:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3633:   size_t      nz  = aij->i[mat->rmap->n];


3637:   /* allocate space for values if not already there */
3638:   if (!aij->saved_values) { PetscMalloc1(nz + 1, &aij->saved_values); }

3640:   /* copy values over */
3641:   PetscArraycpy(aij->saved_values, aij->a, nz);
3642:   return 0;
3643: }

3645: /*@
3646:     MatStoreValues - Stashes a copy of the matrix values; this allows, for
3647:        example, reuse of the linear part of a Jacobian, while recomputing the
3648:        nonlinear portion.

3650:    Logically Collect

3652:   Input Parameters:
3653: .  mat - the matrix (currently only `MATAIJ` matrices support this option)

3655:   Level: advanced

3657:   Common Usage, with `SNESSolve()`:
3658: $    Create Jacobian matrix
3659: $    Set linear terms into matrix
3660: $    Apply boundary conditions to matrix, at this time matrix must have
3661: $      final nonzero structure (i.e. setting the nonlinear terms and applying
3662: $      boundary conditions again will not change the nonzero structure
3663: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3664: $    MatStoreValues(mat);
3665: $    Call SNESSetJacobian() with matrix
3666: $    In your Jacobian routine
3667: $      MatRetrieveValues(mat);
3668: $      Set nonlinear terms in matrix

3670:   Common Usage without SNESSolve(), i.e. when you handle nonlinear solve yourself:
3671: $    // build linear portion of Jacobian
3672: $    MatSetOption(mat,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);
3673: $    MatStoreValues(mat);
3674: $    loop over nonlinear iterations
3675: $       MatRetrieveValues(mat);
3676: $       // call MatSetValues(mat,...) to set nonliner portion of Jacobian
3677: $       // call MatAssemblyBegin/End() on matrix
3678: $       Solve linear system with Jacobian
3679: $    endloop

3681:   Notes:
3682:     Matrix must already be assemblied before calling this routine
3683:     Must set the matrix option `MatSetOption`(mat,`MAT_NEW_NONZERO_LOCATIONS`,`PETSC_FALSE`); before
3684:     calling this routine.

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

3689: .seealso: `MatRetrieveValues()`
3690: @*/
3691: PetscErrorCode MatStoreValues(Mat mat)
3692: {
3696:   PetscUseMethod(mat, "MatStoreValues_C", (Mat), (mat));
3697:   return 0;
3698: }

3700: PetscErrorCode MatRetrieveValues_SeqAIJ(Mat mat)
3701: {
3702:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3703:   PetscInt    nz  = aij->i[mat->rmap->n];

3707:   /* copy values over */
3708:   PetscArraycpy(aij->a, aij->saved_values, nz);
3709:   return 0;
3710: }

3712: /*@
3713:     MatRetrieveValues - Retrieves the copy of the matrix values; this allows, for
3714:        example, reuse of the linear part of a Jacobian, while recomputing the
3715:        nonlinear portion.

3717:    Logically Collect

3719:   Input Parameters:
3720: .  mat - the matrix (currently only `MATAIJ` matrices support this option)

3722:   Level: advanced

3724: .seealso: `MatStoreValues()`
3725: @*/
3726: PetscErrorCode MatRetrieveValues(Mat mat)
3727: {
3731:   PetscUseMethod(mat, "MatRetrieveValues_C", (Mat), (mat));
3732:   return 0;
3733: }

3735: /* --------------------------------------------------------------------------------*/
3736: /*@C
3737:    MatCreateSeqAIJ - Creates a sparse matrix in `MATSEQAIJ` (compressed row) format
3738:    (the default parallel PETSc format).  For good matrix assembly performance
3739:    the user should preallocate the matrix storage by setting the parameter nz
3740:    (or the array nnz).  By setting these parameters accurately, performance
3741:    during matrix assembly can be increased by more than a factor of 50.

3743:    Collective

3745:    Input Parameters:
3746: +  comm - MPI communicator, set to `PETSC_COMM_SELF`
3747: .  m - number of rows
3748: .  n - number of columns
3749: .  nz - number of nonzeros per row (same for all rows)
3750: -  nnz - array containing the number of nonzeros in the various rows
3751:          (possibly different for each row) or NULL

3753:    Output Parameter:
3754: .  A - the matrix

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

3760:    Notes:
3761:    If nnz is given then nz is ignored

3763:    The AIJ format, also called
3764:    compressed row storage, is fully compatible with standard Fortran 77
3765:    storage.  That is, the stored row and column indices can begin at
3766:    either one (as in Fortran) or zero.  See the users' manual for details.

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

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

3778:    Options Database Keys:
3779: +  -mat_no_inode  - Do not use inodes
3780: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3782:    Level: intermediate

3784: .seealso: [Sparse Matrix Creation](sec_matsparse), `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`
3785: @*/
3786: PetscErrorCode MatCreateSeqAIJ(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A)
3787: {
3788:   MatCreate(comm, A);
3789:   MatSetSizes(*A, m, n, m, n);
3790:   MatSetType(*A, MATSEQAIJ);
3791:   MatSeqAIJSetPreallocation_SeqAIJ(*A, nz, nnz);
3792:   return 0;
3793: }

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

3801:    Collective

3803:    Input Parameters:
3804: +  B - The matrix
3805: .  nz - number of nonzeros per row (same for all rows)
3806: -  nnz - array containing the number of nonzeros in the various rows
3807:          (possibly different for each row) or NULL

3809:    Notes:
3810:      If nnz is given then nz is ignored

3812:     The `MATSEQAIJ` format also called
3813:    compressed row storage, is fully compatible with standard Fortran 77
3814:    storage.  That is, the stored row and column indices can begin at
3815:    either one (as in Fortran) or zero.  See the users' manual for details.

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

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

3827:    Developer Notes:
3828:    Use nz of `MAT_SKIP_ALLOCATION` to not allocate any space for the matrix
3829:    entries or columns indices

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

3836:    Options Database Keys:
3837: +  -mat_no_inode  - Do not use inodes
3838: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3840:    Level: intermediate

3842: .seealso: `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`, `MatGetInfo()`,
3843:           `MatSeqAIJSetTotalPreallocation()`
3844: @*/
3845: PetscErrorCode MatSeqAIJSetPreallocation(Mat B, PetscInt nz, const PetscInt nnz[])
3846: {
3849:   PetscTryMethod(B, "MatSeqAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[]), (B, nz, nnz));
3850:   return 0;
3851: }

3853: PetscErrorCode MatSeqAIJSetPreallocation_SeqAIJ(Mat B, PetscInt nz, const PetscInt *nnz)
3854: {
3855:   Mat_SeqAIJ *b;
3856:   PetscBool   skipallocation = PETSC_FALSE, realalloc = PETSC_FALSE;
3857:   PetscInt    i;

3859:   if (nz >= 0 || nnz) realalloc = PETSC_TRUE;
3860:   if (nz == MAT_SKIP_ALLOCATION) {
3861:     skipallocation = PETSC_TRUE;
3862:     nz             = 0;
3863:   }
3864:   PetscLayoutSetUp(B->rmap);
3865:   PetscLayoutSetUp(B->cmap);

3867:   if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 5;
3869:   if (PetscUnlikelyDebug(nnz)) {
3870:     for (i = 0; i < B->rmap->n; i++) {
3873:     }
3874:   }

3876:   B->preallocated = PETSC_TRUE;

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

3880:   if (!skipallocation) {
3881:     if (!b->imax) { PetscMalloc1(B->rmap->n, &b->imax); }
3882:     if (!b->ilen) {
3883:       /* b->ilen will count nonzeros in each row so far. */
3884:       PetscCalloc1(B->rmap->n, &b->ilen);
3885:     } else {
3886:       PetscMemzero(b->ilen, B->rmap->n * sizeof(PetscInt));
3887:     }
3888:     if (!b->ipre) { PetscMalloc1(B->rmap->n, &b->ipre); }
3889:     if (!nnz) {
3890:       if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 10;
3891:       else if (nz < 0) nz = 1;
3892:       nz = PetscMin(nz, B->cmap->n);
3893:       for (i = 0; i < B->rmap->n; i++) b->imax[i] = nz;
3894:       nz = nz * B->rmap->n;
3895:     } else {
3896:       PetscInt64 nz64 = 0;
3897:       for (i = 0; i < B->rmap->n; i++) {
3898:         b->imax[i] = nnz[i];
3899:         nz64 += nnz[i];
3900:       }
3901:       PetscIntCast(nz64, &nz);
3902:     }

3904:     /* allocate the matrix space */
3905:     /* FIXME: should B's old memory be unlogged? */
3906:     MatSeqXAIJFreeAIJ(B, &b->a, &b->j, &b->i);
3907:     if (B->structure_only) {
3908:       PetscMalloc1(nz, &b->j);
3909:       PetscMalloc1(B->rmap->n + 1, &b->i);
3910:     } else {
3911:       PetscMalloc3(nz, &b->a, nz, &b->j, B->rmap->n + 1, &b->i);
3912:     }
3913:     b->i[0] = 0;
3914:     for (i = 1; i < B->rmap->n + 1; i++) b->i[i] = b->i[i - 1] + b->imax[i - 1];
3915:     if (B->structure_only) {
3916:       b->singlemalloc = PETSC_FALSE;
3917:       b->free_a       = PETSC_FALSE;
3918:     } else {
3919:       b->singlemalloc = PETSC_TRUE;
3920:       b->free_a       = PETSC_TRUE;
3921:     }
3922:     b->free_ij = PETSC_TRUE;
3923:   } else {
3924:     b->free_a  = PETSC_FALSE;
3925:     b->free_ij = PETSC_FALSE;
3926:   }

3928:   if (b->ipre && nnz != b->ipre && b->imax) {
3929:     /* reserve user-requested sparsity */
3930:     PetscArraycpy(b->ipre, b->imax, B->rmap->n);
3931:   }

3933:   b->nz               = 0;
3934:   b->maxnz            = nz;
3935:   B->info.nz_unneeded = (double)b->maxnz;
3936:   if (realalloc) MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE);
3937:   B->was_assembled = PETSC_FALSE;
3938:   B->assembled     = PETSC_FALSE;
3939:   /* We simply deem preallocation has changed nonzero state. Updating the state
3940:      will give clients (like AIJKokkos) a chance to know something has happened.
3941:   */
3942:   B->nonzerostate++;
3943:   return 0;
3944: }

3946: PetscErrorCode MatResetPreallocation_SeqAIJ(Mat A)
3947: {
3948:   Mat_SeqAIJ *a;
3949:   PetscInt    i;


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

3956:   a = (Mat_SeqAIJ *)A->data;
3957:   /* if no saved info, we error out */


3962:   PetscArraycpy(a->imax, a->ipre, A->rmap->n);
3963:   PetscArrayzero(a->ilen, A->rmap->n);
3964:   a->i[0] = 0;
3965:   for (i = 1; i < A->rmap->n + 1; i++) a->i[i] = a->i[i - 1] + a->imax[i - 1];
3966:   A->preallocated     = PETSC_TRUE;
3967:   a->nz               = 0;
3968:   a->maxnz            = a->i[A->rmap->n];
3969:   A->info.nz_unneeded = (double)a->maxnz;
3970:   A->was_assembled    = PETSC_FALSE;
3971:   A->assembled        = PETSC_FALSE;
3972:   return 0;
3973: }

3975: /*@
3976:    MatSeqAIJSetPreallocationCSR - Allocates memory for a sparse sequential matrix in `MATSEQAIJ` format.

3978:    Input Parameters:
3979: +  B - the matrix
3980: .  i - the indices into j for the start of each row (starts with zero)
3981: .  j - the column indices for each row (starts with zero) these must be sorted for each row
3982: -  v - optional values in the matrix

3984:    Level: developer

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

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

3992:     Developer Notes:
3993:       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
3994:       then just copies the v values directly with `PetscMemcpy()`.

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

3998: .seealso: `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatSeqAIJSetPreallocation()`, `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MatResetPreallocation()`
3999: @*/
4000: PetscErrorCode MatSeqAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
4001: {
4004:   PetscTryMethod(B, "MatSeqAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
4005:   return 0;
4006: }

4008: PetscErrorCode MatSeqAIJSetPreallocationCSR_SeqAIJ(Mat B, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
4009: {
4010:   PetscInt  i;
4011:   PetscInt  m, n;
4012:   PetscInt  nz;
4013:   PetscInt *nnz;


4017:   PetscLayoutSetUp(B->rmap);
4018:   PetscLayoutSetUp(B->cmap);

4020:   MatGetSize(B, &m, &n);
4021:   PetscMalloc1(m + 1, &nnz);
4022:   for (i = 0; i < m; i++) {
4023:     nz = Ii[i + 1] - Ii[i];
4025:     nnz[i] = nz;
4026:   }
4027:   MatSeqAIJSetPreallocation(B, 0, nnz);
4028:   PetscFree(nnz);

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

4032:   MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY);
4033:   MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY);

4035:   MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE);
4036:   return 0;
4037: }

4039: /*@
4040:    MatSeqAIJKron - Computes C, the Kronecker product of A and B.

4042:    Input Parameters:
4043: +  A - left-hand side matrix
4044: .  B - right-hand side matrix
4045: -  reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

4047:    Output Parameter:
4048: .  C - Kronecker product of A and B

4050:    Level: intermediate

4052:    Note:
4053:       `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the product matrix has not changed from that last call to `MatSeqAIJKron()`.

4055: .seealso: `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MATKAIJ`, `MatReuse`
4056: @*/
4057: PetscErrorCode MatSeqAIJKron(Mat A, Mat B, MatReuse reuse, Mat *C)
4058: {
4064:   if (reuse == MAT_REUSE_MATRIX) {
4067:   }
4068:   PetscTryMethod(A, "MatSeqAIJKron_C", (Mat, Mat, MatReuse, Mat *), (A, B, reuse, C));
4069:   return 0;
4070: }

4072: PetscErrorCode MatSeqAIJKron_SeqAIJ(Mat A, Mat B, MatReuse reuse, Mat *C)
4073: {
4074:   Mat                newmat;
4075:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
4076:   Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;
4077:   PetscScalar       *v;
4078:   const PetscScalar *aa, *ba;
4079:   PetscInt          *i, *j, m, n, p, q, nnz = 0, am = A->rmap->n, bm = B->rmap->n, an = A->cmap->n, bn = B->cmap->n;
4080:   PetscBool          flg;

4086:   PetscObjectTypeCompare((PetscObject)B, MATSEQAIJ, &flg);
4089:   if (reuse == MAT_INITIAL_MATRIX) {
4090:     PetscMalloc2(am * bm + 1, &i, a->i[am] * b->i[bm], &j);
4091:     MatCreate(PETSC_COMM_SELF, &newmat);
4092:     MatSetSizes(newmat, am * bm, an * bn, am * bm, an * bn);
4093:     MatSetType(newmat, MATAIJ);
4094:     i[0] = 0;
4095:     for (m = 0; m < am; ++m) {
4096:       for (p = 0; p < bm; ++p) {
4097:         i[m * bm + p + 1] = i[m * bm + p] + (a->i[m + 1] - a->i[m]) * (b->i[p + 1] - b->i[p]);
4098:         for (n = a->i[m]; n < a->i[m + 1]; ++n) {
4099:           for (q = b->i[p]; q < b->i[p + 1]; ++q) j[nnz++] = a->j[n] * bn + b->j[q];
4100:         }
4101:       }
4102:     }
4103:     MatSeqAIJSetPreallocationCSR(newmat, i, j, NULL);
4104:     *C = newmat;
4105:     PetscFree2(i, j);
4106:     nnz = 0;
4107:   }
4108:   MatSeqAIJGetArray(*C, &v);
4109:   MatSeqAIJGetArrayRead(A, &aa);
4110:   MatSeqAIJGetArrayRead(B, &ba);
4111:   for (m = 0; m < am; ++m) {
4112:     for (p = 0; p < bm; ++p) {
4113:       for (n = a->i[m]; n < a->i[m + 1]; ++n) {
4114:         for (q = b->i[p]; q < b->i[p + 1]; ++q) v[nnz++] = aa[n] * ba[q];
4115:       }
4116:     }
4117:   }
4118:   MatSeqAIJRestoreArray(*C, &v);
4119:   MatSeqAIJRestoreArrayRead(A, &aa);
4120:   MatSeqAIJRestoreArrayRead(B, &ba);
4121:   return 0;
4122: }

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

4127: /*
4128:     Computes (B'*A')' since computing B*A directly is untenable

4130:                n                       p                          p
4131:         [             ]       [             ]         [                 ]
4132:       m [      A      ]  *  n [       B     ]   =   m [         C       ]
4133:         [             ]       [             ]         [                 ]

4135: */
4136: PetscErrorCode MatMatMultNumeric_SeqDense_SeqAIJ(Mat A, Mat B, Mat C)
4137: {
4138:   Mat_SeqDense      *sub_a = (Mat_SeqDense *)A->data;
4139:   Mat_SeqAIJ        *sub_b = (Mat_SeqAIJ *)B->data;
4140:   Mat_SeqDense      *sub_c = (Mat_SeqDense *)C->data;
4141:   PetscInt           i, j, n, m, q, p;
4142:   const PetscInt    *ii, *idx;
4143:   const PetscScalar *b, *a, *a_q;
4144:   PetscScalar       *c, *c_q;
4145:   PetscInt           clda = sub_c->lda;
4146:   PetscInt           alda = sub_a->lda;

4148:   m = A->rmap->n;
4149:   n = A->cmap->n;
4150:   p = B->cmap->n;
4151:   a = sub_a->v;
4152:   b = sub_b->a;
4153:   c = sub_c->v;
4154:   if (clda == m) {
4155:     PetscArrayzero(c, m * p);
4156:   } else {
4157:     for (j = 0; j < p; j++)
4158:       for (i = 0; i < m; i++) c[j * clda + i] = 0.0;
4159:   }
4160:   ii  = sub_b->i;
4161:   idx = sub_b->j;
4162:   for (i = 0; i < n; i++) {
4163:     q = ii[i + 1] - ii[i];
4164:     while (q-- > 0) {
4165:       c_q = c + clda * (*idx);
4166:       a_q = a + alda * i;
4167:       PetscKernelAXPY(c_q, *b, a_q, m);
4168:       idx++;
4169:       b++;
4170:     }
4171:   }
4172:   return 0;
4173: }

4175: PetscErrorCode MatMatMultSymbolic_SeqDense_SeqAIJ(Mat A, Mat B, PetscReal fill, Mat C)
4176: {
4177:   PetscInt  m = A->rmap->n, n = B->cmap->n;
4178:   PetscBool cisdense;

4181:   MatSetSizes(C, m, n, m, n);
4182:   MatSetBlockSizesFromMats(C, A, B);
4183:   PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSECUDA, "");
4184:   if (!cisdense) MatSetType(C, MATDENSE);
4185:   MatSetUp(C);

4187:   C->ops->matmultnumeric = MatMatMultNumeric_SeqDense_SeqAIJ;
4188:   return 0;
4189: }

4191: /* ----------------------------------------------------------------*/
4192: /*MC
4193:    MATSEQAIJ - MATSEQAIJ = "seqaij" - A matrix type to be used for sequential sparse matrices,
4194:    based on compressed sparse row format.

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

4199:    Level: beginner

4201:    Notes:
4202:     `MatSetValues()` may be called for this matrix type with a NULL argument for the numerical values,
4203:     in this case the values associated with the rows and columns one passes in are set to zero
4204:     in the matrix

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

4209:   Developer Note:
4210:     It would be nice if all matrix formats supported passing NULL in for the numerical values

4212: .seealso: `MatCreateSeqAIJ()`, `MatSetFromOptions()`, `MatSetType()`, `MatCreate()`, `MatType`, `MATSELL`, `MATSEQSELL`, `MATMPISELL`
4213: M*/

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

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

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

4227:    Note:
4228:    Subclasses include `MATAIJCUSPARSE`, `MATAIJPERM`, `MATAIJSELL`, `MATAIJMKL`, `MATAIJCRL`, and also automatically switches over to use inodes when
4229:    enough exist.

4231:   Level: beginner

4233: .seealso: `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MATMPIAIJ`, `MATSELL`, `MATSEQSELL`, `MATMPISELL`
4234: M*/

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

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

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

4248:   Level: beginner

4250: .seealso: `MatCreateMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`
4251: M*/

4253: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCRL(Mat, MatType, MatReuse, Mat *);
4254: #if defined(PETSC_HAVE_ELEMENTAL)
4255: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
4256: #endif
4257: #if defined(PETSC_HAVE_SCALAPACK)
4258: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
4259: #endif
4260: #if defined(PETSC_HAVE_HYPRE)
4261: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat A, MatType, MatReuse, Mat *);
4262: #endif

4264: PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqSELL(Mat, MatType, MatReuse, Mat *);
4265: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
4266: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);

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

4271:    Not Collective

4273:    Input Parameter:
4274: .  mat - a `MATSEQAIJ` matrix

4276:    Output Parameter:
4277: .   array - pointer to the data

4279:    Level: intermediate

4281: .seealso: `MatSeqAIJRestoreArray()`, `MatSeqAIJGetArrayF90()`
4282: @*/
4283: PetscErrorCode MatSeqAIJGetArray(Mat A, PetscScalar **array)
4284: {
4285:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4287:   if (aij->ops->getarray) {
4288:     (*aij->ops->getarray)(A, array);
4289:   } else {
4290:     *array = aij->a;
4291:   }
4292:   return 0;
4293: }

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

4298:    Not Collective

4300:    Input Parameters:
4301: +  mat - a `MATSEQAIJ` matrix
4302: -  array - pointer to the data

4304:    Level: intermediate

4306: .seealso: `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayF90()`
4307: @*/
4308: PetscErrorCode MatSeqAIJRestoreArray(Mat A, PetscScalar **array)
4309: {
4310:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4312:   if (aij->ops->restorearray) {
4313:     (*aij->ops->restorearray)(A, array);
4314:   } else {
4315:     *array = NULL;
4316:   }
4317:   MatSeqAIJInvalidateDiagonal(A);
4318:   PetscObjectStateIncrease((PetscObject)A);
4319:   return 0;
4320: }

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

4325:    Not Collective

4327:    Input Parameter:
4328: .  mat - a `MATSEQAIJ` matrix

4330:    Output Parameter:
4331: .   array - pointer to the data

4333:    Level: intermediate

4335: .seealso: `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayRead()`
4336: @*/
4337: PetscErrorCode MatSeqAIJGetArrayRead(Mat A, const PetscScalar **array)
4338: {
4339:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4341:   if (aij->ops->getarrayread) {
4342:     (*aij->ops->getarrayread)(A, array);
4343:   } else {
4344:     *array = aij->a;
4345:   }
4346:   return 0;
4347: }

4349: /*@C
4350:    MatSeqAIJRestoreArrayRead - restore the read-only access array obtained from `MatSeqAIJGetArrayRead()`

4352:    Not Collective

4354:    Input Parameter:
4355: .  mat - a `MATSEQAIJ` matrix

4357:    Output Parameter:
4358: .   array - pointer to the data

4360:    Level: intermediate

4362: .seealso: `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4363: @*/
4364: PetscErrorCode MatSeqAIJRestoreArrayRead(Mat A, const PetscScalar **array)
4365: {
4366:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4368:   if (aij->ops->restorearrayread) {
4369:     (*aij->ops->restorearrayread)(A, array);
4370:   } else {
4371:     *array = NULL;
4372:   }
4373:   return 0;
4374: }

4376: /*@C
4377:    MatSeqAIJGetArrayWrite - gives write-only access to the array where the data for a `MATSEQAIJ` matrix is stored

4379:    Not Collective

4381:    Input Parameter:
4382: .  mat - a `MATSEQAIJ` matrix

4384:    Output Parameter:
4385: .   array - pointer to the data

4387:    Level: intermediate

4389: .seealso: `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayRead()`
4390: @*/
4391: PetscErrorCode MatSeqAIJGetArrayWrite(Mat A, PetscScalar **array)
4392: {
4393:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4395:   if (aij->ops->getarraywrite) {
4396:     (*aij->ops->getarraywrite)(A, array);
4397:   } else {
4398:     *array = aij->a;
4399:   }
4400:   MatSeqAIJInvalidateDiagonal(A);
4401:   PetscObjectStateIncrease((PetscObject)A);
4402:   return 0;
4403: }

4405: /*@C
4406:    MatSeqAIJRestoreArrayWrite - restore the read-only access array obtained from MatSeqAIJGetArrayRead

4408:    Not Collective

4410:    Input Parameter:
4411: .  mat - a MATSEQAIJ matrix

4413:    Output Parameter:
4414: .   array - pointer to the data

4416:    Level: intermediate

4418: .seealso: `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4419: @*/
4420: PetscErrorCode MatSeqAIJRestoreArrayWrite(Mat A, PetscScalar **array)
4421: {
4422:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4424:   if (aij->ops->restorearraywrite) {
4425:     (*aij->ops->restorearraywrite)(A, array);
4426:   } else {
4427:     *array = NULL;
4428:   }
4429:   return 0;
4430: }

4432: /*@C
4433:    MatSeqAIJGetCSRAndMemType - Get the CSR arrays and the memory type of the `MATSEQAIJ` matrix

4435:    Not Collective

4437:    Input Parameter:
4438: .  mat - a matrix of type `MATSEQAIJ` or its subclasses

4440:    Output Parameters:
4441: +  i - row map array of the matrix
4442: .  j - column index array of the matrix
4443: .  a - data array of the matrix
4444: -  memtype - memory type of the arrays

4446:   Notes:
4447:    Any of the output parameters can be NULL, in which case the corresponding value is not returned.
4448:    If mat is a device matrix, the arrays are on the device. Otherwise, they are on the host.

4450:    One can call this routine on a preallocated but not assembled matrix to just get the memory of the CSR underneath the matrix.
4451:    If the matrix is assembled, the data array 'a' is guaranteed to have the latest values of the matrix.

4453:    Level: Developer

4455: .seealso: `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4456: @*/
4457: PetscErrorCode MatSeqAIJGetCSRAndMemType(Mat mat, const PetscInt **i, const PetscInt **j, PetscScalar **a, PetscMemType *mtype)
4458: {
4459:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;

4462:   if (aij->ops->getcsrandmemtype) {
4463:     (*aij->ops->getcsrandmemtype)(mat, i, j, a, mtype);
4464:   } else {
4465:     if (i) *i = aij->i;
4466:     if (j) *j = aij->j;
4467:     if (a) *a = aij->a;
4468:     if (mtype) *mtype = PETSC_MEMTYPE_HOST;
4469:   }
4470:   return 0;
4471: }

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

4476:    Not Collective

4478:    Input Parameter:
4479: .  mat - a `MATSEQAIJ` matrix

4481:    Output Parameter:
4482: .   nz - the maximum number of nonzeros in any row

4484:    Level: intermediate

4486: .seealso: `MatSeqAIJRestoreArray()`, `MatSeqAIJGetArrayF90()`
4487: @*/
4488: PetscErrorCode MatSeqAIJGetMaxRowNonzeros(Mat A, PetscInt *nz)
4489: {
4490:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4492:   *nz = aij->rmax;
4493:   return 0;
4494: }

4496: PetscErrorCode MatSetPreallocationCOO_SeqAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
4497: {
4498:   MPI_Comm     comm;
4499:   PetscInt    *i, *j;
4500:   PetscInt     M, N, row;
4501:   PetscCount   k, p, q, nneg, nnz, start, end; /* Index the coo array, so use PetscCount as their type */
4502:   PetscInt    *Ai;                             /* Change to PetscCount once we use it for row pointers */
4503:   PetscInt    *Aj;
4504:   PetscScalar *Aa;
4505:   Mat_SeqAIJ  *seqaij = (Mat_SeqAIJ *)(mat->data);
4506:   MatType      rtype;
4507:   PetscCount  *perm, *jmap;

4509:   MatResetPreallocationCOO_SeqAIJ(mat);
4510:   PetscObjectGetComm((PetscObject)mat, &comm);
4511:   MatGetSize(mat, &M, &N);
4512:   i = coo_i;
4513:   j = coo_j;
4514:   PetscMalloc1(coo_n, &perm);
4515:   for (k = 0; k < coo_n; k++) { /* Ignore entries with negative row or col indices */
4516:     if (j[k] < 0) i[k] = -1;
4517:     perm[k] = k;
4518:   }

4520:   /* Sort by row */
4521:   PetscSortIntWithIntCountArrayPair(coo_n, i, j, perm);
4522:   for (k = 0; k < coo_n; k++) {
4523:     if (i[k] >= 0) break;
4524:   } /* Advance k to the first row with a non-negative index */
4525:   nneg = k;
4526:   PetscMalloc1(coo_n - nneg + 1, &jmap); /* +1 to make a CSR-like data structure. jmap[i] originally is the number of repeats for i-th nonzero */
4527:   nnz = 0;                                          /* Total number of unique nonzeros to be counted */
4528:   jmap++;                                           /* Inc jmap by 1 for convenience */

4530:   PetscCalloc1(M + 1, &Ai);        /* CSR of A */
4531:   PetscMalloc1(coo_n - nneg, &Aj); /* We have at most coo_n-nneg unique nonzeros */

4533:   /* In each row, sort by column, then unique column indices to get row length */
4534:   Ai++;  /* Inc by 1 for convenience */
4535:   q = 0; /* q-th unique nonzero, with q starting from 0 */
4536:   while (k < coo_n) {
4537:     row   = i[k];
4538:     start = k; /* [start,end) indices for this row */
4539:     while (k < coo_n && i[k] == row) k++;
4540:     end = k;
4541:     PetscSortIntWithCountArray(end - start, j + start, perm + start);
4542:     /* Find number of unique col entries in this row */
4543:     Aj[q]   = j[start]; /* Log the first nonzero in this row */
4544:     jmap[q] = 1;        /* Number of repeats of this nozero entry */
4545:     Ai[row] = 1;
4546:     nnz++;

4548:     for (p = start + 1; p < end; p++) { /* Scan remaining nonzero in this row */
4549:       if (j[p] != j[p - 1]) {           /* Meet a new nonzero */
4550:         q++;
4551:         jmap[q] = 1;
4552:         Aj[q]   = j[p];
4553:         Ai[row]++;
4554:         nnz++;
4555:       } else {
4556:         jmap[q]++;
4557:       }
4558:     }
4559:     q++; /* Move to next row and thus next unique nonzero */
4560:   }

4562:   Ai--; /* Back to the beginning of Ai[] */
4563:   for (k = 0; k < M; k++) Ai[k + 1] += Ai[k];
4564:   jmap--; /* Back to the beginning of jmap[] */
4565:   jmap[0] = 0;
4566:   for (k = 0; k < nnz; k++) jmap[k + 1] += jmap[k];
4567:   if (nnz < coo_n - nneg) { /* Realloc with actual number of unique nonzeros */
4568:     PetscCount *jmap_new;
4569:     PetscInt   *Aj_new;

4571:     PetscMalloc1(nnz + 1, &jmap_new);
4572:     PetscArraycpy(jmap_new, jmap, nnz + 1);
4573:     PetscFree(jmap);
4574:     jmap = jmap_new;

4576:     PetscMalloc1(nnz, &Aj_new);
4577:     PetscArraycpy(Aj_new, Aj, nnz);
4578:     PetscFree(Aj);
4579:     Aj = Aj_new;
4580:   }

4582:   if (nneg) { /* Discard heading entries with negative indices in perm[], as we'll access it from index 0 in MatSetValuesCOO */
4583:     PetscCount *perm_new;

4585:     PetscMalloc1(coo_n - nneg, &perm_new);
4586:     PetscArraycpy(perm_new, perm + nneg, coo_n - nneg);
4587:     PetscFree(perm);
4588:     perm = perm_new;
4589:   }

4591:   MatGetRootType_Private(mat, &rtype);
4592:   PetscCalloc1(nnz, &Aa); /* Zero the matrix */
4593:   MatSetSeqAIJWithArrays_private(PETSC_COMM_SELF, M, N, Ai, Aj, Aa, rtype, mat);

4595:   seqaij->singlemalloc = PETSC_FALSE;            /* Ai, Aj and Aa are not allocated in one big malloc */
4596:   seqaij->free_a = seqaij->free_ij = PETSC_TRUE; /* Let newmat own Ai, Aj and Aa */
4597:   /* Record COO fields */
4598:   seqaij->coo_n = coo_n;
4599:   seqaij->Atot  = coo_n - nneg; /* Annz is seqaij->nz, so no need to record that again */
4600:   seqaij->jmap  = jmap;         /* of length nnz+1 */
4601:   seqaij->perm  = perm;
4602:   return 0;
4603: }

4605: static PetscErrorCode MatSetValuesCOO_SeqAIJ(Mat A, const PetscScalar v[], InsertMode imode)
4606: {
4607:   Mat_SeqAIJ  *aseq = (Mat_SeqAIJ *)A->data;
4608:   PetscCount   i, j, Annz = aseq->nz;
4609:   PetscCount  *perm = aseq->perm, *jmap = aseq->jmap;
4610:   PetscScalar *Aa;

4612:   MatSeqAIJGetArray(A, &Aa);
4613:   for (i = 0; i < Annz; i++) {
4614:     PetscScalar sum = 0.0;
4615:     for (j = jmap[i]; j < jmap[i + 1]; j++) sum += v[perm[j]];
4616:     Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
4617:   }
4618:   MatSeqAIJRestoreArray(A, &Aa);
4619:   return 0;
4620: }

4622: #if defined(PETSC_HAVE_CUDA)
4623: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
4624: #endif
4625: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
4626: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJKokkos(Mat, MatType, MatReuse, Mat *);
4627: #endif

4629: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJ(Mat B)
4630: {
4631:   Mat_SeqAIJ *b;
4632:   PetscMPIInt size;

4634:   MPI_Comm_size(PetscObjectComm((PetscObject)B), &size);

4637:   PetscNew(&b);

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

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

4644:   b->row                = NULL;
4645:   b->col                = NULL;
4646:   b->icol               = NULL;
4647:   b->reallocs           = 0;
4648:   b->ignorezeroentries  = PETSC_FALSE;
4649:   b->roworiented        = PETSC_TRUE;
4650:   b->nonew              = 0;
4651:   b->diag               = NULL;
4652:   b->solve_work         = NULL;
4653:   B->spptr              = NULL;
4654:   b->saved_values       = NULL;
4655:   b->idiag              = NULL;
4656:   b->mdiag              = NULL;
4657:   b->ssor_work          = NULL;
4658:   b->omega              = 1.0;
4659:   b->fshift             = 0.0;
4660:   b->idiagvalid         = PETSC_FALSE;
4661:   b->ibdiagvalid        = PETSC_FALSE;
4662:   b->keepnonzeropattern = PETSC_FALSE;

4664:   PetscObjectChangeTypeName((PetscObject)B, MATSEQAIJ);
4665: #if defined(PETSC_HAVE_MATLAB)
4666:   PetscObjectComposeFunction((PetscObject)B, "PetscMatlabEnginePut_C", MatlabEnginePut_SeqAIJ);
4667:   PetscObjectComposeFunction((PetscObject)B, "PetscMatlabEngineGet_C", MatlabEngineGet_SeqAIJ);
4668: #endif
4669:   PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetColumnIndices_C", MatSeqAIJSetColumnIndices_SeqAIJ);
4670:   PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_SeqAIJ);
4671:   PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_SeqAIJ);
4672:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqsbaij_C", MatConvert_SeqAIJ_SeqSBAIJ);
4673:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqbaij_C", MatConvert_SeqAIJ_SeqBAIJ);
4674:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijperm_C", MatConvert_SeqAIJ_SeqAIJPERM);
4675:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijsell_C", MatConvert_SeqAIJ_SeqAIJSELL);
4676: #if defined(PETSC_HAVE_MKL_SPARSE)
4677:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijmkl_C", MatConvert_SeqAIJ_SeqAIJMKL);
4678: #endif
4679: #if defined(PETSC_HAVE_CUDA)
4680:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijcusparse_C", MatConvert_SeqAIJ_SeqAIJCUSPARSE);
4681:   PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaijcusparse_seqaij_C", MatProductSetFromOptions_SeqAIJ);
4682:   PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaijcusparse_C", MatProductSetFromOptions_SeqAIJ);
4683: #endif
4684: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
4685:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijkokkos_C", MatConvert_SeqAIJ_SeqAIJKokkos);
4686: #endif
4687:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijcrl_C", MatConvert_SeqAIJ_SeqAIJCRL);
4688: #if defined(PETSC_HAVE_ELEMENTAL)
4689:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_elemental_C", MatConvert_SeqAIJ_Elemental);
4690: #endif
4691: #if defined(PETSC_HAVE_SCALAPACK)
4692:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_scalapack_C", MatConvert_AIJ_ScaLAPACK);
4693: #endif
4694: #if defined(PETSC_HAVE_HYPRE)
4695:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_hypre_C", MatConvert_AIJ_HYPRE);
4696:   PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_seqaij_seqaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ);
4697: #endif
4698:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqdense_C", MatConvert_SeqAIJ_SeqDense);
4699:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqsell_C", MatConvert_SeqAIJ_SeqSELL);
4700:   PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_is_C", MatConvert_XAIJ_IS);
4701:   PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_SeqAIJ);
4702:   PetscObjectComposeFunction((PetscObject)B, "MatIsHermitianTranspose_C", MatIsTranspose_SeqAIJ);
4703:   PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetPreallocation_C", MatSeqAIJSetPreallocation_SeqAIJ);
4704:   PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_SeqAIJ);
4705:   PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetPreallocationCSR_C", MatSeqAIJSetPreallocationCSR_SeqAIJ);
4706:   PetscObjectComposeFunction((PetscObject)B, "MatReorderForNonzeroDiagonal_C", MatReorderForNonzeroDiagonal_SeqAIJ);
4707:   PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_seqaij_C", MatProductSetFromOptions_IS_XAIJ);
4708:   PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdense_seqaij_C", MatProductSetFromOptions_SeqDense_SeqAIJ);
4709:   PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaij_C", MatProductSetFromOptions_SeqAIJ);
4710:   PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJKron_C", MatSeqAIJKron_SeqAIJ);
4711:   PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_SeqAIJ);
4712:   PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_SeqAIJ);
4713:   MatCreate_SeqAIJ_Inode(B);
4714:   PetscObjectChangeTypeName((PetscObject)B, MATSEQAIJ);
4715:   MatSeqAIJSetTypeFromOptions(B); /* this allows changing the matrix subtype to say MATSEQAIJPERM */
4716:   return 0;
4717: }

4719: /*
4720:     Given a matrix generated with MatGetFactor() duplicates all the information in A into C
4721: */
4722: PetscErrorCode MatDuplicateNoCreate_SeqAIJ(Mat C, Mat A, MatDuplicateOption cpvalues, PetscBool mallocmatspace)
4723: {
4724:   Mat_SeqAIJ *c = (Mat_SeqAIJ *)C->data, *a = (Mat_SeqAIJ *)A->data;
4725:   PetscInt    m = A->rmap->n, i;


4729:   C->factortype = A->factortype;
4730:   c->row        = NULL;
4731:   c->col        = NULL;
4732:   c->icol       = NULL;
4733:   c->reallocs   = 0;

4735:   C->assembled    = A->assembled;
4736:   C->preallocated = A->preallocated;

4738:   if (A->preallocated) {
4739:     PetscLayoutReference(A->rmap, &C->rmap);
4740:     PetscLayoutReference(A->cmap, &C->cmap);

4742:     PetscMalloc1(m, &c->imax);
4743:     PetscMemcpy(c->imax, a->imax, m * sizeof(PetscInt));
4744:     PetscMalloc1(m, &c->ilen);
4745:     PetscMemcpy(c->ilen, a->ilen, m * sizeof(PetscInt));

4747:     /* allocate the matrix space */
4748:     if (mallocmatspace) {
4749:       PetscMalloc3(a->i[m], &c->a, a->i[m], &c->j, m + 1, &c->i);

4751:       c->singlemalloc = PETSC_TRUE;

4753:       PetscArraycpy(c->i, a->i, m + 1);
4754:       if (m > 0) {
4755:         PetscArraycpy(c->j, a->j, a->i[m]);
4756:         if (cpvalues == MAT_COPY_VALUES) {
4757:           const PetscScalar *aa;

4759:           MatSeqAIJGetArrayRead(A, &aa);
4760:           PetscArraycpy(c->a, aa, a->i[m]);
4761:           MatSeqAIJGetArrayRead(A, &aa);
4762:         } else {
4763:           PetscArrayzero(c->a, a->i[m]);
4764:         }
4765:       }
4766:     }

4768:     c->ignorezeroentries = a->ignorezeroentries;
4769:     c->roworiented       = a->roworiented;
4770:     c->nonew             = a->nonew;
4771:     if (a->diag) {
4772:       PetscMalloc1(m + 1, &c->diag);
4773:       PetscMemcpy(c->diag, a->diag, m * sizeof(PetscInt));
4774:     } else c->diag = NULL;

4776:     c->solve_work         = NULL;
4777:     c->saved_values       = NULL;
4778:     c->idiag              = NULL;
4779:     c->ssor_work          = NULL;
4780:     c->keepnonzeropattern = a->keepnonzeropattern;
4781:     c->free_a             = PETSC_TRUE;
4782:     c->free_ij            = PETSC_TRUE;

4784:     c->rmax  = a->rmax;
4785:     c->nz    = a->nz;
4786:     c->maxnz = a->nz; /* Since we allocate exactly the right amount */

4788:     c->compressedrow.use   = a->compressedrow.use;
4789:     c->compressedrow.nrows = a->compressedrow.nrows;
4790:     if (a->compressedrow.use) {
4791:       i = a->compressedrow.nrows;
4792:       PetscMalloc2(i + 1, &c->compressedrow.i, i, &c->compressedrow.rindex);
4793:       PetscArraycpy(c->compressedrow.i, a->compressedrow.i, i + 1);
4794:       PetscArraycpy(c->compressedrow.rindex, a->compressedrow.rindex, i);
4795:     } else {
4796:       c->compressedrow.use    = PETSC_FALSE;
4797:       c->compressedrow.i      = NULL;
4798:       c->compressedrow.rindex = NULL;
4799:     }
4800:     c->nonzerorowcnt = a->nonzerorowcnt;
4801:     C->nonzerostate  = A->nonzerostate;

4803:     MatDuplicate_SeqAIJ_Inode(A, cpvalues, &C);
4804:   }
4805:   PetscFunctionListDuplicate(((PetscObject)A)->qlist, &((PetscObject)C)->qlist);
4806:   return 0;
4807: }

4809: PetscErrorCode MatDuplicate_SeqAIJ(Mat A, MatDuplicateOption cpvalues, Mat *B)
4810: {
4811:   MatCreate(PetscObjectComm((PetscObject)A), B);
4812:   MatSetSizes(*B, A->rmap->n, A->cmap->n, A->rmap->n, A->cmap->n);
4813:   if (!(A->rmap->n % A->rmap->bs) && !(A->cmap->n % A->cmap->bs)) MatSetBlockSizesFromMats(*B, A, A);
4814:   MatSetType(*B, ((PetscObject)A)->type_name);
4815:   MatDuplicateNoCreate_SeqAIJ(*B, A, cpvalues, PETSC_TRUE);
4816:   return 0;
4817: }

4819: PetscErrorCode MatLoad_SeqAIJ(Mat newMat, PetscViewer viewer)
4820: {
4821:   PetscBool isbinary, ishdf5;

4825:   /* force binary viewer to load .info file if it has not yet done so */
4826:   PetscViewerSetUp(viewer);
4827:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary);
4828:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
4829:   if (isbinary) {
4830:     MatLoad_SeqAIJ_Binary(newMat, viewer);
4831:   } else if (ishdf5) {
4832: #if defined(PETSC_HAVE_HDF5)
4833:     MatLoad_AIJ_HDF5(newMat, viewer);
4834: #else
4835:     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
4836: #endif
4837:   } else {
4838:     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "Viewer type %s not yet supported for reading %s matrices", ((PetscObject)viewer)->type_name, ((PetscObject)newMat)->type_name);
4839:   }
4840:   return 0;
4841: }

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

4848:   PetscViewerSetUp(viewer);

4850:   /* read in matrix header */
4851:   PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT);
4853:   M  = header[1];
4854:   N  = header[2];
4855:   nz = header[3];

4860:   /* set block sizes from the viewer's .info file */
4861:   MatLoad_Binary_BlockSizes(mat, viewer);
4862:   /* set local and global sizes if not set already */
4863:   if (mat->rmap->n < 0) mat->rmap->n = M;
4864:   if (mat->cmap->n < 0) mat->cmap->n = N;
4865:   if (mat->rmap->N < 0) mat->rmap->N = M;
4866:   if (mat->cmap->N < 0) mat->cmap->N = N;
4867:   PetscLayoutSetUp(mat->rmap);
4868:   PetscLayoutSetUp(mat->cmap);

4870:   /* check if the matrix sizes are correct */
4871:   MatGetSize(mat, &rows, &cols);

4874:   /* read in row lengths */
4875:   PetscMalloc1(M, &rowlens);
4876:   PetscViewerBinaryRead(viewer, rowlens, M, NULL, PETSC_INT);
4877:   /* check if sum(rowlens) is same as nz */
4878:   sum = 0;
4879:   for (i = 0; i < M; i++) sum += rowlens[i];
4881:   /* preallocate and check sizes */
4882:   MatSeqAIJSetPreallocation_SeqAIJ(mat, 0, rowlens);
4883:   MatGetSize(mat, &rows, &cols);
4885:   /* store row lengths */
4886:   PetscArraycpy(a->ilen, rowlens, M);
4887:   PetscFree(rowlens);

4889:   /* fill in "i" row pointers */
4890:   a->i[0] = 0;
4891:   for (i = 0; i < M; i++) a->i[i + 1] = a->i[i] + a->ilen[i];
4892:   /* read in "j" column indices */
4893:   PetscViewerBinaryRead(viewer, a->j, nz, NULL, PETSC_INT);
4894:   /* read in "a" nonzero values */
4895:   PetscViewerBinaryRead(viewer, a->a, nz, NULL, PETSC_SCALAR);

4897:   MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY);
4898:   MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY);
4899:   return 0;
4900: }

4902: PetscErrorCode MatEqual_SeqAIJ(Mat A, Mat B, PetscBool *flg)
4903: {
4904:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)B->data;
4905:   const PetscScalar *aa, *ba;
4906: #if defined(PETSC_USE_COMPLEX)
4907:   PetscInt k;
4908: #endif

4910:   /* If the  matrix dimensions are not equal,or no of nonzeros */
4911:   if ((A->rmap->n != B->rmap->n) || (A->cmap->n != B->cmap->n) || (a->nz != b->nz)) {
4912:     *flg = PETSC_FALSE;
4913:     return 0;
4914:   }

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

4920:   /* if a->j are the same */
4921:   PetscArraycmp(a->j, b->j, a->nz, flg);
4922:   if (!*flg) return 0;

4924:   MatSeqAIJGetArrayRead(A, &aa);
4925:   MatSeqAIJGetArrayRead(B, &ba);
4926:   /* if a->a are the same */
4927: #if defined(PETSC_USE_COMPLEX)
4928:   for (k = 0; k < a->nz; k++) {
4929:     if (PetscRealPart(aa[k]) != PetscRealPart(ba[k]) || PetscImaginaryPart(aa[k]) != PetscImaginaryPart(ba[k])) {
4930:       *flg = PETSC_FALSE;
4931:       return 0;
4932:     }
4933:   }
4934: #else
4935:   PetscArraycmp(aa, ba, a->nz, flg);
4936: #endif
4937:   MatSeqAIJRestoreArrayRead(A, &aa);
4938:   MatSeqAIJRestoreArrayRead(B, &ba);
4939:   return 0;
4940: }

4942: /*@
4943:      MatCreateSeqAIJWithArrays - Creates an sequential `MATSEQAIJ` matrix using matrix elements (in CSR format)
4944:               provided by the user.

4946:       Collective

4948:    Input Parameters:
4949: +   comm - must be an MPI communicator of size 1
4950: .   m - number of rows
4951: .   n - number of columns
4952: .   i - row indices; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
4953: .   j - column indices
4954: -   a - matrix values

4956:    Output Parameter:
4957: .   mat - the matrix

4959:    Level: intermediate

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

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

4967:        The i and j indices are 0 based

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

4973: $        1 0 0
4974: $        2 0 3
4975: $        4 5 6
4976: $
4977: $        i =  {0,1,3,6}  [size = nrow+1  = 3+1]
4978: $        j =  {0,0,2,0,1,2}  [size = 6]; values must be sorted for each row
4979: $        v =  {1,2,3,4,5,6}  [size = 6]

4981: .seealso: `MatCreate()`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MatCreateMPIAIJWithArrays()`, `MatMPIAIJSetPreallocationCSR()`
4982: @*/
4983: PetscErrorCode MatCreateSeqAIJWithArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt i[], PetscInt j[], PetscScalar a[], Mat *mat)
4984: {
4985:   PetscInt    ii;
4986:   Mat_SeqAIJ *aij;
4987:   PetscInt    jj;

4990:   MatCreate(comm, mat);
4991:   MatSetSizes(*mat, m, n, m, n);
4992:   /* MatSetBlockSizes(*mat,,); */
4993:   MatSetType(*mat, MATSEQAIJ);
4994:   MatSeqAIJSetPreallocation_SeqAIJ(*mat, MAT_SKIP_ALLOCATION, NULL);
4995:   aij = (Mat_SeqAIJ *)(*mat)->data;
4996:   PetscMalloc1(m, &aij->imax);
4997:   PetscMalloc1(m, &aij->ilen);

4999:   aij->i            = i;
5000:   aij->j            = j;
5001:   aij->a            = a;
5002:   aij->singlemalloc = PETSC_FALSE;
5003:   aij->nonew        = -1; /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
5004:   aij->free_a       = PETSC_FALSE;
5005:   aij->free_ij      = PETSC_FALSE;

5007:   for (ii = 0, aij->nonzerorowcnt = 0, aij->rmax = 0; ii < m; ii++) {
5008:     aij->ilen[ii] = aij->imax[ii] = i[ii + 1] - i[ii];
5009:     if (PetscDefined(USE_DEBUG)) {
5011:       for (jj = i[ii] + 1; jj < i[ii + 1]; jj++) {
5014:       }
5015:     }
5016:   }
5017:   if (PetscDefined(USE_DEBUG)) {
5018:     for (ii = 0; ii < aij->i[m]; ii++) {
5021:     }
5022:   }

5024:   MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY);
5025:   MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY);
5026:   return 0;
5027: }

5029: /*@
5030:      MatCreateSeqAIJFromTriple - Creates an sequential `MATSEQAIJ` matrix using matrix elements (in COO format)
5031:               provided by the user.

5033:       Collective

5035:    Input Parameters:
5036: +   comm - must be an MPI communicator of size 1
5037: .   m   - number of rows
5038: .   n   - number of columns
5039: .   i   - row indices
5040: .   j   - column indices
5041: .   a   - matrix values
5042: .   nz  - number of nonzeros
5043: -   idx - if the i and j indices start with 1 use `PETSC_TRUE` otherwise use `PETSC_FALSE`

5045:    Output Parameter:
5046: .   mat - the matrix

5048:    Level: intermediate

5050:    Example:
5051:        For the following matrix, the input data expected is as shown (using 0 based indexing)
5052: .vb
5053:         1 0 0
5054:         2 0 3
5055:         4 5 6

5057:         i =  {0,1,1,2,2,2}
5058:         j =  {0,0,2,0,1,2}
5059:         v =  {1,2,3,4,5,6}
5060: .ve
5061:   Notes:
5062:     Instead of using this function, users should also consider `MatSetPreallocationCOO()` and `MatSetValuesCOO()`, which allow repeated or remote entries,
5063:     and are particularly useful in iterative applications.

5065: .seealso: `MatCreate()`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MatCreateSeqAIJWithArrays()`, `MatMPIAIJSetPreallocationCSR()`, `MatSetValuesCOO()`, `MatSetPreallocationCOO()`
5066: @*/
5067: PetscErrorCode MatCreateSeqAIJFromTriple(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt i[], PetscInt j[], PetscScalar a[], Mat *mat, PetscInt nz, PetscBool idx)
5068: {
5069:   PetscInt ii, *nnz, one = 1, row, col;

5071:   PetscCalloc1(m, &nnz);
5072:   for (ii = 0; ii < nz; ii++) nnz[i[ii] - !!idx] += 1;
5073:   MatCreate(comm, mat);
5074:   MatSetSizes(*mat, m, n, m, n);
5075:   MatSetType(*mat, MATSEQAIJ);
5076:   MatSeqAIJSetPreallocation_SeqAIJ(*mat, 0, nnz);
5077:   for (ii = 0; ii < nz; ii++) {
5078:     if (idx) {
5079:       row = i[ii] - 1;
5080:       col = j[ii] - 1;
5081:     } else {
5082:       row = i[ii];
5083:       col = j[ii];
5084:     }
5085:     MatSetValues(*mat, one, &row, one, &col, &a[ii], ADD_VALUES);
5086:   }
5087:   MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY);
5088:   MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY);
5089:   PetscFree(nnz);
5090:   return 0;
5091: }

5093: PetscErrorCode MatSeqAIJInvalidateDiagonal(Mat A)
5094: {
5095:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

5097:   a->idiagvalid  = PETSC_FALSE;
5098:   a->ibdiagvalid = PETSC_FALSE;

5100:   MatSeqAIJInvalidateDiagonal_Inode(A);
5101:   return 0;
5102: }

5104: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
5105: {
5106:   MatCreateMPIMatConcatenateSeqMat_MPIAIJ(comm, inmat, n, scall, outmat);
5107:   return 0;
5108: }

5110: /*
5111:  Permute A into C's *local* index space using rowemb,colemb.
5112:  The embedding are supposed to be injections and the above implies that the range of rowemb is a subset
5113:  of [0,m), colemb is in [0,n).
5114:  If pattern == DIFFERENT_NONZERO_PATTERN, C is preallocated according to A.
5115:  */
5116: PetscErrorCode MatSetSeqMat_SeqAIJ(Mat C, IS rowemb, IS colemb, MatStructure pattern, Mat B)
5117: {
5118:   /* If making this function public, change the error returned in this function away from _PLIB. */
5119:   Mat_SeqAIJ     *Baij;
5120:   PetscBool       seqaij;
5121:   PetscInt        m, n, *nz, i, j, count;
5122:   PetscScalar     v;
5123:   const PetscInt *rowindices, *colindices;

5125:   if (!B) return 0;
5126:   /* Check to make sure the target matrix (and embeddings) are compatible with C and each other. */
5127:   PetscObjectBaseTypeCompare((PetscObject)B, MATSEQAIJ, &seqaij);
5129:   if (rowemb) {
5130:     ISGetLocalSize(rowemb, &m);
5132:   } else {
5134:   }
5135:   if (colemb) {
5136:     ISGetLocalSize(colemb, &n);
5138:   } else {
5140:   }

5142:   Baij = (Mat_SeqAIJ *)(B->data);
5143:   if (pattern == DIFFERENT_NONZERO_PATTERN) {
5144:     PetscMalloc1(B->rmap->n, &nz);
5145:     for (i = 0; i < B->rmap->n; i++) nz[i] = Baij->i[i + 1] - Baij->i[i];
5146:     MatSeqAIJSetPreallocation(C, 0, nz);
5147:     PetscFree(nz);
5148:   }
5149:   if (pattern == SUBSET_NONZERO_PATTERN) MatZeroEntries(C);
5150:   count      = 0;
5151:   rowindices = NULL;
5152:   colindices = NULL;
5153:   if (rowemb) ISGetIndices(rowemb, &rowindices);
5154:   if (colemb) ISGetIndices(colemb, &colindices);
5155:   for (i = 0; i < B->rmap->n; i++) {
5156:     PetscInt row;
5157:     row = i;
5158:     if (rowindices) row = rowindices[i];
5159:     for (j = Baij->i[i]; j < Baij->i[i + 1]; j++) {
5160:       PetscInt col;
5161:       col = Baij->j[count];
5162:       if (colindices) col = colindices[col];
5163:       v = Baij->a[count];
5164:       MatSetValues(C, 1, &row, 1, &col, &v, INSERT_VALUES);
5165:       ++count;
5166:     }
5167:   }
5168:   /* FIXME: set C's nonzerostate correctly. */
5169:   /* Assembly for C is necessary. */
5170:   C->preallocated  = PETSC_TRUE;
5171:   C->assembled     = PETSC_TRUE;
5172:   C->was_assembled = PETSC_FALSE;
5173:   return 0;
5174: }

5176: PetscFunctionList MatSeqAIJList = NULL;

5178: /*@C
5179:    MatSeqAIJSetType - Converts a `MATSEQAIJ` matrix to a subtype

5181:    Collective

5183:    Input Parameters:
5184: +  mat      - the matrix object
5185: -  matype   - matrix type

5187:    Options Database Key:
5188: .  -mat_seqai_type  <method> - for example seqaijcrl

5190:   Level: intermediate

5192: .seealso: `PCSetType()`, `VecSetType()`, `MatCreate()`, `MatType`, `Mat`
5193: @*/
5194: PetscErrorCode MatSeqAIJSetType(Mat mat, MatType matype)
5195: {
5196:   PetscBool sametype;
5197:   PetscErrorCode (*r)(Mat, MatType, MatReuse, Mat *);

5200:   PetscObjectTypeCompare((PetscObject)mat, matype, &sametype);
5201:   if (sametype) return 0;

5203:   PetscFunctionListFind(MatSeqAIJList, matype, &r);
5205:   (*r)(mat, matype, MAT_INPLACE_MATRIX, &mat);
5206:   return 0;
5207: }

5209: /*@C
5210:   MatSeqAIJRegister -  - Adds a new sub-matrix type for sequential `MATSEQAIJ` matrices

5212:    Not Collective

5214:    Input Parameters:
5215: +  name - name of a new user-defined matrix type, for example `MATSEQAIJCRL`
5216: -  function - routine to convert to subtype

5218:    Notes:
5219:    `MatSeqAIJRegister()` may be called multiple times to add several user-defined solvers.

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

5224:    Level: advanced

5226: .seealso: `MatSeqAIJRegisterAll()`
5227: @*/
5228: PetscErrorCode MatSeqAIJRegister(const char sname[], PetscErrorCode (*function)(Mat, MatType, MatReuse, Mat *))
5229: {
5230:   MatInitializePackage();
5231:   PetscFunctionListAdd(&MatSeqAIJList, sname, function);
5232:   return 0;
5233: }

5235: PetscBool MatSeqAIJRegisterAllCalled = PETSC_FALSE;

5237: /*@C
5238:   MatSeqAIJRegisterAll - Registers all of the matrix subtypes of `MATSSEQAIJ`

5240:   Not Collective

5242:   Level: advanced

5244: .seealso: `MatRegisterAll()`, `MatSeqAIJRegister()`
5245: @*/
5246: PetscErrorCode MatSeqAIJRegisterAll(void)
5247: {
5248:   if (MatSeqAIJRegisterAllCalled) return 0;
5249:   MatSeqAIJRegisterAllCalled = PETSC_TRUE;

5251:   MatSeqAIJRegister(MATSEQAIJCRL, MatConvert_SeqAIJ_SeqAIJCRL);
5252:   MatSeqAIJRegister(MATSEQAIJPERM, MatConvert_SeqAIJ_SeqAIJPERM);
5253:   MatSeqAIJRegister(MATSEQAIJSELL, MatConvert_SeqAIJ_SeqAIJSELL);
5254: #if defined(PETSC_HAVE_MKL_SPARSE)
5255:   MatSeqAIJRegister(MATSEQAIJMKL, MatConvert_SeqAIJ_SeqAIJMKL);
5256: #endif
5257: #if defined(PETSC_HAVE_CUDA)
5258:   MatSeqAIJRegister(MATSEQAIJCUSPARSE, MatConvert_SeqAIJ_SeqAIJCUSPARSE);
5259: #endif
5260: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
5261:   MatSeqAIJRegister(MATSEQAIJKOKKOS, MatConvert_SeqAIJ_SeqAIJKokkos);
5262: #endif
5263: #if defined(PETSC_HAVE_VIENNACL) && defined(PETSC_HAVE_VIENNACL_NO_CUDA)
5264:   MatSeqAIJRegister(MATMPIAIJVIENNACL, MatConvert_SeqAIJ_SeqAIJViennaCL);
5265: #endif
5266:   return 0;
5267: }

5269: /*
5270:     Special version for direct calls from Fortran
5271: */
5272: #include <petsc/private/fortranimpl.h>
5273: #if defined(PETSC_HAVE_FORTRAN_CAPS)
5274:   #define matsetvaluesseqaij_ MATSETVALUESSEQAIJ
5275: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
5276:   #define matsetvaluesseqaij_ matsetvaluesseqaij
5277: #endif

5279: /* Change these macros so can be used in void function */

5281: /* Change these macros so can be used in void function */
5282: /* Identical to PetscCallVoid, except it assigns to *_ierr */
5283: #undef PetscCall
5284: #define PetscCall(...) \
5285:   do { \
5286:     PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
5287:     if (PetscUnlikely(ierr_msv_mpiaij)) { \
5288:       *_PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
5289:       return; \
5290:     } \
5291:   } while (0)

5293: #undef SETERRQ
5294: #define SETERRQ(comm, ierr, ...) \
5295:   do { \
5296:     *_PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
5297:     return; \
5298:   } while (0)

5300: PETSC_EXTERN void matsetvaluesseqaij_(Mat *AA, PetscInt *mm, const PetscInt im[], PetscInt *nn, const PetscInt in[], const PetscScalar v[], InsertMode *isis, PetscErrorCode *_ierr)
5301: {
5302:   Mat         A = *AA;
5303:   PetscInt    m = *mm, n = *nn;
5304:   InsertMode  is = *isis;
5305:   Mat_SeqAIJ *a  = (Mat_SeqAIJ *)A->data;
5306:   PetscInt   *rp, k, low, high, t, ii, row, nrow, i, col, l, rmax, N;
5307:   PetscInt   *imax, *ai, *ailen;
5308:   PetscInt   *aj, nonew = a->nonew, lastcol = -1;
5309:   MatScalar  *ap, value, *aa;
5310:   PetscBool   ignorezeroentries = a->ignorezeroentries;
5311:   PetscBool   roworiented       = a->roworiented;

5313:   MatCheckPreallocated(A, 1);
5314:   imax  = a->imax;
5315:   ai    = a->i;
5316:   ailen = a->ilen;
5317:   aj    = a->j;
5318:   aa    = a->a;

5320:   for (k = 0; k < m; k++) { /* loop over added rows */
5321:     row = im[k];
5322:     if (row < 0) continue;
5324:     rp   = aj + ai[row];
5325:     ap   = aa + ai[row];
5326:     rmax = imax[row];
5327:     nrow = ailen[row];
5328:     low  = 0;
5329:     high = nrow;
5330:     for (l = 0; l < n; l++) { /* loop over added columns */
5331:       if (in[l] < 0) continue;
5333:       col = in[l];
5334:       if (roworiented) value = v[l + k * n];
5335:       else value = v[k + l * m];

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

5339:       if (col <= lastcol) low = 0;
5340:       else high = nrow;
5341:       lastcol = col;
5342:       while (high - low > 5) {
5343:         t = (low + high) / 2;
5344:         if (rp[t] > col) high = t;
5345:         else low = t;
5346:       }
5347:       for (i = low; i < high; i++) {
5348:         if (rp[i] > col) break;
5349:         if (rp[i] == col) {
5350:           if (is == ADD_VALUES) ap[i] += value;
5351:           else ap[i] = value;
5352:           goto noinsert;
5353:         }
5354:       }
5355:       if (value == 0.0 && ignorezeroentries) goto noinsert;
5356:       if (nonew == 1) goto noinsert;
5358:       MatSeqXAIJReallocateAIJ(A, A->rmap->n, 1, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
5359:       N = nrow++ - 1;
5360:       a->nz++;
5361:       high++;
5362:       /* shift up all the later entries in this row */
5363:       for (ii = N; ii >= i; ii--) {
5364:         rp[ii + 1] = rp[ii];
5365:         ap[ii + 1] = ap[ii];
5366:       }
5367:       rp[i] = col;
5368:       ap[i] = value;
5369:       A->nonzerostate++;
5370:     noinsert:;
5371:       low = i + 1;
5372:     }
5373:     ailen[row] = nrow;
5374:   }
5375:   return;
5376: }
5377: /* Undefining these here since they were redefined from their original definition above! No
5378:  * other PETSc functions should be defined past this point, as it is impossible to recover the
5379:  * original definitions */
5380: #undef PetscCall
5381: #undef SETERRQ