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:   MatScalar  *ap, *aa;

580:   MatSeqAIJGetArray(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:   MatSeqAIJRestoreArray(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:   PetscScalar     work[25], *v_work;

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

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

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

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

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

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

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

1884:   diag  = a->diag;
1885:   t     = a->ssor_work;
1886:   idiag = a->idiag;
1887:   mdiag = a->mdiag;

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

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

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

1919:     to a vector efficiently using Eisenstat's trick.
1920:     */
1921:     scale = (2.0 / omega) - 1.0;

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

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

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

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

2038: PetscErrorCode MatGetInfo_SeqAIJ(Mat A, MatInfoType flag, MatInfo *info)
2039: {
2040:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2358: PetscErrorCode MatIsSymmetric_SeqAIJ(Mat A, PetscReal tol, PetscBool *f)
2359: {
2360:   MatIsTranspose_SeqAIJ(A, A, tol, f);
2361:   return 0;
2362: }

2364: PetscErrorCode MatIsHermitian_SeqAIJ(Mat A, PetscReal tol, PetscBool *f)
2365: {
2366:   MatIsHermitianTranspose_SeqAIJ(A, A, tol, f);
2367:   return 0;
2368: }

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

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

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

2423:   ISGetIndices(isrow, &irow);
2424:   ISGetLocalSize(isrow, &nrows);
2425:   ISGetLocalSize(iscol, &ncols);

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

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

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

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

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

2568:   ISRestoreIndices(isrow, &irow);
2569:   *B = C;
2570:   return 0;
2571: }

2573: PetscErrorCode MatGetMultiProcBlock_SeqAIJ(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
2574: {
2575:   Mat B;

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

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


2598:   ISIdentity(row, &row_identity);
2599:   ISIdentity(col, &col_identity);

2601:   outA             = inA;
2602:   outA->factortype = MAT_FACTOR_LU;
2603:   PetscFree(inA->solvertype);
2604:   PetscStrallocpy(MATSOLVERPETSC, &inA->solvertype);

2606:   PetscObjectReference((PetscObject)row);
2607:   ISDestroy(&a->row);

2609:   a->row = row;

2611:   PetscObjectReference((PetscObject)col);
2612:   ISDestroy(&a->col);

2614:   a->col = col;

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

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

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

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

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

2648: PetscErrorCode MatDestroySubMatrix_Private(Mat_SubSppt *submatj)
2649: {
2650:   PetscInt i;

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

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

2658:     if (submatj->rbuf1) {
2659:       PetscFree(submatj->rbuf1[0]);
2660:       PetscFree(submatj->rbuf1);
2661:     }

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

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

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

2685:   PetscFree(submatj);
2686:   return 0;
2687: }

2689: PetscErrorCode MatDestroySubMatrix_SeqAIJ(Mat C)
2690: {
2691:   Mat_SeqAIJ  *c       = (Mat_SeqAIJ *)C->data;
2692:   Mat_SubSppt *submatj = c->submatis1;

2694:   (*submatj->destroy)(C);
2695:   MatDestroySubMatrix_Private(submatj);
2696:   return 0;
2697: }

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

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

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

2730:   PetscFree(*mat);
2731:   return 0;
2732: }

2734: PetscErrorCode MatCreateSubMatrices_SeqAIJ(Mat A, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *B[])
2735: {
2736:   PetscInt i;

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

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

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

2752:   m  = A->rmap->n / bs;
2753:   ai = a->i;
2754:   aj = a->j;


2758:   PetscMalloc1(m + 1, &nidx);
2759:   PetscBTCreate(m, &table);

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

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

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

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

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

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

2834:   ISInvertPermutation(rowp, PETSC_DECIDE, &irowp);
2835:   ISGetIndices(irowp, &row);
2836:   ISInvertPermutation(colp, PETSC_DECIDE, &icolp);
2837:   ISGetIndices(icolp, &col);

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

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

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

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

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

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

2892: PetscErrorCode MatSetUp_SeqAIJ(Mat A)
2893: {
2894:   MatSeqAIJSetPreallocation_SeqAIJ(A, PETSC_DEFAULT, NULL);
2895:   return 0;
2896: }

2898: PETSC_INTERN PetscErrorCode MatSeqAIJGetArray_SeqAIJ(Mat A, PetscScalar *array[])
2899: {
2900:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

2902:   *array = a->a;
2903:   return 0;
2904: }

2906: PETSC_INTERN PetscErrorCode MatSeqAIJRestoreArray_SeqAIJ(Mat A, PetscScalar *array[])
2907: {
2908:   *array = NULL;
2909:   return 0;
2910: }

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

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

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

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

2947: PetscErrorCode MatAXPY_SeqAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
2948: {
2949:   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data, *y = (Mat_SeqAIJ *)Y->data;

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

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

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

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

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

3021:   MatSeqAIJGetArrayRead(A, &av);
3022:   aa = av;
3023:   ai = a->i;
3024:   aj = a->j;

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

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

3056:   MatSeqAIJGetArrayRead(A, &av);
3057:   aa = av;
3058:   ai = a->i;
3059:   aj = a->j;

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

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

3105:   MatSeqAIJGetArrayRead(A, &av);
3106:   aa = av;
3107:   ai = a->i;
3108:   aj = a->j;

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

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

3156:   MatSeqAIJGetArrayRead(A, &av);
3157:   aa = av;
3158:   ai = a->i;
3159:   aj = a->j;

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

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

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

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

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

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

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

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

3529: PetscErrorCode MatSeqAIJSetColumnIndices_SeqAIJ(Mat mat, PetscInt *indices)
3530: {
3531:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3532:   PetscInt    i, nz, n;

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

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

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

3594: /*@
3595:     MatSeqAIJSetColumnIndices - Set the column indices for all the rows
3596:        in the matrix.

3598:   Input Parameters:
3599: +  mat - the `MATSEQAIJ` matrix
3600: -  indices - the column indices

3602:   Level: advanced

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

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

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

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

3616: @*/
3617: PetscErrorCode MatSeqAIJSetColumnIndices(Mat mat, PetscInt *indices)
3618: {
3621:   PetscUseMethod(mat, "MatSeqAIJSetColumnIndices_C", (Mat, PetscInt *), (mat, indices));
3622:   return 0;
3623: }

3625: /* ----------------------------------------------------------------------------------------*/

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


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

3637:   /* copy values over */
3638:   PetscArraycpy(aij->saved_values, aij->a, nz);
3639:   return 0;
3640: }

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

3647:    Logically Collect

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

3652:   Level: advanced

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

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

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

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

3686: .seealso: `MatRetrieveValues()`
3687: @*/
3688: PetscErrorCode MatStoreValues(Mat mat)
3689: {
3693:   PetscUseMethod(mat, "MatStoreValues_C", (Mat), (mat));
3694:   return 0;
3695: }

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

3704:   /* copy values over */
3705:   PetscArraycpy(aij->a, aij->saved_values, nz);
3706:   return 0;
3707: }

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

3714:    Logically Collect

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

3719:   Level: advanced

3721: .seealso: `MatStoreValues()`
3722: @*/
3723: PetscErrorCode MatRetrieveValues(Mat mat)
3724: {
3728:   PetscUseMethod(mat, "MatRetrieveValues_C", (Mat), (mat));
3729:   return 0;
3730: }

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

3740:    Collective

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

3750:    Output Parameter:
3751: .  A - the matrix

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

3757:    Notes:
3758:    If nnz is given then nz is ignored

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

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

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

3775:    Options Database Keys:
3776: +  -mat_no_inode  - Do not use inodes
3777: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3779:    Level: intermediate

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

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

3798:    Collective

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

3806:    Notes:
3807:      If nnz is given then nz is ignored

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

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

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

3824:    Developer Notes:
3825:    Use nz of `MAT_SKIP_ALLOCATION` to not allocate any space for the matrix
3826:    entries or columns indices

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

3833:    Options Database Keys:
3834: +  -mat_no_inode  - Do not use inodes
3835: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)

3837:    Level: intermediate

3839: .seealso: `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`, `MatGetInfo()`,
3840:           `MatSeqAIJSetTotalPreallocation()`
3841: @*/
3842: PetscErrorCode MatSeqAIJSetPreallocation(Mat B, PetscInt nz, const PetscInt nnz[])
3843: {
3846:   PetscTryMethod(B, "MatSeqAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[]), (B, nz, nnz));
3847:   return 0;
3848: }

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

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

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

3873:   B->preallocated = PETSC_TRUE;

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

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

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

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

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

3943: PetscErrorCode MatResetPreallocation_SeqAIJ(Mat A)
3944: {
3945:   Mat_SeqAIJ *a;
3946:   PetscInt    i;


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

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


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

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

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

3981:    Level: developer

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

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

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

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

3995: .seealso: `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatSeqAIJSetPreallocation()`, `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MatResetPreallocation()`
3996: @*/
3997: PetscErrorCode MatSeqAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
3998: {
4001:   PetscTryMethod(B, "MatSeqAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
4002:   return 0;
4003: }

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


4014:   PetscLayoutSetUp(B->rmap);
4015:   PetscLayoutSetUp(B->cmap);

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

4027:   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);

4029:   MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY);
4030:   MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY);

4032:   MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE);
4033:   return 0;
4034: }

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

4039:    Input Parameters:
4040: +  A - left-hand side matrix
4041: .  B - right-hand side matrix
4042: -  reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

4044:    Output Parameter:
4045: .  C - Kronecker product of A and B

4047:    Level: intermediate

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

4052: .seealso: `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MATKAIJ`, `MatReuse`
4053: @*/
4054: PetscErrorCode MatSeqAIJKron(Mat A, Mat B, MatReuse reuse, Mat *C)
4055: {
4061:   if (reuse == MAT_REUSE_MATRIX) {
4064:   }
4065:   PetscTryMethod(A, "MatSeqAIJKron_C", (Mat, Mat, MatReuse, Mat *), (A, B, reuse, C));
4066:   return 0;
4067: }

4069: PetscErrorCode MatSeqAIJKron_SeqAIJ(Mat A, Mat B, MatReuse reuse, Mat *C)
4070: {
4071:   Mat                newmat;
4072:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
4073:   Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;
4074:   PetscScalar       *v;
4075:   const PetscScalar *aa, *ba;
4076:   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;
4077:   PetscBool          flg;

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

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

4124: /*
4125:     Computes (B'*A')' since computing B*A directly is untenable

4127:                n                       p                          p
4128:         [             ]       [             ]         [                 ]
4129:       m [      A      ]  *  n [       B     ]   =   m [         C       ]
4130:         [             ]       [             ]         [                 ]

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

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

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

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

4184:   C->ops->matmultnumeric = MatMatMultNumeric_SeqDense_SeqAIJ;
4185:   return 0;
4186: }

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

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

4196:    Level: beginner

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

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

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

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

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

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

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

4224:    Note:
4225:    Subclasses include `MATAIJCUSPARSE`, `MATAIJPERM`, `MATAIJSELL`, `MATAIJMKL`, `MATAIJCRL`, and also automatically switches over to use inodes when
4226:    enough exist.

4228:   Level: beginner

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

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

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

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

4245:   Level: beginner

4247: .seealso: `MatCreateMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`
4248: M*/

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

4261: PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqSELL(Mat, MatType, MatReuse, Mat *);
4262: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
4263: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);

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

4268:    Not Collective

4270:    Input Parameter:
4271: .  mat - a `MATSEQAIJ` matrix

4273:    Output Parameter:
4274: .   array - pointer to the data

4276:    Level: intermediate

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

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

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

4295:    Not Collective

4297:    Input Parameters:
4298: +  mat - a `MATSEQAIJ` matrix
4299: -  array - pointer to the data

4301:    Level: intermediate

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

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

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

4322:    Not Collective

4324:    Input Parameter:
4325: .  mat - a `MATSEQAIJ` matrix

4327:    Output Parameter:
4328: .   array - pointer to the data

4330:    Level: intermediate

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

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

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

4349:    Not Collective

4351:    Input Parameter:
4352: .  mat - a `MATSEQAIJ` matrix

4354:    Output Parameter:
4355: .   array - pointer to the data

4357:    Level: intermediate

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

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

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

4376:    Not Collective

4378:    Input Parameter:
4379: .  mat - a `MATSEQAIJ` matrix

4381:    Output Parameter:
4382: .   array - pointer to the data

4384:    Level: intermediate

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

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

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

4405:    Not Collective

4407:    Input Parameter:
4408: .  mat - a MATSEQAIJ matrix

4410:    Output Parameter:
4411: .   array - pointer to the data

4413:    Level: intermediate

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

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

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

4432:    Not Collective

4434:    Input Parameter:
4435: .  mat - a matrix of type `MATSEQAIJ` or its subclasses

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

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

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

4450:    Level: Developer

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

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

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

4473:    Not Collective

4475:    Input Parameter:
4476: .  mat - a `MATSEQAIJ` matrix

4478:    Output Parameter:
4479: .   nz - the maximum number of nonzeros in any row

4481:    Level: intermediate

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

4489:   *nz = aij->rmax;
4490:   return 0;
4491: }

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

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

4517:   /* Sort by row */
4518:   PetscSortIntWithIntCountArrayPair(coo_n, i, j, perm);
4519:   for (k = 0; k < coo_n; k++) {
4520:     if (i[k] >= 0) break;
4521:   } /* Advance k to the first row with a non-negative index */
4522:   nneg = k;
4523:   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 */
4524:   nnz = 0;                                          /* Total number of unique nonzeros to be counted */
4525:   jmap++;                                           /* Inc jmap by 1 for convinience */

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

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

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

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

4568:     PetscMalloc1(nnz + 1, &jmap_new);
4569:     PetscArraycpy(jmap_new, jmap, nnz + 1);
4570:     PetscFree(jmap);
4571:     jmap = jmap_new;

4573:     PetscMalloc1(nnz, &Aj_new);
4574:     PetscArraycpy(Aj_new, Aj, nnz);
4575:     PetscFree(Aj);
4576:     Aj = Aj_new;
4577:   }

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

4582:     PetscMalloc1(coo_n - nneg, &perm_new);
4583:     PetscArraycpy(perm_new, perm + nneg, coo_n - nneg);
4584:     PetscFree(perm);
4585:     perm = perm_new;
4586:   }

4588:   MatGetRootType_Private(mat, &rtype);
4589:   PetscCalloc1(nnz, &Aa); /* Zero the matrix */
4590:   MatSetSeqAIJWithArrays_private(PETSC_COMM_SELF, M, N, Ai, Aj, Aa, rtype, mat);

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

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

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

4619: #if defined(PETSC_HAVE_CUDA)
4620: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
4621: #endif
4622: #if defined(PETSC_HAVE_KOKKOS_KERNELS)
4623: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJKokkos(Mat, MatType, MatReuse, Mat *);
4624: #endif

4626: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJ(Mat B)
4627: {
4628:   Mat_SeqAIJ *b;
4629:   PetscMPIInt size;

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

4634:   PetscNew(&b);

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

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

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

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

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


4726:   C->factortype = A->factortype;
4727:   c->row        = NULL;
4728:   c->col        = NULL;
4729:   c->icol       = NULL;
4730:   c->reallocs   = 0;

4732:   C->assembled    = A->assembled;
4733:   C->preallocated = A->preallocated;

4735:   if (A->preallocated) {
4736:     PetscLayoutReference(A->rmap, &C->rmap);
4737:     PetscLayoutReference(A->cmap, &C->cmap);

4739:     PetscMalloc1(m, &c->imax);
4740:     PetscMemcpy(c->imax, a->imax, m * sizeof(PetscInt));
4741:     PetscMalloc1(m, &c->ilen);
4742:     PetscMemcpy(c->ilen, a->ilen, m * sizeof(PetscInt));

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

4748:       c->singlemalloc = PETSC_TRUE;

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

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

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

4773:     c->solve_work         = NULL;
4774:     c->saved_values       = NULL;
4775:     c->idiag              = NULL;
4776:     c->ssor_work          = NULL;
4777:     c->keepnonzeropattern = a->keepnonzeropattern;
4778:     c->free_a             = PETSC_TRUE;
4779:     c->free_ij            = PETSC_TRUE;

4781:     c->rmax  = a->rmax;
4782:     c->nz    = a->nz;
4783:     c->maxnz = a->nz; /* Since we allocate exactly the right amount */

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

4800:     MatDuplicate_SeqAIJ_Inode(A, cpvalues, &C);
4801:   }
4802:   PetscFunctionListDuplicate(((PetscObject)A)->qlist, &((PetscObject)C)->qlist);
4803:   return 0;
4804: }

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

4816: PetscErrorCode MatLoad_SeqAIJ(Mat newMat, PetscViewer viewer)
4817: {
4818:   PetscBool isbinary, ishdf5;

4822:   /* force binary viewer to load .info file if it has not yet done so */
4823:   PetscViewerSetUp(viewer);
4824:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary);
4825:   PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
4826:   if (isbinary) {
4827:     MatLoad_SeqAIJ_Binary(newMat, viewer);
4828:   } else if (ishdf5) {
4829: #if defined(PETSC_HAVE_HDF5)
4830:     MatLoad_AIJ_HDF5(newMat, viewer);
4831: #else
4832:     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
4833: #endif
4834:   } else {
4835:     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);
4836:   }
4837:   return 0;
4838: }

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

4845:   PetscViewerSetUp(viewer);

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

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

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

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

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

4894:   MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY);
4895:   MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY);
4896:   return 0;
4897: }

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

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

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

4917:   /* if a->j are the same */
4918:   PetscArraycmp(a->j, b->j, a->nz, flg);
4919:   if (!*flg) return 0;

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

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

4943:       Collective

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

4953:    Output Parameter:
4954: .   mat - the matrix

4956:    Level: intermediate

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

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

4964:        The i and j indices are 0 based

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

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

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

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

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

5004:   for (ii = 0, aij->nonzerorowcnt = 0, aij->rmax = 0; ii < m; ii++) {
5005:     aij->ilen[ii] = aij->imax[ii] = i[ii + 1] - i[ii];
5006:     if (PetscDefined(USE_DEBUG)) {
5008:       for (jj = i[ii] + 1; jj < i[ii + 1]; jj++) {
5011:       }
5012:     }
5013:   }
5014:   if (PetscDefined(USE_DEBUG)) {
5015:     for (ii = 0; ii < aij->i[m]; ii++) {
5018:     }
5019:   }

5021:   MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY);
5022:   MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY);
5023:   return 0;
5024: }

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

5030:       Collective

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

5042:    Output Parameter:
5043: .   mat - the matrix

5045:    Level: intermediate

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

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

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

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

5090: PetscErrorCode MatSeqAIJInvalidateDiagonal(Mat A)
5091: {
5092:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

5094:   a->idiagvalid  = PETSC_FALSE;
5095:   a->ibdiagvalid = PETSC_FALSE;

5097:   MatSeqAIJInvalidateDiagonal_Inode(A);
5098:   return 0;
5099: }

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

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

5122:   if (!B) return 0;
5123:   /* Check to make sure the target matrix (and embeddings) are compatible with C and each other. */
5124:   PetscObjectBaseTypeCompare((PetscObject)B, MATSEQAIJ, &seqaij);
5126:   if (rowemb) {
5127:     ISGetLocalSize(rowemb, &m);
5129:   } else {
5131:   }
5132:   if (colemb) {
5133:     ISGetLocalSize(colemb, &n);
5135:   } else {
5137:   }

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

5173: PetscFunctionList MatSeqAIJList = NULL;

5175: /*@C
5176:    MatSeqAIJSetType - Converts a `MATSEQAIJ` matrix to a subtype

5178:    Collective

5180:    Input Parameters:
5181: +  mat      - the matrix object
5182: -  matype   - matrix type

5184:    Options Database Key:
5185: .  -mat_seqai_type  <method> - for example seqaijcrl

5187:   Level: intermediate

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

5197:   PetscObjectTypeCompare((PetscObject)mat, matype, &sametype);
5198:   if (sametype) return 0;

5200:   PetscFunctionListFind(MatSeqAIJList, matype, &r);
5202:   (*r)(mat, matype, MAT_INPLACE_MATRIX, &mat);
5203:   return 0;
5204: }

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

5209:    Not Collective

5211:    Input Parameters:
5212: +  name - name of a new user-defined matrix type, for example `MATSEQAIJCRL`
5213: -  function - routine to convert to subtype

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

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

5221:    Level: advanced

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

5232: PetscBool MatSeqAIJRegisterAllCalled = PETSC_FALSE;

5234: /*@C
5235:   MatSeqAIJRegisterAll - Registers all of the matrix subtypes of `MATSSEQAIJ`

5237:   Not Collective

5239:   Level: advanced

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

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

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

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

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

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

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

5310:   MatCheckPreallocated(A, 1);
5311:   imax  = a->imax;
5312:   ai    = a->i;
5313:   ailen = a->ilen;
5314:   aj    = a->j;
5315:   aa    = a->a;

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

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

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