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: /* defines MatSetValues_Seq_Hash(), MatAssemblyEnd_Seq_Hash(), MatSetUp_Seq_Hash() */
 12: #define TYPE AIJ
 13: #define TYPE_BS
 14: #include "../src/mat/impls/aij/seq/seqhashmatsetvalues.h"
 15: #include "../src/mat/impls/aij/seq/seqhashmat.h"
 16: #undef TYPE
 17: #undef TYPE_BS

 19: MatGetDiagonalMarkers(SeqAIJ, 1)

 21: static PetscErrorCode MatSeqAIJSetTypeFromOptions(Mat A)
 22: {
 23:   PetscBool flg;
 24:   char      type[256];

 26:   PetscFunctionBegin;
 27:   PetscObjectOptionsBegin((PetscObject)A);
 28:   PetscCall(PetscOptionsFList("-mat_seqaij_type", "Matrix SeqAIJ type", "MatSeqAIJSetType", MatSeqAIJList, "seqaij", type, 256, &flg));
 29:   if (flg) PetscCall(MatSeqAIJSetType(A, type));
 30:   PetscOptionsEnd();
 31:   PetscFunctionReturn(PETSC_SUCCESS);
 32: }

 34: static PetscErrorCode MatGetColumnReductions_SeqAIJ(Mat A, PetscInt type, PetscReal *reductions)
 35: {
 36:   PetscInt    i, m, n;
 37:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

 39:   PetscFunctionBegin;
 40:   PetscCall(MatGetSize(A, &m, &n));
 41:   PetscCall(PetscArrayzero(reductions, n));
 42:   if (type == NORM_2) {
 43:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscAbsScalar(aij->a[i] * aij->a[i]);
 44:   } else if (type == NORM_1) {
 45:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscAbsScalar(aij->a[i]);
 46:   } else if (type == NORM_INFINITY) {
 47:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] = PetscMax(PetscAbsScalar(aij->a[i]), reductions[aij->j[i]]);
 48:   } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
 49:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscRealPart(aij->a[i]);
 50:   } else if (type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART) {
 51:     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscImaginaryPart(aij->a[i]);
 52:   } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");

 54:   if (type == NORM_2) {
 55:     for (i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
 56:   } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
 57:     for (i = 0; i < n; i++) reductions[i] /= m;
 58:   }
 59:   PetscFunctionReturn(PETSC_SUCCESS);
 60: }

 62: static PetscErrorCode MatFindOffBlockDiagonalEntries_SeqAIJ(Mat A, IS *is)
 63: {
 64:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
 65:   PetscInt        i, m = A->rmap->n, cnt = 0, bs = A->rmap->bs;
 66:   const PetscInt *jj = a->j, *ii = a->i;
 67:   PetscInt       *rows;

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

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

 93:   PetscFunctionBegin;
 94:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
 95:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, NULL));
 96:   for (i = 0; i < m; i++) {
 97:     if ((diag[i] >= ii[i + 1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) cnt++;
 98:   }
 99:   PetscCall(PetscMalloc1(cnt, &rows));
100:   cnt = 0;
101:   for (i = 0; i < m; i++) {
102:     if ((diag[i] >= ii[i + 1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) rows[cnt++] = i;
103:   }
104:   *nrows = cnt;
105:   *zrows = rows;
106:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
107:   PetscFunctionReturn(PETSC_SUCCESS);
108: }

110: static PetscErrorCode MatFindZeroDiagonals_SeqAIJ(Mat A, IS *zrows)
111: {
112:   PetscInt nrows, *rows;

114:   PetscFunctionBegin;
115:   *zrows = NULL;
116:   PetscCall(MatFindZeroDiagonals_SeqAIJ_Private(A, &nrows, &rows));
117:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), nrows, rows, PETSC_OWN_POINTER, zrows));
118:   PetscFunctionReturn(PETSC_SUCCESS);
119: }

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

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

166: PetscErrorCode MatDiagonalSet_SeqAIJ(Mat Y, Vec D, InsertMode is)
167: {
168:   PetscInt           i, m = Y->rmap->n;
169:   const PetscInt    *diag;
170:   MatScalar         *aa;
171:   const PetscScalar *v;
172:   PetscBool          diagDense;

174:   PetscFunctionBegin;
175:   if (Y->assembled) {
176:     PetscCall(MatGetDiagonalMarkers_SeqAIJ(Y, &diag, &diagDense));
177:     if (diagDense) {
178:       PetscCall(VecGetArrayRead(D, &v));
179:       PetscCall(MatSeqAIJGetArray(Y, &aa));
180:       if (is == INSERT_VALUES) {
181:         for (i = 0; i < m; i++) aa[diag[i]] = v[i];
182:       } else {
183:         for (i = 0; i < m; i++) aa[diag[i]] += v[i];
184:       }
185:       PetscCall(MatSeqAIJRestoreArray(Y, &aa));
186:       PetscCall(VecRestoreArrayRead(D, &v));
187:       PetscFunctionReturn(PETSC_SUCCESS);
188:     }
189:   }
190:   PetscCall(MatDiagonalSet_Default(Y, D, is));
191:   PetscFunctionReturn(PETSC_SUCCESS);
192: }

194: PetscErrorCode MatGetRowIJ_SeqAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
195: {
196:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
197:   PetscInt    i, ishift;

199:   PetscFunctionBegin;
200:   if (m) *m = A->rmap->n;
201:   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);
202:   ishift = 0;
203:   if (symmetric && A->structurally_symmetric != PETSC_BOOL3_TRUE) {
204:     PetscCall(MatToSymmetricIJ_SeqAIJ(A->rmap->n, a->i, a->j, PETSC_TRUE, ishift, oshift, (PetscInt **)ia, (PetscInt **)ja));
205:   } else if (oshift == 1) {
206:     PetscInt *tia;
207:     PetscInt  nz = a->i[A->rmap->n];

209:     /* malloc space and  add 1 to i and j indices */
210:     PetscCall(PetscMalloc1(A->rmap->n + 1, &tia));
211:     for (i = 0; i < A->rmap->n + 1; i++) tia[i] = a->i[i] + 1;
212:     *ia = tia;
213:     if (ja) {
214:       PetscInt *tja;

216:       PetscCall(PetscMalloc1(nz + 1, &tja));
217:       for (i = 0; i < nz; i++) tja[i] = a->j[i] + 1;
218:       *ja = tja;
219:     }
220:   } else {
221:     *ia = a->i;
222:     if (ja) *ja = a->j;
223:   }
224:   PetscFunctionReturn(PETSC_SUCCESS);
225: }

227: PetscErrorCode MatRestoreRowIJ_SeqAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
228: {
229:   PetscFunctionBegin;
230:   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);
231:   if ((symmetric && A->structurally_symmetric != PETSC_BOOL3_TRUE) || oshift == 1) {
232:     PetscCall(PetscFree(*ia));
233:     if (ja) PetscCall(PetscFree(*ja));
234:   }
235:   PetscFunctionReturn(PETSC_SUCCESS);
236: }

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

244:   PetscFunctionBegin;
245:   *nn = n;
246:   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);
247:   if (symmetric) {
248:     PetscCall(MatToSymmetricIJ_SeqAIJ(A->rmap->n, a->i, a->j, PETSC_TRUE, 0, oshift, (PetscInt **)ia, (PetscInt **)ja));
249:   } else {
250:     PetscCall(PetscCalloc1(n, &collengths));
251:     PetscCall(PetscMalloc1(n + 1, &cia));
252:     PetscCall(PetscMalloc1(nz, &cja));
253:     jj = a->j;
254:     for (i = 0; i < nz; i++) collengths[jj[i]]++;
255:     cia[0] = oshift;
256:     for (i = 0; i < n; i++) cia[i + 1] = cia[i] + collengths[i];
257:     PetscCall(PetscArrayzero(collengths, n));
258:     jj = a->j;
259:     for (row = 0; row < m; row++) {
260:       mr = a->i[row + 1] - a->i[row];
261:       for (i = 0; i < mr; i++) {
262:         col = *jj++;

264:         cja[cia[col] + collengths[col]++ - oshift] = row + oshift;
265:       }
266:     }
267:     PetscCall(PetscFree(collengths));
268:     *ia = cia;
269:     *ja = cja;
270:   }
271:   PetscFunctionReturn(PETSC_SUCCESS);
272: }

274: PetscErrorCode MatRestoreColumnIJ_SeqAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
275: {
276:   PetscFunctionBegin;
277:   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);

279:   PetscCall(PetscFree(*ia));
280:   PetscCall(PetscFree(*ja));
281:   PetscFunctionReturn(PETSC_SUCCESS);
282: }

284: /*
285:  MatGetColumnIJ_SeqAIJ_Color() and MatRestoreColumnIJ_SeqAIJ_Color() are customized from
286:  MatGetColumnIJ_SeqAIJ() and MatRestoreColumnIJ_SeqAIJ() by adding an output
287:  spidx[], index of a->a, to be used in MatTransposeColoringCreate_SeqAIJ() and MatFDColoringCreate_SeqXAIJ()
288: */
289: PetscErrorCode MatGetColumnIJ_SeqAIJ_Color(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *nn, const PetscInt *ia[], const PetscInt *ja[], PetscInt *spidx[], PetscBool *done)
290: {
291:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
292:   PetscInt        i, *collengths, *cia, *cja, n = A->cmap->n, m = A->rmap->n;
293:   PetscInt        nz = a->i[m], row, mr, col, tmp;
294:   PetscInt       *cspidx;
295:   const PetscInt *jj;

297:   PetscFunctionBegin;
298:   *nn = n;
299:   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);

301:   PetscCall(PetscCalloc1(n, &collengths));
302:   PetscCall(PetscMalloc1(n + 1, &cia));
303:   PetscCall(PetscMalloc1(nz, &cja));
304:   PetscCall(PetscMalloc1(nz, &cspidx));
305:   jj = a->j;
306:   for (i = 0; i < nz; i++) collengths[jj[i]]++;
307:   cia[0] = oshift;
308:   for (i = 0; i < n; i++) cia[i + 1] = cia[i] + collengths[i];
309:   PetscCall(PetscArrayzero(collengths, n));
310:   jj = a->j;
311:   for (row = 0; row < m; row++) {
312:     mr = a->i[row + 1] - a->i[row];
313:     for (i = 0; i < mr; i++) {
314:       col         = *jj++;
315:       tmp         = cia[col] + collengths[col]++ - oshift;
316:       cspidx[tmp] = a->i[row] + i; /* index of a->j */
317:       cja[tmp]    = row + oshift;
318:     }
319:   }
320:   PetscCall(PetscFree(collengths));
321:   *ia    = cia;
322:   *ja    = cja;
323:   *spidx = cspidx;
324:   PetscFunctionReturn(PETSC_SUCCESS);
325: }

327: PetscErrorCode MatRestoreColumnIJ_SeqAIJ_Color(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscInt *spidx[], PetscBool *done)
328: {
329:   PetscFunctionBegin;
330:   PetscCall(MatRestoreColumnIJ_SeqAIJ(A, oshift, symmetric, inodecompressed, n, ia, ja, done));
331:   PetscCall(PetscFree(*spidx));
332:   PetscFunctionReturn(PETSC_SUCCESS);
333: }

335: static PetscErrorCode MatSetValuesRow_SeqAIJ(Mat A, PetscInt row, const PetscScalar v[])
336: {
337:   Mat_SeqAIJ  *a  = (Mat_SeqAIJ *)A->data;
338:   PetscInt    *ai = a->i;
339:   PetscScalar *aa;

341:   PetscFunctionBegin;
342:   PetscCall(MatSeqAIJGetArray(A, &aa));
343:   PetscCall(PetscArraycpy(aa + ai[row], v, ai[row + 1] - ai[row]));
344:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
345:   PetscFunctionReturn(PETSC_SUCCESS);
346: }

348: #include <petsc/private/isimpl.h>

350: /*@
351:   MatSeqAIJSetValuesLocalFast - An optimized version of `MatSetValuesLocal()` for `MATSEQAIJ` matrices, valid under
352:   several restrictive assumptions.

354:   Not Collective

356:   Input Parameters:
357: + A  - the `MATSEQAIJ` matrix
358: . m  - the number of rows being set (must be 1)
359: . im - array of length `m` giving the local row index
360: . n  - the number of columns being set
361: . in - array of length `n` giving the local column indices
362: . v  - array of length `n` of values to add
363: - is - the insert mode (must be `ADD_VALUES`)

365:   Level: developer

367:   Notes:
368:   This routine requires that a single row of values is set with each call, that no row or column
369:   index is negative or larger than the number of rows or columns, that values are always added
370:   (not inserted), and that no new nonzero locations are introduced.

372:   The global column indices are not assumed to be sorted.

374: .seealso: `Mat`, `MATSEQAIJ`, `MatSetValuesLocal()`, `MatSetValues()`
375: @*/
376: PetscErrorCode MatSeqAIJSetValuesLocalFast(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
377: {
378:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
379:   PetscInt        low, high, t, row, nrow, i, col, l;
380:   const PetscInt *rp, *ai = a->i, *ailen = a->ilen, *aj = a->j;
381:   PetscInt        lastcol = -1;
382:   MatScalar      *ap, value, *aa;
383:   const PetscInt *ridx = A->rmap->mapping->indices, *cidx = A->cmap->mapping->indices;

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

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

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

427:   PetscFunctionBegin;
428:   PetscCall(MatSeqAIJGetArray(A, &aa));
429:   for (k = 0; k < m; k++) { /* loop over added rows */
430:     row = im[k];
431:     if (row < 0) continue;
432:     PetscCheck(row < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, row, A->rmap->n - 1);
433:     rp = PetscSafePointerPlusOffset(aj, ai[row]);
434:     if (!A->structure_only) ap = PetscSafePointerPlusOffset(aa, ai[row]);
435:     rmax = imax[row];
436:     nrow = ailen[row];
437:     low  = 0;
438:     high = nrow;
439:     for (l = 0; l < n; l++) { /* loop over added columns */
440:       if (in[l] < 0) continue;
441:       PetscCheck(in[l] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[l], A->cmap->n - 1);
442:       col = in[l];
443:       if (v && !A->structure_only) value = roworiented ? v[l + k * n] : v[k + l * m];
444:       if (!A->structure_only && value == 0.0 && ignorezeroentries && is == ADD_VALUES && row != col) continue;

446:       if (col <= lastcol) low = 0;
447:       else high = nrow;
448:       lastcol = col;
449:       while (high - low > 5) {
450:         t = (low + high) / 2;
451:         if (rp[t] > col) high = t;
452:         else low = t;
453:       }
454:       for (i = low; i < high; i++) {
455:         if (rp[i] > col) break;
456:         if (rp[i] == col) {
457:           if (!A->structure_only) {
458:             if (is == ADD_VALUES) {
459:               ap[i] += value;
460:               (void)PetscLogFlops(1.0);
461:             } else ap[i] = value;
462:           }
463:           low = i + 1;
464:           goto noinsert;
465:         }
466:       }
467:       if (value == 0.0 && ignorezeroentries && row != col) goto noinsert;
468:       if (nonew == 1) goto noinsert;
469:       PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at (%" PetscInt_FMT ",%" PetscInt_FMT ") in the matrix", row, col);
470:       if (A->structure_only) {
471:         MatSeqXAIJReallocateAIJ_structure_only(A, A->rmap->n, 1, nrow, row, col, rmax, ai, aj, rp, imax, nonew, MatScalar);
472:       } else {
473:         MatSeqXAIJReallocateAIJ(A, A->rmap->n, 1, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
474:       }
475:       N = nrow++ - 1;
476:       a->nz++;
477:       high++;
478:       /* shift up all the later entries in this row */
479:       PetscCall(PetscArraymove(rp + i + 1, rp + i, N - i + 1));
480:       rp[i] = col;
481:       if (!A->structure_only) {
482:         PetscCall(PetscArraymove(ap + i + 1, ap + i, N - i + 1));
483:         ap[i] = value;
484:       }
485:       low = i + 1;
486:     noinsert:;
487:     }
488:     ailen[row] = nrow;
489:   }
490:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
491:   PetscFunctionReturn(PETSC_SUCCESS);
492: }

494: static PetscErrorCode MatSetValues_SeqAIJ_SortedFullNoPreallocation(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
495: {
496:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
497:   PetscInt   *rp, k, row;
498:   PetscInt   *ai = a->i;
499:   PetscInt   *aj = a->j;
500:   MatScalar  *aa, *ap;

502:   PetscFunctionBegin;
503:   PetscCheck(!A->was_assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot call on assembled matrix.");
504:   PetscCheck(m * n + a->nz <= a->maxnz, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of entries in matrix will be larger than maximum nonzeros allocated for %" PetscInt_FMT " in MatSeqAIJSetTotalPreallocation()", a->maxnz);

506:   PetscCall(MatSeqAIJGetArray(A, &aa));
507:   for (k = 0; k < m; k++) { /* loop over added rows */
508:     row = im[k];
509:     rp  = aj + ai[row];
510:     ap  = PetscSafePointerPlusOffset(aa, ai[row]);

512:     PetscCall(PetscArraycpy(rp, in, n));
513:     if (!A->structure_only) {
514:       if (v) {
515:         PetscCall(PetscArraycpy(ap, v, n));
516:         v += n;
517:       } else {
518:         PetscCall(PetscMemzero(ap, n * sizeof(PetscScalar)));
519:       }
520:     }
521:     a->ilen[row]  = n;
522:     a->imax[row]  = n;
523:     a->i[row + 1] = a->i[row] + n;
524:     a->nz += n;
525:   }
526:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
527:   PetscFunctionReturn(PETSC_SUCCESS);
528: }

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

533:   Input Parameters:
534: + A       - the `MATSEQAIJ` matrix
535: - nztotal - bound on the number of nonzeros

537:   Level: advanced

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

544: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MAT_SORTED_FULL`, `MatSetValues()`, `MatSeqAIJSetPreallocation()`
545: @*/
546: PetscErrorCode MatSeqAIJSetTotalPreallocation(Mat A, PetscInt nztotal)
547: {
548:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

550:   PetscFunctionBegin;
551:   PetscCall(PetscLayoutSetUp(A->rmap));
552:   PetscCall(PetscLayoutSetUp(A->cmap));
553:   a->maxnz = nztotal;
554:   if (!a->imax) PetscCall(PetscMalloc1(A->rmap->n, &a->imax));
555:   if (!a->ilen) {
556:     PetscCall(PetscMalloc1(A->rmap->n, &a->ilen));
557:   } else {
558:     PetscCall(PetscMemzero(a->ilen, A->rmap->n * sizeof(PetscInt)));
559:   }

561:   /* allocate the matrix space */
562:   PetscCall(PetscShmgetAllocateArray(A->rmap->n + 1, sizeof(PetscInt), (void **)&a->i));
563:   PetscCall(PetscShmgetAllocateArray(nztotal, sizeof(PetscInt), (void **)&a->j));
564:   a->free_ij = PETSC_TRUE;
565:   if (A->structure_only) {
566:     a->free_a = PETSC_FALSE;
567:   } else {
568:     PetscCall(PetscShmgetAllocateArray(nztotal, sizeof(PetscScalar), (void **)&a->a));
569:     a->free_a = PETSC_TRUE;
570:   }
571:   a->i[0]           = 0;
572:   A->ops->setvalues = MatSetValues_SeqAIJ_SortedFullNoPreallocation;
573:   A->preallocated   = PETSC_TRUE;
574:   PetscFunctionReturn(PETSC_SUCCESS);
575: }

577: static PetscErrorCode MatSetValues_SeqAIJ_SortedFull(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
578: {
579:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
580:   PetscInt   *rp, k, row;
581:   PetscInt   *ai = a->i, *ailen = a->ilen;
582:   PetscInt   *aj = a->j;
583:   MatScalar  *aa, *ap;

585:   PetscFunctionBegin;
586:   PetscCall(MatSeqAIJGetArray(A, &aa));
587:   for (k = 0; k < m; k++) { /* loop over added rows */
588:     row = im[k];
589:     PetscCheck(n <= a->imax[row], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Preallocation for row %" PetscInt_FMT " does not match number of columns provided", n);
590:     rp = aj + ai[row];
591:     ap = aa + ai[row];
592:     if (!A->was_assembled) PetscCall(PetscArraycpy(rp, in, n));
593:     if (!A->structure_only) {
594:       if (v) {
595:         PetscCall(PetscArraycpy(ap, v, n));
596:         v += n;
597:       } else {
598:         PetscCall(PetscMemzero(ap, n * sizeof(PetscScalar)));
599:       }
600:     }
601:     ailen[row] = n;
602:     a->nz += n;
603:   }
604:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
605:   PetscFunctionReturn(PETSC_SUCCESS);
606: }

608: static PetscErrorCode MatGetValues_SeqAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], PetscScalar v[])
609: {
610:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
611:   PetscInt        *rp, k, low, high, t, row, nrow, i, col, l, *aj = a->j;
612:   PetscInt        *ai = a->i, *ailen = a->ilen;
613:   const MatScalar *ap, *aa;
614:   PetscBool        hyprecoo;
615:   PetscBool        roworiented = a->roworiented;
616:   PetscScalar     *value;

618:   PetscFunctionBegin;
619:   PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", ((PetscObject)A)->name, &hyprecoo));

621:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
622:   for (k = 0; k < m; k++) { /* loop over rows */
623:     row = im[k];
624:     if (row < 0) continue; /* negative row */
625:     PetscCheck(row < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, row, A->rmap->n - 1);
626:     rp   = PetscSafePointerPlusOffset(aj, ai[row]);
627:     ap   = PetscSafePointerPlusOffset(aa, ai[row]);
628:     nrow = ailen[row];
629:     for (l = 0; l < n; l++) {  /* loop over columns */
630:       if (in[l] < 0) continue; /* negative column */
631:       value = roworiented ? &v[l + k * n] : &v[k + l * m];
632:       PetscCheck(in[l] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, in[l], A->cmap->n - 1);
633:       col = in[l];
634:       /* hypre coo mat stores its diagonal at the front, out of sort */
635:       if (hyprecoo) {
636:         if (col == rp[0]) {
637:           *value = ap[0];
638:           goto finished;
639:         }
640:         low = 1;
641:       } else low = 0;
642:       high = nrow;
643:       /* assume sorted */
644:       while (high - low > 5) {
645:         t = (low + high) / 2;
646:         if (rp[t] > col) high = t;
647:         else low = t;
648:       }
649:       for (i = low; i < high; i++) {
650:         if (rp[i] > col) break;
651:         if (rp[i] == col) {
652:           *value = ap[i];
653:           goto finished;
654:         }
655:       }
656:       *value = 0.0;
657:     finished:;
658:     }
659:   }
660:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
661:   PetscFunctionReturn(PETSC_SUCCESS);
662: }

664: static PetscErrorCode MatView_SeqAIJ_Binary(Mat mat, PetscViewer viewer)
665: {
666:   Mat_SeqAIJ        *A = (Mat_SeqAIJ *)mat->data;
667:   const PetscScalar *av;
668:   PetscInt           header[4], M, N, m, nz, i;
669:   PetscInt          *rowlens;

671:   PetscFunctionBegin;
672:   PetscCall(PetscViewerSetUp(viewer));

674:   M  = mat->rmap->N;
675:   N  = mat->cmap->N;
676:   m  = mat->rmap->n;
677:   nz = A->nz;

679:   /* write matrix header */
680:   header[0] = MAT_FILE_CLASSID;
681:   header[1] = M;
682:   header[2] = N;
683:   header[3] = nz;
684:   PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));

686:   /* fill in and store row lengths */
687:   PetscCall(PetscMalloc1(m, &rowlens));
688:   for (i = 0; i < m; i++) rowlens[i] = A->i[i + 1] - A->i[i];
689:   if (PetscDefined(USE_DEBUG)) {
690:     PetscInt mnz = 0;

692:     for (i = 0; i < m; i++) mnz += rowlens[i];
693:     PetscCheck(nz == mnz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Row lens %" PetscInt_FMT " do not sum to nz %" PetscInt_FMT, mnz, nz);
694:   }
695:   PetscCall(PetscViewerBinaryWrite(viewer, rowlens, m, PETSC_INT));
696:   PetscCall(PetscFree(rowlens));
697:   /* store column indices */
698:   PetscCall(PetscViewerBinaryWrite(viewer, A->j, nz, PETSC_INT));
699:   /* store nonzero values */
700:   PetscCall(MatSeqAIJGetArrayRead(mat, &av));
701:   PetscCall(PetscViewerBinaryWrite(viewer, av, nz, PETSC_SCALAR));
702:   PetscCall(MatSeqAIJRestoreArrayRead(mat, &av));

704:   /* write block size option to the viewer's .info file */
705:   PetscCall(MatView_Binary_BlockSizes(mat, viewer));
706:   PetscFunctionReturn(PETSC_SUCCESS);
707: }

709: static PetscErrorCode MatView_SeqAIJ_ASCII_structonly(Mat A, PetscViewer viewer)
710: {
711:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
712:   PetscInt    i, k, m = A->rmap->N;

714:   PetscFunctionBegin;
715:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
716:   for (i = 0; i < m; i++) {
717:     PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
718:     for (k = a->i[i]; k < a->i[i + 1]; k++) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ") ", a->j[k]));
719:     PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
720:   }
721:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
722:   PetscFunctionReturn(PETSC_SUCCESS);
723: }

725: static PetscErrorCode MatView_SeqAIJ_ASCII(Mat A, PetscViewer viewer)
726: {
727:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
728:   const PetscScalar *av;
729:   PetscInt           i, j, m = A->rmap->n;
730:   const char        *name;
731:   PetscViewerFormat  format;

733:   PetscFunctionBegin;
734:   if (A->structure_only) {
735:     PetscCall(MatView_SeqAIJ_ASCII_structonly(A, viewer));
736:     PetscFunctionReturn(PETSC_SUCCESS);
737:   }

739:   PetscCall(PetscViewerGetFormat(viewer, &format));
740:   // By petsc's rule, even PETSC_VIEWER_ASCII_INFO_DETAIL doesn't print matrix entries
741:   if (format == PETSC_VIEWER_ASCII_FACTOR_INFO || format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscFunctionReturn(PETSC_SUCCESS);

743:   /* trigger copy to CPU if needed */
744:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
745:   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
746:   if (format == PETSC_VIEWER_ASCII_MATLAB) {
747:     PetscInt nofinalvalue = 0;
748:     if (m && ((a->i[m] == a->i[m - 1]) || (a->j[a->nz - 1] != A->cmap->n - 1))) {
749:       /* Need a dummy value to ensure the dimension of the matrix. */
750:       nofinalvalue = 1;
751:     }
752:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
753:     PetscCall(PetscViewerASCIIPrintf(viewer, "%% Size = %" PetscInt_FMT " %" PetscInt_FMT " \n", m, A->cmap->n));
754:     PetscCall(PetscViewerASCIIPrintf(viewer, "%% Nonzeros = %" PetscInt_FMT " \n", a->nz));
755:     PetscCall(PetscViewerASCIIPrintf(viewer, "zzz = zeros(%" PetscInt_FMT ",%d);\n", a->nz + nofinalvalue, PetscDefined(USE_COMPLEX) ? 4 : 3));
756:     PetscCall(PetscViewerASCIIPrintf(viewer, "zzz = [\n"));

758:     for (i = 0; i < m; i++) {
759:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
760: #if PetscDefined(USE_COMPLEX)
761:         PetscCall(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])));
762: #else
763:         PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e\n", i + 1, a->j[j] + 1, (double)a->a[j]));
764: #endif
765:       }
766:     }
767:     if (nofinalvalue) {
768:       if (PetscDefined(USE_COMPLEX)) PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e %18.16e\n", m, A->cmap->n, 0., 0.));
769:       else PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e\n", m, A->cmap->n, 0.0));
770:     }
771:     PetscCall(PetscObjectGetName((PetscObject)A, &name));
772:     PetscCall(PetscViewerASCIIPrintf(viewer, "];\n %s = spconvert(zzz);\n", name));
773:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
774:   } else if (format == PETSC_VIEWER_ASCII_COMMON) {
775:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
776:     for (i = 0; i < m; i++) {
777:       PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
778:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
779: #if PetscDefined(USE_COMPLEX)
780:         if (PetscImaginaryPart(a->a[j]) > 0.0 && PetscRealPart(a->a[j]) != 0.0) {
781:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
782:         } else if (PetscImaginaryPart(a->a[j]) < 0.0 && PetscRealPart(a->a[j]) != 0.0) {
783:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)-PetscImaginaryPart(a->a[j])));
784:         } else if (PetscRealPart(a->a[j]) != 0.0) {
785:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
786:         }
787: #else
788:         if (a->a[j] != 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]));
789: #endif
790:       }
791:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
792:     }
793:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
794:   } else if (format == PETSC_VIEWER_ASCII_SYMMODU) {
795:     PetscInt nzd = 0, fshift = 1, *sptr;
796:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
797:     PetscCall(PetscMalloc1(m + 1, &sptr));
798:     for (i = 0; i < m; i++) {
799:       sptr[i] = nzd + 1;
800:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
801:         if (a->j[j] >= i) {
802:           if (PetscDefined(USE_COMPLEX) ? (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) : a->a[j] != 0.0) nzd++;
803:         }
804:       }
805:     }
806:     sptr[m] = nzd + 1;
807:     PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT "\n\n", m, nzd));
808:     for (i = 0; i < m + 1; i += 6) {
809:       if (i + 4 < m) {
810:         PetscCall(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]));
811:       } else if (i + 3 < m) {
812:         PetscCall(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]));
813:       } else if (i + 2 < m) {
814:         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2], sptr[i + 3]));
815:       } else if (i + 1 < m) {
816:         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2]));
817:       } else if (i < m) {
818:         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1]));
819:       } else {
820:         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT "\n", sptr[i]));
821:       }
822:     }
823:     PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
824:     PetscCall(PetscFree(sptr));
825:     for (i = 0; i < m; i++) {
826:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
827:         if (a->j[j] >= i) PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " ", a->j[j] + fshift));
828:       }
829:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
830:     }
831:     PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
832:     for (i = 0; i < m; i++) {
833:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
834:         if (a->j[j] >= i) {
835: #if PetscDefined(USE_COMPLEX)
836:           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " %18.16e %18.16e ", (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
837: #else
838:           if (a->a[j] != 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " %18.16e ", (double)a->a[j]));
839: #endif
840:         }
841:       }
842:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
843:     }
844:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
845:   } else if (format == PETSC_VIEWER_ASCII_DENSE) {
846:     PetscInt    cnt = 0, jcnt;
847:     PetscScalar value;
848:     PetscBool   realonly = PETSC_TRUE;

850:     if (PetscDefined(USE_COMPLEX)) {
851:       for (i = 0; i < a->i[m]; i++) {
852:         if (PetscImaginaryPart(a->a[i]) != 0.0) {
853:           realonly = PETSC_FALSE;
854:           break;
855:         }
856:       }
857:     }

859:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
860:     for (i = 0; i < m; i++) {
861:       jcnt = 0;
862:       for (j = 0; j < A->cmap->n; j++) {
863:         if (jcnt < a->i[i + 1] - a->i[i] && j == a->j[cnt]) {
864:           value = a->a[cnt++];
865:           jcnt++;
866:         } else {
867:           value = 0.0;
868:         }
869:         if (!PetscDefined(USE_COMPLEX) || realonly) {
870:           PetscCall(PetscViewerASCIIPrintf(viewer, " %7.5e ", (double)PetscRealPart(value)));
871:         } else {
872:           PetscCall(PetscViewerASCIIPrintf(viewer, " %7.5e+%7.5e i ", (double)PetscRealPart(value), (double)PetscImaginaryPart(value)));
873:         }
874:       }
875:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
876:     }
877:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
878:   } else if (format == PETSC_VIEWER_ASCII_MATRIXMARKET) {
879:     PetscInt fshift = 1;
880:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
881:     PetscCall(PetscViewerASCIIPrintf(viewer, "%%%%MatrixMarket matrix coordinate %s general\n", PetscDefined(USE_COMPLEX) ? "complex" : "real"));
882:     PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", m, A->cmap->n, a->nz));
883:     for (i = 0; i < m; i++) {
884:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
885: #if PetscDefined(USE_COMPLEX)
886:         PetscCall(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])));
887: #else
888:         PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT " %g\n", i + fshift, a->j[j] + fshift, (double)a->a[j]));
889: #endif
890:       }
891:     }
892:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
893:   } else {
894:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
895:     if (A->factortype) {
896:       const PetscInt *adiag;

898:       PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &adiag, NULL));
899:       for (i = 0; i < m; i++) {
900:         PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
901:         /* L part */
902:         for (j = a->i[i]; j < a->i[i + 1]; j++) {
903:           if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) > 0.0) {
904:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
905:           } else if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) < 0.0) {
906:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)(-PetscImaginaryPart(a->a[j]))));
907:           } else {
908:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
909:           }
910:         }
911:         /* diagonal */
912:         j = adiag[i];
913:         if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) > 0.0) {
914:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(1 / a->a[j]), (double)PetscImaginaryPart(1 / a->a[j])));
915:         } else if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) < 0.0) {
916:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(1 / a->a[j]), (double)(-PetscImaginaryPart(1 / a->a[j]))));
917:         } else {
918:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(1 / a->a[j])));
919:         }

921:         /* U part */
922:         for (j = adiag[i + 1] + 1; j < adiag[i]; j++) {
923:           if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) > 0.0) {
924:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
925:           } else if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) < 0.0) {
926:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)(-PetscImaginaryPart(a->a[j]))));
927:           } else {
928:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
929:           }
930:         }
931:         PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
932:       }
933:     } else {
934:       for (i = 0; i < m; i++) {
935:         PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
936:         for (j = a->i[i]; j < a->i[i + 1]; j++) {
937:           if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) > 0.0) {
938:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
939:           } else if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[j]) < 0.0) {
940:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)-PetscImaginaryPart(a->a[j])));
941:           } else {
942:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
943:           }
944:         }
945:         PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
946:       }
947:     }
948:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
949:   }
950:   PetscCall(PetscViewerFlush(viewer));
951:   PetscFunctionReturn(PETSC_SUCCESS);
952: }

954: #include <petscdraw.h>
955: static PetscErrorCode MatView_SeqAIJ_Draw_Zoom(PetscDraw draw, void *Aa)
956: {
957:   Mat                A = (Mat)Aa;
958:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
959:   PetscInt           i, j, m = A->rmap->n;
960:   int                color;
961:   PetscReal          xl, yl, xr, yr, x_l, x_r, y_l, y_r;
962:   PetscViewer        viewer;
963:   PetscViewerFormat  format;
964:   const PetscScalar *aa;

966:   PetscFunctionBegin;
967:   PetscCall(PetscObjectQuery((PetscObject)A, "Zoomviewer", (PetscObject *)&viewer));
968:   PetscCall(PetscViewerGetFormat(viewer, &format));
969:   PetscCall(PetscDrawGetCoordinates(draw, &xl, &yl, &xr, &yr));

971:   /* loop over matrix elements drawing boxes */
972:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
973:   if (format != PETSC_VIEWER_DRAW_CONTOUR) {
974:     PetscDrawCollectiveBegin(draw);
975:     /* Blue for negative, Cyan for zero and  Red for positive */
976:     color = PETSC_DRAW_BLUE;
977:     for (i = 0; i < m; i++) {
978:       y_l = m - i - 1.0;
979:       y_r = y_l + 1.0;
980:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
981:         x_l = a->j[j];
982:         x_r = x_l + 1.0;
983:         if (PetscRealPart(aa[j]) >= 0.) continue;
984:         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
985:       }
986:     }
987:     color = PETSC_DRAW_CYAN;
988:     for (i = 0; i < m; i++) {
989:       y_l = m - i - 1.0;
990:       y_r = y_l + 1.0;
991:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
992:         x_l = a->j[j];
993:         x_r = x_l + 1.0;
994:         if (aa[j] != 0.) continue;
995:         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
996:       }
997:     }
998:     color = PETSC_DRAW_RED;
999:     for (i = 0; i < m; i++) {
1000:       y_l = m - i - 1.0;
1001:       y_r = y_l + 1.0;
1002:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
1003:         x_l = a->j[j];
1004:         x_r = x_l + 1.0;
1005:         if (PetscRealPart(aa[j]) <= 0.) continue;
1006:         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
1007:       }
1008:     }
1009:     PetscDrawCollectiveEnd(draw);
1010:   } else {
1011:     /* use contour shading to indicate magnitude of values */
1012:     /* first determine max of all nonzero values */
1013:     PetscReal minv = 0.0, maxv = 0.0;
1014:     PetscInt  nz = a->nz, count = 0;
1015:     PetscDraw popup;

1017:     for (i = 0; i < nz; i++) {
1018:       if (PetscAbsScalar(aa[i]) > maxv) maxv = PetscAbsScalar(aa[i]);
1019:     }
1020:     if (minv >= maxv) maxv = minv + PETSC_SMALL;
1021:     PetscCall(PetscDrawGetPopup(draw, &popup));
1022:     PetscCall(PetscDrawScalePopup(popup, minv, maxv));

1024:     PetscDrawCollectiveBegin(draw);
1025:     for (i = 0; i < m; i++) {
1026:       y_l = m - i - 1.0;
1027:       y_r = y_l + 1.0;
1028:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
1029:         x_l   = a->j[j];
1030:         x_r   = x_l + 1.0;
1031:         color = PetscDrawRealToColor(PetscAbsScalar(aa[count]), minv, maxv);
1032:         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
1033:         count++;
1034:       }
1035:     }
1036:     PetscDrawCollectiveEnd(draw);
1037:   }
1038:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1039:   PetscFunctionReturn(PETSC_SUCCESS);
1040: }

1042: #include <petscdraw.h>
1043: static PetscErrorCode MatView_SeqAIJ_Draw(Mat A, PetscViewer viewer)
1044: {
1045:   PetscDraw draw;
1046:   PetscReal xr, yr, xl, yl, h, w;
1047:   PetscBool isnull;

1049:   PetscFunctionBegin;
1050:   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1051:   PetscCall(PetscDrawIsNull(draw, &isnull));
1052:   if (isnull) PetscFunctionReturn(PETSC_SUCCESS);

1054:   xr = A->cmap->n;
1055:   yr = A->rmap->n;
1056:   h  = yr / 10.0;
1057:   w  = xr / 10.0;
1058:   xr += w;
1059:   yr += h;
1060:   xl = -w;
1061:   yl = -h;
1062:   PetscCall(PetscDrawSetCoordinates(draw, xl, yl, xr, yr));
1063:   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", (PetscObject)viewer));
1064:   PetscCall(PetscDrawZoom(draw, MatView_SeqAIJ_Draw_Zoom, A));
1065:   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", NULL));
1066:   PetscCall(PetscDrawSave(draw));
1067:   PetscFunctionReturn(PETSC_SUCCESS);
1068: }

1070: PetscErrorCode MatView_SeqAIJ(Mat A, PetscViewer viewer)
1071: {
1072:   PetscBool isascii, isbinary, isdraw;

1074:   PetscFunctionBegin;
1075:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1076:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1077:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1078:   if (isascii) PetscCall(MatView_SeqAIJ_ASCII(A, viewer));
1079:   else if (isbinary) PetscCall(MatView_SeqAIJ_Binary(A, viewer));
1080:   else if (isdraw) PetscCall(MatView_SeqAIJ_Draw(A, viewer));
1081:   PetscCall(MatView_SeqAIJ_Inode(A, viewer));
1082:   PetscFunctionReturn(PETSC_SUCCESS);
1083: }

1085: PetscErrorCode MatAssemblyEnd_SeqAIJ(Mat A, MatAssemblyType mode)
1086: {
1087:   Mat_SeqAIJ *a      = (Mat_SeqAIJ *)A->data;
1088:   PetscInt    fshift = 0, i, *ai = a->i, *aj = a->j, *imax = a->imax;
1089:   PetscInt    m = A->rmap->n, *ip, N, *ailen = a->ilen, rmax = 0;
1090:   MatScalar  *aa    = a->a, *ap;
1091:   PetscReal   ratio = 0.6;

1093:   PetscFunctionBegin;
1094:   if (mode == MAT_FLUSH_ASSEMBLY) PetscFunctionReturn(PETSC_SUCCESS);
1095:   if (A->was_assembled && A->ass_nonzerostate == A->nonzerostate) {
1096:     /* we need to respect users asking to use or not the inodes routine in between matrix assemblies, e.g., via MatSetOption(A, MAT_USE_INODES, val) */
1097:     PetscCall(MatAssemblyEnd_SeqAIJ_Inode(A, mode)); /* read the sparsity pattern */
1098:     PetscFunctionReturn(PETSC_SUCCESS);
1099:   }

1101:   if (m) rmax = ailen[0]; /* determine row with most nonzeros */
1102:   for (i = 1; i < m; i++) {
1103:     /* move each row back by the amount of empty slots (fshift) before it*/
1104:     fshift += imax[i - 1] - ailen[i - 1];
1105:     rmax = PetscMax(rmax, ailen[i]);
1106:     if (fshift) {
1107:       ip = aj + ai[i];
1108:       ap = aa + ai[i];
1109:       N  = ailen[i];
1110:       PetscCall(PetscArraymove(ip - fshift, ip, N));
1111:       if (!A->structure_only) PetscCall(PetscArraymove(ap - fshift, ap, N));
1112:     }
1113:     ai[i] = ai[i - 1] + ailen[i - 1];
1114:   }
1115:   if (m) {
1116:     fshift += imax[m - 1] - ailen[m - 1];
1117:     ai[m] = ai[m - 1] + ailen[m - 1];
1118:   }
1119:   /* reset ilen and imax for each row */
1120:   a->nonzerorowcnt = 0;
1121:   if (A->structure_only) {
1122:     PetscCall(PetscFree(a->imax));
1123:     PetscCall(PetscFree(a->ilen));
1124:   } else { /* !A->structure_only */
1125:     for (i = 0; i < m; i++) {
1126:       ailen[i] = imax[i] = ai[i + 1] - ai[i];
1127:       a->nonzerorowcnt += ((ai[i + 1] - ai[i]) > 0);
1128:     }
1129:   }
1130:   a->nz = ai[m];
1131:   PetscCheck(!fshift || a->nounused != -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unused space detected in matrix: %" PetscInt_FMT " X %" PetscInt_FMT ", %" PetscInt_FMT " unneeded", m, A->cmap->n, fshift);
1132:   PetscCall(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));
1133:   PetscCall(PetscInfo(A, "Number of mallocs during MatSetValues() is %" PetscInt_FMT "\n", a->reallocs));
1134:   PetscCall(PetscInfo(A, "Maximum nonzeros in any row is %" PetscInt_FMT "\n", rmax));

1136:   A->info.mallocs += a->reallocs;
1137:   a->reallocs         = 0;
1138:   A->info.nz_unneeded = (PetscReal)fshift;
1139:   a->rmax             = rmax;

1141:   if (!A->structure_only) PetscCall(MatCheckCompressedRow(A, a->nonzerorowcnt, &a->compressedrow, a->i, m, ratio));
1142:   PetscCall(MatAssemblyEnd_SeqAIJ_Inode(A, mode));
1143:   PetscFunctionReturn(PETSC_SUCCESS);
1144: }

1146: static PetscErrorCode MatRealPart_SeqAIJ(Mat A)
1147: {
1148:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1149:   PetscInt    i, nz = a->nz;
1150:   MatScalar  *aa;

1152:   PetscFunctionBegin;
1153:   PetscCall(MatSeqAIJGetArray(A, &aa));
1154:   for (i = 0; i < nz; i++) aa[i] = PetscRealPart(aa[i]);
1155:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
1156:   PetscFunctionReturn(PETSC_SUCCESS);
1157: }

1159: static PetscErrorCode MatImaginaryPart_SeqAIJ(Mat A)
1160: {
1161:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1162:   PetscInt    i, nz = a->nz;
1163:   MatScalar  *aa;

1165:   PetscFunctionBegin;
1166:   PetscCall(MatSeqAIJGetArray(A, &aa));
1167:   for (i = 0; i < nz; i++) aa[i] = PetscImaginaryPart(aa[i]);
1168:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
1169:   PetscFunctionReturn(PETSC_SUCCESS);
1170: }

1172: PetscErrorCode MatZeroEntries_SeqAIJ(Mat A)
1173: {
1174:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1175:   MatScalar  *aa;

1177:   PetscFunctionBegin;
1178:   PetscCall(MatSeqAIJGetArrayWrite(A, &aa));
1179:   PetscCall(PetscArrayzero(aa, a->i[A->rmap->n]));
1180:   PetscCall(MatSeqAIJRestoreArrayWrite(A, &aa));
1181:   PetscFunctionReturn(PETSC_SUCCESS);
1182: }

1184: static PetscErrorCode MatReset_SeqAIJ(Mat A)
1185: {
1186:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

1188:   PetscFunctionBegin;
1189:   if (A->hash_active) {
1190:     A->ops[0] = a->cops;
1191:     PetscCall(PetscHMapIJVDestroy(&a->ht));
1192:     PetscCall(PetscFree(a->dnz));
1193:     A->hash_active = PETSC_FALSE;
1194:   }

1196:   PetscCall(PetscLogObjectState((PetscObject)A, "Rows=%" PetscInt_FMT ", Cols=%" PetscInt_FMT ", NZ=%" PetscInt_FMT, A->rmap->n, A->cmap->n, a->nz));
1197:   PetscCall(MatSeqXAIJFreeAIJ(A, &a->a, &a->j, &a->i));
1198:   PetscCall(ISDestroy(&a->row));
1199:   PetscCall(ISDestroy(&a->col));
1200:   PetscCall(PetscFree(a->diag));
1201:   PetscCall(PetscFree(a->ibdiag));
1202:   PetscCall(PetscFree(a->imax));
1203:   PetscCall(PetscFree(a->ilen));
1204:   PetscCall(PetscFree(a->ipre));
1205:   PetscCall(PetscFree3(a->idiag, a->mdiag, a->ssor_work));
1206:   PetscCall(PetscFree(a->solve_work));
1207:   PetscCall(ISDestroy(&a->icol));
1208:   PetscCall(PetscFree(a->saved_values));
1209:   a->compressedrow.use = PETSC_FALSE;
1210:   PetscCall(PetscFree2(a->compressedrow.i, a->compressedrow.rindex));
1211:   PetscCall(MatDestroy_SeqAIJ_Inode(A));
1212:   PetscFunctionReturn(PETSC_SUCCESS);
1213: }

1215: static PetscErrorCode MatResetHash_SeqAIJ(Mat A)
1216: {
1217:   PetscFunctionBegin;
1218:   PetscCall(MatReset_SeqAIJ(A));
1219:   PetscCall(MatCreate_SeqAIJ_Inode(A));
1220:   PetscCall(MatSetUp_Seq_Hash(A));
1221:   A->nonzerostate++;
1222:   PetscFunctionReturn(PETSC_SUCCESS);
1223: }

1225: PetscErrorCode MatDestroy_SeqAIJ(Mat A)
1226: {
1227:   PetscFunctionBegin;
1228:   PetscCall(MatReset_SeqAIJ(A));
1229:   PetscCall(PetscFree(A->data));

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

1238:   PetscCall(PetscObjectChangeTypeName((PetscObject)A, NULL));
1239:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "PetscMatlabEnginePut_C", NULL));
1240:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "PetscMatlabEngineGet_C", NULL));
1241:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetColumnIndices_C", NULL));
1242:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatStoreValues_C", NULL));
1243:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatRetrieveValues_C", NULL));
1244:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqsbaij_C", NULL));
1245:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqbaij_C", NULL));
1246:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijperm_C", NULL));
1247:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijsell_C", NULL));
1248: #if PetscDefined(HAVE_MKL_SPARSE)
1249:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijmkl_C", NULL));
1250: #endif
1251: #if PetscDefined(HAVE_CUDA)
1252:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijcusparse_C", NULL));
1253:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijcusparse_seqaij_C", NULL));
1254:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaijcusparse_C", NULL));
1255: #endif
1256: #if PetscDefined(HAVE_HIP)
1257:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijhipsparse_C", NULL));
1258:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqaij_C", NULL));
1259:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaijhipsparse_C", NULL));
1260: #endif
1261: #if PetscDefined(HAVE_KOKKOS_KERNELS)
1262:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijkokkos_C", NULL));
1263: #endif
1264:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijcrl_C", NULL));
1265: #if PetscDefined(HAVE_ELEMENTAL)
1266:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_elemental_C", NULL));
1267: #endif
1268: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
1269:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_scalapack_C", NULL));
1270: #endif
1271: #if PetscDefined(HAVE_HYPRE)
1272:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_hypre_C", NULL));
1273:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_transpose_seqaij_seqaij_C", NULL));
1274: #endif
1275:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqdense_C", NULL));
1276:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqsell_C", NULL));
1277:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_is_C", NULL));
1278:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatIsTranspose_C", NULL));
1279:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatIsHermitianTranspose_C", NULL));
1280:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetPreallocation_C", NULL));
1281:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatResetPreallocation_C", NULL));
1282:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatResetHash_C", NULL));
1283:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetPreallocationCSR_C", NULL));
1284:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatReorderForNonzeroDiagonal_C", NULL));
1285:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_is_seqaij_C", NULL));
1286:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqdense_seqaij_C", NULL));
1287:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaij_C", NULL));
1288:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJKron_C", NULL));
1289:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL));
1290:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL));
1291:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatFactorGetSolverType_C", NULL));
1292:   /* these calls do not belong here: the subclasses Duplicate/Destroy are wrong */
1293:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijsell_seqaij_C", NULL));
1294:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijperm_seqaij_C", NULL));
1295:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijviennacl_C", NULL));
1296:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijviennacl_seqdense_C", NULL));
1297:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijviennacl_seqaij_C", NULL));
1298:   PetscFunctionReturn(PETSC_SUCCESS);
1299: }

1301: PetscErrorCode MatSetOption_SeqAIJ(Mat A, MatOption op, PetscBool flg)
1302: {
1303:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

1305:   PetscFunctionBegin;
1306:   switch (op) {
1307:   case MAT_ROW_ORIENTED:
1308:     a->roworiented = flg;
1309:     break;
1310:   case MAT_KEEP_NONZERO_PATTERN:
1311:     a->keepnonzeropattern = flg;
1312:     break;
1313:   case MAT_NEW_NONZERO_LOCATIONS:
1314:     a->nonew = (flg ? 0 : 1);
1315:     break;
1316:   case MAT_NEW_NONZERO_LOCATION_ERR:
1317:     a->nonew = (flg ? -1 : 0);
1318:     break;
1319:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1320:     a->nonew = (flg ? -2 : 0);
1321:     break;
1322:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1323:     a->nounused = (flg ? -1 : 0);
1324:     break;
1325:   case MAT_IGNORE_ZERO_ENTRIES:
1326:     a->ignorezeroentries = flg;
1327:     break;
1328:   case MAT_USE_INODES:
1329:     PetscCall(MatSetOption_SeqAIJ_Inode(A, MAT_USE_INODES, flg));
1330:     break;
1331:   case MAT_SUBMAT_SINGLEIS:
1332:     A->submat_singleis = flg;
1333:     break;
1334:   case MAT_SORTED_FULL:
1335:     if (flg) A->ops->setvalues = MatSetValues_SeqAIJ_SortedFull;
1336:     else A->ops->setvalues = MatSetValues_SeqAIJ;
1337:     break;
1338:   case MAT_FORM_EXPLICIT_TRANSPOSE:
1339:     A->form_explicit_transpose = flg;
1340:     break;
1341:   default:
1342:     break;
1343:   }
1344:   PetscFunctionReturn(PETSC_SUCCESS);
1345: }

1347: PETSC_INTERN PetscErrorCode MatGetDiagonal_SeqAIJ(Mat A, Vec v)
1348: {
1349:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1350:   PetscInt           n, *ai = a->i;
1351:   PetscScalar       *x;
1352:   const PetscScalar *aa;
1353:   const PetscInt    *diag;
1354:   PetscBool          diagDense;

1356:   PetscFunctionBegin;
1357:   PetscCall(VecGetLocalSize(v, &n));
1358:   PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
1359:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
1360:   if (A->factortype == MAT_FACTOR_ILU || A->factortype == MAT_FACTOR_LU) {
1361:     PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, NULL));
1362:     PetscCall(VecGetArrayWrite(v, &x));
1363:     for (PetscInt i = 0; i < n; i++) x[i] = 1.0 / aa[diag[i]];
1364:     PetscCall(VecRestoreArrayWrite(v, &x));
1365:     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1366:     PetscFunctionReturn(PETSC_SUCCESS);
1367:   }

1369:   PetscCheck(A->factortype == MAT_FACTOR_NONE, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Not for factor matrices that are not ILU or LU");
1370:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, &diagDense));
1371:   PetscCall(VecGetArrayWrite(v, &x));
1372:   if (diagDense) {
1373:     for (PetscInt i = 0; i < n; i++) x[i] = aa[diag[i]];
1374:   } else {
1375:     for (PetscInt i = 0; i < n; i++) x[i] = (diag[i] == ai[i + 1]) ? 0.0 : aa[diag[i]];
1376:   }
1377:   PetscCall(VecRestoreArrayWrite(v, &x));
1378:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1379:   PetscFunctionReturn(PETSC_SUCCESS);
1380: }

1382: #include <../src/mat/impls/aij/seq/ftn-kernels/fmult.h>
1383: PetscErrorCode MatMultTransposeAdd_SeqAIJ(Mat A, Vec xx, Vec zz, Vec yy)
1384: {
1385:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1386:   const MatScalar   *aa;
1387:   PetscScalar       *y;
1388:   const PetscScalar *x;
1389:   PetscInt           m = A->rmap->n;
1390: #if !PetscDefined(USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1391:   const MatScalar  *v;
1392:   PetscScalar       alpha;
1393:   PetscInt          n, i, j;
1394:   const PetscInt   *idx, *ii, *ridx = NULL;
1395:   Mat_CompressedRow cprow    = a->compressedrow;
1396:   PetscBool         usecprow = cprow.use;
1397: #endif

1399:   PetscFunctionBegin;
1400:   if (zz != yy) PetscCall(VecCopy(zz, yy));
1401:   PetscCall(VecGetArrayRead(xx, &x));
1402:   PetscCall(VecGetArray(yy, &y));
1403:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));

1405: #if PetscDefined(USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1406:   fortranmulttransposeaddaij_(&m, x, a->i, a->j, aa, y);
1407: #else
1408:   if (usecprow) {
1409:     m    = cprow.nrows;
1410:     ii   = cprow.i;
1411:     ridx = cprow.rindex;
1412:   } else {
1413:     ii = a->i;
1414:   }
1415:   for (i = 0; i < m; i++) {
1416:     idx = a->j + ii[i];
1417:     v   = aa + ii[i];
1418:     n   = ii[i + 1] - ii[i];
1419:     if (usecprow) {
1420:       alpha = x[ridx[i]];
1421:     } else {
1422:       alpha = x[i];
1423:     }
1424:     for (j = 0; j < n; j++) y[idx[j]] += alpha * v[j];
1425:   }
1426: #endif
1427:   PetscCall(PetscLogFlops(2.0 * a->nz));
1428:   PetscCall(VecRestoreArrayRead(xx, &x));
1429:   PetscCall(VecRestoreArray(yy, &y));
1430:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1431:   PetscFunctionReturn(PETSC_SUCCESS);
1432: }

1434: PetscErrorCode MatMultTranspose_SeqAIJ(Mat A, Vec xx, Vec yy)
1435: {
1436:   PetscFunctionBegin;
1437:   PetscCall(VecSet(yy, 0.0));
1438:   PetscCall(MatMultTransposeAdd_SeqAIJ(A, xx, yy, yy));
1439:   PetscFunctionReturn(PETSC_SUCCESS);
1440: }

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

1444: PetscErrorCode MatMult_SeqAIJ(Mat A, Vec xx, Vec yy)
1445: {
1446:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1447:   PetscScalar       *y;
1448:   const PetscScalar *x;
1449:   const MatScalar   *a_a;
1450:   PetscInt           m = A->rmap->n;
1451:   const PetscInt    *ii, *ridx = NULL;
1452:   PetscBool          usecprow = a->compressedrow.use;

1454: #if PetscDefined(HAVE_PRAGMA_DISJOINT)
1455:   #pragma disjoint(*x, *y, *aa)
1456: #endif

1458:   PetscFunctionBegin;
1459:   if (a->inode.use && a->inode.checked) {
1460:     PetscCall(MatMult_SeqAIJ_Inode(A, xx, yy));
1461:     PetscFunctionReturn(PETSC_SUCCESS);
1462:   }
1463:   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1464:   PetscCall(VecGetArrayRead(xx, &x));
1465:   PetscCall(VecGetArray(yy, &y));
1466:   ii = a->i;
1467:   if (usecprow) { /* use compressed row format */
1468:     PetscCall(PetscArrayzero(y, m));
1469:     m    = a->compressedrow.nrows;
1470:     ii   = a->compressedrow.i;
1471:     ridx = a->compressedrow.rindex;
1472:     PetscPragmaUseOMPKernels(parallel for)
1473:     for (PetscInt i = 0; i < m; i++) {
1474:       PetscInt           n   = ii[i + 1] - ii[i];
1475:       const PetscInt    *aj  = a->j + ii[i];
1476:       const PetscScalar *aa  = a_a + ii[i];
1477:       PetscScalar        sum = 0.0;
1478:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1479:       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1480:       y[ridx[i]] = sum;
1481:     }
1482:   } else { /* do not use compressed row format */
1483: #if PetscDefined(USE_FORTRAN_KERNEL_MULTAIJ)
1484:     fortranmultaij_(&m, x, ii, a->j, a_a, y);
1485: #else
1486:     PetscPragmaUseOMPKernels(parallel for)
1487:     for (PetscInt i = 0; i < m; i++) {
1488:       PetscInt           n   = ii[i + 1] - ii[i];
1489:       const PetscInt    *aj  = a->j + ii[i];
1490:       const PetscScalar *aa  = a_a + ii[i];
1491:       PetscScalar        sum = 0.0;
1492:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1493:       y[i] = sum;
1494:     }
1495: #endif
1496:   }
1497:   PetscCall(PetscLogFlops(2.0 * a->nz - a->nonzerorowcnt));
1498:   PetscCall(VecRestoreArrayRead(xx, &x));
1499:   PetscCall(VecRestoreArray(yy, &y));
1500:   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1501:   PetscFunctionReturn(PETSC_SUCCESS);
1502: }

1504: // HACK!!!!! Used by src/mat/tests/ex170.c
1505: PETSC_EXTERN PetscErrorCode MatMultMax_SeqAIJ(Mat A, Vec xx, Vec yy)
1506: {
1507:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1508:   PetscScalar       *y;
1509:   const PetscScalar *x;
1510:   const MatScalar   *aa, *a_a;
1511:   PetscInt           m = A->rmap->n;
1512:   const PetscInt    *aj, *ii, *ridx   = NULL;
1513:   PetscInt           n, i, nonzerorow = 0;
1514:   PetscScalar        sum;
1515:   PetscBool          usecprow = a->compressedrow.use;

1517: #if PetscDefined(HAVE_PRAGMA_DISJOINT)
1518:   #pragma disjoint(*x, *y, *aa)
1519: #endif

1521:   PetscFunctionBegin;
1522:   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1523:   PetscCall(VecGetArrayRead(xx, &x));
1524:   PetscCall(VecGetArray(yy, &y));
1525:   if (usecprow) { /* use compressed row format */
1526:     m    = a->compressedrow.nrows;
1527:     ii   = a->compressedrow.i;
1528:     ridx = a->compressedrow.rindex;
1529:     for (i = 0; i < m; i++) {
1530:       n   = ii[i + 1] - ii[i];
1531:       aj  = a->j + ii[i];
1532:       aa  = a_a + ii[i];
1533:       sum = 0.0;
1534:       nonzerorow += (n > 0);
1535:       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1536:       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1537:       y[*ridx++] = sum;
1538:     }
1539:   } else { /* do not use compressed row format */
1540:     ii = a->i;
1541:     for (i = 0; i < m; i++) {
1542:       n   = ii[i + 1] - ii[i];
1543:       aj  = a->j + ii[i];
1544:       aa  = a_a + ii[i];
1545:       sum = 0.0;
1546:       nonzerorow += (n > 0);
1547:       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1548:       y[i] = sum;
1549:     }
1550:   }
1551:   PetscCall(PetscLogFlops(2.0 * a->nz - nonzerorow));
1552:   PetscCall(VecRestoreArrayRead(xx, &x));
1553:   PetscCall(VecRestoreArray(yy, &y));
1554:   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1555:   PetscFunctionReturn(PETSC_SUCCESS);
1556: }

1558: // HACK!!!!! Used by src/mat/tests/ex170.c
1559: PETSC_EXTERN PetscErrorCode MatMultAddMax_SeqAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1560: {
1561:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1562:   PetscScalar       *y, *z;
1563:   const PetscScalar *x;
1564:   const MatScalar   *aa, *a_a;
1565:   PetscInt           m = A->rmap->n, *aj, *ii;
1566:   PetscInt           n, i, *ridx = NULL;
1567:   PetscScalar        sum;
1568:   PetscBool          usecprow = a->compressedrow.use;

1570:   PetscFunctionBegin;
1571:   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1572:   PetscCall(VecGetArrayRead(xx, &x));
1573:   PetscCall(VecGetArrayPair(yy, zz, &y, &z));
1574:   if (usecprow) { /* use compressed row format */
1575:     if (zz != yy) PetscCall(PetscArraycpy(z, y, m));
1576:     m    = a->compressedrow.nrows;
1577:     ii   = a->compressedrow.i;
1578:     ridx = a->compressedrow.rindex;
1579:     for (i = 0; i < m; i++) {
1580:       n   = ii[i + 1] - ii[i];
1581:       aj  = a->j + ii[i];
1582:       aa  = a_a + ii[i];
1583:       sum = y[*ridx];
1584:       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1585:       z[*ridx++] = sum;
1586:     }
1587:   } else { /* do not use compressed row format */
1588:     ii = a->i;
1589:     for (i = 0; i < m; i++) {
1590:       n   = ii[i + 1] - ii[i];
1591:       aj  = a->j + ii[i];
1592:       aa  = a_a + ii[i];
1593:       sum = y[i];
1594:       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1595:       z[i] = sum;
1596:     }
1597:   }
1598:   PetscCall(PetscLogFlops(2.0 * a->nz));
1599:   PetscCall(VecRestoreArrayRead(xx, &x));
1600:   PetscCall(VecRestoreArrayPair(yy, zz, &y, &z));
1601:   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1602:   PetscFunctionReturn(PETSC_SUCCESS);
1603: }

1605: #include <../src/mat/impls/aij/seq/ftn-kernels/fmultadd.h>
1606: PetscErrorCode MatMultAdd_SeqAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1607: {
1608:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1609:   PetscScalar       *y, *z;
1610:   const PetscScalar *x;
1611:   const MatScalar   *a_a;
1612:   const PetscInt    *ii, *ridx = NULL;
1613:   PetscInt           m        = A->rmap->n;
1614:   PetscBool          usecprow = a->compressedrow.use;

1616:   PetscFunctionBegin;
1617:   if (a->inode.use && a->inode.checked) {
1618:     PetscCall(MatMultAdd_SeqAIJ_Inode(A, xx, yy, zz));
1619:     PetscFunctionReturn(PETSC_SUCCESS);
1620:   }
1621:   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1622:   PetscCall(VecGetArrayRead(xx, &x));
1623:   PetscCall(VecGetArrayPair(yy, zz, &y, &z));
1624:   if (usecprow) { /* use compressed row format */
1625:     if (zz != yy) PetscCall(PetscArraycpy(z, y, m));
1626:     m    = a->compressedrow.nrows;
1627:     ii   = a->compressedrow.i;
1628:     ridx = a->compressedrow.rindex;
1629:     for (PetscInt i = 0; i < m; i++) {
1630:       PetscInt           n   = ii[i + 1] - ii[i];
1631:       const PetscInt    *aj  = a->j + ii[i];
1632:       const PetscScalar *aa  = a_a + ii[i];
1633:       PetscScalar        sum = y[*ridx];
1634:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1635:       z[*ridx++] = sum;
1636:     }
1637:   } else { /* do not use compressed row format */
1638:     ii = a->i;
1639: #if PetscDefined(USE_FORTRAN_KERNEL_MULTADDAIJ)
1640:     fortranmultaddaij_(&m, x, ii, a->j, a_a, y, z);
1641: #else
1642:     PetscPragmaUseOMPKernels(parallel for)
1643:     for (PetscInt i = 0; i < m; i++) {
1644:       PetscInt           n   = ii[i + 1] - ii[i];
1645:       const PetscInt    *aj  = a->j + ii[i];
1646:       const PetscScalar *aa  = a_a + ii[i];
1647:       PetscScalar        sum = y[i];
1648:       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1649:       z[i] = sum;
1650:     }
1651: #endif
1652:   }
1653:   PetscCall(PetscLogFlops(2.0 * a->nz));
1654:   PetscCall(VecRestoreArrayRead(xx, &x));
1655:   PetscCall(VecRestoreArrayPair(yy, zz, &y, &z));
1656:   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1657:   PetscFunctionReturn(PETSC_SUCCESS);
1658: }

1660: static PetscErrorCode MatShift_SeqAIJ(Mat A, PetscScalar v)
1661: {
1662:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
1663:   const PetscInt *diag;
1664:   const PetscInt *ii = (const PetscInt *)a->i;
1665:   PetscBool       diagDense;

1667:   PetscFunctionBegin;
1668:   if (!A->preallocated || !a->nz) {
1669:     PetscCall(MatSeqAIJSetPreallocation(A, 1, NULL));
1670:     PetscCall(MatShift_Basic(A, v));
1671:     PetscFunctionReturn(PETSC_SUCCESS);
1672:   }

1674:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, &diagDense));
1675:   if (diagDense) {
1676:     PetscScalar *Aa;

1678:     PetscCall(MatSeqAIJGetArray(A, &Aa));
1679:     for (PetscInt i = 0; i < A->rmap->n; i++) Aa[diag[i]] += v;
1680:     PetscCall(MatSeqAIJRestoreArray(A, &Aa));
1681:   } else {
1682:     PetscScalar       *olda = a->a; /* preserve pointers to current matrix nonzeros structure and values */
1683:     PetscInt          *oldj = a->j, *oldi = a->i;
1684:     PetscBool          free_a = a->free_a, free_ij = a->free_ij;
1685:     const PetscScalar *Aa;
1686:     PetscInt          *mdiag = NULL;

1688:     PetscCall(PetscCalloc1(A->rmap->n, &mdiag));
1689:     for (PetscInt i = 0; i < A->rmap->n; i++) {
1690:       if (i < A->cmap->n && diag[i] >= ii[i + 1]) { /* 'out of range' rows never have diagonals */
1691:         mdiag[i] = 1;
1692:       }
1693:     }
1694:     PetscCall(MatSeqAIJGetArrayRead(A, &Aa)); // sync the host
1695:     PetscCall(MatSeqAIJRestoreArrayRead(A, &Aa));

1697:     a->a = NULL;
1698:     a->j = NULL;
1699:     a->i = NULL;
1700:     /* increase the values in imax for each row where a diagonal is being inserted then reallocate the matrix data structures */
1701:     for (PetscInt i = 0; i < PetscMin(A->rmap->n, A->cmap->n); i++) a->imax[i] += mdiag[i];
1702:     PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(A, 0, a->imax));

1704:     /* copy old values into new matrix data structure */
1705:     for (PetscInt i = 0; i < A->rmap->n; i++) {
1706:       PetscCall(MatSetValues(A, 1, &i, a->imax[i] - mdiag[i], &oldj[oldi[i]], &olda[oldi[i]], ADD_VALUES));
1707:       if (i < A->cmap->n) PetscCall(MatSetValue(A, i, i, v, ADD_VALUES));
1708:     }
1709:     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1710:     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1711:     if (free_a) PetscCall(PetscShmgetDeallocateArray((void **)&olda));
1712:     if (free_ij) PetscCall(PetscShmgetDeallocateArray((void **)&oldj));
1713:     if (free_ij) PetscCall(PetscShmgetDeallocateArray((void **)&oldi));
1714:     PetscCall(PetscFree(mdiag));
1715:   }
1716:   PetscFunctionReturn(PETSC_SUCCESS);
1717: }

1719: #include <petscblaslapack.h>
1720: #include <petsc/private/kernels/blockinvert.h>

1722: /*
1723:     Note that values is allocated externally by the PC and then passed into this routine
1724: */
1725: static PetscErrorCode MatInvertVariableBlockDiagonal_SeqAIJ(Mat A, PetscInt nblocks, const PetscInt *bsizes, PetscScalar *diag)
1726: {
1727:   PetscInt        n = A->rmap->n, i, ncnt = 0, *indx, j, bsizemax = 0, *v_pivots;
1728:   PetscBool       allowzeropivot, zeropivotdetected = PETSC_FALSE;
1729:   const PetscReal shift = 0.0;
1730:   PetscInt        ipvt[5];
1731:   PetscCount      flops = 0;
1732:   PetscScalar     work[25], *v_work;

1734:   PetscFunctionBegin;
1735:   allowzeropivot = PetscNot(A->erroriffailure);
1736:   for (i = 0; i < nblocks; i++) ncnt += bsizes[i];
1737:   PetscCheck(ncnt == n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Total blocksizes %" PetscInt_FMT " doesn't match number matrix rows %" PetscInt_FMT, ncnt, n);
1738:   for (i = 0; i < nblocks; i++) bsizemax = PetscMax(bsizemax, bsizes[i]);
1739:   PetscCall(PetscMalloc1(bsizemax, &indx));
1740:   if (bsizemax > 7) PetscCall(PetscMalloc2(bsizemax, &v_work, bsizemax, &v_pivots));
1741:   ncnt = 0;
1742:   for (i = 0; i < nblocks; i++) {
1743:     for (j = 0; j < bsizes[i]; j++) indx[j] = ncnt + j;
1744:     PetscCall(MatGetValues(A, bsizes[i], indx, bsizes[i], indx, diag));
1745:     switch (bsizes[i]) {
1746:     case 1:
1747:       *diag = 1.0 / (*diag);
1748:       break;
1749:     case 2:
1750:       PetscCall(PetscKernel_A_gets_inverse_A_2(diag, shift, allowzeropivot, &zeropivotdetected));
1751:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1752:       PetscCall(PetscKernel_A_gets_transpose_A_2(diag));
1753:       break;
1754:     case 3:
1755:       PetscCall(PetscKernel_A_gets_inverse_A_3(diag, shift, allowzeropivot, &zeropivotdetected));
1756:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1757:       PetscCall(PetscKernel_A_gets_transpose_A_3(diag));
1758:       break;
1759:     case 4:
1760:       PetscCall(PetscKernel_A_gets_inverse_A_4(diag, shift, allowzeropivot, &zeropivotdetected));
1761:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1762:       PetscCall(PetscKernel_A_gets_transpose_A_4(diag));
1763:       break;
1764:     case 5:
1765:       PetscCall(PetscKernel_A_gets_inverse_A_5(diag, ipvt, work, shift, allowzeropivot, &zeropivotdetected));
1766:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1767:       PetscCall(PetscKernel_A_gets_transpose_A_5(diag));
1768:       break;
1769:     case 6:
1770:       PetscCall(PetscKernel_A_gets_inverse_A_6(diag, shift, allowzeropivot, &zeropivotdetected));
1771:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1772:       PetscCall(PetscKernel_A_gets_transpose_A_6(diag));
1773:       break;
1774:     case 7:
1775:       PetscCall(PetscKernel_A_gets_inverse_A_7(diag, shift, allowzeropivot, &zeropivotdetected));
1776:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1777:       PetscCall(PetscKernel_A_gets_transpose_A_7(diag));
1778:       break;
1779:     default:
1780:       PetscCall(PetscKernel_A_gets_inverse_A(bsizes[i], diag, v_pivots, v_work, allowzeropivot, &zeropivotdetected));
1781:       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1782:       PetscCall(PetscKernel_A_gets_transpose_A_N(diag, bsizes[i]));
1783:     }
1784:     ncnt += bsizes[i];
1785:     diag += bsizes[i] * bsizes[i];
1786:     flops += 2 * PetscPowInt64(bsizes[i], 3) / 3;
1787:   }
1788:   PetscCall(PetscLogFlops(flops));
1789:   if (bsizemax > 7) PetscCall(PetscFree2(v_work, v_pivots));
1790:   PetscCall(PetscFree(indx));
1791:   PetscFunctionReturn(PETSC_SUCCESS);
1792: }

1794: /*
1795:    Negative shift indicates do not generate an error if there is a zero diagonal, just invert it anyways
1796: */
1797: static PetscErrorCode MatInvertDiagonalForSOR_SeqAIJ(Mat A, PetscScalar omega, PetscScalar fshift)
1798: {
1799:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
1800:   PetscInt         i, m = A->rmap->n;
1801:   const MatScalar *v;
1802:   PetscScalar     *idiag, *mdiag;
1803:   PetscBool        diagDense;
1804:   const PetscInt  *diag;

1806:   PetscFunctionBegin;
1807:   if (a->idiagState == ((PetscObject)A)->state && a->omega == omega && a->fshift == fshift) PetscFunctionReturn(PETSC_SUCCESS);
1808:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, &diagDense));
1809:   PetscCheck(diagDense, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix must have all diagonal locations to invert them");
1810:   if (!a->idiag) PetscCall(PetscMalloc3(m, &a->idiag, m, &a->mdiag, m, &a->ssor_work));

1812:   mdiag = a->mdiag;
1813:   idiag = a->idiag;
1814:   PetscCall(MatSeqAIJGetArrayRead(A, &v));
1815:   if (omega == 1.0 && PetscRealPart(fshift) <= 0.0) {
1816:     for (i = 0; i < m; i++) {
1817:       mdiag[i] = v[diag[i]];
1818:       if (!PetscAbsScalar(mdiag[i])) { /* zero diagonal */
1819:         PetscCheck(PetscRealPart(fshift), PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Zero diagonal on row %" PetscInt_FMT, i);
1820:         PetscCall(PetscInfo(A, "Zero diagonal on row %" PetscInt_FMT "\n", i));
1821:         A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1822:         A->factorerror_zeropivot_value = 0.0;
1823:         A->factorerror_zeropivot_row   = i;
1824:       }
1825:       idiag[i] = 1.0 / v[diag[i]];
1826:     }
1827:     PetscCall(PetscLogFlops(m));
1828:   } else {
1829:     for (i = 0; i < m; i++) {
1830:       mdiag[i] = v[diag[i]];
1831:       idiag[i] = omega / (fshift + v[diag[i]]);
1832:     }
1833:     PetscCall(PetscLogFlops(2.0 * m));
1834:   }
1835:   PetscCall(MatSeqAIJRestoreArrayRead(A, &v));
1836:   a->idiagState = ((PetscObject)A)->state;
1837:   a->omega      = omega;
1838:   a->fshift     = fshift;
1839:   PetscFunctionReturn(PETSC_SUCCESS);
1840: }

1842: PetscErrorCode MatSOR_SeqAIJ(Mat A, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1843: {
1844:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1845:   PetscScalar       *x, d, sum, *t, scale;
1846:   const MatScalar   *v, *idiag = NULL, *mdiag, *aa;
1847:   const PetscScalar *b, *bs, *xb, *ts;
1848:   PetscInt           n, m = A->rmap->n, i;
1849:   const PetscInt    *idx, *diag;

1851:   PetscFunctionBegin;
1852:   if (a->inode.use && a->inode.checked && omega == 1.0 && fshift == 0.0) {
1853:     PetscCall(MatSOR_SeqAIJ_Inode(A, bb, omega, flag, fshift, its, lits, xx));
1854:     PetscFunctionReturn(PETSC_SUCCESS);
1855:   }
1856:   its = its * lits;
1857:   PetscCall(MatInvertDiagonalForSOR_SeqAIJ(A, omega, fshift));
1858:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, NULL));
1859:   t     = a->ssor_work;
1860:   idiag = a->idiag;
1861:   mdiag = a->mdiag;

1863:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
1864:   PetscCall(VecGetArray(xx, &x));
1865:   PetscCall(VecGetArrayRead(bb, &b));
1866:   /* We count flops by assuming the upper triangular and lower triangular parts have the same number of nonzeros */
1867:   if (flag == SOR_APPLY_UPPER) {
1868:     /* apply (U + D/omega) to the vector */
1869:     bs = b;
1870:     for (i = 0; i < m; i++) {
1871:       d   = fshift + mdiag[i];
1872:       n   = a->i[i + 1] - diag[i] - 1;
1873:       idx = a->j + diag[i] + 1;
1874:       v   = aa + diag[i] + 1;
1875:       sum = b[i] * d / omega;
1876:       PetscSparseDensePlusDot(sum, bs, v, idx, n);
1877:       x[i] = sum;
1878:     }
1879:     PetscCall(VecRestoreArray(xx, &x));
1880:     PetscCall(VecRestoreArrayRead(bb, &b));
1881:     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1882:     PetscCall(PetscLogFlops(a->nz));
1883:     PetscFunctionReturn(PETSC_SUCCESS);
1884:   }

1886:   PetscCheck(flag != SOR_APPLY_LOWER, PETSC_COMM_SELF, PETSC_ERR_SUP, "SOR_APPLY_LOWER is not implemented");
1887:   if (flag & SOR_EISENSTAT) {
1888:     /* Let  A = L + U + D; where L is lower triangular,
1889:     U is upper triangular, E = D/omega; This routine applies

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

1893:     to a vector efficiently using Eisenstat's trick.
1894:     */
1895:     scale = (2.0 / omega) - 1.0;

1897:     /*  x = (E + U)^{-1} b */
1898:     for (i = m - 1; i >= 0; i--) {
1899:       n   = a->i[i + 1] - diag[i] - 1;
1900:       idx = a->j + diag[i] + 1;
1901:       v   = aa + diag[i] + 1;
1902:       sum = b[i];
1903:       PetscSparseDenseMinusDot(sum, x, v, idx, n);
1904:       x[i] = sum * idiag[i];
1905:     }

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

1911:     /*  t = (E + L)^{-1}t */
1912:     ts   = t;
1913:     diag = a->diag;
1914:     for (i = 0; i < m; i++) {
1915:       n   = diag[i] - a->i[i];
1916:       idx = a->j + a->i[i];
1917:       v   = aa + a->i[i];
1918:       sum = t[i];
1919:       PetscSparseDenseMinusDot(sum, ts, v, idx, n);
1920:       t[i] = sum * idiag[i];
1921:       /*  x = x + t */
1922:       x[i] += t[i];
1923:     }

1925:     PetscCall(PetscLogFlops(6.0 * m - 1 + 2.0 * a->nz));
1926:     PetscCall(VecRestoreArray(xx, &x));
1927:     PetscCall(VecRestoreArrayRead(bb, &b));
1928:     PetscFunctionReturn(PETSC_SUCCESS);
1929:   }
1930:   if (flag & SOR_ZERO_INITIAL_GUESS) {
1931:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1932:       for (i = 0; i < m; i++) {
1933:         n   = diag[i] - a->i[i];
1934:         idx = a->j + a->i[i];
1935:         v   = aa + a->i[i];
1936:         sum = b[i];
1937:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
1938:         t[i] = sum;
1939:         x[i] = sum * idiag[i];
1940:       }
1941:       xb = t;
1942:       PetscCall(PetscLogFlops(a->nz));
1943:     } else xb = b;
1944:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1945:       for (i = m - 1; i >= 0; i--) {
1946:         n   = a->i[i + 1] - diag[i] - 1;
1947:         idx = a->j + diag[i] + 1;
1948:         v   = aa + diag[i] + 1;
1949:         sum = xb[i];
1950:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
1951:         if (xb == b) {
1952:           x[i] = sum * idiag[i];
1953:         } else {
1954:           x[i] = (1 - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
1955:         }
1956:       }
1957:       PetscCall(PetscLogFlops(a->nz)); /* assumes 1/2 in upper */
1958:     }
1959:     its--;
1960:   }
1961:   while (its--) {
1962:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1963:       for (i = 0; i < m; i++) {
1964:         /* lower */
1965:         n   = diag[i] - a->i[i];
1966:         idx = a->j + a->i[i];
1967:         v   = aa + a->i[i];
1968:         sum = b[i];
1969:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
1970:         t[i] = sum; /* save application of the lower-triangular part */
1971:         /* upper */
1972:         n   = a->i[i + 1] - diag[i] - 1;
1973:         idx = a->j + diag[i] + 1;
1974:         v   = aa + diag[i] + 1;
1975:         PetscSparseDenseMinusDot(sum, x, v, idx, n);
1976:         x[i] = (1. - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
1977:       }
1978:       xb = t;
1979:       PetscCall(PetscLogFlops(2.0 * a->nz));
1980:     } else xb = b;
1981:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1982:       for (i = m - 1; i >= 0; i--) {
1983:         sum = xb[i];
1984:         if (xb == b) {
1985:           /* whole matrix (no checkpointing available) */
1986:           n   = a->i[i + 1] - a->i[i];
1987:           idx = a->j + a->i[i];
1988:           v   = aa + a->i[i];
1989:           PetscSparseDenseMinusDot(sum, x, v, idx, n);
1990:           x[i] = (1. - omega) * x[i] + (sum + mdiag[i] * x[i]) * idiag[i];
1991:         } else { /* lower-triangular part has been saved, so only apply upper-triangular */
1992:           n   = a->i[i + 1] - diag[i] - 1;
1993:           idx = a->j + diag[i] + 1;
1994:           v   = aa + diag[i] + 1;
1995:           PetscSparseDenseMinusDot(sum, x, v, idx, n);
1996:           x[i] = (1. - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
1997:         }
1998:       }
1999:       if (xb == b) PetscCall(PetscLogFlops(2.0 * a->nz));
2000:       else PetscCall(PetscLogFlops(a->nz)); /* assumes 1/2 in upper */
2001:     }
2002:   }
2003:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2004:   PetscCall(VecRestoreArray(xx, &x));
2005:   PetscCall(VecRestoreArrayRead(bb, &b));
2006:   PetscFunctionReturn(PETSC_SUCCESS);
2007: }

2009: static PetscErrorCode MatGetInfo_SeqAIJ(Mat A, MatInfoType flag, MatInfo *info)
2010: {
2011:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

2013:   PetscFunctionBegin;
2014:   info->block_size   = 1.0;
2015:   info->nz_allocated = a->maxnz;
2016:   info->nz_used      = a->nz;
2017:   info->nz_unneeded  = (a->maxnz - a->nz);
2018:   info->assemblies   = A->num_ass;
2019:   info->mallocs      = A->info.mallocs;
2020:   info->memory       = 0; /* REVIEW ME */
2021:   if (A->factortype) {
2022:     info->fill_ratio_given  = A->info.fill_ratio_given;
2023:     info->fill_ratio_needed = A->info.fill_ratio_needed;
2024:     info->factor_mallocs    = A->info.factor_mallocs;
2025:   } else {
2026:     info->fill_ratio_given  = 0;
2027:     info->fill_ratio_needed = 0;
2028:     info->factor_mallocs    = 0;
2029:   }
2030:   PetscFunctionReturn(PETSC_SUCCESS);
2031: }

2033: static PetscErrorCode MatZeroRows_SeqAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diagv, Vec x, Vec b)
2034: {
2035:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2036:   PetscInt           i, m = A->rmap->n - 1;
2037:   const PetscScalar *xx;
2038:   PetscScalar       *bb, *aa;
2039:   PetscInt           d = 0;
2040:   const PetscInt    *diag;

2042:   PetscFunctionBegin;
2043:   if (x && b) {
2044:     PetscCall(VecGetArrayRead(x, &xx));
2045:     PetscCall(VecGetArray(b, &bb));
2046:     for (i = 0; i < N; i++) {
2047:       PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2048:       if (rows[i] >= A->cmap->n) continue;
2049:       bb[rows[i]] = diagv * xx[rows[i]];
2050:     }
2051:     PetscCall(VecRestoreArrayRead(x, &xx));
2052:     PetscCall(VecRestoreArray(b, &bb));
2053:   }

2055:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, NULL));
2056:   PetscCall(MatSeqAIJGetArray(A, &aa));
2057:   if (a->keepnonzeropattern) {
2058:     for (i = 0; i < N; i++) {
2059:       PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2060:       PetscCall(PetscArrayzero(&aa[a->i[rows[i]]], a->ilen[rows[i]]));
2061:     }
2062:     if (diagv != 0.0) {
2063:       for (i = 0; i < N; i++) {
2064:         d = rows[i];
2065:         if (d >= A->cmap->n) continue;
2066:         PetscCheck(diag[d] < a->i[d + 1], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix is missing diagonal entry in the zeroed row %" PetscInt_FMT, d);
2067:         aa[diag[d]] = diagv;
2068:       }
2069:     }
2070:   } else {
2071:     if (diagv != 0.0) {
2072:       for (i = 0; i < N; i++) {
2073:         PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2074:         if (a->ilen[rows[i]] > 0) {
2075:           if (rows[i] >= A->cmap->n) {
2076:             a->ilen[rows[i]] = 0;
2077:           } else {
2078:             a->ilen[rows[i]]    = 1;
2079:             aa[a->i[rows[i]]]   = diagv;
2080:             a->j[a->i[rows[i]]] = rows[i];
2081:           }
2082:         } else if (rows[i] < A->cmap->n) { /* in case row was completely empty */
2083:           PetscCall(MatSetValues_SeqAIJ(A, 1, &rows[i], 1, &rows[i], &diagv, INSERT_VALUES));
2084:         }
2085:       }
2086:     } else {
2087:       for (i = 0; i < N; i++) {
2088:         PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2089:         a->ilen[rows[i]] = 0;
2090:       }
2091:     }
2092:     A->nonzerostate++;
2093:   }
2094:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
2095:   PetscUseTypeMethod(A, assemblyend, MAT_FINAL_ASSEMBLY);
2096:   PetscFunctionReturn(PETSC_SUCCESS);
2097: }

2099: static PetscErrorCode MatZeroRowsColumns_SeqAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diagv, Vec x, Vec b)
2100: {
2101:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2102:   PetscInt           i, j, m = A->rmap->n - 1, d = 0;
2103:   PetscBool         *zeroed, vecs = PETSC_FALSE;
2104:   const PetscScalar *xx;
2105:   PetscScalar       *bb, *aa;
2106:   const PetscInt    *diag;
2107:   PetscBool          diagDense;

2109:   PetscFunctionBegin;
2110:   if (!N) PetscFunctionReturn(PETSC_SUCCESS);
2111:   PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &diag, &diagDense));
2112:   PetscCall(MatSeqAIJGetArray(A, &aa));
2113:   if (x && b) {
2114:     PetscCall(VecGetArrayRead(x, &xx));
2115:     PetscCall(VecGetArray(b, &bb));
2116:     vecs = PETSC_TRUE;
2117:   }
2118:   PetscCall(PetscCalloc1(A->rmap->n, &zeroed));
2119:   for (i = 0; i < N; i++) {
2120:     PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2121:     PetscCall(PetscArrayzero(PetscSafePointerPlusOffset(aa, a->i[rows[i]]), a->ilen[rows[i]]));

2123:     zeroed[rows[i]] = PETSC_TRUE;
2124:   }
2125:   for (i = 0; i < A->rmap->n; i++) {
2126:     if (!zeroed[i]) {
2127:       for (j = a->i[i]; j < a->i[i + 1]; j++) {
2128:         if (a->j[j] < A->rmap->n && zeroed[a->j[j]]) {
2129:           if (vecs) bb[i] -= aa[j] * xx[a->j[j]];
2130:           aa[j] = 0.0;
2131:         }
2132:       }
2133:     } else if (vecs && i < A->cmap->N) bb[i] = diagv * xx[i];
2134:   }
2135:   if (x && b) {
2136:     PetscCall(VecRestoreArrayRead(x, &xx));
2137:     PetscCall(VecRestoreArray(b, &bb));
2138:   }
2139:   PetscCall(PetscFree(zeroed));
2140:   if (diagv != 0.0) {
2141:     if (!diagDense) {
2142:       for (i = 0; i < N; i++) {
2143:         if (rows[i] >= A->cmap->N) continue;
2144:         PetscCheck(!a->nonew || rows[i] < d, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix is missing diagonal entry in row %" PetscInt_FMT " (%" PetscInt_FMT ")", d, rows[i]);
2145:         PetscCall(MatSetValues_SeqAIJ(A, 1, &rows[i], 1, &rows[i], &diagv, INSERT_VALUES));
2146:       }
2147:     } else {
2148:       for (i = 0; i < N; i++) aa[diag[rows[i]]] = diagv;
2149:     }
2150:   }
2151:   PetscCall(MatSeqAIJRestoreArray(A, &aa));
2152:   if (!diagDense) PetscUseTypeMethod(A, assemblyend, MAT_FINAL_ASSEMBLY);
2153:   PetscFunctionReturn(PETSC_SUCCESS);
2154: }

2156: PetscErrorCode MatGetRow_SeqAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
2157: {
2158:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2159:   const PetscScalar *aa;

2161:   PetscFunctionBegin;
2162:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
2163:   *nz = a->i[row + 1] - a->i[row];
2164:   if (v) *v = PetscSafePointerPlusOffset((PetscScalar *)aa, a->i[row]);
2165:   if (idx) {
2166:     if (*nz && a->j) *idx = a->j + a->i[row];
2167:     else *idx = NULL;
2168:   }
2169:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2170:   PetscFunctionReturn(PETSC_SUCCESS);
2171: }

2173: PetscErrorCode MatRestoreRow_SeqAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
2174: {
2175:   PetscFunctionBegin;
2176:   PetscFunctionReturn(PETSC_SUCCESS);
2177: }

2179: static PetscErrorCode MatNorm_SeqAIJ(Mat A, NormType type, PetscReal *nrm)
2180: {
2181:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
2182:   const MatScalar *v;
2183:   PetscReal        sum = 0.0;
2184:   PetscInt         i, j;

2186:   PetscFunctionBegin;
2187:   PetscCall(MatSeqAIJGetArrayRead(A, &v));
2188:   if (type == NORM_FROBENIUS) {
2189: #if PetscDefined(USE_REAL___FP16)
2190:     PetscBLASInt one = 1, nz = a->nz;
2191:     PetscCallBLAS("BLASnrm2", *nrm = BLASnrm2_(&nz, v, &one));
2192: #else
2193:     for (i = 0; i < a->nz; i++) {
2194:       sum += PetscRealPart(PetscConj(*v) * (*v));
2195:       v++;
2196:     }
2197:     *nrm = PetscSqrtReal(sum);
2198: #endif
2199:     PetscCall(PetscLogFlops(2.0 * a->nz));
2200:   } else if (type == NORM_1) {
2201:     PetscReal *tmp;
2202:     PetscInt  *jj = a->j;
2203:     PetscCall(PetscCalloc1(A->cmap->n, &tmp));
2204:     *nrm = 0.0;
2205:     for (j = 0; j < a->nz; j++) {
2206:       tmp[*jj++] += PetscAbsScalar(*v);
2207:       v++;
2208:     }
2209:     for (j = 0; j < A->cmap->n; j++) {
2210:       if (tmp[j] > *nrm) *nrm = tmp[j];
2211:     }
2212:     PetscCall(PetscFree(tmp));
2213:     PetscCall(PetscLogFlops(a->nz));
2214:   } else if (type == NORM_INFINITY) {
2215:     *nrm = 0.0;
2216:     for (j = 0; j < A->rmap->n; j++) {
2217:       const PetscScalar *v2 = PetscSafePointerPlusOffset(v, a->i[j]);
2218:       sum                   = 0.0;
2219:       for (i = 0; i < a->i[j + 1] - a->i[j]; i++) {
2220:         sum += PetscAbsScalar(*v2);
2221:         v2++;
2222:       }
2223:       if (sum > *nrm) *nrm = sum;
2224:     }
2225:     PetscCall(PetscLogFlops(a->nz));
2226:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for two norm");
2227:   PetscCall(MatSeqAIJRestoreArrayRead(A, &v));
2228:   PetscFunctionReturn(PETSC_SUCCESS);
2229: }

2231: static PetscErrorCode MatIsTranspose_SeqAIJ(Mat A, Mat B, PetscReal tol, PetscBool *f)
2232: {
2233:   Mat_SeqAIJ      *aij = (Mat_SeqAIJ *)A->data, *bij = (Mat_SeqAIJ *)B->data;
2234:   PetscInt        *adx, *bdx, *aii, *bii, *aptr, *bptr;
2235:   const MatScalar *va, *vb;
2236:   PetscInt         ma, na, mb, nb, i;

2238:   PetscFunctionBegin;
2239:   PetscCall(MatGetSize(A, &ma, &na));
2240:   PetscCall(MatGetSize(B, &mb, &nb));
2241:   if (ma != nb || na != mb) {
2242:     *f = PETSC_FALSE;
2243:     PetscFunctionReturn(PETSC_SUCCESS);
2244:   }
2245:   PetscCall(MatSeqAIJGetArrayRead(A, &va));
2246:   PetscCall(MatSeqAIJGetArrayRead(B, &vb));
2247:   aii = aij->i;
2248:   bii = bij->i;
2249:   adx = aij->j;
2250:   bdx = bij->j;
2251:   PetscCall(PetscMalloc1(ma, &aptr));
2252:   PetscCall(PetscMalloc1(mb, &bptr));
2253:   for (i = 0; i < ma; i++) aptr[i] = aii[i];
2254:   for (i = 0; i < mb; i++) bptr[i] = bii[i];

2256:   *f = PETSC_TRUE;
2257:   for (i = 0; i < ma; i++) {
2258:     while (aptr[i] < aii[i + 1]) {
2259:       PetscInt    idc, idr;
2260:       PetscScalar vc, vr;
2261:       /* column/row index/value */
2262:       idc = adx[aptr[i]];
2263:       idr = bdx[bptr[idc]];
2264:       vc  = va[aptr[i]];
2265:       vr  = vb[bptr[idc]];
2266:       if (i != idr || PetscAbsScalar(vc - vr) > tol) {
2267:         *f = PETSC_FALSE;
2268:         goto done;
2269:       } else {
2270:         aptr[i]++;
2271:         if (B || i != idc) bptr[idc]++;
2272:       }
2273:     }
2274:   }
2275: done:
2276:   PetscCall(PetscFree(aptr));
2277:   PetscCall(PetscFree(bptr));
2278:   PetscCall(MatSeqAIJRestoreArrayRead(A, &va));
2279:   PetscCall(MatSeqAIJRestoreArrayRead(B, &vb));
2280:   PetscFunctionReturn(PETSC_SUCCESS);
2281: }

2283: static PetscErrorCode MatIsHermitianTranspose_SeqAIJ(Mat A, Mat B, PetscReal tol, PetscBool *f)
2284: {
2285:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data, *bij = (Mat_SeqAIJ *)B->data;
2286:   PetscInt   *adx, *bdx, *aii, *bii, *aptr, *bptr;
2287:   MatScalar  *va, *vb;
2288:   PetscInt    ma, na, mb, nb, i;

2290:   PetscFunctionBegin;
2291:   PetscCall(MatGetSize(A, &ma, &na));
2292:   PetscCall(MatGetSize(B, &mb, &nb));
2293:   if (ma != nb || na != mb) {
2294:     *f = PETSC_FALSE;
2295:     PetscFunctionReturn(PETSC_SUCCESS);
2296:   }
2297:   aii = aij->i;
2298:   bii = bij->i;
2299:   adx = aij->j;
2300:   bdx = bij->j;
2301:   va  = aij->a;
2302:   vb  = bij->a;
2303:   PetscCall(PetscMalloc1(ma, &aptr));
2304:   PetscCall(PetscMalloc1(mb, &bptr));
2305:   for (i = 0; i < ma; i++) aptr[i] = aii[i];
2306:   for (i = 0; i < mb; i++) bptr[i] = bii[i];

2308:   *f = PETSC_TRUE;
2309:   for (i = 0; i < ma; i++) {
2310:     while (aptr[i] < aii[i + 1]) {
2311:       PetscInt    idc, idr;
2312:       PetscScalar vc, vr;
2313:       /* column/row index/value */
2314:       idc = adx[aptr[i]];
2315:       idr = bdx[bptr[idc]];
2316:       vc  = va[aptr[i]];
2317:       vr  = vb[bptr[idc]];
2318:       if (i != idr || PetscAbsScalar(vc - PetscConj(vr)) > tol) {
2319:         *f = PETSC_FALSE;
2320:         goto done;
2321:       } else {
2322:         aptr[i]++;
2323:         if (B || i != idc) bptr[idc]++;
2324:       }
2325:     }
2326:   }
2327: done:
2328:   PetscCall(PetscFree(aptr));
2329:   PetscCall(PetscFree(bptr));
2330:   PetscFunctionReturn(PETSC_SUCCESS);
2331: }

2333: PetscErrorCode MatDiagonalScale_SeqAIJ(Mat A, Vec ll, Vec rr)
2334: {
2335:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2336:   const PetscScalar *l, *r;
2337:   PetscScalar        x;
2338:   MatScalar         *v;
2339:   PetscInt           i, j, m = A->rmap->n, n = A->cmap->n, M, nz = a->nz;
2340:   const PetscInt    *jj;

2342:   PetscFunctionBegin;
2343:   if (ll) {
2344:     /* The local size is used so that VecMPI can be passed to this routine
2345:        by MatDiagonalScale_MPIAIJ */
2346:     PetscCall(VecGetLocalSize(ll, &m));
2347:     PetscCheck(m == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Left scaling vector wrong length");
2348:     PetscCall(VecGetArrayRead(ll, &l));
2349:     PetscCall(MatSeqAIJGetArray(A, &v));
2350:     for (i = 0; i < m; i++) {
2351:       x = l[i];
2352:       M = a->i[i + 1] - a->i[i];
2353:       for (j = 0; j < M; j++) (*v++) *= x;
2354:     }
2355:     PetscCall(VecRestoreArrayRead(ll, &l));
2356:     PetscCall(PetscLogFlops(nz));
2357:     PetscCall(MatSeqAIJRestoreArray(A, &v));
2358:   }
2359:   if (rr) {
2360:     PetscCall(VecGetLocalSize(rr, &n));
2361:     PetscCheck(n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Right scaling vector wrong length");
2362:     PetscCall(VecGetArrayRead(rr, &r));
2363:     PetscCall(MatSeqAIJGetArray(A, &v));
2364:     jj = a->j;
2365:     for (i = 0; i < nz; i++) (*v++) *= r[*jj++];
2366:     PetscCall(MatSeqAIJRestoreArray(A, &v));
2367:     PetscCall(VecRestoreArrayRead(rr, &r));
2368:     PetscCall(PetscLogFlops(nz));
2369:   }
2370:   PetscFunctionReturn(PETSC_SUCCESS);
2371: }

2373: PetscErrorCode MatCreateSubMatrix_SeqAIJ(Mat A, IS isrow, IS iscol, PetscInt csize, MatReuse scall, Mat *B)
2374: {
2375:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data, *c;
2376:   PetscInt          *smap, i, k, kstart, kend, oldcols = A->cmap->n, *lens;
2377:   PetscInt           row, mat_i, *mat_j, tcol, first, step, *mat_ilen, sum, lensi;
2378:   const PetscInt    *irow, *icol;
2379:   const PetscScalar *aa;
2380:   PetscInt           nrows, ncols;
2381:   PetscInt          *starts, *j_new, *i_new, *aj = a->j, *ai = a->i, ii, *ailen = a->ilen;
2382:   MatScalar         *a_new, *mat_a, *c_a;
2383:   Mat                C;
2384:   PetscBool          stride;

2386:   PetscFunctionBegin;
2387:   PetscCall(ISGetIndices(isrow, &irow));
2388:   PetscCall(ISGetLocalSize(isrow, &nrows));
2389:   PetscCall(ISGetLocalSize(iscol, &ncols));

2391:   PetscCall(PetscObjectTypeCompare((PetscObject)iscol, ISSTRIDE, &stride));
2392:   if (stride) {
2393:     PetscCall(ISStrideGetInfo(iscol, &first, &step));
2394:   } else {
2395:     first = 0;
2396:     step  = 0;
2397:   }
2398:   if (stride && step == 1) {
2399:     /* special case of contiguous rows */
2400:     PetscCall(PetscMalloc2(nrows, &lens, nrows, &starts));
2401:     /* loop over new rows determining lens and starting points */
2402:     for (i = 0; i < nrows; i++) {
2403:       kstart    = ai[irow[i]];
2404:       kend      = kstart + ailen[irow[i]];
2405:       starts[i] = kstart;
2406:       for (k = kstart; k < kend; k++) {
2407:         if (aj[k] >= first) {
2408:           starts[i] = k;
2409:           break;
2410:         }
2411:       }
2412:       sum = 0;
2413:       while (k < kend) {
2414:         if (aj[k++] >= first + ncols) break;
2415:         sum++;
2416:       }
2417:       lens[i] = sum;
2418:     }
2419:     /* create submatrix */
2420:     if (scall == MAT_REUSE_MATRIX) {
2421:       PetscInt n_cols, n_rows;
2422:       PetscCall(MatGetSize(*B, &n_rows, &n_cols));
2423:       PetscCheck(n_rows == nrows && n_cols == ncols, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Reused submatrix wrong size");
2424:       PetscCall(MatZeroEntries(*B));
2425:       C = *B;
2426:     } else {
2427:       PetscInt rbs, cbs;
2428:       PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &C));
2429:       PetscCall(MatSetSizes(C, nrows, ncols, PETSC_DETERMINE, PETSC_DETERMINE));
2430:       PetscCall(ISGetBlockSize(isrow, &rbs));
2431:       PetscCall(ISGetBlockSize(iscol, &cbs));
2432:       PetscCall(MatSetBlockSizes(C, rbs, cbs));
2433:       PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
2434:       PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(C, 0, lens));
2435:     }
2436:     c = (Mat_SeqAIJ *)C->data;

2438:     /* loop over rows inserting into submatrix */
2439:     PetscCall(MatSeqAIJGetArrayWrite(C, &a_new)); // Not 'a_new = c->a-new', since that raw usage ignores offload state of C
2440:     j_new = c->j;
2441:     i_new = c->i;
2442:     PetscCall(MatSeqAIJGetArrayRead(A, &aa));
2443:     for (i = 0; i < nrows; i++) {
2444:       ii    = starts[i];
2445:       lensi = lens[i];
2446:       if (lensi) {
2447:         for (k = 0; k < lensi; k++) *j_new++ = aj[ii + k] - first;
2448:         PetscCall(PetscArraycpy(a_new, aa + starts[i], lensi));
2449:         a_new += lensi;
2450:       }
2451:       i_new[i + 1] = i_new[i] + lensi;
2452:       c->ilen[i]   = lensi;
2453:     }
2454:     PetscCall(MatSeqAIJRestoreArrayWrite(C, &a_new)); // Set C's offload state properly
2455:     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2456:     PetscCall(PetscFree2(lens, starts));
2457:   } else {
2458:     PetscCall(ISGetIndices(iscol, &icol));
2459:     PetscCall(PetscCalloc1(oldcols, &smap));
2460:     PetscCall(PetscMalloc1(1 + nrows, &lens));
2461:     for (i = 0; i < ncols; i++) {
2462:       PetscCheck(icol[i] < oldcols, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Requesting column beyond largest column icol[%" PetscInt_FMT "] %" PetscInt_FMT " >= A->cmap->n %" PetscInt_FMT, i, icol[i], oldcols);
2463:       smap[icol[i]] = i + 1;
2464:     }

2466:     /* determine lens of each row */
2467:     for (i = 0; i < nrows; i++) {
2468:       kstart  = ai[irow[i]];
2469:       kend    = kstart + a->ilen[irow[i]];
2470:       lens[i] = 0;
2471:       for (k = kstart; k < kend; k++) {
2472:         if (smap[aj[k]]) lens[i]++;
2473:       }
2474:     }
2475:     /* Create and fill new matrix */
2476:     if (scall == MAT_REUSE_MATRIX) {
2477:       PetscBool equal;

2479:       c = (Mat_SeqAIJ *)((*B)->data);
2480:       PetscCheck((*B)->rmap->n == nrows && (*B)->cmap->n == ncols, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot reuse matrix. wrong size");
2481:       PetscCall(PetscArraycmp(c->ilen, lens, (*B)->rmap->n, &equal));
2482:       PetscCheck(equal, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot reuse matrix. wrong number of nonzeros");
2483:       PetscCall(PetscArrayzero(c->ilen, (*B)->rmap->n));
2484:       C = *B;
2485:     } else {
2486:       PetscInt rbs, cbs;
2487:       PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &C));
2488:       PetscCall(MatSetSizes(C, nrows, ncols, PETSC_DETERMINE, PETSC_DETERMINE));
2489:       PetscCall(ISGetBlockSize(isrow, &rbs));
2490:       PetscCall(ISGetBlockSize(iscol, &cbs));
2491:       if (rbs > 1 || cbs > 1) PetscCall(MatSetBlockSizes(C, rbs, cbs));
2492:       PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
2493:       PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(C, 0, lens));
2494:     }
2495:     PetscCall(MatSeqAIJGetArrayRead(A, &aa));

2497:     c = (Mat_SeqAIJ *)C->data;
2498:     PetscCall(MatSeqAIJGetArrayWrite(C, &c_a)); // Not 'c->a', since that raw usage ignores offload state of C
2499:     for (i = 0; i < nrows; i++) {
2500:       row      = irow[i];
2501:       kstart   = ai[row];
2502:       kend     = kstart + a->ilen[row];
2503:       mat_i    = c->i[i];
2504:       mat_j    = PetscSafePointerPlusOffset(c->j, mat_i);
2505:       mat_a    = PetscSafePointerPlusOffset(c_a, mat_i);
2506:       mat_ilen = c->ilen + i;
2507:       for (k = kstart; k < kend; k++) {
2508:         if ((tcol = smap[a->j[k]])) {
2509:           *mat_j++ = tcol - 1;
2510:           *mat_a++ = aa[k];
2511:           (*mat_ilen)++;
2512:         }
2513:       }
2514:     }
2515:     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2516:     /* Free work space */
2517:     PetscCall(ISRestoreIndices(iscol, &icol));
2518:     PetscCall(PetscFree(smap));
2519:     PetscCall(PetscFree(lens));
2520:     /* sort */
2521:     for (i = 0; i < nrows; i++) {
2522:       PetscInt ilen;

2524:       mat_i = c->i[i];
2525:       mat_j = PetscSafePointerPlusOffset(c->j, mat_i);
2526:       mat_a = PetscSafePointerPlusOffset(c_a, mat_i);
2527:       ilen  = c->ilen[i];
2528:       PetscCall(PetscSortIntWithScalarArray(ilen, mat_j, mat_a));
2529:     }
2530:     PetscCall(MatSeqAIJRestoreArrayWrite(C, &c_a));
2531:   }
2532: #if PetscDefined(HAVE_DEVICE)
2533:   PetscCall(MatBindToCPU(C, A->boundtocpu));
2534: #endif
2535:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2536:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));

2538:   PetscCall(ISRestoreIndices(isrow, &irow));
2539:   *B = C;
2540:   PetscFunctionReturn(PETSC_SUCCESS);
2541: }

2543: static PetscErrorCode MatGetMultiProcBlock_SeqAIJ(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
2544: {
2545:   Mat B;

2547:   PetscFunctionBegin;
2548:   if (scall == MAT_INITIAL_MATRIX) {
2549:     PetscCall(MatCreate(subComm, &B));
2550:     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->n, mat->cmap->n));
2551:     PetscCall(MatSetBlockSizesFromMats(B, mat, mat));
2552:     PetscCall(MatSetType(B, MATSEQAIJ));
2553:     PetscCall(MatDuplicateNoCreate_SeqAIJ(B, mat, MAT_COPY_VALUES, PETSC_TRUE));
2554:     *subMat = B;
2555:   } else {
2556:     PetscCall(MatCopy_SeqAIJ(mat, *subMat, SAME_NONZERO_PATTERN));
2557:   }
2558:   PetscFunctionReturn(PETSC_SUCCESS);
2559: }

2561: static PetscErrorCode MatILUFactor_SeqAIJ(Mat inA, IS row, IS col, const MatFactorInfo *info)
2562: {
2563:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)inA->data;
2564:   Mat         outA;
2565:   PetscBool   row_identity, col_identity;

2567:   PetscFunctionBegin;
2568:   PetscCheck(info->levels == 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only levels=0 supported for in-place ilu");

2570:   PetscCall(ISIdentity(row, &row_identity));
2571:   PetscCall(ISIdentity(col, &col_identity));

2573:   outA = inA;
2574:   PetscCall(PetscFree(inA->solvertype));
2575:   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &inA->solvertype));

2577:   PetscCall(PetscObjectReference((PetscObject)row));
2578:   PetscCall(ISDestroy(&a->row));

2580:   a->row = row;

2582:   PetscCall(PetscObjectReference((PetscObject)col));
2583:   PetscCall(ISDestroy(&a->col));

2585:   a->col = col;

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

2591:   if (!a->solve_work) { /* this matrix may have been factored before */
2592:     PetscCall(PetscMalloc1(inA->rmap->n, &a->solve_work));
2593:   }

2595:   if (row_identity && col_identity) {
2596:     PetscCall(MatLUFactorNumeric_SeqAIJ_inplace(outA, inA, info));
2597:   } else {
2598:     PetscCall(MatLUFactorNumeric_SeqAIJ_InplaceWithPerm(outA, inA, info));
2599:   }
2600:   outA->factortype = MAT_FACTOR_LU;
2601:   PetscFunctionReturn(PETSC_SUCCESS);
2602: }

2604: PetscErrorCode MatScale_SeqAIJ(Mat inA, PetscScalar alpha)
2605: {
2606:   Mat_SeqAIJ  *a = (Mat_SeqAIJ *)inA->data;
2607:   PetscScalar *v;
2608:   PetscBLASInt one = 1, bnz;

2610:   PetscFunctionBegin;
2611:   PetscCall(MatSeqAIJGetArray(inA, &v));
2612:   PetscCall(PetscBLASIntCast(a->nz, &bnz));
2613:   PetscCallBLAS("BLASscal", BLASscal_(&bnz, &alpha, v, &one));
2614:   PetscCall(PetscLogFlops(a->nz));
2615:   PetscCall(MatSeqAIJRestoreArray(inA, &v));
2616:   PetscFunctionReturn(PETSC_SUCCESS);
2617: }

2619: PetscErrorCode MatDestroySubMatrix_Private(Mat_SubSppt *submatj)
2620: {
2621:   PetscInt i;

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

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

2630:     if (submatj->rbuf1) {
2631:       PetscCall(PetscFree(submatj->rbuf1[0]));
2632:       PetscCall(PetscFree(submatj->rbuf1));
2633:     }

2635:     for (i = 0; i < submatj->nrqs; ++i) PetscCall(PetscFree(submatj->rbuf3[i]));
2636:     PetscCall(PetscFree3(submatj->req_source2, submatj->rbuf2, submatj->rbuf3));
2637:     PetscCall(PetscFree(submatj->pa));
2638:   }

2640: #if PetscDefined(USE_CTABLE)
2641:   PetscCall(PetscHMapIDestroy(&submatj->rmap));
2642:   PetscCall(PetscFree(submatj->cmap_loc));
2643:   PetscCall(PetscFree(submatj->rmap_loc));
2644: #else
2645:   PetscCall(PetscFree(submatj->rmap));
2646: #endif

2648:   if (!submatj->allcolumns) {
2649: #if PetscDefined(USE_CTABLE)
2650:     PetscCall(PetscHMapIDestroy(&submatj->cmap));
2651: #else
2652:     PetscCall(PetscFree(submatj->cmap));
2653: #endif
2654:   }
2655:   PetscCall(PetscFree(submatj->row2proc));

2657:   PetscCall(PetscFree(submatj));
2658:   PetscFunctionReturn(PETSC_SUCCESS);
2659: }

2661: PetscErrorCode MatDestroySubMatrix_SeqAIJ(Mat C)
2662: {
2663:   Mat_SeqAIJ  *c       = (Mat_SeqAIJ *)C->data;
2664:   Mat_SubSppt *submatj = c->submatis1;

2666:   PetscFunctionBegin;
2667:   PetscCall((*submatj->destroy)(C));
2668:   PetscCall(MatDestroySubMatrix_Private(submatj));
2669:   PetscFunctionReturn(PETSC_SUCCESS);
2670: }

2672: /* Note this has code duplication with MatDestroySubMatrices_SeqBAIJ() */
2673: static PetscErrorCode MatDestroySubMatrices_SeqAIJ(PetscInt n, Mat *mat[])
2674: {
2675:   PetscInt     i;
2676:   Mat          C;
2677:   Mat_SeqAIJ  *c;
2678:   Mat_SubSppt *submatj;

2680:   PetscFunctionBegin;
2681:   for (i = 0; i < n; i++) {
2682:     C       = (*mat)[i];
2683:     c       = (Mat_SeqAIJ *)C->data;
2684:     submatj = c->submatis1;
2685:     if (submatj) {
2686:       if (--((PetscObject)C)->refct <= 0) {
2687:         PetscCall(PetscFree(C->factorprefix));
2688:         PetscCall((*submatj->destroy)(C));
2689:         PetscCall(MatDestroySubMatrix_Private(submatj));
2690:         PetscCall(PetscFree(C->defaultvectype));
2691:         PetscCall(PetscFree(C->defaultrandtype));
2692:         PetscCall(PetscLayoutDestroy(&C->rmap));
2693:         PetscCall(PetscLayoutDestroy(&C->cmap));
2694:         PetscCall(PetscHeaderDestroy(&C));
2695:       }
2696:     } else {
2697:       PetscCall(MatDestroy(&C));
2698:     }
2699:   }

2701:   /* Destroy Dummy submatrices created for reuse */
2702:   PetscCall(MatDestroySubMatrices_Dummy(n, mat));

2704:   PetscCall(PetscFree(*mat));
2705:   PetscFunctionReturn(PETSC_SUCCESS);
2706: }

2708: static PetscErrorCode MatCreateSubMatrices_SeqAIJ(Mat A, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *B[])
2709: {
2710:   PetscInt i;

2712:   PetscFunctionBegin;
2713:   if (scall == MAT_INITIAL_MATRIX) PetscCall(PetscCalloc1(n + 1, B));

2715:   for (i = 0; i < n; i++) PetscCall(MatCreateSubMatrix_SeqAIJ(A, irow[i], icol[i], PETSC_DECIDE, scall, &(*B)[i]));
2716:   PetscFunctionReturn(PETSC_SUCCESS);
2717: }

2719: static PetscErrorCode MatIncreaseOverlap_SeqAIJ(Mat A, PetscInt is_max, IS is[], PetscInt ov)
2720: {
2721:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
2722:   PetscInt        row, i, j, k, l, ll, m, n, *nidx, isz, val;
2723:   const PetscInt *idx;
2724:   PetscInt        start, end, *ai, *aj, bs = A->rmap->bs == A->cmap->bs ? A->rmap->bs : 1;
2725:   PetscBT         table;

2727:   PetscFunctionBegin;
2728:   m  = A->rmap->n / bs;
2729:   ai = a->i;
2730:   aj = a->j;

2732:   PetscCheck(ov >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "illegal negative overlap value used");

2734:   PetscCall(PetscMalloc1(m + 1, &nidx));
2735:   PetscCall(PetscBTCreate(m, &table));

2737:   for (i = 0; i < is_max; i++) {
2738:     /* Initialize the two local arrays */
2739:     isz = 0;
2740:     PetscCall(PetscBTMemzero(m, table));

2742:     /* Extract the indices, assume there can be duplicate entries */
2743:     PetscCall(ISGetIndices(is[i], &idx));
2744:     PetscCall(ISGetLocalSize(is[i], &n));

2746:     if (bs > 1) {
2747:       /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2748:       for (j = 0; j < n; ++j) {
2749:         if (!PetscBTLookupSet(table, idx[j] / bs)) nidx[isz++] = idx[j] / bs;
2750:       }
2751:       PetscCall(ISRestoreIndices(is[i], &idx));
2752:       PetscCall(ISDestroy(&is[i]));

2754:       k = 0;
2755:       for (j = 0; j < ov; j++) { /* for each overlap */
2756:         n = isz;
2757:         for (; k < n; k++) { /* do only those rows in nidx[k], which are not done yet */
2758:           for (ll = 0; ll < bs; ll++) {
2759:             row   = bs * nidx[k] + ll;
2760:             start = ai[row];
2761:             end   = ai[row + 1];
2762:             for (l = start; l < end; l++) {
2763:               val = aj[l] / bs;
2764:               if (!PetscBTLookupSet(table, val)) nidx[isz++] = val;
2765:             }
2766:           }
2767:         }
2768:       }
2769:       PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, isz, nidx, PETSC_COPY_VALUES, is + i));
2770:     } else {
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])) nidx[isz++] = idx[j];
2774:       }
2775:       PetscCall(ISRestoreIndices(is[i], &idx));
2776:       PetscCall(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:           row   = nidx[k];
2783:           start = ai[row];
2784:           end   = ai[row + 1];
2785:           for (l = start; l < end; l++) {
2786:             val = aj[l];
2787:             if (!PetscBTLookupSet(table, val)) nidx[isz++] = val;
2788:           }
2789:         }
2790:       }
2791:       PetscCall(ISCreateGeneral(PETSC_COMM_SELF, isz, nidx, PETSC_COPY_VALUES, is + i));
2792:     }
2793:   }
2794:   PetscCall(PetscBTDestroy(&table));
2795:   PetscCall(PetscFree(nidx));
2796:   PetscFunctionReturn(PETSC_SUCCESS);
2797: }

2799: static PetscErrorCode MatPermute_SeqAIJ(Mat A, IS rowp, IS colp, Mat *B)
2800: {
2801:   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
2802:   PetscInt        i, nz = 0, m = A->rmap->n, n = A->cmap->n;
2803:   const PetscInt *row, *col;
2804:   PetscInt       *cnew, j, *lens;
2805:   IS              icolp, irowp;
2806:   PetscInt       *cwork = NULL;
2807:   PetscScalar    *vwork = NULL;

2809:   PetscFunctionBegin;
2810:   PetscCall(ISInvertPermutation(rowp, PETSC_DECIDE, &irowp));
2811:   PetscCall(ISGetIndices(irowp, &row));
2812:   PetscCall(ISInvertPermutation(colp, PETSC_DECIDE, &icolp));
2813:   PetscCall(ISGetIndices(icolp, &col));

2815:   /* determine lengths of permuted rows */
2816:   PetscCall(PetscMalloc1(m + 1, &lens));
2817:   for (i = 0; i < m; i++) lens[row[i]] = a->i[i + 1] - a->i[i];
2818:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), B));
2819:   PetscCall(MatSetSizes(*B, m, n, m, n));
2820:   PetscCall(MatSetBlockSizesFromMats(*B, A, A));
2821:   PetscCall(MatSetType(*B, ((PetscObject)A)->type_name));
2822:   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*B, 0, lens));
2823:   PetscCall(PetscFree(lens));

2825:   PetscCall(PetscMalloc1(n, &cnew));
2826:   for (i = 0; i < m; i++) {
2827:     PetscCall(MatGetRow_SeqAIJ(A, i, &nz, &cwork, &vwork));
2828:     for (j = 0; j < nz; j++) cnew[j] = col[cwork[j]];
2829:     PetscCall(MatSetValues_SeqAIJ(*B, 1, &row[i], nz, cnew, vwork, INSERT_VALUES));
2830:     PetscCall(MatRestoreRow_SeqAIJ(A, i, &nz, &cwork, &vwork));
2831:   }
2832:   PetscCall(PetscFree(cnew));

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

2836: #if PetscDefined(HAVE_DEVICE)
2837:   PetscCall(MatBindToCPU(*B, A->boundtocpu));
2838: #endif
2839:   PetscCall(MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY));
2840:   PetscCall(MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY));
2841:   PetscCall(ISRestoreIndices(irowp, &row));
2842:   PetscCall(ISRestoreIndices(icolp, &col));
2843:   PetscCall(ISDestroy(&irowp));
2844:   PetscCall(ISDestroy(&icolp));
2845:   if (rowp == colp) PetscCall(MatPropagateSymmetryOptions(A, *B));
2846:   PetscFunctionReturn(PETSC_SUCCESS);
2847: }

2849: PetscErrorCode MatCopy_SeqAIJ(Mat A, Mat B, MatStructure str)
2850: {
2851:   PetscFunctionBegin;
2852:   /* If the two matrices have the same copy implementation, use fast copy. */
2853:   if (str == SAME_NONZERO_PATTERN && (A->ops->copy == B->ops->copy)) {
2854:     Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2855:     Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;
2856:     const PetscScalar *aa;
2857:     PetscScalar       *bb;

2859:     PetscCall(MatSeqAIJGetArrayRead(A, &aa));
2860:     PetscCall(MatSeqAIJGetArrayWrite(B, &bb));

2862:     PetscCheck(a->i[A->rmap->n] == b->i[B->rmap->n], PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Number of nonzeros in two matrices are different %" PetscInt_FMT " != %" PetscInt_FMT, a->i[A->rmap->n], b->i[B->rmap->n]);
2863:     PetscCall(PetscArraycpy(bb, aa, a->i[A->rmap->n]));
2864:     PetscCall(PetscObjectStateIncrease((PetscObject)B));
2865:     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2866:     PetscCall(MatSeqAIJRestoreArrayWrite(B, &bb));
2867:   } else {
2868:     PetscCall(MatCopy_Basic(A, B, str));
2869:   }
2870:   PetscFunctionReturn(PETSC_SUCCESS);
2871: }

2873: PETSC_INTERN PetscErrorCode MatSeqAIJGetArray_SeqAIJ(Mat A, PetscScalar *array[])
2874: {
2875:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

2877:   PetscFunctionBegin;
2878:   *array = a->a;
2879:   PetscFunctionReturn(PETSC_SUCCESS);
2880: }

2882: PETSC_INTERN PetscErrorCode MatSeqAIJRestoreArray_SeqAIJ(Mat A, PetscScalar *array[])
2883: {
2884:   PetscFunctionBegin;
2885:   *array = NULL;
2886:   PetscFunctionReturn(PETSC_SUCCESS);
2887: }

2889: /*
2890:    Computes the number of nonzeros per row needed for preallocation when X and Y
2891:    have different nonzero structure.
2892: */
2893: PetscErrorCode MatAXPYGetPreallocation_SeqX_private(PetscInt m, const PetscInt *xi, const PetscInt *xj, const PetscInt *yi, const PetscInt *yj, PetscInt *nnz)
2894: {
2895:   PetscInt i, j, k, nzx, nzy;

2897:   PetscFunctionBegin;
2898:   /* Set the number of nonzeros in the new matrix */
2899:   for (i = 0; i < m; i++) {
2900:     const PetscInt *xjj = PetscSafePointerPlusOffset(xj, xi[i]), *yjj = PetscSafePointerPlusOffset(yj, yi[i]);
2901:     nzx    = xi[i + 1] - xi[i];
2902:     nzy    = yi[i + 1] - yi[i];
2903:     nnz[i] = 0;
2904:     for (j = 0, k = 0; j < nzx; j++) {                  /* Point in X */
2905:       for (; k < nzy && yjj[k] < xjj[j]; k++) nnz[i]++; /* Catch up to X */
2906:       if (k < nzy && yjj[k] == xjj[j]) k++;             /* Skip duplicate */
2907:       nnz[i]++;
2908:     }
2909:     for (; k < nzy; k++) nnz[i]++;
2910:   }
2911:   PetscFunctionReturn(PETSC_SUCCESS);
2912: }

2914: PetscErrorCode MatAXPYGetPreallocation_SeqAIJ(Mat Y, Mat X, PetscInt *nnz)
2915: {
2916:   PetscInt    m = Y->rmap->N;
2917:   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data;
2918:   Mat_SeqAIJ *y = (Mat_SeqAIJ *)Y->data;

2920:   PetscFunctionBegin;
2921:   /* Set the number of nonzeros in the new matrix */
2922:   PetscCall(MatAXPYGetPreallocation_SeqX_private(m, x->i, x->j, y->i, y->j, nnz));
2923:   PetscFunctionReturn(PETSC_SUCCESS);
2924: }

2926: PetscErrorCode MatAXPY_SeqAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
2927: {
2928:   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data, *y = (Mat_SeqAIJ *)Y->data;

2930:   PetscFunctionBegin;
2931:   if (str == UNKNOWN_NONZERO_PATTERN || (PetscDefined(USE_DEBUG) && str == SAME_NONZERO_PATTERN)) {
2932:     PetscBool e = x->nz == y->nz ? PETSC_TRUE : PETSC_FALSE;
2933:     if (e) {
2934:       PetscCall(PetscArraycmp(x->i, y->i, Y->rmap->n + 1, &e));
2935:       if (e) {
2936:         PetscCall(PetscArraycmp(x->j, y->j, y->nz, &e));
2937:         if (e) str = SAME_NONZERO_PATTERN;
2938:       }
2939:     }
2940:     if (!e) PetscCheck(str != SAME_NONZERO_PATTERN, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MatStructure is not SAME_NONZERO_PATTERN");
2941:   }
2942:   if (str == SAME_NONZERO_PATTERN) {
2943:     const PetscScalar *xa;
2944:     PetscScalar       *ya, alpha = a;
2945:     PetscBLASInt       one = 1, bnz;

2947:     PetscCall(PetscBLASIntCast(x->nz, &bnz));
2948:     PetscCall(MatSeqAIJGetArray(Y, &ya));
2949:     PetscCall(MatSeqAIJGetArrayRead(X, &xa));
2950:     PetscCallBLAS("BLASaxpy", BLASaxpy_(&bnz, &alpha, xa, &one, ya, &one));
2951:     PetscCall(MatSeqAIJRestoreArrayRead(X, &xa));
2952:     PetscCall(MatSeqAIJRestoreArray(Y, &ya));
2953:     PetscCall(PetscLogFlops(2.0 * bnz));
2954:     PetscCall(PetscObjectStateIncrease((PetscObject)Y));
2955:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2956:     PetscCall(MatAXPY_Basic(Y, a, X, str));
2957:   } else {
2958:     Mat       B;
2959:     PetscInt *nnz;
2960:     PetscCall(PetscMalloc1(Y->rmap->N, &nnz));
2961:     PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
2962:     PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
2963:     PetscCall(MatSetLayouts(B, Y->rmap, Y->cmap));
2964:     PetscCall(MatSetType(B, ((PetscObject)Y)->type_name));
2965:     PetscCall(MatAXPYGetPreallocation_SeqAIJ(Y, X, nnz));
2966:     PetscCall(MatSeqAIJSetPreallocation(B, 0, nnz));
2967:     PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));
2968:     PetscCall(MatHeaderMerge(Y, &B));
2969:     PetscCall(MatSeqAIJCheckInode(Y));
2970:     PetscCall(PetscFree(nnz));
2971:   }
2972:   PetscFunctionReturn(PETSC_SUCCESS);
2973: }

2975: PETSC_INTERN PetscErrorCode MatConjugate_SeqAIJ(Mat mat)
2976: {
2977:   Mat_SeqAIJ  *aij = (Mat_SeqAIJ *)mat->data;
2978:   PetscInt     i, nz = aij->nz;
2979:   PetscScalar *a;

2981:   PetscFunctionBegin;
2982:   PetscCall(MatSeqAIJGetArray(mat, &a));
2983:   for (i = 0; i < nz; i++) a[i] = PetscConj(a[i]);
2984:   PetscCall(MatSeqAIJRestoreArray(mat, &a));
2985:   PetscFunctionReturn(PETSC_SUCCESS);
2986: }

2988: static PetscErrorCode MatGetRowMaxAbs_SeqAIJ(Mat A, Vec v, PetscInt idx[])
2989: {
2990:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
2991:   PetscInt         i, j, m = A->rmap->n, *ai, *aj, ncols, n;
2992:   PetscReal        atmp;
2993:   PetscScalar     *x;
2994:   const MatScalar *aa, *av;

2996:   PetscFunctionBegin;
2997:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2998:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
2999:   aa = av;
3000:   ai = a->i;
3001:   aj = a->j;

3003:   PetscCall(VecGetArrayWrite(v, &x));
3004:   PetscCall(VecGetLocalSize(v, &n));
3005:   PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
3006:   for (i = 0; i < m; i++) {
3007:     ncols = ai[1] - ai[0];
3008:     ai++;
3009:     x[i] = 0;
3010:     for (j = 0; j < ncols; j++) {
3011:       atmp = PetscAbsScalar(*aa);
3012:       if (PetscAbsScalar(x[i]) < atmp) {
3013:         x[i] = atmp;
3014:         if (idx) idx[i] = *aj;
3015:       }
3016:       aa++;
3017:       aj++;
3018:     }
3019:   }
3020:   PetscCall(VecRestoreArrayWrite(v, &x));
3021:   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
3022:   PetscFunctionReturn(PETSC_SUCCESS);
3023: }

3025: static PetscErrorCode MatGetRowSumAbs_SeqAIJ(Mat A, Vec v)
3026: {
3027:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3028:   PetscInt         i, j, m = A->rmap->n, *ai, ncols, n;
3029:   PetscScalar     *x;
3030:   const MatScalar *aa, *av;

3032:   PetscFunctionBegin;
3033:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3034:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3035:   aa = av;
3036:   ai = a->i;

3038:   PetscCall(VecGetArrayWrite(v, &x));
3039:   PetscCall(VecGetLocalSize(v, &n));
3040:   PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
3041:   for (i = 0; i < m; i++) {
3042:     ncols = ai[1] - ai[0];
3043:     ai++;
3044:     x[i] = 0;
3045:     for (j = 0; j < ncols; j++) {
3046:       x[i] += PetscAbsScalar(*aa);
3047:       aa++;
3048:     }
3049:   }
3050:   PetscCall(VecRestoreArrayWrite(v, &x));
3051:   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
3052:   PetscFunctionReturn(PETSC_SUCCESS);
3053: }

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

3062:   PetscFunctionBegin;
3063:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3064:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3065:   aa = av;
3066:   ai = a->i;
3067:   aj = a->j;

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

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

3112:   PetscFunctionBegin;
3113:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3114:   aa = av;
3115:   ai = a->i;
3116:   aj = a->j;

3118:   PetscCall(VecGetArrayWrite(v, &x));
3119:   PetscCall(VecGetLocalSize(v, &n));
3120:   PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector, %" PetscInt_FMT " vs. %" PetscInt_FMT " rows", m, n);
3121:   for (i = 0; i < m; i++) {
3122:     ncols = ai[1] - ai[0];
3123:     ai++;
3124:     if (ncols == A->cmap->n) { /* row is dense */
3125:       x[i] = *aa;
3126:       if (idx) idx[i] = 0;
3127:     } else { /* row is sparse so already KNOW minimum is 0.0 or higher */
3128:       x[i] = 0.0;
3129:       if (idx) { /* find first implicit 0.0 in the row */
3130:         for (j = 0; j < ncols; j++) {
3131:           if (aj[j] > j) {
3132:             idx[i] = j;
3133:             break;
3134:           }
3135:         }
3136:         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3137:         if (j == ncols && j < A->cmap->n) idx[i] = j;
3138:       }
3139:     }
3140:     for (j = 0; j < ncols; j++) {
3141:       if (PetscAbsScalar(x[i]) > PetscAbsScalar(*aa)) {
3142:         x[i] = *aa;
3143:         if (idx) idx[i] = *aj;
3144:       }
3145:       aa++;
3146:       aj++;
3147:     }
3148:   }
3149:   PetscCall(VecRestoreArrayWrite(v, &x));
3150:   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
3151:   PetscFunctionReturn(PETSC_SUCCESS);
3152: }

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

3162:   PetscFunctionBegin;
3163:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3164:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3165:   aa = av;
3166:   ai = a->i;
3167:   aj = a->j;

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

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

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

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

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

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

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

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

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

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

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

3559:   PetscFunctionBegin;
3561:   PetscAssertPointer(mapping, 2);
3562:   /* use a table */
3563:   PetscCall(PetscHMapICreateWithSize(mat->rmap->n, &gid1_lid1));
3564:   ec = 0;
3565:   for (i = 0; i < nz; i++) {
3566:     PetscInt data, gid1 = jj[i] + 1;
3567:     PetscCall(PetscHMapIGetWithDefault(gid1_lid1, gid1, 0, &data));
3568:     if (!data) {
3569:       /* one based table */
3570:       PetscCall(PetscHMapISet(gid1_lid1, gid1, ++ec));
3571:     }
3572:   }
3573:   /* form array of columns we need */
3574:   PetscCall(PetscMalloc1(ec, &garray));
3575:   PetscHashIterBegin(gid1_lid1, tpos);
3576:   while (!PetscHashIterAtEnd(gid1_lid1, tpos)) {
3577:     PetscHashIterGetKey(gid1_lid1, tpos, gid);
3578:     PetscHashIterGetVal(gid1_lid1, tpos, lid);
3579:     PetscHashIterNext(gid1_lid1, tpos);
3580:     gid--;
3581:     lid--;
3582:     garray[lid] = gid;
3583:   }
3584:   PetscCall(PetscSortInt(ec, garray)); /* sort, and rebuild */
3585:   PetscCall(PetscHMapIClear(gid1_lid1));
3586:   for (i = 0; i < ec; i++) PetscCall(PetscHMapISet(gid1_lid1, garray[i] + 1, i + 1));
3587:   /* compact out the extra columns in B */
3588:   for (i = 0; i < nz; i++) {
3589:     PetscInt gid1 = jj[i] + 1;
3590:     PetscCall(PetscHMapIGetWithDefault(gid1_lid1, gid1, 0, &lid));
3591:     lid--;
3592:     jj[i] = lid;
3593:   }
3594:   PetscCall(PetscLayoutDestroy(&mat->cmap));
3595:   PetscCall(PetscHMapIDestroy(&gid1_lid1));
3596:   PetscCall(PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)mat), ec, ec, 1, &mat->cmap));
3597:   PetscCall(ISLocalToGlobalMappingCreate(PETSC_COMM_SELF, mat->cmap->bs, mat->cmap->n, garray, PETSC_OWN_POINTER, mapping));
3598:   PetscCall(ISLocalToGlobalMappingSetType(*mapping, ISLOCALTOGLOBALMAPPINGHASH));
3599:   PetscFunctionReturn(PETSC_SUCCESS);
3600: }

3602: /*@
3603:   MatSeqAIJSetColumnIndices - Set the column indices for all the rows
3604:   in the matrix.

3606:   Input Parameters:
3607: + mat     - the `MATSEQAIJ` matrix
3608: - indices - the column indices

3610:   Level: advanced

3612:   Notes:
3613:   This can be called if you have precomputed the nonzero structure of the
3614:   matrix and want to provide it to the matrix object to improve the performance
3615:   of the `MatSetValues()` operation.

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

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

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

3624: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJ`
3625: @*/
3626: PetscErrorCode MatSeqAIJSetColumnIndices(Mat mat, PetscInt *indices)
3627: {
3628:   PetscFunctionBegin;
3630:   PetscAssertPointer(indices, 2);
3631:   PetscUseMethod(mat, "MatSeqAIJSetColumnIndices_C", (Mat, PetscInt *), (mat, indices));
3632:   PetscFunctionReturn(PETSC_SUCCESS);
3633: }

3635: static PetscErrorCode MatStoreValues_SeqAIJ(Mat mat)
3636: {
3637:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3638:   size_t      nz  = aij->i[mat->rmap->n];

3640:   PetscFunctionBegin;
3641:   PetscCheck(aij->nonew, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");

3643:   /* allocate space for values if not already there */
3644:   if (!aij->saved_values) PetscCall(PetscMalloc1(nz + 1, &aij->saved_values));

3646:   /* copy values over */
3647:   PetscCall(PetscArraycpy(aij->saved_values, aij->a, nz));
3648:   PetscFunctionReturn(PETSC_SUCCESS);
3649: }

3651: /*@
3652:   MatStoreValues - Stashes a copy of the matrix values; this allows reusing of the linear part of a Jacobian, while recomputing only the
3653:   nonlinear portion.

3655:   Logically Collect

3657:   Input Parameter:
3658: . mat - the matrix (currently only `MATAIJ` matrices support this option)

3660:   Level: advanced

3662:   Example Usage:
3663: .vb
3664:     Using SNES
3665:     Create Jacobian matrix
3666:     Set linear terms into matrix
3667:     Apply boundary conditions to matrix, at this time matrix must have
3668:       final nonzero structure (i.e. setting the nonlinear terms and applying
3669:       boundary conditions again will not change the nonzero structure
3670:     MatSetOption(mat, MAT_NEW_NONZERO_LOCATIONS, PETSC_FALSE);
3671:     MatStoreValues(mat);
3672:     Call SNESSetJacobian() with matrix
3673:     In your Jacobian routine
3674:       MatRetrieveValues(mat);
3675:       Set nonlinear terms in matrix

3677:     Without `SNESSolve()`, i.e. when you handle nonlinear solve yourself:
3678:     // build linear portion of Jacobian
3679:     MatSetOption(mat, MAT_NEW_NONZERO_LOCATIONS, PETSC_FALSE);
3680:     MatStoreValues(mat);
3681:     loop over nonlinear iterations
3682:        MatRetrieveValues(mat);
3683:        // call MatSetValues(mat,...) to set nonliner portion of Jacobian
3684:        // call MatAssemblyBegin/End() on matrix
3685:        Solve linear system with Jacobian
3686:     endloop
3687: .ve

3689:   Notes:
3690:   Matrix must already be assembled before calling this routine
3691:   Must set the matrix option `MatSetOption`(mat,`MAT_NEW_NONZERO_LOCATIONS`,`PETSC_FALSE`); before
3692:   calling this routine.

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

3697: .seealso: [](ch_matrices), `Mat`, `MatRetrieveValues()`
3698: @*/
3699: PetscErrorCode MatStoreValues(Mat mat)
3700: {
3701:   PetscFunctionBegin;
3703:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3704:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3705:   PetscUseMethod(mat, "MatStoreValues_C", (Mat), (mat));
3706:   PetscFunctionReturn(PETSC_SUCCESS);
3707: }

3709: static PetscErrorCode MatRetrieveValues_SeqAIJ(Mat mat)
3710: {
3711:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3712:   PetscInt    nz  = aij->i[mat->rmap->n];

3714:   PetscFunctionBegin;
3715:   PetscCheck(aij->nonew, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");
3716:   PetscCheck(aij->saved_values, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatStoreValues(A);first");
3717:   /* copy values over */
3718:   PetscCall(PetscArraycpy(aij->a, aij->saved_values, nz));
3719:   PetscFunctionReturn(PETSC_SUCCESS);
3720: }

3722: /*@
3723:   MatRetrieveValues - Retrieves the copy of the matrix values that was stored with `MatStoreValues()`

3725:   Logically Collect

3727:   Input Parameter:
3728: . mat - the matrix (currently only `MATAIJ` matrices support this option)

3730:   Level: advanced

3732: .seealso: [](ch_matrices), `Mat`, `MatStoreValues()`
3733: @*/
3734: PetscErrorCode MatRetrieveValues(Mat mat)
3735: {
3736:   PetscFunctionBegin;
3738:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3739:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3740:   PetscUseMethod(mat, "MatRetrieveValues_C", (Mat), (mat));
3741:   PetscFunctionReturn(PETSC_SUCCESS);
3742: }

3744: /*@
3745:   MatCreateSeqAIJ - Creates a sparse matrix in `MATSEQAIJ` (compressed row) format
3746:   (the default parallel PETSc format).  For good matrix assembly performance
3747:   the user should preallocate the matrix storage by setting the parameter `nz`
3748:   (or the array `nnz`).

3750:   Collective

3752:   Input Parameters:
3753: + comm - MPI communicator, set to `PETSC_COMM_SELF`
3754: . m    - number of rows
3755: . n    - number of columns
3756: . nz   - number of nonzeros per row (same for all rows)
3757: - nnz  - array containing the number of nonzeros in the various rows
3758:          (possibly different for each row) or NULL

3760:   Output Parameter:
3761: . A - the matrix

3763:   Options Database Keys:
3764: + -mat_no_inode          - Do not use inodes
3765: - -mat_inode_limit limit - Sets inode limit (max limit=5)

3767:   Level: intermediate

3769:   Notes:
3770:   It is recommend to use `MatCreateFromOptions()` instead of this routine

3772:   If `nnz` is given then `nz` is ignored

3774:   The `MATSEQAIJ` format, also called
3775:   compressed row storage, is fully compatible with standard Fortran
3776:   storage.  That is, the stored row and column indices can begin at
3777:   either one (as in Fortran) or zero.

3779:   Specify the preallocated storage with either `nz` or `nnz` (not both).
3780:   Set `nz` = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
3781:   allocation.

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

3788: .seealso: [](ch_matrices), `Mat`, [Sparse Matrix Creation](sec_matsparse), `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`
3789: @*/
3790: PetscErrorCode MatCreateSeqAIJ(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A)
3791: {
3792:   PetscFunctionBegin;
3793:   PetscCall(MatCreate(comm, A));
3794:   PetscCall(MatSetSizes(*A, m, n, m, n));
3795:   PetscCall(MatSetType(*A, MATSEQAIJ));
3796:   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*A, nz, nnz));
3797:   PetscFunctionReturn(PETSC_SUCCESS);
3798: }

3800: /*@
3801:   MatSeqAIJSetPreallocation - For good matrix assembly performance
3802:   the user should preallocate the matrix storage by setting the parameter nz
3803:   (or the array nnz).  By setting these parameters accurately, performance
3804:   during matrix assembly can be increased by more than a factor of 50.

3806:   Collective

3808:   Input Parameters:
3809: + B   - The matrix
3810: . nz  - number of nonzeros per row (same for all rows)
3811: - nnz - array containing the number of nonzeros in the various rows
3812:          (possibly different for each row) or NULL

3814:   Options Database Keys:
3815: + -mat_no_inode          - Do not use inodes
3816: - -mat_inode_limit limit - Sets inode limit (max limit=5)

3818:   Level: intermediate

3820:   Notes:
3821:   If `nnz` is given then `nz` is ignored

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

3828:   Specify the preallocated storage with either `nz` or `nnz` (not both).
3829:   Set nz = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
3830:   allocation.

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

3837:   Developer Notes:
3838:   Use nz of `MAT_SKIP_ALLOCATION` to not allocate any space for the matrix
3839:   entries or columns indices

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

3846: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`, `MatGetInfo()`,
3847:           `MatSeqAIJSetTotalPreallocation()`
3848: @*/
3849: PetscErrorCode MatSeqAIJSetPreallocation(Mat B, PetscInt nz, const PetscInt nnz[])
3850: {
3851:   PetscFunctionBegin;
3854:   PetscTryMethod(B, "MatSeqAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[]), (B, nz, nnz));
3855:   PetscFunctionReturn(PETSC_SUCCESS);
3856: }

3858: PetscErrorCode MatSeqAIJSetPreallocation_SeqAIJ(Mat B, PetscInt nz, const PetscInt *nnz)
3859: {
3860:   Mat_SeqAIJ *b              = (Mat_SeqAIJ *)B->data;
3861:   PetscBool   skipallocation = PETSC_FALSE, realalloc = PETSC_FALSE;
3862:   PetscInt    i;

3864:   PetscFunctionBegin;
3865:   if (B->hash_active) {
3866:     B->ops[0] = b->cops;
3867:     PetscCall(PetscHMapIJVDestroy(&b->ht));
3868:     PetscCall(PetscFree(b->dnz));
3869:     B->hash_active = PETSC_FALSE;
3870:   }
3871:   if (nz >= 0 || nnz) realalloc = PETSC_TRUE;
3872:   if (nz == MAT_SKIP_ALLOCATION) {
3873:     skipallocation = PETSC_TRUE;
3874:     nz             = 0;
3875:   }
3876:   PetscCall(PetscLayoutSetUp(B->rmap));
3877:   PetscCall(PetscLayoutSetUp(B->cmap));

3879:   if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 5;
3880:   PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nz cannot be less than 0: value %" PetscInt_FMT, nz);
3881:   if (nnz) {
3882:     for (i = 0; i < B->rmap->n; i++) {
3883:       PetscCheck(nnz[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nnz cannot be less than 0: local row %" PetscInt_FMT " value %" PetscInt_FMT, i, nnz[i]);
3884:       PetscCheck(nnz[i] <= B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nnz cannot be greater than row length: local row %" PetscInt_FMT " value %" PetscInt_FMT " rowlength %" PetscInt_FMT, i, nnz[i], B->cmap->n);
3885:     }
3886:   }

3888:   B->preallocated = PETSC_TRUE;
3889:   if (!skipallocation) {
3890:     if (!b->imax) PetscCall(PetscMalloc1(B->rmap->n, &b->imax));
3891:     if (!b->ilen) {
3892:       /* b->ilen will count nonzeros in each row so far. */
3893:       PetscCall(PetscCalloc1(B->rmap->n, &b->ilen));
3894:     } else {
3895:       PetscCall(PetscMemzero(b->ilen, B->rmap->n * sizeof(PetscInt)));
3896:     }
3897:     if (!b->ipre) PetscCall(PetscMalloc1(B->rmap->n, &b->ipre));
3898:     if (!nnz) {
3899:       if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 10;
3900:       else if (nz < 0) nz = 1;
3901:       nz = PetscMin(nz, B->cmap->n);
3902:       for (i = 0; i < B->rmap->n; i++) b->imax[i] = nz;
3903:       PetscCall(PetscIntMultError(nz, B->rmap->n, &nz));
3904:     } else {
3905:       PetscInt64 nz64 = 0;
3906:       for (i = 0; i < B->rmap->n; i++) {
3907:         b->imax[i] = nnz[i];
3908:         nz64 += nnz[i];
3909:       }
3910:       PetscCall(PetscIntCast(nz64, &nz));
3911:     }

3913:     /* allocate the matrix space */
3914:     PetscCall(MatSeqXAIJFreeAIJ(B, &b->a, &b->j, &b->i));
3915:     PetscCall(PetscShmgetAllocateArray(nz, sizeof(PetscInt), (void **)&b->j));
3916:     PetscCall(PetscShmgetAllocateArray(B->rmap->n + 1, sizeof(PetscInt), (void **)&b->i));
3917:     b->free_ij = PETSC_TRUE;
3918:     if (B->structure_only) {
3919:       b->free_a = PETSC_FALSE;
3920:     } else {
3921:       PetscCall(PetscShmgetAllocateArray(nz, sizeof(PetscScalar), (void **)&b->a));
3922:       b->free_a = PETSC_TRUE;
3923:     }
3924:     b->i[0] = 0;
3925:     for (i = 1; i < B->rmap->n + 1; i++) b->i[i] = b->i[i - 1] + b->imax[i - 1];
3926:   } else {
3927:     b->free_a  = PETSC_FALSE;
3928:     b->free_ij = PETSC_FALSE;
3929:   }

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

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

3949: PetscErrorCode MatResetPreallocation_SeqAIJ_Private(Mat A, PetscBool *memoryreset)
3950: {
3951:   Mat_SeqAIJ *a;
3952:   PetscInt    i;
3953:   PetscBool   skipreset;

3955:   PetscFunctionBegin;

3958:   PetscCheck(A->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot reset preallocation after setting some values but not yet calling MatAssemblyBegin()/MatAssemblyEnd()");
3959:   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);

3961:   /* Check local size. If zero, then return */
3962:   if (!A->rmap->n) PetscFunctionReturn(PETSC_SUCCESS);

3964:   a = (Mat_SeqAIJ *)A->data;
3965:   /* if no saved info, we error out */
3966:   PetscCheck(a->ipre, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "No saved preallocation info ");

3968:   PetscCheck(a->i && a->imax && a->ilen, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Memory info is incomplete, and cannot reset preallocation ");

3970:   PetscCall(PetscArraycmp(a->ipre, a->ilen, A->rmap->n, &skipreset));
3971:   if (skipreset) PetscCall(MatZeroEntries(A));
3972:   else {
3973:     PetscCall(PetscArraycpy(a->imax, a->ipre, A->rmap->n));
3974:     PetscCall(PetscArrayzero(a->ilen, A->rmap->n));
3975:     a->i[0] = 0;
3976:     for (i = 1; i < A->rmap->n + 1; i++) a->i[i] = a->i[i - 1] + a->imax[i - 1];
3977:     A->preallocated     = PETSC_TRUE;
3978:     a->nz               = 0;
3979:     a->maxnz            = a->i[A->rmap->n];
3980:     A->info.nz_unneeded = (double)a->maxnz;
3981:     A->was_assembled    = PETSC_FALSE;
3982:     A->assembled        = PETSC_FALSE;
3983:     A->nonzerostate++;
3984:     /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
3985:     PetscCall(PetscObjectStateIncrease((PetscObject)A));
3986:   }
3987:   if (memoryreset) *memoryreset = (PetscBool)!skipreset;
3988:   PetscFunctionReturn(PETSC_SUCCESS);
3989: }

3991: static PetscErrorCode MatResetPreallocation_SeqAIJ(Mat A)
3992: {
3993:   PetscFunctionBegin;
3994:   PetscCall(MatResetPreallocation_SeqAIJ_Private(A, NULL));
3995:   PetscFunctionReturn(PETSC_SUCCESS);
3996: }

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

4001:   Input Parameters:
4002: + B - the matrix
4003: . i - the indices into `j` for the start of each row (indices start with zero)
4004: . j - the column indices for each row (indices start with zero) these must be sorted for each row
4005: - v - optional values in the matrix, use `NULL` if not provided

4007:   Level: developer

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

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

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

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

4021: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatSeqAIJSetPreallocation()`, `MATSEQAIJ`, `MatResetPreallocation()`
4022: @*/
4023: PetscErrorCode MatSeqAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
4024: {
4025:   PetscFunctionBegin;
4028:   PetscTryMethod(B, "MatSeqAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
4029:   PetscFunctionReturn(PETSC_SUCCESS);
4030: }

4032: static PetscErrorCode MatSeqAIJSetPreallocationCSR_SeqAIJ(Mat B, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
4033: {
4034:   PetscInt  i;
4035:   PetscInt  m, n;
4036:   PetscInt  nz;
4037:   PetscInt *nnz;

4039:   PetscFunctionBegin;
4040:   PetscCheck(Ii[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Ii[0] must be 0 it is %" PetscInt_FMT, Ii[0]);

4042:   PetscCall(PetscLayoutSetUp(B->rmap));
4043:   PetscCall(PetscLayoutSetUp(B->cmap));

4045:   PetscCall(MatGetSize(B, &m, &n));
4046:   PetscCall(PetscMalloc1(m + 1, &nnz));
4047:   for (i = 0; i < m; i++) {
4048:     nz = Ii[i + 1] - Ii[i];
4049:     PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Local row %" PetscInt_FMT " has a negative number of columns %" PetscInt_FMT, i, nz);
4050:     nnz[i] = nz;
4051:   }
4052:   PetscCall(MatSeqAIJSetPreallocation(B, 0, nnz));
4053:   PetscCall(PetscFree(nnz));

4055:   for (i = 0; i < m; i++) PetscCall(MatSetValues_SeqAIJ(B, 1, &i, Ii[i + 1] - Ii[i], J + Ii[i], PetscSafePointerPlusOffset(v, Ii[i]), INSERT_VALUES));

4057:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4058:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));

4060:   PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
4061:   PetscFunctionReturn(PETSC_SUCCESS);
4062: }

4064: /*@
4065:   MatSeqAIJKron - Computes `C`, the Kronecker product of `A` and `B`.

4067:   Input Parameters:
4068: + A     - left-hand side matrix
4069: . B     - right-hand side matrix
4070: - reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

4072:   Output Parameter:
4073: . C - Kronecker product of `A` and `B`

4075:   Level: intermediate

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

4080: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MATKAIJ`, `MatReuse`
4081: @*/
4082: PetscErrorCode MatSeqAIJKron(Mat A, Mat B, MatReuse reuse, Mat *C)
4083: {
4084:   PetscFunctionBegin;
4089:   PetscAssertPointer(C, 4);
4090:   if (reuse == MAT_REUSE_MATRIX) {
4093:   }
4094:   PetscTryMethod(A, "MatSeqAIJKron_C", (Mat, Mat, MatReuse, Mat *), (A, B, reuse, C));
4095:   PetscFunctionReturn(PETSC_SUCCESS);
4096: }

4098: static PetscErrorCode MatSeqAIJKron_SeqAIJ(Mat A, Mat B, MatReuse reuse, Mat *C)
4099: {
4100:   Mat                newmat;
4101:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
4102:   Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;
4103:   PetscScalar       *v;
4104:   const PetscScalar *aa, *ba;
4105:   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;
4106:   PetscBool          flg;

4108:   PetscFunctionBegin;
4109:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4110:   PetscCheck(A->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4111:   PetscCheck(!B->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4112:   PetscCheck(B->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4113:   PetscCall(PetscObjectTypeCompare((PetscObject)B, MATSEQAIJ, &flg));
4114:   PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatType %s", ((PetscObject)B)->type_name);
4115:   PetscCheck(reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatReuse %d", (int)reuse);
4116:   if (reuse == MAT_INITIAL_MATRIX) {
4117:     PetscCall(PetscMalloc2(am * bm + 1, &i, a->i[am] * b->i[bm], &j));
4118:     PetscCall(MatCreate(PETSC_COMM_SELF, &newmat));
4119:     PetscCall(MatSetSizes(newmat, am * bm, an * bn, am * bm, an * bn));
4120:     PetscCall(MatSetType(newmat, MATAIJ));
4121:     i[0] = 0;
4122:     for (m = 0; m < am; ++m) {
4123:       for (p = 0; p < bm; ++p) {
4124:         i[m * bm + p + 1] = i[m * bm + p] + (a->i[m + 1] - a->i[m]) * (b->i[p + 1] - b->i[p]);
4125:         for (n = a->i[m]; n < a->i[m + 1]; ++n) {
4126:           for (q = b->i[p]; q < b->i[p + 1]; ++q) j[nnz++] = a->j[n] * bn + b->j[q];
4127:         }
4128:       }
4129:     }
4130:     PetscCall(MatSeqAIJSetPreallocationCSR(newmat, i, j, NULL));
4131:     *C = newmat;
4132:     PetscCall(PetscFree2(i, j));
4133:     nnz = 0;
4134:   }
4135:   PetscCall(MatSeqAIJGetArray(*C, &v));
4136:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
4137:   PetscCall(MatSeqAIJGetArrayRead(B, &ba));
4138:   for (m = 0; m < am; ++m) {
4139:     for (p = 0; p < bm; ++p) {
4140:       for (n = a->i[m]; n < a->i[m + 1]; ++n) {
4141:         for (q = b->i[p]; q < b->i[p + 1]; ++q) v[nnz++] = aa[n] * ba[q];
4142:       }
4143:     }
4144:   }
4145:   PetscCall(MatSeqAIJRestoreArray(*C, &v));
4146:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
4147:   PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
4148:   PetscFunctionReturn(PETSC_SUCCESS);
4149: }

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

4154: /*
4155:     Computes (B'*A')' since computing B*A directly is untenable

4157:                n                       p                          p
4158:         [             ]       [             ]         [                 ]
4159:       m [      A      ]  *  n [       B     ]   =   m [         C       ]
4160:         [             ]       [             ]         [                 ]

4162: */
4163: PetscErrorCode MatMatMultNumeric_SeqDense_SeqAIJ(Mat A, Mat B, Mat C)
4164: {
4165:   Mat_SeqDense      *sub_a = (Mat_SeqDense *)A->data;
4166:   Mat_SeqAIJ        *sub_b = (Mat_SeqAIJ *)B->data;
4167:   Mat_SeqDense      *sub_c = (Mat_SeqDense *)C->data;
4168:   PetscInt           i, j, n, m, q, p;
4169:   const PetscInt    *ii, *idx;
4170:   const PetscScalar *b, *a, *a_q;
4171:   PetscScalar       *c, *c_q;
4172:   PetscInt           clda = sub_c->lda;
4173:   PetscInt           alda = sub_a->lda;

4175:   PetscFunctionBegin;
4176:   m = A->rmap->n;
4177:   n = A->cmap->n;
4178:   p = B->cmap->n;
4179:   a = sub_a->v;
4180:   b = sub_b->a;
4181:   c = sub_c->v;
4182:   if (clda == m) {
4183:     PetscCall(PetscArrayzero(c, m * p));
4184:   } else {
4185:     for (j = 0; j < p; j++)
4186:       for (i = 0; i < m; i++) c[j * clda + i] = 0.0;
4187:   }
4188:   ii  = sub_b->i;
4189:   idx = sub_b->j;
4190:   for (i = 0; i < n; i++) {
4191:     q = ii[i + 1] - ii[i];
4192:     while (q-- > 0) {
4193:       c_q = c + clda * (*idx);
4194:       a_q = a + alda * i;
4195:       PetscKernelAXPY(c_q, *b, a_q, m);
4196:       idx++;
4197:       b++;
4198:     }
4199:   }
4200:   PetscFunctionReturn(PETSC_SUCCESS);
4201: }

4203: PetscErrorCode MatMatMultSymbolic_SeqDense_SeqAIJ(Mat A, Mat B, PetscReal fill, Mat C)
4204: {
4205:   PetscInt  m = A->rmap->n, n = B->cmap->n;
4206:   PetscBool cisdense;

4208:   PetscFunctionBegin;
4209:   PetscCheck(A->cmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "A->cmap->n %" PetscInt_FMT " != B->rmap->n %" PetscInt_FMT, A->cmap->n, B->rmap->n);
4210:   PetscCall(MatSetSizes(C, m, n, m, n));
4211:   PetscCall(MatSetBlockSizesFromMats(C, A, B));
4212:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSECUDA, MATSEQDENSEHIP, ""));
4213:   if (!cisdense) PetscCall(MatSetType(C, MATDENSE));
4214:   PetscCall(MatSetUp(C));

4216:   C->ops->matmultnumeric = MatMatMultNumeric_SeqDense_SeqAIJ;
4217:   PetscFunctionReturn(PETSC_SUCCESS);
4218: }

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

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

4227:    Level: beginner

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

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

4237:   Developer Note:
4238:     It would be nice if all matrix formats supported passing `NULL` in for the numerical values

4240: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqAIJ()`, `MatSetFromOptions()`, `MatSetType()`, `MatCreate()`, `MatType`, `MATSELL`, `MATSEQSELL`, `MATMPISELL`
4241: M*/

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

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

4252:    Options Database Key:
4253: . -mat_type aij - sets the matrix type to "aij" during a call to `MatSetFromOptions()`

4255:   Level: beginner

4257:    Note:
4258:    Subclasses include `MATAIJCUSPARSE`, `MATAIJPERM`, `MATAIJSELL`, `MATAIJMKL`, `MATAIJCRL`, and also automatically switches over to use inodes when
4259:    enough exist.

4261: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MATMPIAIJ`, `MATSELL`, `MATSEQSELL`, `MATMPISELL`
4262: M*/

4264: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCRL(Mat, MatType, MatReuse, Mat *);
4265: #if PetscDefined(HAVE_ELEMENTAL)
4266: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
4267: #endif
4268: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
4269: PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
4270: #endif
4271: #if PetscDefined(HAVE_HYPRE)
4272: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat A, MatType, MatReuse, Mat *);
4273: #endif

4275: PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqSELL(Mat, MatType, MatReuse, Mat *);
4276: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
4277: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);

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

4282:   Not Collective

4284:   Input Parameter:
4285: . A - a `MATSEQAIJ` matrix

4287:   Output Parameter:
4288: . array - pointer to the data

4290:   Level: intermediate

4292: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJRestoreArray()`
4293: @*/
4294: PetscErrorCode MatSeqAIJGetArray(Mat A, PetscScalar *array[])
4295: {
4296:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4298:   PetscFunctionBegin;
4299:   if (aij->ops->getarray) {
4300:     PetscCall((*aij->ops->getarray)(A, array));
4301:   } else {
4302:     *array = aij->a;
4303:   }
4304:   PetscFunctionReturn(PETSC_SUCCESS);
4305: }

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

4310:   Not Collective

4312:   Input Parameters:
4313: + A     - a `MATSEQAIJ` matrix
4314: - array - pointer to the data

4316:   Level: intermediate

4318: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`
4319: @*/
4320: PetscErrorCode MatSeqAIJRestoreArray(Mat A, PetscScalar *array[])
4321: {
4322:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4324:   PetscFunctionBegin;
4325:   if (aij->ops->restorearray) {
4326:     PetscCall((*aij->ops->restorearray)(A, array));
4327:   } else {
4328:     *array = NULL;
4329:   }
4330:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
4331:   PetscFunctionReturn(PETSC_SUCCESS);
4332: }

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

4337:   Not Collective

4339:   Input Parameter:
4340: . A - a `MATSEQAIJ` matrix

4342:   Output Parameter:
4343: . array - pointer to the data

4345:   Level: intermediate

4347: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayRead()`
4348: @*/
4349: PetscErrorCode MatSeqAIJGetArrayRead(Mat A, const PetscScalar *array[])
4350: {
4351:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4353:   PetscFunctionBegin;
4354:   if (aij->ops->getarrayread) {
4355:     PetscCall((*aij->ops->getarrayread)(A, array));
4356:   } else {
4357:     *array = aij->a;
4358:   }
4359:   PetscFunctionReturn(PETSC_SUCCESS);
4360: }

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

4365:   Not Collective

4367:   Input Parameter:
4368: . A - a `MATSEQAIJ` matrix

4370:   Output Parameter:
4371: . array - pointer to the data

4373:   Level: intermediate

4375: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4376: @*/
4377: PetscErrorCode MatSeqAIJRestoreArrayRead(Mat A, const PetscScalar *array[])
4378: {
4379:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4381:   PetscFunctionBegin;
4382:   if (aij->ops->restorearrayread) {
4383:     PetscCall((*aij->ops->restorearrayread)(A, array));
4384:   } else {
4385:     *array = NULL;
4386:   }
4387:   PetscFunctionReturn(PETSC_SUCCESS);
4388: }

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

4393:   Not Collective

4395:   Input Parameter:
4396: . A - a `MATSEQAIJ` matrix

4398:   Output Parameter:
4399: . array - pointer to the data

4401:   Level: intermediate

4403: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayWrite()`
4404: @*/
4405: PetscErrorCode MatSeqAIJGetArrayWrite(Mat A, PetscScalar *array[])
4406: {
4407:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4409:   PetscFunctionBegin;
4410:   if (aij->ops->getarraywrite) {
4411:     PetscCall((*aij->ops->getarraywrite)(A, array));
4412:   } else {
4413:     *array = aij->a;
4414:   }
4415:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
4416:   PetscFunctionReturn(PETSC_SUCCESS);
4417: }

4419: /*@C
4420:   MatSeqAIJRestoreArrayWrite - restore the write-only access array obtained from `MatSeqAIJGetArrayWrite()`

4422:   Not Collective

4424:   Input Parameter:
4425: . A - a `MATSEQAIJ` matrix

4427:   Output Parameter:
4428: . array - pointer to the data

4430:   Level: intermediate

4432: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayWrite()`
4433: @*/
4434: PetscErrorCode MatSeqAIJRestoreArrayWrite(Mat A, PetscScalar *array[])
4435: {
4436:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4438:   PetscFunctionBegin;
4439:   if (aij->ops->restorearraywrite) {
4440:     PetscCall((*aij->ops->restorearraywrite)(A, array));
4441:   } else {
4442:     *array = NULL;
4443:   }
4444:   PetscFunctionReturn(PETSC_SUCCESS);
4445: }

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

4450:   Not Collective; No Fortran Support

4452:   Input Parameter:
4453: . mat - a matrix of type `MATSEQAIJ` or its subclasses

4455:   Output Parameters:
4456: + i     - row map array of the matrix
4457: . j     - column index array of the matrix
4458: . a     - data array of the matrix
4459: - mtype - memory type of the arrays

4461:   Level: developer

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

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

4470: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4471: @*/
4472: PetscErrorCode MatSeqAIJGetCSRAndMemType(Mat mat, const PetscInt *i[], const PetscInt *j[], PetscScalar *a[], PetscMemType *mtype)
4473: {
4474:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;

4476:   PetscFunctionBegin;
4477:   PetscCheck(mat->preallocated, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "matrix is not preallocated");
4478:   if (aij->ops->getcsrandmemtype) {
4479:     PetscCall((*aij->ops->getcsrandmemtype)(mat, i, j, a, mtype));
4480:   } else {
4481:     if (i) *i = aij->i;
4482:     if (j) *j = aij->j;
4483:     if (a) *a = aij->a;
4484:     if (mtype) *mtype = PETSC_MEMTYPE_HOST;
4485:   }
4486:   PetscFunctionReturn(PETSC_SUCCESS);
4487: }

4489: /*@
4490:   MatSeqAIJGetMaxRowNonzeros - returns the maximum number of nonzeros in any row

4492:   Not Collective

4494:   Input Parameter:
4495: . A - a `MATSEQAIJ` matrix

4497:   Output Parameter:
4498: . nz - the maximum number of nonzeros in any row

4500:   Level: intermediate

4502: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJRestoreArray()`
4503: @*/
4504: PetscErrorCode MatSeqAIJGetMaxRowNonzeros(Mat A, PetscInt *nz)
4505: {
4506:   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;

4508:   PetscFunctionBegin;
4509:   *nz = aij->rmax;
4510:   PetscFunctionReturn(PETSC_SUCCESS);
4511: }

4513: static PetscErrorCode MatCOOStructDestroy_SeqAIJ(PetscCtxRt data)
4514: {
4515:   MatCOOStruct_SeqAIJ *coo = *(MatCOOStruct_SeqAIJ **)data;

4517:   PetscFunctionBegin;
4518:   PetscCall(PetscFree(coo->perm));
4519:   PetscCall(PetscFree(coo->jmap));
4520:   PetscCall(PetscFree(coo));
4521:   PetscFunctionReturn(PETSC_SUCCESS);
4522: }

4524: PetscErrorCode MatSetPreallocationCOO_SeqAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
4525: {
4526:   MPI_Comm             comm;
4527:   PetscInt            *i, *j;
4528:   PetscInt             M, N, row, iprev;
4529:   PetscCount           k, p, q, nneg, nnz, start, end; /* Index the coo array, so use PetscCount as their type */
4530:   PetscInt            *Ai;                             /* Change to PetscCount once we use it for row pointers */
4531:   PetscInt            *Aj;
4532:   PetscScalar         *Aa;
4533:   Mat_SeqAIJ          *seqaij = (Mat_SeqAIJ *)mat->data;
4534:   MatType              rtype;
4535:   PetscCount          *perm, *jmap;
4536:   MatCOOStruct_SeqAIJ *coo;
4537:   PetscBool            isorted;
4538:   PetscBool            hypre;

4540:   PetscFunctionBegin;
4541:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
4542:   PetscCall(MatGetSize(mat, &M, &N));
4543:   i = coo_i;
4544:   j = coo_j;
4545:   PetscCall(PetscMalloc1(coo_n, &perm));

4547:   /* Ignore entries with negative row or col indices; at the same time, check if i[] is already sorted (e.g., MatConvert_AlJ_HYPRE results in this case) */
4548:   isorted = PETSC_TRUE;
4549:   iprev   = PETSC_INT_MIN;
4550:   for (k = 0; k < coo_n; k++) {
4551:     if (j[k] < 0) i[k] = -1;
4552:     if (isorted) {
4553:       if (i[k] < iprev) isorted = PETSC_FALSE;
4554:       else iprev = i[k];
4555:     }
4556:     perm[k] = k;
4557:   }

4559:   /* Sort by row if not already */
4560:   if (!isorted) PetscCall(PetscSortIntWithIntCountArrayPair(coo_n, i, j, perm));
4561:   PetscCheck(coo_n == 0 || i[coo_n - 1] < M, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "COO row index %" PetscInt_FMT " is >= the matrix row size %" PetscInt_FMT, i[coo_n - 1], M);

4563:   /* Advance k to the first row with a non-negative index */
4564:   for (k = 0; k < coo_n; k++)
4565:     if (i[k] >= 0) break;
4566:   nneg = k;
4567:   PetscCall(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 */
4568:   nnz = 0;                                          /* Total number of unique nonzeros to be counted */
4569:   jmap++;                                           /* Inc jmap by 1 for convenience */

4571:   PetscCall(PetscShmgetAllocateArray(M + 1, sizeof(PetscInt), (void **)&Ai)); /* CSR of A */
4572:   PetscCall(PetscArrayzero(Ai, M + 1));
4573:   PetscCall(PetscShmgetAllocateArray(coo_n - nneg, sizeof(PetscInt), (void **)&Aj)); /* We have at most coo_n-nneg unique nonzeros */

4575:   PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", ((PetscObject)mat)->name, &hypre));

4577:   /* In each row, sort by column, then unique column indices to get row length */
4578:   Ai++;  /* Inc by 1 for convenience */
4579:   q = 0; /* q-th unique nonzero, with q starting from 0 */
4580:   while (k < coo_n) {
4581:     PetscBool strictly_sorted; // this row is strictly sorted?
4582:     PetscInt  jprev;

4584:     /* get [start,end) indices for this row; also check if cols in this row are strictly sorted */
4585:     row             = i[k];
4586:     start           = k;
4587:     jprev           = PETSC_INT_MIN;
4588:     strictly_sorted = PETSC_TRUE;
4589:     while (k < coo_n && i[k] == row) {
4590:       if (strictly_sorted) {
4591:         if (j[k] <= jprev) strictly_sorted = PETSC_FALSE;
4592:         else jprev = j[k];
4593:       }
4594:       k++;
4595:     }
4596:     end = k;

4598:     /* hack for HYPRE: swap min column to diag so that diagonal values will go first */
4599:     if (hypre) {
4600:       PetscInt  minj    = PETSC_INT_MAX;
4601:       PetscBool hasdiag = PETSC_FALSE;

4603:       if (strictly_sorted) { // fast path to swap the first and the diag
4604:         PetscCount tmp;
4605:         for (p = start; p < end; p++) {
4606:           if (j[p] == row && p != start) {
4607:             j[p]        = j[start]; // swap j[], so that the diagonal value will go first (manipulated by perm[])
4608:             j[start]    = row;
4609:             tmp         = perm[start];
4610:             perm[start] = perm[p]; // also swap perm[] so we can save the call to PetscSortIntWithCountArray() below
4611:             perm[p]     = tmp;
4612:             break;
4613:           }
4614:         }
4615:       } else {
4616:         for (p = start; p < end; p++) {
4617:           hasdiag = (PetscBool)(hasdiag || (j[p] == row));
4618:           minj    = PetscMin(minj, j[p]);
4619:         }

4621:         if (hasdiag) {
4622:           for (p = start; p < end; p++) {
4623:             if (j[p] == minj) j[p] = row;
4624:             else if (j[p] == row) j[p] = minj;
4625:           }
4626:         }
4627:       }
4628:     }
4629:     // sort by columns in a row. perm[] indicates their original order
4630:     if (!strictly_sorted) PetscCall(PetscSortIntWithCountArray(end - start, j + start, perm + start));
4631:     PetscCheck(end == start || j[end - 1] < N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "COO column index %" PetscInt_FMT " is >= the matrix column size %" PetscInt_FMT, j[end - 1], N);

4633:     if (strictly_sorted) { // fast path to set Aj[], jmap[], Ai[], nnz, q
4634:       for (p = start; p < end; p++, q++) {
4635:         Aj[q]   = j[p];
4636:         jmap[q] = 1;
4637:       }
4638:       PetscCall(PetscIntCast(end - start, Ai + row));
4639:       nnz += Ai[row]; // q is already advanced
4640:     } else {
4641:       /* Find number of unique col entries in this row */
4642:       Aj[q]   = j[start]; /* Log the first nonzero in this row */
4643:       jmap[q] = 1;        /* Number of repeats of this nonzero entry */
4644:       Ai[row] = 1;
4645:       nnz++;

4647:       for (p = start + 1; p < end; p++) { /* Scan remaining nonzero in this row */
4648:         if (j[p] != j[p - 1]) {           /* Meet a new nonzero */
4649:           q++;
4650:           jmap[q] = 1;
4651:           Aj[q]   = j[p];
4652:           Ai[row]++;
4653:           nnz++;
4654:         } else {
4655:           jmap[q]++;
4656:         }
4657:       }
4658:       q++; /* Move to next row and thus next unique nonzero */
4659:     }
4660:   }

4662:   Ai--; /* Back to the beginning of Ai[] */
4663:   for (k = 0; k < M; k++) Ai[k + 1] += Ai[k];
4664:   jmap--; // Back to the beginning of jmap[]
4665:   jmap[0] = 0;
4666:   for (k = 0; k < nnz; k++) jmap[k + 1] += jmap[k];

4668:   if (nnz < coo_n - nneg) { /* Reallocate with actual number of unique nonzeros */
4669:     PetscCount *jmap_new;
4670:     PetscInt   *Aj_new;

4672:     PetscCall(PetscMalloc1(nnz + 1, &jmap_new));
4673:     PetscCall(PetscArraycpy(jmap_new, jmap, nnz + 1));
4674:     PetscCall(PetscFree(jmap));
4675:     jmap = jmap_new;

4677:     PetscCall(PetscShmgetAllocateArray(nnz, sizeof(PetscInt), (void **)&Aj_new));
4678:     PetscCall(PetscArraycpy(Aj_new, Aj, nnz));
4679:     PetscCall(PetscShmgetDeallocateArray((void **)&Aj));
4680:     Aj = Aj_new;
4681:   }

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

4686:     PetscCall(PetscMalloc1(coo_n - nneg, &perm_new));
4687:     PetscCall(PetscArraycpy(perm_new, perm + nneg, coo_n - nneg));
4688:     PetscCall(PetscFree(perm));
4689:     perm = perm_new;
4690:   }

4692:   PetscCall(MatGetRootType_Private(mat, &rtype));
4693:   PetscCall(PetscShmgetAllocateArray(nnz, sizeof(PetscScalar), (void **)&Aa));
4694:   PetscCall(PetscArrayzero(Aa, nnz));
4695:   PetscCall(MatSetSeqAIJWithArrays_private(PETSC_COMM_SELF, M, N, Ai, Aj, Aa, rtype, mat));

4697:   seqaij->free_a = seqaij->free_ij = PETSC_TRUE; /* Let newmat own Ai, Aj and Aa */

4699:   // Put the COO struct in a container and then attach that to the matrix
4700:   PetscCall(PetscMalloc1(1, &coo));
4701:   PetscCall(PetscIntCast(nnz, &coo->nz));
4702:   coo->n    = coo_n;
4703:   coo->Atot = coo_n - nneg; // Annz is seqaij->nz, so no need to record that again
4704:   coo->jmap = jmap;         // of length nnz+1
4705:   coo->perm = perm;
4706:   PetscCall(PetscObjectContainerCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Host", coo, MatCOOStructDestroy_SeqAIJ));
4707:   PetscFunctionReturn(PETSC_SUCCESS);
4708: }

4710: static PetscErrorCode MatSetValuesCOO_SeqAIJ(Mat A, const PetscScalar v[], InsertMode imode)
4711: {
4712:   Mat_SeqAIJ          *aseq = (Mat_SeqAIJ *)A->data;
4713:   PetscCount           i, j, Annz = aseq->nz;
4714:   PetscCount          *perm, *jmap;
4715:   PetscScalar         *Aa;
4716:   PetscContainer       container;
4717:   MatCOOStruct_SeqAIJ *coo;

4719:   PetscFunctionBegin;
4720:   PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
4721:   PetscCheck(container, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not found MatCOOStruct on this matrix");
4722:   PetscCall(PetscContainerGetPointer(container, &coo));
4723:   perm = coo->perm;
4724:   jmap = coo->jmap;
4725:   PetscCall(MatSeqAIJGetArray(A, &Aa));
4726:   for (i = 0; i < Annz; i++) {
4727:     PetscScalar sum = 0.0;
4728:     for (j = jmap[i]; j < jmap[i + 1]; j++) sum += v[perm[j]];
4729:     Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
4730:   }
4731:   PetscCall(MatSeqAIJRestoreArray(A, &Aa));
4732:   PetscFunctionReturn(PETSC_SUCCESS);
4733: }

4735: #if PetscDefined(HAVE_CUDA)
4736: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
4737: #endif
4738: #if PetscDefined(HAVE_HIP)
4739: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);
4740: #endif
4741: #if PetscDefined(HAVE_KOKKOS_KERNELS)
4742: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJKokkos(Mat, MatType, MatReuse, Mat *);
4743: #endif

4745: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJ(Mat B)
4746: {
4747:   Mat_SeqAIJ *b;
4748:   PetscMPIInt size;

4750:   PetscFunctionBegin;
4751:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
4752:   PetscCheck(size <= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Comm must be of size 1");

4754:   PetscCall(PetscNew(&b));

4756:   B->data   = (void *)b;
4757:   B->ops[0] = MatOps_Values;
4758:   if (B->sortedfull) B->ops->setvalues = MatSetValues_SeqAIJ_SortedFull;

4760:   b->row                = NULL;
4761:   b->col                = NULL;
4762:   b->icol               = NULL;
4763:   b->reallocs           = 0;
4764:   b->ignorezeroentries  = PETSC_FALSE;
4765:   b->roworiented        = PETSC_TRUE;
4766:   b->nonew              = 0;
4767:   b->diag               = NULL;
4768:   b->solve_work         = NULL;
4769:   B->spptr              = NULL;
4770:   b->saved_values       = NULL;
4771:   b->idiag              = NULL;
4772:   b->mdiag              = NULL;
4773:   b->ssor_work          = NULL;
4774:   b->omega              = 1.0;
4775:   b->fshift             = 0.0;
4776:   b->ibdiagvalid        = PETSC_FALSE;
4777:   b->keepnonzeropattern = PETSC_FALSE;

4779:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATSEQAIJ));
4780: #if PetscDefined(HAVE_MATLAB)
4781:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "PetscMatlabEnginePut_C", MatlabEnginePut_SeqAIJ));
4782:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "PetscMatlabEngineGet_C", MatlabEngineGet_SeqAIJ));
4783: #endif
4784:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetColumnIndices_C", MatSeqAIJSetColumnIndices_SeqAIJ));
4785:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_SeqAIJ));
4786:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_SeqAIJ));
4787:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqsbaij_C", MatConvert_SeqAIJ_SeqSBAIJ));
4788:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqbaij_C", MatConvert_SeqAIJ_SeqBAIJ));
4789:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijperm_C", MatConvert_SeqAIJ_SeqAIJPERM));
4790:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijsell_C", MatConvert_SeqAIJ_SeqAIJSELL));
4791: #if PetscDefined(HAVE_MKL_SPARSE)
4792:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijmkl_C", MatConvert_SeqAIJ_SeqAIJMKL));
4793: #endif
4794: #if PetscDefined(HAVE_CUDA)
4795:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijcusparse_C", MatConvert_SeqAIJ_SeqAIJCUSPARSE));
4796:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaijcusparse_seqaij_C", MatProductSetFromOptions_SeqAIJ));
4797:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaijcusparse_C", MatProductSetFromOptions_SeqAIJ));
4798: #endif
4799: #if PetscDefined(HAVE_HIP)
4800:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijhipsparse_C", MatConvert_SeqAIJ_SeqAIJHIPSPARSE));
4801:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaijhipsparse_seqaij_C", MatProductSetFromOptions_SeqAIJ));
4802:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaijhipsparse_C", MatProductSetFromOptions_SeqAIJ));
4803: #endif
4804: #if PetscDefined(HAVE_KOKKOS_KERNELS)
4805:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijkokkos_C", MatConvert_SeqAIJ_SeqAIJKokkos));
4806: #endif
4807:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijcrl_C", MatConvert_SeqAIJ_SeqAIJCRL));
4808: #if PetscDefined(HAVE_ELEMENTAL)
4809:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_elemental_C", MatConvert_SeqAIJ_Elemental));
4810: #endif
4811: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
4812:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_scalapack_C", MatConvert_AIJ_ScaLAPACK));
4813: #endif
4814: #if PetscDefined(HAVE_HYPRE)
4815:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_hypre_C", MatConvert_AIJ_HYPRE));
4816:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_seqaij_seqaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ));
4817: #endif
4818:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqdense_C", MatConvert_SeqAIJ_SeqDense));
4819:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqsell_C", MatConvert_SeqAIJ_SeqSELL));
4820:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_is_C", MatConvert_XAIJ_IS));
4821:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_SeqAIJ));
4822:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsHermitianTranspose_C", MatIsHermitianTranspose_SeqAIJ));
4823:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetPreallocation_C", MatSeqAIJSetPreallocation_SeqAIJ));
4824:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_SeqAIJ));
4825:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetHash_C", MatResetHash_SeqAIJ));
4826:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetPreallocationCSR_C", MatSeqAIJSetPreallocationCSR_SeqAIJ));
4827:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatReorderForNonzeroDiagonal_C", MatReorderForNonzeroDiagonal_SeqAIJ));
4828:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_seqaij_C", MatProductSetFromOptions_IS_XAIJ));
4829:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdense_seqaij_C", MatProductSetFromOptions_SeqDense_SeqAIJ));
4830:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaij_C", MatProductSetFromOptions_SeqAIJ));
4831:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJKron_C", MatSeqAIJKron_SeqAIJ));
4832:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_SeqAIJ));
4833:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_SeqAIJ));
4834:   PetscCall(MatCreate_SeqAIJ_Inode(B));
4835:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATSEQAIJ));
4836:   PetscCall(MatSeqAIJSetTypeFromOptions(B)); /* this allows changing the matrix subtype to say MATSEQAIJPERM */
4837:   PetscFunctionReturn(PETSC_SUCCESS);
4838: }

4840: /*
4841:     Given a matrix generated with MatGetFactor() duplicates all the information in A into C
4842: */
4843: PetscErrorCode MatDuplicateNoCreate_SeqAIJ(Mat C, Mat A, MatDuplicateOption cpvalues, PetscBool mallocmatspace)
4844: {
4845:   Mat_SeqAIJ *c = (Mat_SeqAIJ *)C->data, *a = (Mat_SeqAIJ *)A->data;
4846:   PetscInt    m = A->rmap->n, i;

4848:   PetscFunctionBegin;
4849:   PetscCheck(A->assembled || cpvalues == MAT_DO_NOT_COPY_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot duplicate unassembled matrix");

4851:   C->factortype = A->factortype;
4852:   c->row        = NULL;
4853:   c->col        = NULL;
4854:   c->icol       = NULL;
4855:   c->reallocs   = 0;
4856:   C->assembled  = A->assembled;

4858:   if (A->preallocated) {
4859:     PetscCall(PetscLayoutReference(A->rmap, &C->rmap));
4860:     PetscCall(PetscLayoutReference(A->cmap, &C->cmap));

4862:     if (!A->hash_active) {
4863:       PetscCall(PetscMalloc1(m, &c->imax));
4864:       PetscCall(PetscArraycpy(c->imax, a->imax, m));
4865:       PetscCall(PetscMalloc1(m, &c->ilen));
4866:       PetscCall(PetscArraycpy(c->ilen, a->ilen, m));

4868:       /* allocate the matrix space */
4869:       if (mallocmatspace) {
4870:         PetscCall(PetscShmgetAllocateArray(a->i[m], sizeof(PetscScalar), (void **)&c->a));
4871:         PetscCall(PetscShmgetAllocateArray(a->i[m], sizeof(PetscInt), (void **)&c->j));
4872:         PetscCall(PetscShmgetAllocateArray(m + 1, sizeof(PetscInt), (void **)&c->i));
4873:         PetscCall(PetscArraycpy(c->i, a->i, m + 1));
4874:         c->free_a  = PETSC_TRUE;
4875:         c->free_ij = PETSC_TRUE;
4876:         if (m > 0) {
4877:           PetscCall(PetscArraycpy(c->j, a->j, a->i[m]));
4878:           if (cpvalues == MAT_COPY_VALUES) {
4879:             const PetscScalar *aa;

4881:             PetscCall(MatSeqAIJGetArrayRead(A, &aa));
4882:             PetscCall(PetscArraycpy(c->a, aa, a->i[m]));
4883:             PetscCall(MatSeqAIJGetArrayRead(A, &aa));
4884:           } else {
4885:             PetscCall(PetscArrayzero(c->a, a->i[m]));
4886:           }
4887:         }
4888:       }
4889:       C->preallocated = PETSC_TRUE;
4890:     } else {
4891:       PetscCheck(mallocmatspace, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Cannot malloc matrix memory from a non-preallocated matrix");
4892:       PetscCall(MatSetUp(C));
4893:     }

4895:     c->ignorezeroentries  = a->ignorezeroentries;
4896:     c->roworiented        = a->roworiented;
4897:     c->nonew              = a->nonew;
4898:     c->solve_work         = NULL;
4899:     c->saved_values       = NULL;
4900:     c->idiag              = NULL;
4901:     c->ssor_work          = NULL;
4902:     c->keepnonzeropattern = a->keepnonzeropattern;

4904:     c->rmax  = a->rmax;
4905:     c->nz    = a->nz;
4906:     c->maxnz = a->nz; /* Since we allocate exactly the right amount */

4908:     c->compressedrow.use   = a->compressedrow.use;
4909:     c->compressedrow.nrows = a->compressedrow.nrows;
4910:     if (a->compressedrow.use) {
4911:       i = a->compressedrow.nrows;
4912:       PetscCall(PetscMalloc2(i + 1, &c->compressedrow.i, i, &c->compressedrow.rindex));
4913:       PetscCall(PetscArraycpy(c->compressedrow.i, a->compressedrow.i, i + 1));
4914:       PetscCall(PetscArraycpy(c->compressedrow.rindex, a->compressedrow.rindex, i));
4915:     } else {
4916:       c->compressedrow.use    = PETSC_FALSE;
4917:       c->compressedrow.i      = NULL;
4918:       c->compressedrow.rindex = NULL;
4919:     }
4920:     c->nonzerorowcnt = a->nonzerorowcnt;
4921:     C->nonzerostate  = A->nonzerostate;

4923:     PetscCall(MatDuplicate_SeqAIJ_Inode(A, cpvalues, &C));
4924:   }
4925:   PetscCall(PetscFunctionListDuplicate(((PetscObject)A)->qlist, &((PetscObject)C)->qlist));
4926:   PetscFunctionReturn(PETSC_SUCCESS);
4927: }

4929: PetscErrorCode MatDuplicate_SeqAIJ(Mat A, MatDuplicateOption cpvalues, Mat *B)
4930: {
4931:   PetscFunctionBegin;
4932:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), B));
4933:   PetscCall(MatSetSizes(*B, A->rmap->n, A->cmap->n, A->rmap->n, A->cmap->n));
4934:   if (!(A->rmap->n % A->rmap->bs) && !(A->cmap->n % A->cmap->bs)) PetscCall(MatSetBlockSizesFromMats(*B, A, A));
4935:   PetscCall(MatSetType(*B, ((PetscObject)A)->type_name));
4936:   PetscCall(MatDuplicateNoCreate_SeqAIJ(*B, A, cpvalues, PETSC_TRUE));
4937:   PetscFunctionReturn(PETSC_SUCCESS);
4938: }

4940: PetscErrorCode MatLoad_SeqAIJ(Mat newMat, PetscViewer viewer)
4941: {
4942:   PetscBool isbinary, ishdf5;

4944:   PetscFunctionBegin;
4947:   /* force binary viewer to load .info file if it has not yet done so */
4948:   PetscCall(PetscViewerSetUp(viewer));
4949:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
4950:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
4951:   if (isbinary) {
4952:     PetscCall(MatLoad_SeqAIJ_Binary(newMat, viewer));
4953:   } else if (ishdf5) {
4954: #if PetscDefined(HAVE_HDF5)
4955:     PetscCall(MatLoad_AIJ_HDF5(newMat, viewer));
4956: #else
4957:     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
4958: #endif
4959:   } else {
4960:     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);
4961:   }
4962:   PetscFunctionReturn(PETSC_SUCCESS);
4963: }

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

4970:   PetscFunctionBegin;
4971:   PetscCall(PetscViewerSetUp(viewer));

4973:   /* read in matrix header */
4974:   PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
4975:   PetscCheck(header[0] == MAT_FILE_CLASSID, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
4976:   M  = header[1];
4977:   N  = header[2];
4978:   nz = header[3];
4979:   PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
4980:   PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
4981:   PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix stored in special format on disk, cannot load as SeqAIJ");

4983:   /* set block sizes from the viewer's .info file */
4984:   PetscCall(MatLoad_Binary_BlockSizes(mat, viewer));
4985:   /* set local and global sizes if not set already */
4986:   if (mat->rmap->n < 0) mat->rmap->n = M;
4987:   if (mat->cmap->n < 0) mat->cmap->n = N;
4988:   if (mat->rmap->N < 0) mat->rmap->N = M;
4989:   if (mat->cmap->N < 0) mat->cmap->N = N;
4990:   PetscCall(PetscLayoutSetUp(mat->rmap));
4991:   PetscCall(PetscLayoutSetUp(mat->cmap));

4993:   /* check if the matrix sizes are correct */
4994:   PetscCall(MatGetSize(mat, &rows, &cols));
4995:   PetscCheck(M == rows && N == cols, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix in file of different sizes (%" PetscInt_FMT ", %" PetscInt_FMT ") than the input matrix (%" PetscInt_FMT ", %" PetscInt_FMT ")", M, N, rows, cols);

4997:   /* read in row lengths */
4998:   PetscCall(PetscMalloc1(M, &rowlens));
4999:   PetscCall(PetscViewerBinaryRead(viewer, rowlens, M, NULL, PETSC_INT));
5000:   /* check if sum(rowlens) is same as nz */
5001:   sum = 0;
5002:   for (i = 0; i < M; i++) sum += rowlens[i];
5003:   PetscCheck(sum == nz, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Inconsistent matrix data in file: nonzeros = %" PetscInt_FMT ", sum-row-lengths = %" PetscInt_FMT, nz, sum);
5004:   /* preallocate and check sizes */
5005:   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(mat, 0, rowlens));
5006:   PetscCall(MatGetSize(mat, &rows, &cols));
5007:   PetscCheck(M == rows && N == cols, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix in file of different length (%" PetscInt_FMT ", %" PetscInt_FMT ") than the input matrix (%" PetscInt_FMT ", %" PetscInt_FMT ")", M, N, rows, cols);
5008:   /* store row lengths */
5009:   PetscCall(PetscArraycpy(a->ilen, rowlens, M));
5010:   PetscCall(PetscFree(rowlens));

5012:   /* fill in "i" row pointers */
5013:   a->i[0] = 0;
5014:   for (i = 0; i < M; i++) a->i[i + 1] = a->i[i] + a->ilen[i];
5015:   /* read in "j" column indices */
5016:   PetscCall(PetscViewerBinaryRead(viewer, a->j, nz, NULL, PETSC_INT));
5017:   /* read in "a" nonzero values */
5018:   PetscCall(PetscViewerBinaryRead(viewer, a->a, nz, NULL, PETSC_SCALAR));

5020:   PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
5021:   PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
5022:   PetscFunctionReturn(PETSC_SUCCESS);
5023: }

5025: PetscErrorCode MatEqual_SeqAIJ(Mat A, Mat B, PetscBool *flg)
5026: {
5027:   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)B->data;
5028:   const PetscScalar *aa, *ba;

5030:   PetscFunctionBegin;
5031:   /* If the  matrix dimensions are not equal,or no of nonzeros */
5032:   if ((A->rmap->n != B->rmap->n) || (A->cmap->n != B->cmap->n) || (a->nz != b->nz)) {
5033:     *flg = PETSC_FALSE;
5034:     PetscFunctionReturn(PETSC_SUCCESS);
5035:   }

5037:   /* if the a->i are the same */
5038:   PetscCall(PetscArraycmp(a->i, b->i, A->rmap->n + 1, flg));
5039:   if (!*flg) PetscFunctionReturn(PETSC_SUCCESS);

5041:   /* if a->j are the same */
5042:   PetscCall(PetscArraycmp(a->j, b->j, a->nz, flg));
5043:   if (!*flg) PetscFunctionReturn(PETSC_SUCCESS);

5045:   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
5046:   PetscCall(MatSeqAIJGetArrayRead(B, &ba));
5047:   /* if a->a are the same */
5048:   PetscCall(PetscArraycmp(aa, ba, a->nz, flg));
5049:   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
5050:   PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
5051:   PetscFunctionReturn(PETSC_SUCCESS);
5052: }

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

5058:   Collective

5060:   Input Parameters:
5061: + comm - must be an MPI communicator of size 1
5062: . m    - number of rows
5063: . n    - number of columns
5064: . i    - row indices; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
5065: . j    - column indices
5066: - a    - matrix values

5068:   Output Parameter:
5069: . mat - the matrix

5071:   Level: intermediate

5073:   Notes:
5074:   The `i`, `j`, and `a` arrays are not copied by this routine, the user must free these arrays
5075:   once the matrix is destroyed and not before

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

5079:   The `i` and `j` indices are 0 based

5081:   The format which is used for the sparse matrix input, is equivalent to a
5082:   row-major ordering.. i.e for the following matrix, the input data expected is
5083:   as shown
5084: .vb
5085:         1 0 0
5086:         2 0 3
5087:         4 5 6

5089:         i =  {0,1,3,6}  [size = nrow+1  = 3+1]
5090:         j =  {0,0,2,0,1,2}  [size = 6]; values must be sorted for each row
5091:         v =  {1,2,3,4,5,6}  [size = 6]
5092: .ve

5094: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MatCreateMPIAIJWithArrays()`, `MatMPIAIJSetPreallocationCSR()`
5095: @*/
5096: PetscErrorCode MatCreateSeqAIJWithArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt i[], PetscInt j[], PetscScalar a[], Mat *mat)
5097: {
5098:   PetscInt    ii;
5099:   Mat_SeqAIJ *aij;

5101:   PetscFunctionBegin;
5102:   PetscCheck(m <= 0 || i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
5103:   PetscCall(MatCreate(comm, mat));
5104:   PetscCall(MatSetSizes(*mat, m, n, m, n));
5105:   /* PetscCall(MatSetBlockSizes(*mat,,)); */
5106:   PetscCall(MatSetType(*mat, MATSEQAIJ));
5107:   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*mat, MAT_SKIP_ALLOCATION, NULL));
5108:   aij = (Mat_SeqAIJ *)(*mat)->data;
5109:   PetscCall(PetscMalloc1(m, &aij->imax));
5110:   PetscCall(PetscMalloc1(m, &aij->ilen));

5112:   aij->i       = i;
5113:   aij->j       = j;
5114:   aij->a       = a;
5115:   aij->nonew   = -1; /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
5116:   aij->free_a  = PETSC_FALSE;
5117:   aij->free_ij = PETSC_FALSE;

5119:   for (ii = 0, aij->nonzerorowcnt = 0, aij->rmax = 0; ii < m; ii++) {
5120:     aij->ilen[ii] = aij->imax[ii] = i[ii + 1] - i[ii];
5121:     if (PetscDefined(USE_DEBUG)) {
5122:       PetscCheck(i[ii + 1] - i[ii] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative row length in i (row indices) row = %" PetscInt_FMT " length = %" PetscInt_FMT, ii, i[ii + 1] - i[ii]);
5123:       for (PetscInt jj = i[ii] + 1; jj < i[ii + 1]; jj++) {
5124:         PetscCheck(j[jj] >= j[jj - 1], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column entry number %" PetscInt_FMT " (actual column %" PetscInt_FMT ") in row %" PetscInt_FMT " is not sorted", jj - i[ii], j[jj], ii);
5125:         PetscCheck(j[jj] != j[jj - 1], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column entry number %" PetscInt_FMT " (actual column %" PetscInt_FMT ") in row %" PetscInt_FMT " is identical to previous entry", jj - i[ii], j[jj], ii);
5126:       }
5127:     }
5128:   }
5129:   if (PetscDefined(USE_DEBUG)) {
5130:     for (ii = 0; ii < aij->i[m]; ii++) {
5131:       PetscCheck(j[ii] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative column index at location = %" PetscInt_FMT " index = %" PetscInt_FMT, ii, j[ii]);
5132:       PetscCheck(j[ii] <= n - 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column index to large at location = %" PetscInt_FMT " index = %" PetscInt_FMT " last column = %" PetscInt_FMT, ii, j[ii], n - 1);
5133:     }
5134:   }

5136:   PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
5137:   PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
5138:   PetscFunctionReturn(PETSC_SUCCESS);
5139: }

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

5145:   Collective

5147:   Input Parameters:
5148: + comm - must be an MPI communicator of size 1
5149: . m    - number of rows
5150: . n    - number of columns
5151: . i    - row indices
5152: . j    - column indices
5153: . a    - matrix values
5154: . nz   - number of nonzeros
5155: - idx  - if the `i` and `j` indices start with 1 use `PETSC_TRUE` otherwise use `PETSC_FALSE`

5157:   Output Parameter:
5158: . mat - the matrix

5160:   Level: intermediate

5162:   Example:
5163:   For the following matrix, the input data expected is as shown (using 0 based indexing)
5164: .vb
5165:         1 0 0
5166:         2 0 3
5167:         4 5 6

5169:         i =  {0,1,1,2,2,2}
5170:         j =  {0,0,2,0,1,2}
5171:         v =  {1,2,3,4,5,6}
5172: .ve

5174:   Note:
5175:   Instead of using this function, users should also consider `MatSetPreallocationCOO()` and `MatSetValuesCOO()`, which allow repeated or remote entries,
5176:   and are particularly useful in iterative applications.

5178: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MatCreateSeqAIJWithArrays()`, `MatMPIAIJSetPreallocationCSR()`, `MatSetValuesCOO()`, `MatSetPreallocationCOO()`
5179: @*/
5180: PetscErrorCode MatCreateSeqAIJFromTriple(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt i[], PetscInt j[], PetscScalar a[], Mat *mat, PetscCount nz, PetscBool idx)
5181: {
5182:   PetscInt ii, *nnz, one = 1, row, col;

5184:   PetscFunctionBegin;
5185:   PetscCall(PetscCalloc1(m, &nnz));
5186:   for (ii = 0; ii < nz; ii++) nnz[i[ii] - !!idx] += 1;
5187:   PetscCall(MatCreate(comm, mat));
5188:   PetscCall(MatSetSizes(*mat, m, n, m, n));
5189:   PetscCall(MatSetType(*mat, MATSEQAIJ));
5190:   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*mat, 0, nnz));
5191:   for (ii = 0; ii < nz; ii++) {
5192:     if (idx) {
5193:       row = i[ii] - 1;
5194:       col = j[ii] - 1;
5195:     } else {
5196:       row = i[ii];
5197:       col = j[ii];
5198:     }
5199:     PetscCall(MatSetValues(*mat, one, &row, one, &col, &a[ii], ADD_VALUES));
5200:   }
5201:   PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
5202:   PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
5203:   PetscCall(PetscFree(nnz));
5204:   PetscFunctionReturn(PETSC_SUCCESS);
5205: }

5207: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
5208: {
5209:   PetscFunctionBegin;
5210:   PetscCall(MatCreateMPIMatConcatenateSeqMat_MPIAIJ(comm, inmat, n, scall, outmat));
5211:   PetscFunctionReturn(PETSC_SUCCESS);
5212: }

5214: /*
5215:  Permute A into C's *local* index space using rowemb,colemb.
5216:  The embedding are supposed to be injections and the above implies that the range of rowemb is a subset
5217:  of [0,m), colemb is in [0,n).
5218:  If pattern == DIFFERENT_NONZERO_PATTERN, C is preallocated according to A.
5219:  */
5220: PetscErrorCode MatSetSeqMat_SeqAIJ(Mat C, IS rowemb, IS colemb, MatStructure pattern, Mat B)
5221: {
5222:   /* If making this function public, change the error returned in this function away from _PLIB. */
5223:   Mat_SeqAIJ     *Baij;
5224:   PetscBool       seqaij;
5225:   PetscInt        m, n, *nz, i, j, count;
5226:   PetscScalar     v;
5227:   const PetscInt *rowindices, *colindices;

5229:   PetscFunctionBegin;
5230:   if (!B) PetscFunctionReturn(PETSC_SUCCESS);
5231:   /* Check to make sure the target matrix (and embeddings) are compatible with C and each other. */
5232:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)B, MATSEQAIJ, &seqaij));
5233:   PetscCheck(seqaij, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input matrix is of wrong type");
5234:   if (rowemb) {
5235:     PetscCall(ISGetLocalSize(rowemb, &m));
5236:     PetscCheck(m == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Row IS of size %" PetscInt_FMT " is incompatible with matrix row size %" PetscInt_FMT, m, B->rmap->n);
5237:   } else PetscCheck(C->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input matrix is row-incompatible with the target matrix");
5238:   if (colemb) {
5239:     PetscCall(ISGetLocalSize(colemb, &n));
5240:     PetscCheck(n == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Diag col IS of size %" PetscInt_FMT " is incompatible with input matrix col size %" PetscInt_FMT, n, B->cmap->n);
5241:   } else PetscCheck(C->cmap->n == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input matrix is col-incompatible with the target matrix");

5243:   Baij       = (Mat_SeqAIJ *)B->data;
5244:   rowindices = NULL;
5245:   if (rowemb) PetscCall(ISGetIndices(rowemb, &rowindices));
5246:   if (pattern == DIFFERENT_NONZERO_PATTERN) {
5247:     PetscCall(PetscMalloc1(C->rmap->n, &nz));
5248:     if (rowemb) {
5249:       PetscCall(PetscArrayzero(nz, C->rmap->n));
5250:       for (i = 0; i < B->rmap->n; i++) nz[rowindices[i]] = Baij->i[i + 1] - Baij->i[i];
5251:     } else {
5252:       for (i = 0; i < B->rmap->n; i++) nz[i] = Baij->i[i + 1] - Baij->i[i];
5253:     }
5254:     PetscCall(MatSeqAIJSetPreallocation(C, 0, nz));
5255:     PetscCall(PetscFree(nz));
5256:   }
5257:   if (pattern == SUBSET_NONZERO_PATTERN) PetscCall(MatZeroEntries(C));
5258:   count      = 0;
5259:   colindices = NULL;
5260:   if (colemb) PetscCall(ISGetIndices(colemb, &colindices));
5261:   for (i = 0; i < B->rmap->n; i++) {
5262:     PetscInt row;
5263:     row = i;
5264:     if (rowindices) row = rowindices[i];
5265:     for (j = Baij->i[i]; j < Baij->i[i + 1]; j++) {
5266:       PetscInt col;
5267:       col = Baij->j[count];
5268:       if (colindices) col = colindices[col];
5269:       v = Baij->a[count];
5270:       PetscCall(MatSetValues(C, 1, &row, 1, &col, &v, INSERT_VALUES));
5271:       ++count;
5272:     }
5273:   }
5274:   if (colemb) PetscCall(ISRestoreIndices(colemb, &colindices));
5275:   if (rowemb) PetscCall(ISRestoreIndices(rowemb, &rowindices));
5276:   /* FIXME: set C's nonzerostate correctly. */
5277:   /* Assembly for C is necessary. */
5278:   C->preallocated  = PETSC_TRUE;
5279:   C->assembled     = PETSC_TRUE;
5280:   C->was_assembled = PETSC_FALSE;
5281:   PetscFunctionReturn(PETSC_SUCCESS);
5282: }

5284: PetscErrorCode MatEliminateZeros_SeqAIJ(Mat A, PetscBool keep)
5285: {
5286:   Mat_SeqAIJ *a  = (Mat_SeqAIJ *)A->data;
5287:   MatScalar  *aa = a->a;
5288:   PetscInt    m = A->rmap->n, fshift = 0, fshift_prev = 0, i, k;
5289:   PetscInt   *ailen = a->ilen, *imax = a->imax, *ai = a->i, *aj = a->j, rmax = 0;

5291:   PetscFunctionBegin;
5292:   PetscCheck(A->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot eliminate zeros for unassembled matrix");
5293:   if (m) rmax = ailen[0]; /* determine row with most nonzeros */
5294:   for (i = 1, a->nonzerorowcnt = 0; i <= m; i++) {
5295:     /* move each nonzero entry back by the amount of zero slots (fshift) before it*/
5296:     for (k = ai[i - 1]; k < ai[i]; k++) {
5297:       if (aa[k] == 0 && (aj[k] != i - 1 || !keep)) fshift++;
5298:       else {
5299:         if (aa[k] == 0 && aj[k] == i - 1) PetscCall(PetscInfo(A, "Keep the diagonal zero at row %" PetscInt_FMT "\n", i - 1));
5300:         aa[k - fshift] = aa[k];
5301:         aj[k - fshift] = aj[k];
5302:       }
5303:     }
5304:     ai[i - 1] -= fshift_prev; // safe to update ai[i-1] now since it will not be used in the next iteration
5305:     fshift_prev = fshift;
5306:     /* reset ilen and imax for each row */
5307:     ailen[i - 1] = imax[i - 1] = ai[i] - fshift - ai[i - 1];
5308:     a->nonzerorowcnt += ((ai[i] - fshift - ai[i - 1]) > 0);
5309:     rmax = PetscMax(rmax, ailen[i - 1]);
5310:   }
5311:   if (fshift) {
5312:     if (m) {
5313:       ai[m] -= fshift;
5314:       a->nz = ai[m];
5315:     }
5316:     PetscCall(PetscInfo(A, "Matrix size: %" PetscInt_FMT " X %" PetscInt_FMT "; zeros eliminated: %" PetscInt_FMT "; nonzeros left: %" PetscInt_FMT "\n", m, A->cmap->n, fshift, a->nz));
5317:     A->nonzerostate++;
5318:     A->info.nz_unneeded += (PetscReal)fshift;
5319:     a->rmax = rmax;
5320:     if (a->inode.use && a->inode.checked) PetscCall(MatSeqAIJCheckInode(A));
5321:     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
5322:     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
5323:   }
5324:   PetscFunctionReturn(PETSC_SUCCESS);
5325: }

5327: PetscFunctionList MatSeqAIJList = NULL;

5329: /*@
5330:   MatSeqAIJSetType - Converts a `MATSEQAIJ` matrix to a subtype

5332:   Collective

5334:   Input Parameters:
5335: + mat    - the matrix object
5336: - matype - matrix type

5338:   Options Database Key:
5339: . -mat_seqaij_type  method - for example seqaijcrl

5341:   Level: intermediate

5343: .seealso: [](ch_matrices), `Mat`, `PCSetType()`, `VecSetType()`, `MatCreate()`, `MatType`
5344: @*/
5345: PetscErrorCode MatSeqAIJSetType(Mat mat, MatType matype)
5346: {
5347:   PetscBool sametype;
5348:   PetscErrorCode (*r)(Mat, MatType, MatReuse, Mat *);

5350:   PetscFunctionBegin;
5352:   PetscCall(PetscObjectTypeCompare((PetscObject)mat, matype, &sametype));
5353:   if (sametype) PetscFunctionReturn(PETSC_SUCCESS);

5355:   PetscCall(PetscFunctionListFind(MatSeqAIJList, matype, &r));
5356:   PetscCheck(r, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown Mat type given: %s", matype);
5357:   PetscCall((*r)(mat, matype, MAT_INPLACE_MATRIX, &mat));
5358:   PetscFunctionReturn(PETSC_SUCCESS);
5359: }

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

5364:   Not Collective, No Fortran Support

5366:   Input Parameters:
5367: + sname    - name of a new user-defined matrix type, for example `MATSEQAIJCRL`
5368: - function - routine to convert to subtype

5370:   Level: advanced

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

5375:   Then, your matrix can be chosen with the procedural interface at runtime via the option
5376: .vb
5377:   -mat_seqaij_type my_mat
5378: .ve

5380: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJRegisterAll()`
5381: @*/
5382: PetscErrorCode MatSeqAIJRegister(const char sname[], PetscErrorCode (*function)(Mat, MatType, MatReuse, Mat *))
5383: {
5384:   PetscFunctionBegin;
5385:   PetscCall(MatInitializePackage());
5386:   PetscCall(PetscFunctionListAdd(&MatSeqAIJList, sname, function));
5387:   PetscFunctionReturn(PETSC_SUCCESS);
5388: }

5390: PetscBool MatSeqAIJRegisterAllCalled = PETSC_FALSE;

5392: /*@C
5393:   MatSeqAIJRegisterAll - Registers all of the matrix subtypes of `MATSSEQAIJ`

5395:   Not Collective

5397:   Level: advanced

5399:   Note:
5400:   This registers the versions of `MATSEQAIJ` for GPUs

5402: .seealso: [](ch_matrices), `Mat`, `MatRegisterAll()`, `MatSeqAIJRegister()`
5403: @*/
5404: PetscErrorCode MatSeqAIJRegisterAll(void)
5405: {
5406:   PetscFunctionBegin;
5407:   if (MatSeqAIJRegisterAllCalled) PetscFunctionReturn(PETSC_SUCCESS);
5408:   MatSeqAIJRegisterAllCalled = PETSC_TRUE;

5410:   PetscCall(MatSeqAIJRegister(MATSEQAIJCRL, MatConvert_SeqAIJ_SeqAIJCRL));
5411:   PetscCall(MatSeqAIJRegister(MATSEQAIJPERM, MatConvert_SeqAIJ_SeqAIJPERM));
5412:   PetscCall(MatSeqAIJRegister(MATSEQAIJSELL, MatConvert_SeqAIJ_SeqAIJSELL));
5413: #if PetscDefined(HAVE_MKL_SPARSE)
5414:   PetscCall(MatSeqAIJRegister(MATSEQAIJMKL, MatConvert_SeqAIJ_SeqAIJMKL));
5415: #endif
5416: #if PetscDefined(HAVE_CUDA)
5417:   PetscCall(MatSeqAIJRegister(MATSEQAIJCUSPARSE, MatConvert_SeqAIJ_SeqAIJCUSPARSE));
5418: #endif
5419: #if PetscDefined(HAVE_HIP)
5420:   PetscCall(MatSeqAIJRegister(MATSEQAIJHIPSPARSE, MatConvert_SeqAIJ_SeqAIJHIPSPARSE));
5421: #endif
5422: #if PetscDefined(HAVE_KOKKOS_KERNELS)
5423:   PetscCall(MatSeqAIJRegister(MATSEQAIJKOKKOS, MatConvert_SeqAIJ_SeqAIJKokkos));
5424: #endif
5425: #if PetscDefined(HAVE_VIENNACL) && PetscDefined(HAVE_VIENNACL_NO_CUDA)
5426:   PetscCall(MatSeqAIJRegister(MATMPIAIJVIENNACL, MatConvert_SeqAIJ_SeqAIJViennaCL));
5427: #endif
5428:   PetscFunctionReturn(PETSC_SUCCESS);
5429: }

5431: /*
5432:     Special version for direct calls from Fortran
5433: */
5434: #if PetscDefined(HAVE_FORTRAN_CAPS)
5435:   #define matsetvaluesseqaij_ MATSETVALUESSEQAIJ
5436: #elif !PetscDefined(HAVE_FORTRAN_UNDERSCORE)
5437:   #define matsetvaluesseqaij_ matsetvaluesseqaij
5438: #endif

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

5442: /* Change these macros so can be used in void function */
5443: /* Identical to PetscCallVoid, except it assigns to *_ierr */
5444: #undef PetscCall
5445: #define PetscCall(...) \
5446:   do { \
5447:     PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
5448:     if (PetscUnlikely(ierr_msv_mpiaij)) { \
5449:       *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
5450:       return; \
5451:     } \
5452:   } while (0)

5454: #undef SETERRQ
5455: #define SETERRQ(comm, ierr, ...) \
5456:   do { \
5457:     *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
5458:     return; \
5459:   } while (0)

5461: PETSC_EXTERN void matsetvaluesseqaij_(Mat *AA, PetscInt *mm, const PetscInt im[], PetscInt *nn, const PetscInt in[], const PetscScalar v[], InsertMode *isis, PetscErrorCode *_ierr)
5462: {
5463:   Mat         A = *AA;
5464:   PetscInt    m = *mm, n = *nn;
5465:   InsertMode  is = *isis;
5466:   Mat_SeqAIJ *a  = (Mat_SeqAIJ *)A->data;
5467:   PetscInt   *rp, k, low, high, t, ii, row, nrow, i, col, l, rmax, N;
5468:   PetscInt   *imax, *ai, *ailen;
5469:   PetscInt   *aj, nonew = a->nonew, lastcol = -1;
5470:   MatScalar  *ap, value, *aa;
5471:   PetscBool   ignorezeroentries = a->ignorezeroentries;
5472:   PetscBool   roworiented       = a->roworiented;

5474:   PetscFunctionBegin;
5475:   MatCheckPreallocated(A, 1);
5476:   imax  = a->imax;
5477:   ai    = a->i;
5478:   ailen = a->ilen;
5479:   aj    = a->j;
5480:   aa    = a->a;

5482:   for (k = 0; k < m; k++) { /* loop over added rows */
5483:     row = im[k];
5484:     if (row < 0) continue;
5485:     PetscCheck(row < A->rmap->n, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Row too large");
5486:     rp   = aj + ai[row];
5487:     ap   = aa + ai[row];
5488:     rmax = imax[row];
5489:     nrow = ailen[row];
5490:     low  = 0;
5491:     high = nrow;
5492:     for (l = 0; l < n; l++) { /* loop over added columns */
5493:       if (in[l] < 0) continue;
5494:       PetscCheck(in[l] < A->cmap->n, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Column too large");
5495:       col = in[l];
5496:       if (roworiented) value = v[l + k * n];
5497:       else value = v[k + l * m];

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

5501:       if (col <= lastcol) low = 0;
5502:       else high = nrow;
5503:       lastcol = col;
5504:       while (high - low > 5) {
5505:         t = (low + high) / 2;
5506:         if (rp[t] > col) high = t;
5507:         else low = t;
5508:       }
5509:       for (i = low; i < high; i++) {
5510:         if (rp[i] > col) break;
5511:         if (rp[i] == col) {
5512:           if (is == ADD_VALUES) ap[i] += value;
5513:           else ap[i] = value;
5514:           goto noinsert;
5515:         }
5516:       }
5517:       if (value == 0.0 && ignorezeroentries) goto noinsert;
5518:       if (nonew == 1) goto noinsert;
5519:       PetscCheck(nonew != -1, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero in the matrix");
5520:       MatSeqXAIJReallocateAIJ(A, A->rmap->n, 1, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
5521:       N = nrow++ - 1;
5522:       a->nz++;
5523:       high++;
5524:       /* shift up all the later entries in this row */
5525:       for (ii = N; ii >= i; ii--) {
5526:         rp[ii + 1] = rp[ii];
5527:         ap[ii + 1] = ap[ii];
5528:       }
5529:       rp[i] = col;
5530:       ap[i] = value;
5531:     noinsert:;
5532:       low = i + 1;
5533:     }
5534:     ailen[row] = nrow;
5535:   }
5536:   PetscFunctionReturnVoid();
5537: }
5538: /* Undefining these here since they were redefined from their original definition above! No
5539:  * other PETSc functions should be defined past this point, as it is impossible to recover the
5540:  * original definitions */
5541: #undef PetscCall
5542: #undef SETERRQ