xref: /petsc/src/mat/impls/aij/seq/aij.c (revision 623b4cf32a4d9ee5e9da0c76cfd89db17cbd9c1f)
1 /*
2     Defines the basic matrix operations for the AIJ (compressed row)
3   matrix storage format.
4 */
5 
6 #include <../src/mat/impls/aij/seq/aij.h> /*I "petscmat.h" I*/
7 #include <petscblaslapack.h>
8 #include <petscbt.h>
9 #include <petsc/private/kernels/blocktranspose.h>
10 
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
18 
19 static PetscErrorCode MatSeqAIJSetTypeFromOptions(Mat A)
20 {
21   PetscBool flg;
22   char      type[256];
23 
24   PetscFunctionBegin;
25   PetscObjectOptionsBegin((PetscObject)A);
26   PetscCall(PetscOptionsFList("-mat_seqaij_type", "Matrix SeqAIJ type", "MatSeqAIJSetType", MatSeqAIJList, "seqaij", type, 256, &flg));
27   if (flg) PetscCall(MatSeqAIJSetType(A, type));
28   PetscOptionsEnd();
29   PetscFunctionReturn(PETSC_SUCCESS);
30 }
31 
32 static PetscErrorCode MatGetColumnReductions_SeqAIJ(Mat A, PetscInt type, PetscReal *reductions)
33 {
34   PetscInt    i, m, n;
35   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
36 
37   PetscFunctionBegin;
38   PetscCall(MatGetSize(A, &m, &n));
39   PetscCall(PetscArrayzero(reductions, n));
40   if (type == NORM_2) {
41     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscAbsScalar(aij->a[i] * aij->a[i]);
42   } else if (type == NORM_1) {
43     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscAbsScalar(aij->a[i]);
44   } else if (type == NORM_INFINITY) {
45     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] = PetscMax(PetscAbsScalar(aij->a[i]), reductions[aij->j[i]]);
46   } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
47     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscRealPart(aij->a[i]);
48   } else if (type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART) {
49     for (i = 0; i < aij->i[m]; i++) reductions[aij->j[i]] += PetscImaginaryPart(aij->a[i]);
50   } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");
51 
52   if (type == NORM_2) {
53     for (i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
54   } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
55     for (i = 0; i < n; i++) reductions[i] /= m;
56   }
57   PetscFunctionReturn(PETSC_SUCCESS);
58 }
59 
60 static PetscErrorCode MatFindOffBlockDiagonalEntries_SeqAIJ(Mat A, IS *is)
61 {
62   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
63   PetscInt        i, m = A->rmap->n, cnt = 0, bs = A->rmap->bs;
64   const PetscInt *jj = a->j, *ii = a->i;
65   PetscInt       *rows;
66 
67   PetscFunctionBegin;
68   for (i = 0; i < m; i++) {
69     if ((ii[i] != ii[i + 1]) && ((jj[ii[i]] < bs * (i / bs)) || (jj[ii[i + 1] - 1] > bs * ((i + bs) / bs) - 1))) cnt++;
70   }
71   PetscCall(PetscMalloc1(cnt, &rows));
72   cnt = 0;
73   for (i = 0; i < m; i++) {
74     if ((ii[i] != ii[i + 1]) && ((jj[ii[i]] < bs * (i / bs)) || (jj[ii[i + 1] - 1] > bs * ((i + bs) / bs) - 1))) {
75       rows[cnt] = i;
76       cnt++;
77     }
78   }
79   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, cnt, rows, PETSC_OWN_POINTER, is));
80   PetscFunctionReturn(PETSC_SUCCESS);
81 }
82 
83 PetscErrorCode MatFindZeroDiagonals_SeqAIJ_Private(Mat A, PetscInt *nrows, PetscInt **zrows)
84 {
85   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
86   const MatScalar *aa;
87   PetscInt         i, m = A->rmap->n, cnt = 0;
88   const PetscInt  *ii = a->i, *jj = a->j, *diag;
89   PetscInt        *rows;
90 
91   PetscFunctionBegin;
92   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
93   PetscCall(MatMarkDiagonal_SeqAIJ(A));
94   diag = a->diag;
95   for (i = 0; i < m; i++) {
96     if ((diag[i] >= ii[i + 1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) cnt++;
97   }
98   PetscCall(PetscMalloc1(cnt, &rows));
99   cnt = 0;
100   for (i = 0; i < m; i++) {
101     if ((diag[i] >= ii[i + 1]) || (jj[diag[i]] != i) || (aa[diag[i]] == 0.0)) rows[cnt++] = i;
102   }
103   *nrows = cnt;
104   *zrows = rows;
105   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
106   PetscFunctionReturn(PETSC_SUCCESS);
107 }
108 
109 static PetscErrorCode MatFindZeroDiagonals_SeqAIJ(Mat A, IS *zrows)
110 {
111   PetscInt nrows, *rows;
112 
113   PetscFunctionBegin;
114   *zrows = NULL;
115   PetscCall(MatFindZeroDiagonals_SeqAIJ_Private(A, &nrows, &rows));
116   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)A), nrows, rows, PETSC_OWN_POINTER, zrows));
117   PetscFunctionReturn(PETSC_SUCCESS);
118 }
119 
120 static PetscErrorCode MatFindNonzeroRows_SeqAIJ(Mat A, IS *keptrows)
121 {
122   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
123   const MatScalar *aa;
124   PetscInt         m = A->rmap->n, cnt = 0;
125   const PetscInt  *ii;
126   PetscInt         n, i, j, *rows;
127 
128   PetscFunctionBegin;
129   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
130   *keptrows = NULL;
131   ii        = a->i;
132   for (i = 0; i < m; i++) {
133     n = ii[i + 1] - ii[i];
134     if (!n) {
135       cnt++;
136       goto ok1;
137     }
138     for (j = ii[i]; j < ii[i + 1]; j++) {
139       if (aa[j] != 0.0) goto ok1;
140     }
141     cnt++;
142   ok1:;
143   }
144   if (!cnt) {
145     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
146     PetscFunctionReturn(PETSC_SUCCESS);
147   }
148   PetscCall(PetscMalloc1(A->rmap->n - cnt, &rows));
149   cnt = 0;
150   for (i = 0; i < m; i++) {
151     n = ii[i + 1] - ii[i];
152     if (!n) continue;
153     for (j = ii[i]; j < ii[i + 1]; j++) {
154       if (aa[j] != 0.0) {
155         rows[cnt++] = i;
156         break;
157       }
158     }
159   }
160   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
161   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, cnt, rows, PETSC_OWN_POINTER, keptrows));
162   PetscFunctionReturn(PETSC_SUCCESS);
163 }
164 
165 PetscErrorCode MatDiagonalSet_SeqAIJ(Mat Y, Vec D, InsertMode is)
166 {
167   Mat_SeqAIJ        *aij = (Mat_SeqAIJ *)Y->data;
168   PetscInt           i, m = Y->rmap->n;
169   const PetscInt    *diag;
170   MatScalar         *aa;
171   const PetscScalar *v;
172   PetscBool          missing;
173 
174   PetscFunctionBegin;
175   if (Y->assembled) {
176     PetscCall(MatMissingDiagonal_SeqAIJ(Y, &missing, NULL));
177     if (!missing) {
178       diag = aij->diag;
179       PetscCall(VecGetArrayRead(D, &v));
180       PetscCall(MatSeqAIJGetArray(Y, &aa));
181       if (is == INSERT_VALUES) {
182         for (i = 0; i < m; i++) aa[diag[i]] = v[i];
183       } else {
184         for (i = 0; i < m; i++) aa[diag[i]] += v[i];
185       }
186       PetscCall(MatSeqAIJRestoreArray(Y, &aa));
187       PetscCall(VecRestoreArrayRead(D, &v));
188       PetscFunctionReturn(PETSC_SUCCESS);
189     }
190     PetscCall(MatSeqAIJInvalidateDiagonal(Y));
191   }
192   PetscCall(MatDiagonalSet_Default(Y, D, is));
193   PetscFunctionReturn(PETSC_SUCCESS);
194 }
195 
196 PetscErrorCode MatGetRowIJ_SeqAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *m, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
197 {
198   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
199   PetscInt    i, ishift;
200 
201   PetscFunctionBegin;
202   if (m) *m = A->rmap->n;
203   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);
204   ishift = 0;
205   if (symmetric && A->structurally_symmetric != PETSC_BOOL3_TRUE) {
206     PetscCall(MatToSymmetricIJ_SeqAIJ(A->rmap->n, a->i, a->j, PETSC_TRUE, ishift, oshift, (PetscInt **)ia, (PetscInt **)ja));
207   } else if (oshift == 1) {
208     PetscInt *tia;
209     PetscInt  nz = a->i[A->rmap->n];
210     /* malloc space and  add 1 to i and j indices */
211     PetscCall(PetscMalloc1(A->rmap->n + 1, &tia));
212     for (i = 0; i < A->rmap->n + 1; i++) tia[i] = a->i[i] + 1;
213     *ia = tia;
214     if (ja) {
215       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 }
226 
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 }
237 
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;
243 
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++;
263 
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 }
273 
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);
278 
279   PetscCall(PetscFree(*ia));
280   PetscCall(PetscFree(*ja));
281   PetscFunctionReturn(PETSC_SUCCESS);
282 }
283 
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;
296 
297   PetscFunctionBegin;
298   *nn = n;
299   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);
300 
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 }
326 
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 }
334 
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;
340 
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 }
347 
348 /*
349     MatSeqAIJSetValuesLocalFast - An optimized version of MatSetValuesLocal() for SeqAIJ matrices with several assumptions
350 
351       -   a single row of values is set with each call
352       -   no row or column indices are negative or (in error) larger than the number of rows or columns
353       -   the values are always added to the matrix, not set
354       -   no new locations are introduced in the nonzero structure of the matrix
355 
356      This does NOT assume the global column indices are sorted
357 
358 */
359 
360 #include <petsc/private/isimpl.h>
361 PetscErrorCode MatSeqAIJSetValuesLocalFast(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
362 {
363   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
364   PetscInt        low, high, t, row, nrow, i, col, l;
365   const PetscInt *rp, *ai = a->i, *ailen = a->ilen, *aj = a->j;
366   PetscInt        lastcol = -1;
367   MatScalar      *ap, value, *aa;
368   const PetscInt *ridx = A->rmap->mapping->indices, *cidx = A->cmap->mapping->indices;
369 
370   PetscFunctionBegin;
371   PetscCall(MatSeqAIJGetArray(A, &aa));
372   row  = ridx[im[0]];
373   rp   = aj + ai[row];
374   ap   = aa + ai[row];
375   nrow = ailen[row];
376   low  = 0;
377   high = nrow;
378   for (l = 0; l < n; l++) { /* loop over added columns */
379     col   = cidx[in[l]];
380     value = v[l];
381 
382     if (col <= lastcol) low = 0;
383     else high = nrow;
384     lastcol = col;
385     while (high - low > 5) {
386       t = (low + high) / 2;
387       if (rp[t] > col) high = t;
388       else low = t;
389     }
390     for (i = low; i < high; i++) {
391       if (rp[i] == col) {
392         ap[i] += value;
393         low = i + 1;
394         break;
395       }
396     }
397   }
398   PetscCall(MatSeqAIJRestoreArray(A, &aa));
399   return PETSC_SUCCESS;
400 }
401 
402 PetscErrorCode MatSetValues_SeqAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
403 {
404   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
405   PetscInt   *rp, k, low, high, t, ii, row, nrow, i, col, l, rmax, N;
406   PetscInt   *imax = a->imax, *ai = a->i, *ailen = a->ilen;
407   PetscInt   *aj = a->j, nonew = a->nonew, lastcol = -1;
408   MatScalar  *ap = NULL, value = 0.0, *aa;
409   PetscBool   ignorezeroentries = a->ignorezeroentries;
410   PetscBool   roworiented       = a->roworiented;
411 
412   PetscFunctionBegin;
413   PetscCall(MatSeqAIJGetArray(A, &aa));
414   for (k = 0; k < m; k++) { /* loop over added rows */
415     row = im[k];
416     if (row < 0) continue;
417     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);
418     rp = PetscSafePointerPlusOffset(aj, ai[row]);
419     if (!A->structure_only) ap = PetscSafePointerPlusOffset(aa, ai[row]);
420     rmax = imax[row];
421     nrow = ailen[row];
422     low  = 0;
423     high = nrow;
424     for (l = 0; l < n; l++) { /* loop over added columns */
425       if (in[l] < 0) continue;
426       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);
427       col = in[l];
428       if (v && !A->structure_only) value = roworiented ? v[l + k * n] : v[k + l * m];
429       if (!A->structure_only && value == 0.0 && ignorezeroentries && is == ADD_VALUES && row != col) continue;
430 
431       if (col <= lastcol) low = 0;
432       else high = nrow;
433       lastcol = col;
434       while (high - low > 5) {
435         t = (low + high) / 2;
436         if (rp[t] > col) high = t;
437         else low = t;
438       }
439       for (i = low; i < high; i++) {
440         if (rp[i] > col) break;
441         if (rp[i] == col) {
442           if (!A->structure_only) {
443             if (is == ADD_VALUES) {
444               ap[i] += value;
445               (void)PetscLogFlops(1.0);
446             } else ap[i] = value;
447           }
448           low = i + 1;
449           goto noinsert;
450         }
451       }
452       if (value == 0.0 && ignorezeroentries && row != col) goto noinsert;
453       if (nonew == 1) goto noinsert;
454       PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero at (%" PetscInt_FMT ",%" PetscInt_FMT ") in the matrix", row, col);
455       if (A->structure_only) {
456         MatSeqXAIJReallocateAIJ_structure_only(A, A->rmap->n, 1, nrow, row, col, rmax, ai, aj, rp, imax, nonew, MatScalar);
457       } else {
458         MatSeqXAIJReallocateAIJ(A, A->rmap->n, 1, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
459       }
460       N = nrow++ - 1;
461       a->nz++;
462       high++;
463       /* shift up all the later entries in this row */
464       PetscCall(PetscArraymove(rp + i + 1, rp + i, N - i + 1));
465       rp[i] = col;
466       if (!A->structure_only) {
467         PetscCall(PetscArraymove(ap + i + 1, ap + i, N - i + 1));
468         ap[i] = value;
469       }
470       low = i + 1;
471       A->nonzerostate++;
472     noinsert:;
473     }
474     ailen[row] = nrow;
475   }
476   PetscCall(MatSeqAIJRestoreArray(A, &aa));
477   PetscFunctionReturn(PETSC_SUCCESS);
478 }
479 
480 static PetscErrorCode MatSetValues_SeqAIJ_SortedFullNoPreallocation(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
481 {
482   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
483   PetscInt   *rp, k, row;
484   PetscInt   *ai = a->i;
485   PetscInt   *aj = a->j;
486   MatScalar  *aa, *ap;
487 
488   PetscFunctionBegin;
489   PetscCheck(!A->was_assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot call on assembled matrix.");
490   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);
491 
492   PetscCall(MatSeqAIJGetArray(A, &aa));
493   for (k = 0; k < m; k++) { /* loop over added rows */
494     row = im[k];
495     rp  = aj + ai[row];
496     ap  = PetscSafePointerPlusOffset(aa, ai[row]);
497 
498     PetscCall(PetscMemcpy(rp, in, n * sizeof(PetscInt)));
499     if (!A->structure_only) {
500       if (v) {
501         PetscCall(PetscMemcpy(ap, v, n * sizeof(PetscScalar)));
502         v += n;
503       } else {
504         PetscCall(PetscMemzero(ap, n * sizeof(PetscScalar)));
505       }
506     }
507     a->ilen[row]  = n;
508     a->imax[row]  = n;
509     a->i[row + 1] = a->i[row] + n;
510     a->nz += n;
511   }
512   PetscCall(MatSeqAIJRestoreArray(A, &aa));
513   PetscFunctionReturn(PETSC_SUCCESS);
514 }
515 
516 /*@
517   MatSeqAIJSetTotalPreallocation - Sets an upper bound on the total number of expected nonzeros in the matrix.
518 
519   Input Parameters:
520 + A       - the `MATSEQAIJ` matrix
521 - nztotal - bound on the number of nonzeros
522 
523   Level: advanced
524 
525   Notes:
526   This can be called if you will be provided the matrix row by row (from row zero) with sorted column indices for each row.
527   Simply call `MatSetValues()` after this call to provide the matrix entries in the usual manner. This matrix may be used
528   as always with multiple matrix assemblies.
529 
530 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MAT_SORTED_FULL`, `MatSetValues()`, `MatSeqAIJSetPreallocation()`
531 @*/
532 PetscErrorCode MatSeqAIJSetTotalPreallocation(Mat A, PetscInt nztotal)
533 {
534   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
535 
536   PetscFunctionBegin;
537   PetscCall(PetscLayoutSetUp(A->rmap));
538   PetscCall(PetscLayoutSetUp(A->cmap));
539   a->maxnz = nztotal;
540   if (!a->imax) { PetscCall(PetscMalloc1(A->rmap->n, &a->imax)); }
541   if (!a->ilen) {
542     PetscCall(PetscMalloc1(A->rmap->n, &a->ilen));
543   } else {
544     PetscCall(PetscMemzero(a->ilen, A->rmap->n * sizeof(PetscInt)));
545   }
546 
547   /* allocate the matrix space */
548   if (A->structure_only) {
549     PetscCall(PetscMalloc1(nztotal, &a->j));
550     PetscCall(PetscMalloc1(A->rmap->n + 1, &a->i));
551   } else {
552     PetscCall(PetscMalloc3(nztotal, &a->a, nztotal, &a->j, A->rmap->n + 1, &a->i));
553   }
554   a->i[0] = 0;
555   if (A->structure_only) {
556     a->singlemalloc = PETSC_FALSE;
557     a->free_a       = PETSC_FALSE;
558   } else {
559     a->singlemalloc = PETSC_TRUE;
560     a->free_a       = PETSC_TRUE;
561   }
562   a->free_ij        = PETSC_TRUE;
563   A->ops->setvalues = MatSetValues_SeqAIJ_SortedFullNoPreallocation;
564   A->preallocated   = PETSC_TRUE;
565   PetscFunctionReturn(PETSC_SUCCESS);
566 }
567 
568 static PetscErrorCode MatSetValues_SeqAIJ_SortedFull(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
569 {
570   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
571   PetscInt   *rp, k, row;
572   PetscInt   *ai = a->i, *ailen = a->ilen;
573   PetscInt   *aj = a->j;
574   MatScalar  *aa, *ap;
575 
576   PetscFunctionBegin;
577   PetscCall(MatSeqAIJGetArray(A, &aa));
578   for (k = 0; k < m; k++) { /* loop over added rows */
579     row = im[k];
580     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);
581     rp = aj + ai[row];
582     ap = aa + ai[row];
583     if (!A->was_assembled) PetscCall(PetscMemcpy(rp, in, n * sizeof(PetscInt)));
584     if (!A->structure_only) {
585       if (v) {
586         PetscCall(PetscMemcpy(ap, v, n * sizeof(PetscScalar)));
587         v += n;
588       } else {
589         PetscCall(PetscMemzero(ap, n * sizeof(PetscScalar)));
590       }
591     }
592     ailen[row] = n;
593     a->nz += n;
594   }
595   PetscCall(MatSeqAIJRestoreArray(A, &aa));
596   PetscFunctionReturn(PETSC_SUCCESS);
597 }
598 
599 static PetscErrorCode MatGetValues_SeqAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], PetscScalar v[])
600 {
601   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
602   PetscInt        *rp, k, low, high, t, row, nrow, i, col, l, *aj = a->j;
603   PetscInt        *ai = a->i, *ailen = a->ilen;
604   const MatScalar *ap, *aa;
605 
606   PetscFunctionBegin;
607   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
608   for (k = 0; k < m; k++) { /* loop over rows */
609     row = im[k];
610     if (row < 0) {
611       v += n;
612       continue;
613     } /* negative row */
614     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);
615     rp   = PetscSafePointerPlusOffset(aj, ai[row]);
616     ap   = PetscSafePointerPlusOffset(aa, ai[row]);
617     nrow = ailen[row];
618     for (l = 0; l < n; l++) { /* loop over columns */
619       if (in[l] < 0) {
620         v++;
621         continue;
622       } /* negative column */
623       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);
624       col  = in[l];
625       high = nrow;
626       low  = 0; /* assume unsorted */
627       while (high - low > 5) {
628         t = (low + high) / 2;
629         if (rp[t] > col) high = t;
630         else low = t;
631       }
632       for (i = low; i < high; i++) {
633         if (rp[i] > col) break;
634         if (rp[i] == col) {
635           *v++ = ap[i];
636           goto finished;
637         }
638       }
639       *v++ = 0.0;
640     finished:;
641     }
642   }
643   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
644   PetscFunctionReturn(PETSC_SUCCESS);
645 }
646 
647 static PetscErrorCode MatView_SeqAIJ_Binary(Mat mat, PetscViewer viewer)
648 {
649   Mat_SeqAIJ        *A = (Mat_SeqAIJ *)mat->data;
650   const PetscScalar *av;
651   PetscInt           header[4], M, N, m, nz, i;
652   PetscInt          *rowlens;
653 
654   PetscFunctionBegin;
655   PetscCall(PetscViewerSetUp(viewer));
656 
657   M  = mat->rmap->N;
658   N  = mat->cmap->N;
659   m  = mat->rmap->n;
660   nz = A->nz;
661 
662   /* write matrix header */
663   header[0] = MAT_FILE_CLASSID;
664   header[1] = M;
665   header[2] = N;
666   header[3] = nz;
667   PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));
668 
669   /* fill in and store row lengths */
670   PetscCall(PetscMalloc1(m, &rowlens));
671   for (i = 0; i < m; i++) rowlens[i] = A->i[i + 1] - A->i[i];
672   PetscCall(PetscViewerBinaryWrite(viewer, rowlens, m, PETSC_INT));
673   PetscCall(PetscFree(rowlens));
674   /* store column indices */
675   PetscCall(PetscViewerBinaryWrite(viewer, A->j, nz, PETSC_INT));
676   /* store nonzero values */
677   PetscCall(MatSeqAIJGetArrayRead(mat, &av));
678   PetscCall(PetscViewerBinaryWrite(viewer, av, nz, PETSC_SCALAR));
679   PetscCall(MatSeqAIJRestoreArrayRead(mat, &av));
680 
681   /* write block size option to the viewer's .info file */
682   PetscCall(MatView_Binary_BlockSizes(mat, viewer));
683   PetscFunctionReturn(PETSC_SUCCESS);
684 }
685 
686 static PetscErrorCode MatView_SeqAIJ_ASCII_structonly(Mat A, PetscViewer viewer)
687 {
688   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
689   PetscInt    i, k, m = A->rmap->N;
690 
691   PetscFunctionBegin;
692   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
693   for (i = 0; i < m; i++) {
694     PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
695     for (k = a->i[i]; k < a->i[i + 1]; k++) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ") ", a->j[k]));
696     PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
697   }
698   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
699   PetscFunctionReturn(PETSC_SUCCESS);
700 }
701 
702 extern PetscErrorCode MatSeqAIJFactorInfo_Matlab(Mat, PetscViewer);
703 
704 static PetscErrorCode MatView_SeqAIJ_ASCII(Mat A, PetscViewer viewer)
705 {
706   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
707   const PetscScalar *av;
708   PetscInt           i, j, m = A->rmap->n;
709   const char        *name;
710   PetscViewerFormat  format;
711 
712   PetscFunctionBegin;
713   if (A->structure_only) {
714     PetscCall(MatView_SeqAIJ_ASCII_structonly(A, viewer));
715     PetscFunctionReturn(PETSC_SUCCESS);
716   }
717 
718   PetscCall(PetscViewerGetFormat(viewer, &format));
719   if (format == PETSC_VIEWER_ASCII_FACTOR_INFO || format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscFunctionReturn(PETSC_SUCCESS);
720 
721   /* trigger copy to CPU if needed */
722   PetscCall(MatSeqAIJGetArrayRead(A, &av));
723   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
724   if (format == PETSC_VIEWER_ASCII_MATLAB) {
725     PetscInt nofinalvalue = 0;
726     if (m && ((a->i[m] == a->i[m - 1]) || (a->j[a->nz - 1] != A->cmap->n - 1))) {
727       /* Need a dummy value to ensure the dimension of the matrix. */
728       nofinalvalue = 1;
729     }
730     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
731     PetscCall(PetscViewerASCIIPrintf(viewer, "%% Size = %" PetscInt_FMT " %" PetscInt_FMT " \n", m, A->cmap->n));
732     PetscCall(PetscViewerASCIIPrintf(viewer, "%% Nonzeros = %" PetscInt_FMT " \n", a->nz));
733 #if defined(PETSC_USE_COMPLEX)
734     PetscCall(PetscViewerASCIIPrintf(viewer, "zzz = zeros(%" PetscInt_FMT ",4);\n", a->nz + nofinalvalue));
735 #else
736     PetscCall(PetscViewerASCIIPrintf(viewer, "zzz = zeros(%" PetscInt_FMT ",3);\n", a->nz + nofinalvalue));
737 #endif
738     PetscCall(PetscViewerASCIIPrintf(viewer, "zzz = [\n"));
739 
740     for (i = 0; i < m; i++) {
741       for (j = a->i[i]; j < a->i[i + 1]; j++) {
742 #if defined(PETSC_USE_COMPLEX)
743         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])));
744 #else
745         PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e\n", i + 1, a->j[j] + 1, (double)a->a[j]));
746 #endif
747       }
748     }
749     if (nofinalvalue) {
750 #if defined(PETSC_USE_COMPLEX)
751       PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e %18.16e\n", m, A->cmap->n, 0., 0.));
752 #else
753       PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "  %18.16e\n", m, A->cmap->n, 0.0));
754 #endif
755     }
756     PetscCall(PetscObjectGetName((PetscObject)A, &name));
757     PetscCall(PetscViewerASCIIPrintf(viewer, "];\n %s = spconvert(zzz);\n", name));
758     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
759   } else if (format == PETSC_VIEWER_ASCII_COMMON) {
760     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
761     for (i = 0; i < m; i++) {
762       PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
763       for (j = a->i[i]; j < a->i[i + 1]; j++) {
764 #if defined(PETSC_USE_COMPLEX)
765         if (PetscImaginaryPart(a->a[j]) > 0.0 && PetscRealPart(a->a[j]) != 0.0) {
766           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
767         } else if (PetscImaginaryPart(a->a[j]) < 0.0 && PetscRealPart(a->a[j]) != 0.0) {
768           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)-PetscImaginaryPart(a->a[j])));
769         } else if (PetscRealPart(a->a[j]) != 0.0) {
770           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
771         }
772 #else
773         if (a->a[j] != 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]));
774 #endif
775       }
776       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
777     }
778     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
779   } else if (format == PETSC_VIEWER_ASCII_SYMMODU) {
780     PetscInt nzd = 0, fshift = 1, *sptr;
781     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
782     PetscCall(PetscMalloc1(m + 1, &sptr));
783     for (i = 0; i < m; i++) {
784       sptr[i] = nzd + 1;
785       for (j = a->i[i]; j < a->i[i + 1]; j++) {
786         if (a->j[j] >= i) {
787 #if defined(PETSC_USE_COMPLEX)
788           if (PetscImaginaryPart(a->a[j]) != 0.0 || PetscRealPart(a->a[j]) != 0.0) nzd++;
789 #else
790           if (a->a[j] != 0.0) nzd++;
791 #endif
792         }
793       }
794     }
795     sptr[m] = nzd + 1;
796     PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT "\n\n", m, nzd));
797     for (i = 0; i < m + 1; i += 6) {
798       if (i + 4 < m) {
799         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]));
800       } else if (i + 3 < m) {
801         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]));
802       } else if (i + 2 < m) {
803         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2], sptr[i + 3]));
804       } else if (i + 1 < m) {
805         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1], sptr[i + 2]));
806       } else if (i < m) {
807         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " %" PetscInt_FMT "\n", sptr[i], sptr[i + 1]));
808       } else {
809         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT "\n", sptr[i]));
810       }
811     }
812     PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
813     PetscCall(PetscFree(sptr));
814     for (i = 0; i < m; i++) {
815       for (j = a->i[i]; j < a->i[i + 1]; j++) {
816         if (a->j[j] >= i) PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT " ", a->j[j] + fshift));
817       }
818       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
819     }
820     PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
821     for (i = 0; i < m; i++) {
822       for (j = a->i[i]; j < a->i[i + 1]; j++) {
823         if (a->j[j] >= i) {
824 #if defined(PETSC_USE_COMPLEX)
825           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])));
826 #else
827           if (a->a[j] != 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " %18.16e ", (double)a->a[j]));
828 #endif
829         }
830       }
831       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
832     }
833     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
834   } else if (format == PETSC_VIEWER_ASCII_DENSE) {
835     PetscInt    cnt = 0, jcnt;
836     PetscScalar value;
837 #if defined(PETSC_USE_COMPLEX)
838     PetscBool realonly = PETSC_TRUE;
839 
840     for (i = 0; i < a->i[m]; i++) {
841       if (PetscImaginaryPart(a->a[i]) != 0.0) {
842         realonly = PETSC_FALSE;
843         break;
844       }
845     }
846 #endif
847 
848     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
849     for (i = 0; i < m; i++) {
850       jcnt = 0;
851       for (j = 0; j < A->cmap->n; j++) {
852         if (jcnt < a->i[i + 1] - a->i[i] && j == a->j[cnt]) {
853           value = a->a[cnt++];
854           jcnt++;
855         } else {
856           value = 0.0;
857         }
858 #if defined(PETSC_USE_COMPLEX)
859         if (realonly) {
860           PetscCall(PetscViewerASCIIPrintf(viewer, " %7.5e ", (double)PetscRealPart(value)));
861         } else {
862           PetscCall(PetscViewerASCIIPrintf(viewer, " %7.5e+%7.5e i ", (double)PetscRealPart(value), (double)PetscImaginaryPart(value)));
863         }
864 #else
865         PetscCall(PetscViewerASCIIPrintf(viewer, " %7.5e ", (double)value));
866 #endif
867       }
868       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
869     }
870     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
871   } else if (format == PETSC_VIEWER_ASCII_MATRIXMARKET) {
872     PetscInt fshift = 1;
873     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
874 #if defined(PETSC_USE_COMPLEX)
875     PetscCall(PetscViewerASCIIPrintf(viewer, "%%%%MatrixMarket matrix coordinate complex general\n"));
876 #else
877     PetscCall(PetscViewerASCIIPrintf(viewer, "%%%%MatrixMarket matrix coordinate real general\n"));
878 #endif
879     PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", m, A->cmap->n, a->nz));
880     for (i = 0; i < m; i++) {
881       for (j = a->i[i]; j < a->i[i + 1]; j++) {
882 #if defined(PETSC_USE_COMPLEX)
883         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])));
884 #else
885         PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT " %g\n", i + fshift, a->j[j] + fshift, (double)a->a[j]));
886 #endif
887       }
888     }
889     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
890   } else {
891     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
892     if (A->factortype) {
893       for (i = 0; i < m; i++) {
894         PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
895         /* L part */
896         for (j = a->i[i]; j < a->i[i + 1]; j++) {
897 #if defined(PETSC_USE_COMPLEX)
898           if (PetscImaginaryPart(a->a[j]) > 0.0) {
899             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
900           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
901             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)(-PetscImaginaryPart(a->a[j]))));
902           } else {
903             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
904           }
905 #else
906           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]));
907 #endif
908         }
909         /* diagonal */
910         j = a->diag[i];
911 #if defined(PETSC_USE_COMPLEX)
912         if (PetscImaginaryPart(a->a[j]) > 0.0) {
913           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(1.0 / a->a[j]), (double)PetscImaginaryPart(1.0 / a->a[j])));
914         } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
915           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(1.0 / a->a[j]), (double)(-PetscImaginaryPart(1.0 / a->a[j]))));
916         } else {
917           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(1.0 / a->a[j])));
918         }
919 #else
920         PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)(1.0 / a->a[j])));
921 #endif
922 
923         /* U part */
924         for (j = a->diag[i + 1] + 1; j < a->diag[i]; j++) {
925 #if defined(PETSC_USE_COMPLEX)
926           if (PetscImaginaryPart(a->a[j]) > 0.0) {
927             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
928           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
929             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)(-PetscImaginaryPart(a->a[j]))));
930           } else {
931             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
932           }
933 #else
934           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]));
935 #endif
936         }
937         PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
938       }
939     } else {
940       for (i = 0; i < m; i++) {
941         PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
942         for (j = a->i[i]; j < a->i[i + 1]; j++) {
943 #if defined(PETSC_USE_COMPLEX)
944           if (PetscImaginaryPart(a->a[j]) > 0.0) {
945             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)PetscImaginaryPart(a->a[j])));
946           } else if (PetscImaginaryPart(a->a[j]) < 0.0) {
947             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i)", a->j[j], (double)PetscRealPart(a->a[j]), (double)-PetscImaginaryPart(a->a[j])));
948           } else {
949             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)PetscRealPart(a->a[j])));
950           }
951 #else
952           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[j], (double)a->a[j]));
953 #endif
954         }
955         PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
956       }
957     }
958     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
959   }
960   PetscCall(PetscViewerFlush(viewer));
961   PetscFunctionReturn(PETSC_SUCCESS);
962 }
963 
964 #include <petscdraw.h>
965 static PetscErrorCode MatView_SeqAIJ_Draw_Zoom(PetscDraw draw, void *Aa)
966 {
967   Mat                A = (Mat)Aa;
968   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
969   PetscInt           i, j, m = A->rmap->n;
970   int                color;
971   PetscReal          xl, yl, xr, yr, x_l, x_r, y_l, y_r;
972   PetscViewer        viewer;
973   PetscViewerFormat  format;
974   const PetscScalar *aa;
975 
976   PetscFunctionBegin;
977   PetscCall(PetscObjectQuery((PetscObject)A, "Zoomviewer", (PetscObject *)&viewer));
978   PetscCall(PetscViewerGetFormat(viewer, &format));
979   PetscCall(PetscDrawGetCoordinates(draw, &xl, &yl, &xr, &yr));
980 
981   /* loop over matrix elements drawing boxes */
982   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
983   if (format != PETSC_VIEWER_DRAW_CONTOUR) {
984     PetscDrawCollectiveBegin(draw);
985     /* Blue for negative, Cyan for zero and  Red for positive */
986     color = PETSC_DRAW_BLUE;
987     for (i = 0; i < m; i++) {
988       y_l = m - i - 1.0;
989       y_r = y_l + 1.0;
990       for (j = a->i[i]; j < a->i[i + 1]; j++) {
991         x_l = a->j[j];
992         x_r = x_l + 1.0;
993         if (PetscRealPart(aa[j]) >= 0.) continue;
994         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
995       }
996     }
997     color = PETSC_DRAW_CYAN;
998     for (i = 0; i < m; i++) {
999       y_l = m - i - 1.0;
1000       y_r = y_l + 1.0;
1001       for (j = a->i[i]; j < a->i[i + 1]; j++) {
1002         x_l = a->j[j];
1003         x_r = x_l + 1.0;
1004         if (aa[j] != 0.) continue;
1005         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
1006       }
1007     }
1008     color = PETSC_DRAW_RED;
1009     for (i = 0; i < m; i++) {
1010       y_l = m - i - 1.0;
1011       y_r = y_l + 1.0;
1012       for (j = a->i[i]; j < a->i[i + 1]; j++) {
1013         x_l = a->j[j];
1014         x_r = x_l + 1.0;
1015         if (PetscRealPart(aa[j]) <= 0.) continue;
1016         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
1017       }
1018     }
1019     PetscDrawCollectiveEnd(draw);
1020   } else {
1021     /* use contour shading to indicate magnitude of values */
1022     /* first determine max of all nonzero values */
1023     PetscReal minv = 0.0, maxv = 0.0;
1024     PetscInt  nz = a->nz, count = 0;
1025     PetscDraw popup;
1026 
1027     for (i = 0; i < nz; i++) {
1028       if (PetscAbsScalar(aa[i]) > maxv) maxv = PetscAbsScalar(aa[i]);
1029     }
1030     if (minv >= maxv) maxv = minv + PETSC_SMALL;
1031     PetscCall(PetscDrawGetPopup(draw, &popup));
1032     PetscCall(PetscDrawScalePopup(popup, minv, maxv));
1033 
1034     PetscDrawCollectiveBegin(draw);
1035     for (i = 0; i < m; i++) {
1036       y_l = m - i - 1.0;
1037       y_r = y_l + 1.0;
1038       for (j = a->i[i]; j < a->i[i + 1]; j++) {
1039         x_l   = a->j[j];
1040         x_r   = x_l + 1.0;
1041         color = PetscDrawRealToColor(PetscAbsScalar(aa[count]), minv, maxv);
1042         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
1043         count++;
1044       }
1045     }
1046     PetscDrawCollectiveEnd(draw);
1047   }
1048   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1049   PetscFunctionReturn(PETSC_SUCCESS);
1050 }
1051 
1052 #include <petscdraw.h>
1053 static PetscErrorCode MatView_SeqAIJ_Draw(Mat A, PetscViewer viewer)
1054 {
1055   PetscDraw draw;
1056   PetscReal xr, yr, xl, yl, h, w;
1057   PetscBool isnull;
1058 
1059   PetscFunctionBegin;
1060   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1061   PetscCall(PetscDrawIsNull(draw, &isnull));
1062   if (isnull) PetscFunctionReturn(PETSC_SUCCESS);
1063 
1064   xr = A->cmap->n;
1065   yr = A->rmap->n;
1066   h  = yr / 10.0;
1067   w  = xr / 10.0;
1068   xr += w;
1069   yr += h;
1070   xl = -w;
1071   yl = -h;
1072   PetscCall(PetscDrawSetCoordinates(draw, xl, yl, xr, yr));
1073   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", (PetscObject)viewer));
1074   PetscCall(PetscDrawZoom(draw, MatView_SeqAIJ_Draw_Zoom, A));
1075   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", NULL));
1076   PetscCall(PetscDrawSave(draw));
1077   PetscFunctionReturn(PETSC_SUCCESS);
1078 }
1079 
1080 PetscErrorCode MatView_SeqAIJ(Mat A, PetscViewer viewer)
1081 {
1082   PetscBool iascii, isbinary, isdraw;
1083 
1084   PetscFunctionBegin;
1085   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
1086   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1087   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1088   if (iascii) PetscCall(MatView_SeqAIJ_ASCII(A, viewer));
1089   else if (isbinary) PetscCall(MatView_SeqAIJ_Binary(A, viewer));
1090   else if (isdraw) PetscCall(MatView_SeqAIJ_Draw(A, viewer));
1091   PetscCall(MatView_SeqAIJ_Inode(A, viewer));
1092   PetscFunctionReturn(PETSC_SUCCESS);
1093 }
1094 
1095 PetscErrorCode MatAssemblyEnd_SeqAIJ(Mat A, MatAssemblyType mode)
1096 {
1097   Mat_SeqAIJ *a      = (Mat_SeqAIJ *)A->data;
1098   PetscInt    fshift = 0, i, *ai = a->i, *aj = a->j, *imax = a->imax;
1099   PetscInt    m = A->rmap->n, *ip, N, *ailen = a->ilen, rmax = 0, n;
1100   MatScalar  *aa    = a->a, *ap;
1101   PetscReal   ratio = 0.6;
1102 
1103   PetscFunctionBegin;
1104   if (mode == MAT_FLUSH_ASSEMBLY) PetscFunctionReturn(PETSC_SUCCESS);
1105   PetscCall(MatSeqAIJInvalidateDiagonal(A));
1106   if (A->was_assembled && A->ass_nonzerostate == A->nonzerostate) {
1107     /* we need to respect users asking to use or not the inodes routine in between matrix assemblies */
1108     PetscCall(MatAssemblyEnd_SeqAIJ_Inode(A, mode));
1109     PetscFunctionReturn(PETSC_SUCCESS);
1110   }
1111 
1112   if (m) rmax = ailen[0]; /* determine row with most nonzeros */
1113   for (i = 1; i < m; i++) {
1114     /* move each row back by the amount of empty slots (fshift) before it*/
1115     fshift += imax[i - 1] - ailen[i - 1];
1116     rmax = PetscMax(rmax, ailen[i]);
1117     if (fshift) {
1118       ip = aj + ai[i];
1119       ap = aa + ai[i];
1120       N  = ailen[i];
1121       PetscCall(PetscArraymove(ip - fshift, ip, N));
1122       if (!A->structure_only) PetscCall(PetscArraymove(ap - fshift, ap, N));
1123     }
1124     ai[i] = ai[i - 1] + ailen[i - 1];
1125   }
1126   if (m) {
1127     fshift += imax[m - 1] - ailen[m - 1];
1128     ai[m] = ai[m - 1] + ailen[m - 1];
1129   }
1130   /* reset ilen and imax for each row */
1131   a->nonzerorowcnt = 0;
1132   if (A->structure_only) {
1133     PetscCall(PetscFree(a->imax));
1134     PetscCall(PetscFree(a->ilen));
1135   } else { /* !A->structure_only */
1136     for (i = 0; i < m; i++) {
1137       ailen[i] = imax[i] = ai[i + 1] - ai[i];
1138       a->nonzerorowcnt += ((ai[i + 1] - ai[i]) > 0);
1139     }
1140   }
1141   a->nz = ai[m];
1142   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);
1143   PetscCall(MatMarkDiagonal_SeqAIJ(A)); // since diagonal info is used a lot, it is helpful to set them up at the end of assembly
1144   a->diagonaldense = PETSC_TRUE;
1145   n                = PetscMin(A->rmap->n, A->cmap->n);
1146   for (i = 0; i < n; i++) {
1147     if (a->diag[i] >= ai[i + 1]) {
1148       a->diagonaldense = PETSC_FALSE;
1149       break;
1150     }
1151   }
1152   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));
1153   PetscCall(PetscInfo(A, "Number of mallocs during MatSetValues() is %" PetscInt_FMT "\n", a->reallocs));
1154   PetscCall(PetscInfo(A, "Maximum nonzeros in any row is %" PetscInt_FMT "\n", rmax));
1155 
1156   A->info.mallocs += a->reallocs;
1157   a->reallocs         = 0;
1158   A->info.nz_unneeded = (PetscReal)fshift;
1159   a->rmax             = rmax;
1160 
1161   if (!A->structure_only) PetscCall(MatCheckCompressedRow(A, a->nonzerorowcnt, &a->compressedrow, a->i, m, ratio));
1162   PetscCall(MatAssemblyEnd_SeqAIJ_Inode(A, mode));
1163   PetscFunctionReturn(PETSC_SUCCESS);
1164 }
1165 
1166 static PetscErrorCode MatRealPart_SeqAIJ(Mat A)
1167 {
1168   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1169   PetscInt    i, nz = a->nz;
1170   MatScalar  *aa;
1171 
1172   PetscFunctionBegin;
1173   PetscCall(MatSeqAIJGetArray(A, &aa));
1174   for (i = 0; i < nz; i++) aa[i] = PetscRealPart(aa[i]);
1175   PetscCall(MatSeqAIJRestoreArray(A, &aa));
1176   PetscCall(MatSeqAIJInvalidateDiagonal(A));
1177   PetscFunctionReturn(PETSC_SUCCESS);
1178 }
1179 
1180 static PetscErrorCode MatImaginaryPart_SeqAIJ(Mat A)
1181 {
1182   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1183   PetscInt    i, nz = a->nz;
1184   MatScalar  *aa;
1185 
1186   PetscFunctionBegin;
1187   PetscCall(MatSeqAIJGetArray(A, &aa));
1188   for (i = 0; i < nz; i++) aa[i] = PetscImaginaryPart(aa[i]);
1189   PetscCall(MatSeqAIJRestoreArray(A, &aa));
1190   PetscCall(MatSeqAIJInvalidateDiagonal(A));
1191   PetscFunctionReturn(PETSC_SUCCESS);
1192 }
1193 
1194 PetscErrorCode MatZeroEntries_SeqAIJ(Mat A)
1195 {
1196   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1197   MatScalar  *aa;
1198 
1199   PetscFunctionBegin;
1200   PetscCall(MatSeqAIJGetArrayWrite(A, &aa));
1201   PetscCall(PetscArrayzero(aa, a->i[A->rmap->n]));
1202   PetscCall(MatSeqAIJRestoreArrayWrite(A, &aa));
1203   PetscCall(MatSeqAIJInvalidateDiagonal(A));
1204   PetscFunctionReturn(PETSC_SUCCESS);
1205 }
1206 
1207 PetscErrorCode MatDestroy_SeqAIJ(Mat A)
1208 {
1209   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1210 
1211   PetscFunctionBegin;
1212   if (A->hash_active) {
1213     A->ops[0] = a->cops;
1214     PetscCall(PetscHMapIJVDestroy(&a->ht));
1215     PetscCall(PetscFree(a->dnz));
1216     A->hash_active = PETSC_FALSE;
1217   }
1218 
1219   PetscCall(PetscLogObjectState((PetscObject)A, "Rows=%" PetscInt_FMT ", Cols=%" PetscInt_FMT ", NZ=%" PetscInt_FMT, A->rmap->n, A->cmap->n, a->nz));
1220   PetscCall(MatSeqXAIJFreeAIJ(A, &a->a, &a->j, &a->i));
1221   PetscCall(ISDestroy(&a->row));
1222   PetscCall(ISDestroy(&a->col));
1223   PetscCall(PetscFree(a->diag));
1224   PetscCall(PetscFree(a->ibdiag));
1225   PetscCall(PetscFree(a->imax));
1226   PetscCall(PetscFree(a->ilen));
1227   PetscCall(PetscFree(a->ipre));
1228   PetscCall(PetscFree3(a->idiag, a->mdiag, a->ssor_work));
1229   PetscCall(PetscFree(a->solve_work));
1230   PetscCall(ISDestroy(&a->icol));
1231   PetscCall(PetscFree(a->saved_values));
1232   PetscCall(PetscFree2(a->compressedrow.i, a->compressedrow.rindex));
1233   PetscCall(MatDestroy_SeqAIJ_Inode(A));
1234   PetscCall(PetscFree(A->data));
1235 
1236   /* MatMatMultNumeric_SeqAIJ_SeqAIJ_Sorted may allocate this.
1237      That function is so heavily used (sometimes in an hidden way through multnumeric function pointers)
1238      that is hard to properly add this data to the MatProduct data. We free it here to avoid
1239      users reusing the matrix object with different data to incur in obscure segmentation faults
1240      due to different matrix sizes */
1241   PetscCall(PetscObjectCompose((PetscObject)A, "__PETSc__ab_dense", NULL));
1242 
1243   PetscCall(PetscObjectChangeTypeName((PetscObject)A, NULL));
1244   PetscCall(PetscObjectComposeFunction((PetscObject)A, "PetscMatlabEnginePut_C", NULL));
1245   PetscCall(PetscObjectComposeFunction((PetscObject)A, "PetscMatlabEngineGet_C", NULL));
1246   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetColumnIndices_C", NULL));
1247   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatStoreValues_C", NULL));
1248   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatRetrieveValues_C", NULL));
1249   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqsbaij_C", NULL));
1250   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqbaij_C", NULL));
1251   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijperm_C", NULL));
1252   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijsell_C", NULL));
1253 #if defined(PETSC_HAVE_MKL_SPARSE)
1254   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijmkl_C", NULL));
1255 #endif
1256 #if defined(PETSC_HAVE_CUDA)
1257   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijcusparse_C", NULL));
1258   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijcusparse_seqaij_C", NULL));
1259   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaijcusparse_C", NULL));
1260 #endif
1261 #if defined(PETSC_HAVE_HIP)
1262   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijhipsparse_C", NULL));
1263   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqaij_C", NULL));
1264   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaijhipsparse_C", NULL));
1265 #endif
1266 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
1267   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijkokkos_C", NULL));
1268 #endif
1269   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijcrl_C", NULL));
1270 #if defined(PETSC_HAVE_ELEMENTAL)
1271   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_elemental_C", NULL));
1272 #endif
1273 #if defined(PETSC_HAVE_SCALAPACK)
1274   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_scalapack_C", NULL));
1275 #endif
1276 #if defined(PETSC_HAVE_HYPRE)
1277   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_hypre_C", NULL));
1278   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_transpose_seqaij_seqaij_C", NULL));
1279 #endif
1280   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqdense_C", NULL));
1281   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqsell_C", NULL));
1282   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_is_C", NULL));
1283   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatIsTranspose_C", NULL));
1284   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatIsHermitianTranspose_C", NULL));
1285   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetPreallocation_C", NULL));
1286   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatResetPreallocation_C", NULL));
1287   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJSetPreallocationCSR_C", NULL));
1288   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatReorderForNonzeroDiagonal_C", NULL));
1289   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_is_seqaij_C", NULL));
1290   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqdense_seqaij_C", NULL));
1291   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaij_seqaij_C", NULL));
1292   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJKron_C", NULL));
1293   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL));
1294   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL));
1295   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatFactorGetSolverType_C", NULL));
1296   /* these calls do not belong here: the subclasses Duplicate/Destroy are wrong */
1297   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijsell_seqaij_C", NULL));
1298   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijperm_seqaij_C", NULL));
1299   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaij_seqaijviennacl_C", NULL));
1300   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijviennacl_seqdense_C", NULL));
1301   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijviennacl_seqaij_C", NULL));
1302   PetscFunctionReturn(PETSC_SUCCESS);
1303 }
1304 
1305 PetscErrorCode MatSetOption_SeqAIJ(Mat A, MatOption op, PetscBool flg)
1306 {
1307   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1308 
1309   PetscFunctionBegin;
1310   switch (op) {
1311   case MAT_ROW_ORIENTED:
1312     a->roworiented = flg;
1313     break;
1314   case MAT_KEEP_NONZERO_PATTERN:
1315     a->keepnonzeropattern = flg;
1316     break;
1317   case MAT_NEW_NONZERO_LOCATIONS:
1318     a->nonew = (flg ? 0 : 1);
1319     break;
1320   case MAT_NEW_NONZERO_LOCATION_ERR:
1321     a->nonew = (flg ? -1 : 0);
1322     break;
1323   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1324     a->nonew = (flg ? -2 : 0);
1325     break;
1326   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1327     a->nounused = (flg ? -1 : 0);
1328     break;
1329   case MAT_IGNORE_ZERO_ENTRIES:
1330     a->ignorezeroentries = flg;
1331     break;
1332   case MAT_SPD:
1333   case MAT_SYMMETRIC:
1334   case MAT_STRUCTURALLY_SYMMETRIC:
1335   case MAT_HERMITIAN:
1336   case MAT_SYMMETRY_ETERNAL:
1337   case MAT_STRUCTURE_ONLY:
1338   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
1339   case MAT_SPD_ETERNAL:
1340     /* if the diagonal matrix is square it inherits some of the properties above */
1341     break;
1342   case MAT_FORCE_DIAGONAL_ENTRIES:
1343   case MAT_IGNORE_OFF_PROC_ENTRIES:
1344   case MAT_USE_HASH_TABLE:
1345     PetscCall(PetscInfo(A, "Option %s ignored\n", MatOptions[op]));
1346     break;
1347   case MAT_USE_INODES:
1348     PetscCall(MatSetOption_SeqAIJ_Inode(A, MAT_USE_INODES, flg));
1349     break;
1350   case MAT_SUBMAT_SINGLEIS:
1351     A->submat_singleis = flg;
1352     break;
1353   case MAT_SORTED_FULL:
1354     if (flg) A->ops->setvalues = MatSetValues_SeqAIJ_SortedFull;
1355     else A->ops->setvalues = MatSetValues_SeqAIJ;
1356     break;
1357   case MAT_FORM_EXPLICIT_TRANSPOSE:
1358     A->form_explicit_transpose = flg;
1359     break;
1360   default:
1361     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "unknown option %d", op);
1362   }
1363   PetscFunctionReturn(PETSC_SUCCESS);
1364 }
1365 
1366 static PetscErrorCode MatGetDiagonal_SeqAIJ(Mat A, Vec v)
1367 {
1368   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1369   PetscInt           i, j, n, *ai = a->i, *aj = a->j;
1370   PetscScalar       *x;
1371   const PetscScalar *aa;
1372 
1373   PetscFunctionBegin;
1374   PetscCall(VecGetLocalSize(v, &n));
1375   PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
1376   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
1377   if (A->factortype == MAT_FACTOR_ILU || A->factortype == MAT_FACTOR_LU) {
1378     PetscInt *diag = a->diag;
1379     PetscCall(VecGetArrayWrite(v, &x));
1380     for (i = 0; i < n; i++) x[i] = 1.0 / aa[diag[i]];
1381     PetscCall(VecRestoreArrayWrite(v, &x));
1382     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1383     PetscFunctionReturn(PETSC_SUCCESS);
1384   }
1385 
1386   PetscCall(VecGetArrayWrite(v, &x));
1387   for (i = 0; i < n; i++) {
1388     x[i] = 0.0;
1389     for (j = ai[i]; j < ai[i + 1]; j++) {
1390       if (aj[j] == i) {
1391         x[i] = aa[j];
1392         break;
1393       }
1394     }
1395   }
1396   PetscCall(VecRestoreArrayWrite(v, &x));
1397   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1398   PetscFunctionReturn(PETSC_SUCCESS);
1399 }
1400 
1401 #include <../src/mat/impls/aij/seq/ftn-kernels/fmult.h>
1402 PetscErrorCode MatMultTransposeAdd_SeqAIJ(Mat A, Vec xx, Vec zz, Vec yy)
1403 {
1404   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1405   const MatScalar   *aa;
1406   PetscScalar       *y;
1407   const PetscScalar *x;
1408   PetscInt           m = A->rmap->n;
1409 #if !defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1410   const MatScalar  *v;
1411   PetscScalar       alpha;
1412   PetscInt          n, i, j;
1413   const PetscInt   *idx, *ii, *ridx = NULL;
1414   Mat_CompressedRow cprow    = a->compressedrow;
1415   PetscBool         usecprow = cprow.use;
1416 #endif
1417 
1418   PetscFunctionBegin;
1419   if (zz != yy) PetscCall(VecCopy(zz, yy));
1420   PetscCall(VecGetArrayRead(xx, &x));
1421   PetscCall(VecGetArray(yy, &y));
1422   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
1423 
1424 #if defined(PETSC_USE_FORTRAN_KERNEL_MULTTRANSPOSEAIJ)
1425   fortranmulttransposeaddaij_(&m, x, a->i, a->j, aa, y);
1426 #else
1427   if (usecprow) {
1428     m    = cprow.nrows;
1429     ii   = cprow.i;
1430     ridx = cprow.rindex;
1431   } else {
1432     ii = a->i;
1433   }
1434   for (i = 0; i < m; i++) {
1435     idx = a->j + ii[i];
1436     v   = aa + ii[i];
1437     n   = ii[i + 1] - ii[i];
1438     if (usecprow) {
1439       alpha = x[ridx[i]];
1440     } else {
1441       alpha = x[i];
1442     }
1443     for (j = 0; j < n; j++) y[idx[j]] += alpha * v[j];
1444   }
1445 #endif
1446   PetscCall(PetscLogFlops(2.0 * a->nz));
1447   PetscCall(VecRestoreArrayRead(xx, &x));
1448   PetscCall(VecRestoreArray(yy, &y));
1449   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1450   PetscFunctionReturn(PETSC_SUCCESS);
1451 }
1452 
1453 PetscErrorCode MatMultTranspose_SeqAIJ(Mat A, Vec xx, Vec yy)
1454 {
1455   PetscFunctionBegin;
1456   PetscCall(VecSet(yy, 0.0));
1457   PetscCall(MatMultTransposeAdd_SeqAIJ(A, xx, yy, yy));
1458   PetscFunctionReturn(PETSC_SUCCESS);
1459 }
1460 
1461 #include <../src/mat/impls/aij/seq/ftn-kernels/fmult.h>
1462 
1463 PetscErrorCode MatMult_SeqAIJ(Mat A, Vec xx, Vec yy)
1464 {
1465   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1466   PetscScalar       *y;
1467   const PetscScalar *x;
1468   const MatScalar   *aa, *a_a;
1469   PetscInt           m = A->rmap->n;
1470   const PetscInt    *aj, *ii, *ridx = NULL;
1471   PetscInt           n, i;
1472   PetscScalar        sum;
1473   PetscBool          usecprow = a->compressedrow.use;
1474 
1475 #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1476   #pragma disjoint(*x, *y, *aa)
1477 #endif
1478 
1479   PetscFunctionBegin;
1480   if (a->inode.use && a->inode.checked) {
1481     PetscCall(MatMult_SeqAIJ_Inode(A, xx, yy));
1482     PetscFunctionReturn(PETSC_SUCCESS);
1483   }
1484   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1485   PetscCall(VecGetArrayRead(xx, &x));
1486   PetscCall(VecGetArray(yy, &y));
1487   ii = a->i;
1488   if (usecprow) { /* use compressed row format */
1489     PetscCall(PetscArrayzero(y, m));
1490     m    = a->compressedrow.nrows;
1491     ii   = a->compressedrow.i;
1492     ridx = a->compressedrow.rindex;
1493     for (i = 0; i < m; i++) {
1494       n   = ii[i + 1] - ii[i];
1495       aj  = a->j + ii[i];
1496       aa  = a_a + ii[i];
1497       sum = 0.0;
1498       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1499       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1500       y[*ridx++] = sum;
1501     }
1502   } else { /* do not use compressed row format */
1503 #if defined(PETSC_USE_FORTRAN_KERNEL_MULTAIJ)
1504     aj = a->j;
1505     aa = a_a;
1506     fortranmultaij_(&m, x, ii, aj, aa, y);
1507 #else
1508     for (i = 0; i < m; i++) {
1509       n   = ii[i + 1] - ii[i];
1510       aj  = a->j + ii[i];
1511       aa  = a_a + ii[i];
1512       sum = 0.0;
1513       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1514       y[i] = sum;
1515     }
1516 #endif
1517   }
1518   PetscCall(PetscLogFlops(2.0 * a->nz - a->nonzerorowcnt));
1519   PetscCall(VecRestoreArrayRead(xx, &x));
1520   PetscCall(VecRestoreArray(yy, &y));
1521   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1522   PetscFunctionReturn(PETSC_SUCCESS);
1523 }
1524 
1525 // HACK!!!!! Used by src/mat/tests/ex170.c
1526 PETSC_EXTERN PetscErrorCode MatMultMax_SeqAIJ(Mat A, Vec xx, Vec yy)
1527 {
1528   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1529   PetscScalar       *y;
1530   const PetscScalar *x;
1531   const MatScalar   *aa, *a_a;
1532   PetscInt           m = A->rmap->n;
1533   const PetscInt    *aj, *ii, *ridx   = NULL;
1534   PetscInt           n, i, nonzerorow = 0;
1535   PetscScalar        sum;
1536   PetscBool          usecprow = a->compressedrow.use;
1537 
1538 #if defined(PETSC_HAVE_PRAGMA_DISJOINT)
1539   #pragma disjoint(*x, *y, *aa)
1540 #endif
1541 
1542   PetscFunctionBegin;
1543   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1544   PetscCall(VecGetArrayRead(xx, &x));
1545   PetscCall(VecGetArray(yy, &y));
1546   if (usecprow) { /* use compressed row format */
1547     m    = a->compressedrow.nrows;
1548     ii   = a->compressedrow.i;
1549     ridx = a->compressedrow.rindex;
1550     for (i = 0; i < m; i++) {
1551       n   = ii[i + 1] - ii[i];
1552       aj  = a->j + ii[i];
1553       aa  = a_a + ii[i];
1554       sum = 0.0;
1555       nonzerorow += (n > 0);
1556       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1557       /* for (j=0; j<n; j++) sum += (*aa++)*x[*aj++]; */
1558       y[*ridx++] = sum;
1559     }
1560   } else { /* do not use compressed row format */
1561     ii = a->i;
1562     for (i = 0; i < m; i++) {
1563       n   = ii[i + 1] - ii[i];
1564       aj  = a->j + ii[i];
1565       aa  = a_a + ii[i];
1566       sum = 0.0;
1567       nonzerorow += (n > 0);
1568       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1569       y[i] = sum;
1570     }
1571   }
1572   PetscCall(PetscLogFlops(2.0 * a->nz - nonzerorow));
1573   PetscCall(VecRestoreArrayRead(xx, &x));
1574   PetscCall(VecRestoreArray(yy, &y));
1575   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1576   PetscFunctionReturn(PETSC_SUCCESS);
1577 }
1578 
1579 // HACK!!!!! Used by src/mat/tests/ex170.c
1580 PETSC_EXTERN PetscErrorCode MatMultAddMax_SeqAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1581 {
1582   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1583   PetscScalar       *y, *z;
1584   const PetscScalar *x;
1585   const MatScalar   *aa, *a_a;
1586   PetscInt           m = A->rmap->n, *aj, *ii;
1587   PetscInt           n, i, *ridx = NULL;
1588   PetscScalar        sum;
1589   PetscBool          usecprow = a->compressedrow.use;
1590 
1591   PetscFunctionBegin;
1592   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1593   PetscCall(VecGetArrayRead(xx, &x));
1594   PetscCall(VecGetArrayPair(yy, zz, &y, &z));
1595   if (usecprow) { /* use compressed row format */
1596     if (zz != yy) PetscCall(PetscArraycpy(z, y, m));
1597     m    = a->compressedrow.nrows;
1598     ii   = a->compressedrow.i;
1599     ridx = a->compressedrow.rindex;
1600     for (i = 0; i < m; i++) {
1601       n   = ii[i + 1] - ii[i];
1602       aj  = a->j + ii[i];
1603       aa  = a_a + ii[i];
1604       sum = y[*ridx];
1605       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1606       z[*ridx++] = sum;
1607     }
1608   } else { /* do not use compressed row format */
1609     ii = a->i;
1610     for (i = 0; i < m; i++) {
1611       n   = ii[i + 1] - ii[i];
1612       aj  = a->j + ii[i];
1613       aa  = a_a + ii[i];
1614       sum = y[i];
1615       PetscSparseDenseMaxDot(sum, x, aa, aj, n);
1616       z[i] = sum;
1617     }
1618   }
1619   PetscCall(PetscLogFlops(2.0 * a->nz));
1620   PetscCall(VecRestoreArrayRead(xx, &x));
1621   PetscCall(VecRestoreArrayPair(yy, zz, &y, &z));
1622   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1623   PetscFunctionReturn(PETSC_SUCCESS);
1624 }
1625 
1626 #include <../src/mat/impls/aij/seq/ftn-kernels/fmultadd.h>
1627 PetscErrorCode MatMultAdd_SeqAIJ(Mat A, Vec xx, Vec yy, Vec zz)
1628 {
1629   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1630   PetscScalar       *y, *z;
1631   const PetscScalar *x;
1632   const MatScalar   *aa, *a_a;
1633   const PetscInt    *aj, *ii, *ridx = NULL;
1634   PetscInt           m = A->rmap->n, n, i;
1635   PetscScalar        sum;
1636   PetscBool          usecprow = a->compressedrow.use;
1637 
1638   PetscFunctionBegin;
1639   if (a->inode.use && a->inode.checked) {
1640     PetscCall(MatMultAdd_SeqAIJ_Inode(A, xx, yy, zz));
1641     PetscFunctionReturn(PETSC_SUCCESS);
1642   }
1643   PetscCall(MatSeqAIJGetArrayRead(A, &a_a));
1644   PetscCall(VecGetArrayRead(xx, &x));
1645   PetscCall(VecGetArrayPair(yy, zz, &y, &z));
1646   if (usecprow) { /* use compressed row format */
1647     if (zz != yy) PetscCall(PetscArraycpy(z, y, m));
1648     m    = a->compressedrow.nrows;
1649     ii   = a->compressedrow.i;
1650     ridx = a->compressedrow.rindex;
1651     for (i = 0; i < m; i++) {
1652       n   = ii[i + 1] - ii[i];
1653       aj  = a->j + ii[i];
1654       aa  = a_a + ii[i];
1655       sum = y[*ridx];
1656       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1657       z[*ridx++] = sum;
1658     }
1659   } else { /* do not use compressed row format */
1660     ii = a->i;
1661 #if defined(PETSC_USE_FORTRAN_KERNEL_MULTADDAIJ)
1662     aj = a->j;
1663     aa = a_a;
1664     fortranmultaddaij_(&m, x, ii, aj, aa, y, z);
1665 #else
1666     for (i = 0; i < m; i++) {
1667       n   = ii[i + 1] - ii[i];
1668       aj  = a->j + ii[i];
1669       aa  = a_a + ii[i];
1670       sum = y[i];
1671       PetscSparseDensePlusDot(sum, x, aa, aj, n);
1672       z[i] = sum;
1673     }
1674 #endif
1675   }
1676   PetscCall(PetscLogFlops(2.0 * a->nz));
1677   PetscCall(VecRestoreArrayRead(xx, &x));
1678   PetscCall(VecRestoreArrayPair(yy, zz, &y, &z));
1679   PetscCall(MatSeqAIJRestoreArrayRead(A, &a_a));
1680   PetscFunctionReturn(PETSC_SUCCESS);
1681 }
1682 
1683 /*
1684      Adds diagonal pointers to sparse matrix structure.
1685 */
1686 PetscErrorCode MatMarkDiagonal_SeqAIJ(Mat A)
1687 {
1688   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1689   PetscInt    i, j, m = A->rmap->n;
1690   PetscBool   alreadySet = PETSC_TRUE;
1691 
1692   PetscFunctionBegin;
1693   if (!a->diag) {
1694     PetscCall(PetscMalloc1(m, &a->diag));
1695     alreadySet = PETSC_FALSE;
1696   }
1697   for (i = 0; i < A->rmap->n; i++) {
1698     /* If A's diagonal is already correctly set, this fast track enables cheap and repeated MatMarkDiagonal_SeqAIJ() calls */
1699     if (alreadySet) {
1700       PetscInt pos = a->diag[i];
1701       if (pos >= a->i[i] && pos < a->i[i + 1] && a->j[pos] == i) continue;
1702     }
1703 
1704     a->diag[i] = a->i[i + 1];
1705     for (j = a->i[i]; j < a->i[i + 1]; j++) {
1706       if (a->j[j] == i) {
1707         a->diag[i] = j;
1708         break;
1709       }
1710     }
1711   }
1712   PetscFunctionReturn(PETSC_SUCCESS);
1713 }
1714 
1715 static PetscErrorCode MatShift_SeqAIJ(Mat A, PetscScalar v)
1716 {
1717   Mat_SeqAIJ     *a    = (Mat_SeqAIJ *)A->data;
1718   const PetscInt *diag = (const PetscInt *)a->diag;
1719   const PetscInt *ii   = (const PetscInt *)a->i;
1720   PetscInt        i, *mdiag = NULL;
1721   PetscInt        cnt = 0; /* how many diagonals are missing */
1722 
1723   PetscFunctionBegin;
1724   if (!A->preallocated || !a->nz) {
1725     PetscCall(MatSeqAIJSetPreallocation(A, 1, NULL));
1726     PetscCall(MatShift_Basic(A, v));
1727     PetscFunctionReturn(PETSC_SUCCESS);
1728   }
1729 
1730   if (a->diagonaldense) {
1731     cnt = 0;
1732   } else {
1733     PetscCall(PetscCalloc1(A->rmap->n, &mdiag));
1734     for (i = 0; i < A->rmap->n; i++) {
1735       if (i < A->cmap->n && diag[i] >= ii[i + 1]) { /* 'out of range' rows never have diagonals */
1736         cnt++;
1737         mdiag[i] = 1;
1738       }
1739     }
1740   }
1741   if (!cnt) {
1742     PetscCall(MatShift_Basic(A, v));
1743   } else {
1744     PetscScalar       *olda = a->a; /* preserve pointers to current matrix nonzeros structure and values */
1745     PetscInt          *oldj = a->j, *oldi = a->i;
1746     PetscBool          singlemalloc = a->singlemalloc, free_a = a->free_a, free_ij = a->free_ij;
1747     const PetscScalar *Aa;
1748 
1749     PetscCall(MatSeqAIJGetArrayRead(A, &Aa)); // sync the host
1750     PetscCall(MatSeqAIJRestoreArrayRead(A, &Aa));
1751 
1752     a->a = NULL;
1753     a->j = NULL;
1754     a->i = NULL;
1755     /* increase the values in imax for each row where a diagonal is being inserted then reallocate the matrix data structures */
1756     for (i = 0; i < PetscMin(A->rmap->n, A->cmap->n); i++) a->imax[i] += mdiag[i];
1757     PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(A, 0, a->imax));
1758 
1759     /* copy old values into new matrix data structure */
1760     for (i = 0; i < A->rmap->n; i++) {
1761       PetscCall(MatSetValues(A, 1, &i, a->imax[i] - mdiag[i], &oldj[oldi[i]], &olda[oldi[i]], ADD_VALUES));
1762       if (i < A->cmap->n) PetscCall(MatSetValue(A, i, i, v, ADD_VALUES));
1763     }
1764     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1765     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1766     if (singlemalloc) {
1767       PetscCall(PetscFree3(olda, oldj, oldi));
1768     } else {
1769       if (free_a) PetscCall(PetscFree(olda));
1770       if (free_ij) PetscCall(PetscFree(oldj));
1771       if (free_ij) PetscCall(PetscFree(oldi));
1772     }
1773   }
1774   PetscCall(PetscFree(mdiag));
1775   a->diagonaldense = PETSC_TRUE;
1776   PetscFunctionReturn(PETSC_SUCCESS);
1777 }
1778 
1779 /*
1780      Checks for missing diagonals
1781 */
1782 PetscErrorCode MatMissingDiagonal_SeqAIJ(Mat A, PetscBool *missing, PetscInt *d)
1783 {
1784   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1785   PetscInt   *diag, *ii = a->i, i;
1786 
1787   PetscFunctionBegin;
1788   *missing = PETSC_FALSE;
1789   if (A->rmap->n > 0 && !ii) {
1790     *missing = PETSC_TRUE;
1791     if (d) *d = 0;
1792     PetscCall(PetscInfo(A, "Matrix has no entries therefore is missing diagonal\n"));
1793   } else {
1794     PetscInt n;
1795     n    = PetscMin(A->rmap->n, A->cmap->n);
1796     diag = a->diag;
1797     for (i = 0; i < n; i++) {
1798       if (diag[i] >= ii[i + 1]) {
1799         *missing = PETSC_TRUE;
1800         if (d) *d = i;
1801         PetscCall(PetscInfo(A, "Matrix is missing diagonal number %" PetscInt_FMT "\n", i));
1802         break;
1803       }
1804     }
1805   }
1806   PetscFunctionReturn(PETSC_SUCCESS);
1807 }
1808 
1809 #include <petscblaslapack.h>
1810 #include <petsc/private/kernels/blockinvert.h>
1811 
1812 /*
1813     Note that values is allocated externally by the PC and then passed into this routine
1814 */
1815 static PetscErrorCode MatInvertVariableBlockDiagonal_SeqAIJ(Mat A, PetscInt nblocks, const PetscInt *bsizes, PetscScalar *diag)
1816 {
1817   PetscInt        n = A->rmap->n, i, ncnt = 0, *indx, j, bsizemax = 0, *v_pivots;
1818   PetscBool       allowzeropivot, zeropivotdetected = PETSC_FALSE;
1819   const PetscReal shift = 0.0;
1820   PetscInt        ipvt[5];
1821   PetscCount      flops = 0;
1822   PetscScalar     work[25], *v_work;
1823 
1824   PetscFunctionBegin;
1825   allowzeropivot = PetscNot(A->erroriffailure);
1826   for (i = 0; i < nblocks; i++) ncnt += bsizes[i];
1827   PetscCheck(ncnt == n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Total blocksizes %" PetscInt_FMT " doesn't match number matrix rows %" PetscInt_FMT, ncnt, n);
1828   for (i = 0; i < nblocks; i++) bsizemax = PetscMax(bsizemax, bsizes[i]);
1829   PetscCall(PetscMalloc1(bsizemax, &indx));
1830   if (bsizemax > 7) PetscCall(PetscMalloc2(bsizemax, &v_work, bsizemax, &v_pivots));
1831   ncnt = 0;
1832   for (i = 0; i < nblocks; i++) {
1833     for (j = 0; j < bsizes[i]; j++) indx[j] = ncnt + j;
1834     PetscCall(MatGetValues(A, bsizes[i], indx, bsizes[i], indx, diag));
1835     switch (bsizes[i]) {
1836     case 1:
1837       *diag = 1.0 / (*diag);
1838       break;
1839     case 2:
1840       PetscCall(PetscKernel_A_gets_inverse_A_2(diag, shift, allowzeropivot, &zeropivotdetected));
1841       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1842       PetscCall(PetscKernel_A_gets_transpose_A_2(diag));
1843       break;
1844     case 3:
1845       PetscCall(PetscKernel_A_gets_inverse_A_3(diag, shift, allowzeropivot, &zeropivotdetected));
1846       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1847       PetscCall(PetscKernel_A_gets_transpose_A_3(diag));
1848       break;
1849     case 4:
1850       PetscCall(PetscKernel_A_gets_inverse_A_4(diag, shift, allowzeropivot, &zeropivotdetected));
1851       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1852       PetscCall(PetscKernel_A_gets_transpose_A_4(diag));
1853       break;
1854     case 5:
1855       PetscCall(PetscKernel_A_gets_inverse_A_5(diag, ipvt, work, shift, allowzeropivot, &zeropivotdetected));
1856       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1857       PetscCall(PetscKernel_A_gets_transpose_A_5(diag));
1858       break;
1859     case 6:
1860       PetscCall(PetscKernel_A_gets_inverse_A_6(diag, shift, allowzeropivot, &zeropivotdetected));
1861       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1862       PetscCall(PetscKernel_A_gets_transpose_A_6(diag));
1863       break;
1864     case 7:
1865       PetscCall(PetscKernel_A_gets_inverse_A_7(diag, shift, allowzeropivot, &zeropivotdetected));
1866       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1867       PetscCall(PetscKernel_A_gets_transpose_A_7(diag));
1868       break;
1869     default:
1870       PetscCall(PetscKernel_A_gets_inverse_A(bsizes[i], diag, v_pivots, v_work, allowzeropivot, &zeropivotdetected));
1871       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1872       PetscCall(PetscKernel_A_gets_transpose_A_N(diag, bsizes[i]));
1873     }
1874     ncnt += bsizes[i];
1875     diag += bsizes[i] * bsizes[i];
1876     flops += 2 * PetscPowInt(bsizes[i], 3) / 3;
1877   }
1878   PetscCall(PetscLogFlops(flops));
1879   if (bsizemax > 7) PetscCall(PetscFree2(v_work, v_pivots));
1880   PetscCall(PetscFree(indx));
1881   PetscFunctionReturn(PETSC_SUCCESS);
1882 }
1883 
1884 /*
1885    Negative shift indicates do not generate an error if there is a zero diagonal, just invert it anyways
1886 */
1887 static PetscErrorCode MatInvertDiagonal_SeqAIJ(Mat A, PetscScalar omega, PetscScalar fshift)
1888 {
1889   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
1890   PetscInt         i, *diag, m = A->rmap->n;
1891   const MatScalar *v;
1892   PetscScalar     *idiag, *mdiag;
1893 
1894   PetscFunctionBegin;
1895   if (a->idiagvalid) PetscFunctionReturn(PETSC_SUCCESS);
1896   PetscCall(MatMarkDiagonal_SeqAIJ(A));
1897   diag = a->diag;
1898   if (!a->idiag) { PetscCall(PetscMalloc3(m, &a->idiag, m, &a->mdiag, m, &a->ssor_work)); }
1899 
1900   mdiag = a->mdiag;
1901   idiag = a->idiag;
1902   PetscCall(MatSeqAIJGetArrayRead(A, &v));
1903   if (omega == 1.0 && PetscRealPart(fshift) <= 0.0) {
1904     for (i = 0; i < m; i++) {
1905       mdiag[i] = v[diag[i]];
1906       if (!PetscAbsScalar(mdiag[i])) { /* zero diagonal */
1907         if (PetscRealPart(fshift)) {
1908           PetscCall(PetscInfo(A, "Zero diagonal on row %" PetscInt_FMT "\n", i));
1909           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
1910           A->factorerror_zeropivot_value = 0.0;
1911           A->factorerror_zeropivot_row   = i;
1912         } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Zero diagonal on row %" PetscInt_FMT, i);
1913       }
1914       idiag[i] = 1.0 / v[diag[i]];
1915     }
1916     PetscCall(PetscLogFlops(m));
1917   } else {
1918     for (i = 0; i < m; i++) {
1919       mdiag[i] = v[diag[i]];
1920       idiag[i] = omega / (fshift + v[diag[i]]);
1921     }
1922     PetscCall(PetscLogFlops(2.0 * m));
1923   }
1924   a->idiagvalid = PETSC_TRUE;
1925   PetscCall(MatSeqAIJRestoreArrayRead(A, &v));
1926   PetscFunctionReturn(PETSC_SUCCESS);
1927 }
1928 
1929 PetscErrorCode MatSOR_SeqAIJ(Mat A, Vec bb, PetscReal omega, MatSORType flag, PetscReal fshift, PetscInt its, PetscInt lits, Vec xx)
1930 {
1931   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
1932   PetscScalar       *x, d, sum, *t, scale;
1933   const MatScalar   *v, *idiag = NULL, *mdiag, *aa;
1934   const PetscScalar *b, *bs, *xb, *ts;
1935   PetscInt           n, m = A->rmap->n, i;
1936   const PetscInt    *idx, *diag;
1937 
1938   PetscFunctionBegin;
1939   if (a->inode.use && a->inode.checked && omega == 1.0 && fshift == 0.0) {
1940     PetscCall(MatSOR_SeqAIJ_Inode(A, bb, omega, flag, fshift, its, lits, xx));
1941     PetscFunctionReturn(PETSC_SUCCESS);
1942   }
1943   its = its * lits;
1944 
1945   if (fshift != a->fshift || omega != a->omega) a->idiagvalid = PETSC_FALSE; /* must recompute idiag[] */
1946   if (!a->idiagvalid) PetscCall(MatInvertDiagonal_SeqAIJ(A, omega, fshift));
1947   a->fshift = fshift;
1948   a->omega  = omega;
1949 
1950   diag  = a->diag;
1951   t     = a->ssor_work;
1952   idiag = a->idiag;
1953   mdiag = a->mdiag;
1954 
1955   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
1956   PetscCall(VecGetArray(xx, &x));
1957   PetscCall(VecGetArrayRead(bb, &b));
1958   /* We count flops by assuming the upper triangular and lower triangular parts have the same number of nonzeros */
1959   if (flag == SOR_APPLY_UPPER) {
1960     /* apply (U + D/omega) to the vector */
1961     bs = b;
1962     for (i = 0; i < m; i++) {
1963       d   = fshift + mdiag[i];
1964       n   = a->i[i + 1] - diag[i] - 1;
1965       idx = a->j + diag[i] + 1;
1966       v   = aa + diag[i] + 1;
1967       sum = b[i] * d / omega;
1968       PetscSparseDensePlusDot(sum, bs, v, idx, n);
1969       x[i] = sum;
1970     }
1971     PetscCall(VecRestoreArray(xx, &x));
1972     PetscCall(VecRestoreArrayRead(bb, &b));
1973     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
1974     PetscCall(PetscLogFlops(a->nz));
1975     PetscFunctionReturn(PETSC_SUCCESS);
1976   }
1977 
1978   PetscCheck(flag != SOR_APPLY_LOWER, PETSC_COMM_SELF, PETSC_ERR_SUP, "SOR_APPLY_LOWER is not implemented");
1979   if (flag & SOR_EISENSTAT) {
1980     /* Let  A = L + U + D; where L is lower triangular,
1981     U is upper triangular, E = D/omega; This routine applies
1982 
1983             (L + E)^{-1} A (U + E)^{-1}
1984 
1985     to a vector efficiently using Eisenstat's trick.
1986     */
1987     scale = (2.0 / omega) - 1.0;
1988 
1989     /*  x = (E + U)^{-1} b */
1990     for (i = m - 1; i >= 0; i--) {
1991       n   = a->i[i + 1] - diag[i] - 1;
1992       idx = a->j + diag[i] + 1;
1993       v   = aa + diag[i] + 1;
1994       sum = b[i];
1995       PetscSparseDenseMinusDot(sum, x, v, idx, n);
1996       x[i] = sum * idiag[i];
1997     }
1998 
1999     /*  t = b - (2*E - D)x */
2000     v = aa;
2001     for (i = 0; i < m; i++) t[i] = b[i] - scale * (v[*diag++]) * x[i];
2002 
2003     /*  t = (E + L)^{-1}t */
2004     ts   = t;
2005     diag = a->diag;
2006     for (i = 0; i < m; i++) {
2007       n   = diag[i] - a->i[i];
2008       idx = a->j + a->i[i];
2009       v   = aa + a->i[i];
2010       sum = t[i];
2011       PetscSparseDenseMinusDot(sum, ts, v, idx, n);
2012       t[i] = sum * idiag[i];
2013       /*  x = x + t */
2014       x[i] += t[i];
2015     }
2016 
2017     PetscCall(PetscLogFlops(6.0 * m - 1 + 2.0 * a->nz));
2018     PetscCall(VecRestoreArray(xx, &x));
2019     PetscCall(VecRestoreArrayRead(bb, &b));
2020     PetscFunctionReturn(PETSC_SUCCESS);
2021   }
2022   if (flag & SOR_ZERO_INITIAL_GUESS) {
2023     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
2024       for (i = 0; i < m; i++) {
2025         n   = diag[i] - a->i[i];
2026         idx = a->j + a->i[i];
2027         v   = aa + a->i[i];
2028         sum = b[i];
2029         PetscSparseDenseMinusDot(sum, x, v, idx, n);
2030         t[i] = sum;
2031         x[i] = sum * idiag[i];
2032       }
2033       xb = t;
2034       PetscCall(PetscLogFlops(a->nz));
2035     } else xb = b;
2036     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
2037       for (i = m - 1; i >= 0; i--) {
2038         n   = a->i[i + 1] - diag[i] - 1;
2039         idx = a->j + diag[i] + 1;
2040         v   = aa + diag[i] + 1;
2041         sum = xb[i];
2042         PetscSparseDenseMinusDot(sum, x, v, idx, n);
2043         if (xb == b) {
2044           x[i] = sum * idiag[i];
2045         } else {
2046           x[i] = (1 - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
2047         }
2048       }
2049       PetscCall(PetscLogFlops(a->nz)); /* assumes 1/2 in upper */
2050     }
2051     its--;
2052   }
2053   while (its--) {
2054     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
2055       for (i = 0; i < m; i++) {
2056         /* lower */
2057         n   = diag[i] - a->i[i];
2058         idx = a->j + a->i[i];
2059         v   = aa + a->i[i];
2060         sum = b[i];
2061         PetscSparseDenseMinusDot(sum, x, v, idx, n);
2062         t[i] = sum; /* save application of the lower-triangular part */
2063         /* upper */
2064         n   = a->i[i + 1] - diag[i] - 1;
2065         idx = a->j + diag[i] + 1;
2066         v   = aa + diag[i] + 1;
2067         PetscSparseDenseMinusDot(sum, x, v, idx, n);
2068         x[i] = (1. - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
2069       }
2070       xb = t;
2071       PetscCall(PetscLogFlops(2.0 * a->nz));
2072     } else xb = b;
2073     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
2074       for (i = m - 1; i >= 0; i--) {
2075         sum = xb[i];
2076         if (xb == b) {
2077           /* whole matrix (no checkpointing available) */
2078           n   = a->i[i + 1] - a->i[i];
2079           idx = a->j + a->i[i];
2080           v   = aa + a->i[i];
2081           PetscSparseDenseMinusDot(sum, x, v, idx, n);
2082           x[i] = (1. - omega) * x[i] + (sum + mdiag[i] * x[i]) * idiag[i];
2083         } else { /* lower-triangular part has been saved, so only apply upper-triangular */
2084           n   = a->i[i + 1] - diag[i] - 1;
2085           idx = a->j + diag[i] + 1;
2086           v   = aa + diag[i] + 1;
2087           PetscSparseDenseMinusDot(sum, x, v, idx, n);
2088           x[i] = (1. - omega) * x[i] + sum * idiag[i]; /* omega in idiag */
2089         }
2090       }
2091       if (xb == b) {
2092         PetscCall(PetscLogFlops(2.0 * a->nz));
2093       } else {
2094         PetscCall(PetscLogFlops(a->nz)); /* assumes 1/2 in upper */
2095       }
2096     }
2097   }
2098   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2099   PetscCall(VecRestoreArray(xx, &x));
2100   PetscCall(VecRestoreArrayRead(bb, &b));
2101   PetscFunctionReturn(PETSC_SUCCESS);
2102 }
2103 
2104 static PetscErrorCode MatGetInfo_SeqAIJ(Mat A, MatInfoType flag, MatInfo *info)
2105 {
2106   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
2107 
2108   PetscFunctionBegin;
2109   info->block_size   = 1.0;
2110   info->nz_allocated = a->maxnz;
2111   info->nz_used      = a->nz;
2112   info->nz_unneeded  = (a->maxnz - a->nz);
2113   info->assemblies   = A->num_ass;
2114   info->mallocs      = A->info.mallocs;
2115   info->memory       = 0; /* REVIEW ME */
2116   if (A->factortype) {
2117     info->fill_ratio_given  = A->info.fill_ratio_given;
2118     info->fill_ratio_needed = A->info.fill_ratio_needed;
2119     info->factor_mallocs    = A->info.factor_mallocs;
2120   } else {
2121     info->fill_ratio_given  = 0;
2122     info->fill_ratio_needed = 0;
2123     info->factor_mallocs    = 0;
2124   }
2125   PetscFunctionReturn(PETSC_SUCCESS);
2126 }
2127 
2128 static PetscErrorCode MatZeroRows_SeqAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
2129 {
2130   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2131   PetscInt           i, m = A->rmap->n - 1;
2132   const PetscScalar *xx;
2133   PetscScalar       *bb, *aa;
2134   PetscInt           d = 0;
2135 
2136   PetscFunctionBegin;
2137   if (x && b) {
2138     PetscCall(VecGetArrayRead(x, &xx));
2139     PetscCall(VecGetArray(b, &bb));
2140     for (i = 0; i < N; i++) {
2141       PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2142       if (rows[i] >= A->cmap->n) continue;
2143       bb[rows[i]] = diag * xx[rows[i]];
2144     }
2145     PetscCall(VecRestoreArrayRead(x, &xx));
2146     PetscCall(VecRestoreArray(b, &bb));
2147   }
2148 
2149   PetscCall(MatSeqAIJGetArray(A, &aa));
2150   if (a->keepnonzeropattern) {
2151     for (i = 0; i < N; i++) {
2152       PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2153       PetscCall(PetscArrayzero(&aa[a->i[rows[i]]], a->ilen[rows[i]]));
2154     }
2155     if (diag != 0.0) {
2156       for (i = 0; i < N; i++) {
2157         d = rows[i];
2158         if (rows[i] >= A->cmap->n) continue;
2159         PetscCheck(a->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);
2160       }
2161       for (i = 0; i < N; i++) {
2162         if (rows[i] >= A->cmap->n) continue;
2163         aa[a->diag[rows[i]]] = diag;
2164       }
2165     }
2166   } else {
2167     if (diag != 0.0) {
2168       for (i = 0; i < N; i++) {
2169         PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2170         if (a->ilen[rows[i]] > 0) {
2171           if (rows[i] >= A->cmap->n) {
2172             a->ilen[rows[i]] = 0;
2173           } else {
2174             a->ilen[rows[i]]    = 1;
2175             aa[a->i[rows[i]]]   = diag;
2176             a->j[a->i[rows[i]]] = rows[i];
2177           }
2178         } else if (rows[i] < A->cmap->n) { /* in case row was completely empty */
2179           PetscCall(MatSetValues_SeqAIJ(A, 1, &rows[i], 1, &rows[i], &diag, INSERT_VALUES));
2180         }
2181       }
2182     } else {
2183       for (i = 0; i < N; i++) {
2184         PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2185         a->ilen[rows[i]] = 0;
2186       }
2187     }
2188     A->nonzerostate++;
2189   }
2190   PetscCall(MatSeqAIJRestoreArray(A, &aa));
2191   PetscUseTypeMethod(A, assemblyend, MAT_FINAL_ASSEMBLY);
2192   PetscFunctionReturn(PETSC_SUCCESS);
2193 }
2194 
2195 static PetscErrorCode MatZeroRowsColumns_SeqAIJ(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
2196 {
2197   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2198   PetscInt           i, j, m = A->rmap->n - 1, d = 0;
2199   PetscBool          missing, *zeroed, vecs = PETSC_FALSE;
2200   const PetscScalar *xx;
2201   PetscScalar       *bb, *aa;
2202 
2203   PetscFunctionBegin;
2204   if (!N) PetscFunctionReturn(PETSC_SUCCESS);
2205   PetscCall(MatSeqAIJGetArray(A, &aa));
2206   if (x && b) {
2207     PetscCall(VecGetArrayRead(x, &xx));
2208     PetscCall(VecGetArray(b, &bb));
2209     vecs = PETSC_TRUE;
2210   }
2211   PetscCall(PetscCalloc1(A->rmap->n, &zeroed));
2212   for (i = 0; i < N; i++) {
2213     PetscCheck(rows[i] >= 0 && rows[i] <= m, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", rows[i]);
2214     PetscCall(PetscArrayzero(PetscSafePointerPlusOffset(aa, a->i[rows[i]]), a->ilen[rows[i]]));
2215 
2216     zeroed[rows[i]] = PETSC_TRUE;
2217   }
2218   for (i = 0; i < A->rmap->n; i++) {
2219     if (!zeroed[i]) {
2220       for (j = a->i[i]; j < a->i[i + 1]; j++) {
2221         if (a->j[j] < A->rmap->n && zeroed[a->j[j]]) {
2222           if (vecs) bb[i] -= aa[j] * xx[a->j[j]];
2223           aa[j] = 0.0;
2224         }
2225       }
2226     } else if (vecs && i < A->cmap->N) bb[i] = diag * xx[i];
2227   }
2228   if (x && b) {
2229     PetscCall(VecRestoreArrayRead(x, &xx));
2230     PetscCall(VecRestoreArray(b, &bb));
2231   }
2232   PetscCall(PetscFree(zeroed));
2233   if (diag != 0.0) {
2234     PetscCall(MatMissingDiagonal_SeqAIJ(A, &missing, &d));
2235     if (missing) {
2236       for (i = 0; i < N; i++) {
2237         if (rows[i] >= A->cmap->N) continue;
2238         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]);
2239         PetscCall(MatSetValues_SeqAIJ(A, 1, &rows[i], 1, &rows[i], &diag, INSERT_VALUES));
2240       }
2241     } else {
2242       for (i = 0; i < N; i++) aa[a->diag[rows[i]]] = diag;
2243     }
2244   }
2245   PetscCall(MatSeqAIJRestoreArray(A, &aa));
2246   PetscUseTypeMethod(A, assemblyend, MAT_FINAL_ASSEMBLY);
2247   PetscFunctionReturn(PETSC_SUCCESS);
2248 }
2249 
2250 PetscErrorCode MatGetRow_SeqAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
2251 {
2252   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2253   const PetscScalar *aa;
2254 
2255   PetscFunctionBegin;
2256   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
2257   *nz = a->i[row + 1] - a->i[row];
2258   if (v) *v = PetscSafePointerPlusOffset((PetscScalar *)aa, a->i[row]);
2259   if (idx) {
2260     if (*nz && a->j) *idx = a->j + a->i[row];
2261     else *idx = NULL;
2262   }
2263   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2264   PetscFunctionReturn(PETSC_SUCCESS);
2265 }
2266 
2267 PetscErrorCode MatRestoreRow_SeqAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
2268 {
2269   PetscFunctionBegin;
2270   PetscFunctionReturn(PETSC_SUCCESS);
2271 }
2272 
2273 static PetscErrorCode MatNorm_SeqAIJ(Mat A, NormType type, PetscReal *nrm)
2274 {
2275   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
2276   const MatScalar *v;
2277   PetscReal        sum = 0.0;
2278   PetscInt         i, j;
2279 
2280   PetscFunctionBegin;
2281   PetscCall(MatSeqAIJGetArrayRead(A, &v));
2282   if (type == NORM_FROBENIUS) {
2283 #if defined(PETSC_USE_REAL___FP16)
2284     PetscBLASInt one = 1, nz = a->nz;
2285     PetscCallBLAS("BLASnrm2", *nrm = BLASnrm2_(&nz, v, &one));
2286 #else
2287     for (i = 0; i < a->nz; i++) {
2288       sum += PetscRealPart(PetscConj(*v) * (*v));
2289       v++;
2290     }
2291     *nrm = PetscSqrtReal(sum);
2292 #endif
2293     PetscCall(PetscLogFlops(2.0 * a->nz));
2294   } else if (type == NORM_1) {
2295     PetscReal *tmp;
2296     PetscInt  *jj = a->j;
2297     PetscCall(PetscCalloc1(A->cmap->n + 1, &tmp));
2298     *nrm = 0.0;
2299     for (j = 0; j < a->nz; j++) {
2300       tmp[*jj++] += PetscAbsScalar(*v);
2301       v++;
2302     }
2303     for (j = 0; j < A->cmap->n; j++) {
2304       if (tmp[j] > *nrm) *nrm = tmp[j];
2305     }
2306     PetscCall(PetscFree(tmp));
2307     PetscCall(PetscLogFlops(PetscMax(a->nz - 1, 0)));
2308   } else if (type == NORM_INFINITY) {
2309     *nrm = 0.0;
2310     for (j = 0; j < A->rmap->n; j++) {
2311       const PetscScalar *v2 = PetscSafePointerPlusOffset(v, a->i[j]);
2312       sum                   = 0.0;
2313       for (i = 0; i < a->i[j + 1] - a->i[j]; i++) {
2314         sum += PetscAbsScalar(*v2);
2315         v2++;
2316       }
2317       if (sum > *nrm) *nrm = sum;
2318     }
2319     PetscCall(PetscLogFlops(PetscMax(a->nz - 1, 0)));
2320   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for two norm");
2321   PetscCall(MatSeqAIJRestoreArrayRead(A, &v));
2322   PetscFunctionReturn(PETSC_SUCCESS);
2323 }
2324 
2325 static PetscErrorCode MatIsTranspose_SeqAIJ(Mat A, Mat B, PetscReal tol, PetscBool *f)
2326 {
2327   Mat_SeqAIJ      *aij = (Mat_SeqAIJ *)A->data, *bij = (Mat_SeqAIJ *)B->data;
2328   PetscInt        *adx, *bdx, *aii, *bii, *aptr, *bptr;
2329   const MatScalar *va, *vb;
2330   PetscInt         ma, na, mb, nb, i;
2331 
2332   PetscFunctionBegin;
2333   PetscCall(MatGetSize(A, &ma, &na));
2334   PetscCall(MatGetSize(B, &mb, &nb));
2335   if (ma != nb || na != mb) {
2336     *f = PETSC_FALSE;
2337     PetscFunctionReturn(PETSC_SUCCESS);
2338   }
2339   PetscCall(MatSeqAIJGetArrayRead(A, &va));
2340   PetscCall(MatSeqAIJGetArrayRead(B, &vb));
2341   aii = aij->i;
2342   bii = bij->i;
2343   adx = aij->j;
2344   bdx = bij->j;
2345   PetscCall(PetscMalloc1(ma, &aptr));
2346   PetscCall(PetscMalloc1(mb, &bptr));
2347   for (i = 0; i < ma; i++) aptr[i] = aii[i];
2348   for (i = 0; i < mb; i++) bptr[i] = bii[i];
2349 
2350   *f = PETSC_TRUE;
2351   for (i = 0; i < ma; i++) {
2352     while (aptr[i] < aii[i + 1]) {
2353       PetscInt    idc, idr;
2354       PetscScalar vc, vr;
2355       /* column/row index/value */
2356       idc = adx[aptr[i]];
2357       idr = bdx[bptr[idc]];
2358       vc  = va[aptr[i]];
2359       vr  = vb[bptr[idc]];
2360       if (i != idr || PetscAbsScalar(vc - vr) > tol) {
2361         *f = PETSC_FALSE;
2362         goto done;
2363       } else {
2364         aptr[i]++;
2365         if (B || i != idc) bptr[idc]++;
2366       }
2367     }
2368   }
2369 done:
2370   PetscCall(PetscFree(aptr));
2371   PetscCall(PetscFree(bptr));
2372   PetscCall(MatSeqAIJRestoreArrayRead(A, &va));
2373   PetscCall(MatSeqAIJRestoreArrayRead(B, &vb));
2374   PetscFunctionReturn(PETSC_SUCCESS);
2375 }
2376 
2377 static PetscErrorCode MatIsHermitianTranspose_SeqAIJ(Mat A, Mat B, PetscReal tol, PetscBool *f)
2378 {
2379   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data, *bij = (Mat_SeqAIJ *)B->data;
2380   PetscInt   *adx, *bdx, *aii, *bii, *aptr, *bptr;
2381   MatScalar  *va, *vb;
2382   PetscInt    ma, na, mb, nb, i;
2383 
2384   PetscFunctionBegin;
2385   PetscCall(MatGetSize(A, &ma, &na));
2386   PetscCall(MatGetSize(B, &mb, &nb));
2387   if (ma != nb || na != mb) {
2388     *f = PETSC_FALSE;
2389     PetscFunctionReturn(PETSC_SUCCESS);
2390   }
2391   aii = aij->i;
2392   bii = bij->i;
2393   adx = aij->j;
2394   bdx = bij->j;
2395   va  = aij->a;
2396   vb  = bij->a;
2397   PetscCall(PetscMalloc1(ma, &aptr));
2398   PetscCall(PetscMalloc1(mb, &bptr));
2399   for (i = 0; i < ma; i++) aptr[i] = aii[i];
2400   for (i = 0; i < mb; i++) bptr[i] = bii[i];
2401 
2402   *f = PETSC_TRUE;
2403   for (i = 0; i < ma; i++) {
2404     while (aptr[i] < aii[i + 1]) {
2405       PetscInt    idc, idr;
2406       PetscScalar vc, vr;
2407       /* column/row index/value */
2408       idc = adx[aptr[i]];
2409       idr = bdx[bptr[idc]];
2410       vc  = va[aptr[i]];
2411       vr  = vb[bptr[idc]];
2412       if (i != idr || PetscAbsScalar(vc - PetscConj(vr)) > tol) {
2413         *f = PETSC_FALSE;
2414         goto done;
2415       } else {
2416         aptr[i]++;
2417         if (B || i != idc) bptr[idc]++;
2418       }
2419     }
2420   }
2421 done:
2422   PetscCall(PetscFree(aptr));
2423   PetscCall(PetscFree(bptr));
2424   PetscFunctionReturn(PETSC_SUCCESS);
2425 }
2426 
2427 static PetscErrorCode MatIsSymmetric_SeqAIJ(Mat A, PetscReal tol, PetscBool *f)
2428 {
2429   PetscFunctionBegin;
2430   PetscCall(MatIsTranspose_SeqAIJ(A, A, tol, f));
2431   PetscFunctionReturn(PETSC_SUCCESS);
2432 }
2433 
2434 static PetscErrorCode MatIsHermitian_SeqAIJ(Mat A, PetscReal tol, PetscBool *f)
2435 {
2436   PetscFunctionBegin;
2437   PetscCall(MatIsHermitianTranspose_SeqAIJ(A, A, tol, f));
2438   PetscFunctionReturn(PETSC_SUCCESS);
2439 }
2440 
2441 PetscErrorCode MatDiagonalScale_SeqAIJ(Mat A, Vec ll, Vec rr)
2442 {
2443   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2444   const PetscScalar *l, *r;
2445   PetscScalar        x;
2446   MatScalar         *v;
2447   PetscInt           i, j, m = A->rmap->n, n = A->cmap->n, M, nz = a->nz;
2448   const PetscInt    *jj;
2449 
2450   PetscFunctionBegin;
2451   if (ll) {
2452     /* The local size is used so that VecMPI can be passed to this routine
2453        by MatDiagonalScale_MPIAIJ */
2454     PetscCall(VecGetLocalSize(ll, &m));
2455     PetscCheck(m == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Left scaling vector wrong length");
2456     PetscCall(VecGetArrayRead(ll, &l));
2457     PetscCall(MatSeqAIJGetArray(A, &v));
2458     for (i = 0; i < m; i++) {
2459       x = l[i];
2460       M = a->i[i + 1] - a->i[i];
2461       for (j = 0; j < M; j++) (*v++) *= x;
2462     }
2463     PetscCall(VecRestoreArrayRead(ll, &l));
2464     PetscCall(PetscLogFlops(nz));
2465     PetscCall(MatSeqAIJRestoreArray(A, &v));
2466   }
2467   if (rr) {
2468     PetscCall(VecGetLocalSize(rr, &n));
2469     PetscCheck(n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Right scaling vector wrong length");
2470     PetscCall(VecGetArrayRead(rr, &r));
2471     PetscCall(MatSeqAIJGetArray(A, &v));
2472     jj = a->j;
2473     for (i = 0; i < nz; i++) (*v++) *= r[*jj++];
2474     PetscCall(MatSeqAIJRestoreArray(A, &v));
2475     PetscCall(VecRestoreArrayRead(rr, &r));
2476     PetscCall(PetscLogFlops(nz));
2477   }
2478   PetscCall(MatSeqAIJInvalidateDiagonal(A));
2479   PetscFunctionReturn(PETSC_SUCCESS);
2480 }
2481 
2482 PetscErrorCode MatCreateSubMatrix_SeqAIJ(Mat A, IS isrow, IS iscol, PetscInt csize, MatReuse scall, Mat *B)
2483 {
2484   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data, *c;
2485   PetscInt          *smap, i, k, kstart, kend, oldcols = A->cmap->n, *lens;
2486   PetscInt           row, mat_i, *mat_j, tcol, first, step, *mat_ilen, sum, lensi;
2487   const PetscInt    *irow, *icol;
2488   const PetscScalar *aa;
2489   PetscInt           nrows, ncols;
2490   PetscInt          *starts, *j_new, *i_new, *aj = a->j, *ai = a->i, ii, *ailen = a->ilen;
2491   MatScalar         *a_new, *mat_a, *c_a;
2492   Mat                C;
2493   PetscBool          stride;
2494 
2495   PetscFunctionBegin;
2496   PetscCall(ISGetIndices(isrow, &irow));
2497   PetscCall(ISGetLocalSize(isrow, &nrows));
2498   PetscCall(ISGetLocalSize(iscol, &ncols));
2499 
2500   PetscCall(PetscObjectTypeCompare((PetscObject)iscol, ISSTRIDE, &stride));
2501   if (stride) {
2502     PetscCall(ISStrideGetInfo(iscol, &first, &step));
2503   } else {
2504     first = 0;
2505     step  = 0;
2506   }
2507   if (stride && step == 1) {
2508     /* special case of contiguous rows */
2509     PetscCall(PetscMalloc2(nrows, &lens, nrows, &starts));
2510     /* loop over new rows determining lens and starting points */
2511     for (i = 0; i < nrows; i++) {
2512       kstart    = ai[irow[i]];
2513       kend      = kstart + ailen[irow[i]];
2514       starts[i] = kstart;
2515       for (k = kstart; k < kend; k++) {
2516         if (aj[k] >= first) {
2517           starts[i] = k;
2518           break;
2519         }
2520       }
2521       sum = 0;
2522       while (k < kend) {
2523         if (aj[k++] >= first + ncols) break;
2524         sum++;
2525       }
2526       lens[i] = sum;
2527     }
2528     /* create submatrix */
2529     if (scall == MAT_REUSE_MATRIX) {
2530       PetscInt n_cols, n_rows;
2531       PetscCall(MatGetSize(*B, &n_rows, &n_cols));
2532       PetscCheck(n_rows == nrows && n_cols == ncols, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Reused submatrix wrong size");
2533       PetscCall(MatZeroEntries(*B));
2534       C = *B;
2535     } else {
2536       PetscInt rbs, cbs;
2537       PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &C));
2538       PetscCall(MatSetSizes(C, nrows, ncols, PETSC_DETERMINE, PETSC_DETERMINE));
2539       PetscCall(ISGetBlockSize(isrow, &rbs));
2540       PetscCall(ISGetBlockSize(iscol, &cbs));
2541       PetscCall(MatSetBlockSizes(C, rbs, cbs));
2542       PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
2543       PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(C, 0, lens));
2544     }
2545     c = (Mat_SeqAIJ *)C->data;
2546 
2547     /* loop over rows inserting into submatrix */
2548     PetscCall(MatSeqAIJGetArrayWrite(C, &a_new)); // Not 'a_new = c->a-new', since that raw usage ignores offload state of C
2549     j_new = c->j;
2550     i_new = c->i;
2551     PetscCall(MatSeqAIJGetArrayRead(A, &aa));
2552     for (i = 0; i < nrows; i++) {
2553       ii    = starts[i];
2554       lensi = lens[i];
2555       if (lensi) {
2556         for (k = 0; k < lensi; k++) *j_new++ = aj[ii + k] - first;
2557         PetscCall(PetscArraycpy(a_new, aa + starts[i], lensi));
2558         a_new += lensi;
2559       }
2560       i_new[i + 1] = i_new[i] + lensi;
2561       c->ilen[i]   = lensi;
2562     }
2563     PetscCall(MatSeqAIJRestoreArrayWrite(C, &a_new)); // Set C's offload state properly
2564     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2565     PetscCall(PetscFree2(lens, starts));
2566   } else {
2567     PetscCall(ISGetIndices(iscol, &icol));
2568     PetscCall(PetscCalloc1(oldcols, &smap));
2569     PetscCall(PetscMalloc1(1 + nrows, &lens));
2570     for (i = 0; i < ncols; i++) {
2571       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);
2572       smap[icol[i]] = i + 1;
2573     }
2574 
2575     /* determine lens of each row */
2576     for (i = 0; i < nrows; i++) {
2577       kstart  = ai[irow[i]];
2578       kend    = kstart + a->ilen[irow[i]];
2579       lens[i] = 0;
2580       for (k = kstart; k < kend; k++) {
2581         if (smap[aj[k]]) lens[i]++;
2582       }
2583     }
2584     /* Create and fill new matrix */
2585     if (scall == MAT_REUSE_MATRIX) {
2586       PetscBool equal;
2587 
2588       c = (Mat_SeqAIJ *)((*B)->data);
2589       PetscCheck((*B)->rmap->n == nrows && (*B)->cmap->n == ncols, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot reuse matrix. wrong size");
2590       PetscCall(PetscArraycmp(c->ilen, lens, (*B)->rmap->n, &equal));
2591       PetscCheck(equal, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot reuse matrix. wrong number of nonzeros");
2592       PetscCall(PetscArrayzero(c->ilen, (*B)->rmap->n));
2593       C = *B;
2594     } else {
2595       PetscInt rbs, cbs;
2596       PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &C));
2597       PetscCall(MatSetSizes(C, nrows, ncols, PETSC_DETERMINE, PETSC_DETERMINE));
2598       PetscCall(ISGetBlockSize(isrow, &rbs));
2599       PetscCall(ISGetBlockSize(iscol, &cbs));
2600       if (rbs > 1 || cbs > 1) PetscCall(MatSetBlockSizes(C, rbs, cbs));
2601       PetscCall(MatSetType(C, ((PetscObject)A)->type_name));
2602       PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(C, 0, lens));
2603     }
2604     PetscCall(MatSeqAIJGetArrayRead(A, &aa));
2605 
2606     c = (Mat_SeqAIJ *)(C->data);
2607     PetscCall(MatSeqAIJGetArrayWrite(C, &c_a)); // Not 'c->a', since that raw usage ignores offload state of C
2608     for (i = 0; i < nrows; i++) {
2609       row      = irow[i];
2610       kstart   = ai[row];
2611       kend     = kstart + a->ilen[row];
2612       mat_i    = c->i[i];
2613       mat_j    = PetscSafePointerPlusOffset(c->j, mat_i);
2614       mat_a    = PetscSafePointerPlusOffset(c_a, mat_i);
2615       mat_ilen = c->ilen + i;
2616       for (k = kstart; k < kend; k++) {
2617         if ((tcol = smap[a->j[k]])) {
2618           *mat_j++ = tcol - 1;
2619           *mat_a++ = aa[k];
2620           (*mat_ilen)++;
2621         }
2622       }
2623     }
2624     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2625     /* Free work space */
2626     PetscCall(ISRestoreIndices(iscol, &icol));
2627     PetscCall(PetscFree(smap));
2628     PetscCall(PetscFree(lens));
2629     /* sort */
2630     for (i = 0; i < nrows; i++) {
2631       PetscInt ilen;
2632 
2633       mat_i = c->i[i];
2634       mat_j = PetscSafePointerPlusOffset(c->j, mat_i);
2635       mat_a = PetscSafePointerPlusOffset(c_a, mat_i);
2636       ilen  = c->ilen[i];
2637       PetscCall(PetscSortIntWithScalarArray(ilen, mat_j, mat_a));
2638     }
2639     PetscCall(MatSeqAIJRestoreArrayWrite(C, &c_a));
2640   }
2641 #if defined(PETSC_HAVE_DEVICE)
2642   PetscCall(MatBindToCPU(C, A->boundtocpu));
2643 #endif
2644   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2645   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2646 
2647   PetscCall(ISRestoreIndices(isrow, &irow));
2648   *B = C;
2649   PetscFunctionReturn(PETSC_SUCCESS);
2650 }
2651 
2652 static PetscErrorCode MatGetMultiProcBlock_SeqAIJ(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
2653 {
2654   Mat B;
2655 
2656   PetscFunctionBegin;
2657   if (scall == MAT_INITIAL_MATRIX) {
2658     PetscCall(MatCreate(subComm, &B));
2659     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->n, mat->cmap->n));
2660     PetscCall(MatSetBlockSizesFromMats(B, mat, mat));
2661     PetscCall(MatSetType(B, MATSEQAIJ));
2662     PetscCall(MatDuplicateNoCreate_SeqAIJ(B, mat, MAT_COPY_VALUES, PETSC_TRUE));
2663     *subMat = B;
2664   } else {
2665     PetscCall(MatCopy_SeqAIJ(mat, *subMat, SAME_NONZERO_PATTERN));
2666   }
2667   PetscFunctionReturn(PETSC_SUCCESS);
2668 }
2669 
2670 static PetscErrorCode MatILUFactor_SeqAIJ(Mat inA, IS row, IS col, const MatFactorInfo *info)
2671 {
2672   Mat_SeqAIJ *a = (Mat_SeqAIJ *)inA->data;
2673   Mat         outA;
2674   PetscBool   row_identity, col_identity;
2675 
2676   PetscFunctionBegin;
2677   PetscCheck(info->levels == 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only levels=0 supported for in-place ilu");
2678 
2679   PetscCall(ISIdentity(row, &row_identity));
2680   PetscCall(ISIdentity(col, &col_identity));
2681 
2682   outA             = inA;
2683   outA->factortype = MAT_FACTOR_LU;
2684   PetscCall(PetscFree(inA->solvertype));
2685   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &inA->solvertype));
2686 
2687   PetscCall(PetscObjectReference((PetscObject)row));
2688   PetscCall(ISDestroy(&a->row));
2689 
2690   a->row = row;
2691 
2692   PetscCall(PetscObjectReference((PetscObject)col));
2693   PetscCall(ISDestroy(&a->col));
2694 
2695   a->col = col;
2696 
2697   /* Create the inverse permutation so that it can be used in MatLUFactorNumeric() */
2698   PetscCall(ISDestroy(&a->icol));
2699   PetscCall(ISInvertPermutation(col, PETSC_DECIDE, &a->icol));
2700 
2701   if (!a->solve_work) { /* this matrix may have been factored before */
2702     PetscCall(PetscMalloc1(inA->rmap->n + 1, &a->solve_work));
2703   }
2704 
2705   PetscCall(MatMarkDiagonal_SeqAIJ(inA));
2706   if (row_identity && col_identity) {
2707     PetscCall(MatLUFactorNumeric_SeqAIJ_inplace(outA, inA, info));
2708   } else {
2709     PetscCall(MatLUFactorNumeric_SeqAIJ_InplaceWithPerm(outA, inA, info));
2710   }
2711   PetscFunctionReturn(PETSC_SUCCESS);
2712 }
2713 
2714 PetscErrorCode MatScale_SeqAIJ(Mat inA, PetscScalar alpha)
2715 {
2716   Mat_SeqAIJ  *a = (Mat_SeqAIJ *)inA->data;
2717   PetscScalar *v;
2718   PetscBLASInt one = 1, bnz;
2719 
2720   PetscFunctionBegin;
2721   PetscCall(MatSeqAIJGetArray(inA, &v));
2722   PetscCall(PetscBLASIntCast(a->nz, &bnz));
2723   PetscCallBLAS("BLASscal", BLASscal_(&bnz, &alpha, v, &one));
2724   PetscCall(PetscLogFlops(a->nz));
2725   PetscCall(MatSeqAIJRestoreArray(inA, &v));
2726   PetscCall(MatSeqAIJInvalidateDiagonal(inA));
2727   PetscFunctionReturn(PETSC_SUCCESS);
2728 }
2729 
2730 PetscErrorCode MatDestroySubMatrix_Private(Mat_SubSppt *submatj)
2731 {
2732   PetscInt i;
2733 
2734   PetscFunctionBegin;
2735   if (!submatj->id) { /* delete data that are linked only to submats[id=0] */
2736     PetscCall(PetscFree4(submatj->sbuf1, submatj->ptr, submatj->tmp, submatj->ctr));
2737 
2738     for (i = 0; i < submatj->nrqr; ++i) PetscCall(PetscFree(submatj->sbuf2[i]));
2739     PetscCall(PetscFree3(submatj->sbuf2, submatj->req_size, submatj->req_source1));
2740 
2741     if (submatj->rbuf1) {
2742       PetscCall(PetscFree(submatj->rbuf1[0]));
2743       PetscCall(PetscFree(submatj->rbuf1));
2744     }
2745 
2746     for (i = 0; i < submatj->nrqs; ++i) PetscCall(PetscFree(submatj->rbuf3[i]));
2747     PetscCall(PetscFree3(submatj->req_source2, submatj->rbuf2, submatj->rbuf3));
2748     PetscCall(PetscFree(submatj->pa));
2749   }
2750 
2751 #if defined(PETSC_USE_CTABLE)
2752   PetscCall(PetscHMapIDestroy(&submatj->rmap));
2753   if (submatj->cmap_loc) PetscCall(PetscFree(submatj->cmap_loc));
2754   PetscCall(PetscFree(submatj->rmap_loc));
2755 #else
2756   PetscCall(PetscFree(submatj->rmap));
2757 #endif
2758 
2759   if (!submatj->allcolumns) {
2760 #if defined(PETSC_USE_CTABLE)
2761     PetscCall(PetscHMapIDestroy((PetscHMapI *)&submatj->cmap));
2762 #else
2763     PetscCall(PetscFree(submatj->cmap));
2764 #endif
2765   }
2766   PetscCall(PetscFree(submatj->row2proc));
2767 
2768   PetscCall(PetscFree(submatj));
2769   PetscFunctionReturn(PETSC_SUCCESS);
2770 }
2771 
2772 PetscErrorCode MatDestroySubMatrix_SeqAIJ(Mat C)
2773 {
2774   Mat_SeqAIJ  *c       = (Mat_SeqAIJ *)C->data;
2775   Mat_SubSppt *submatj = c->submatis1;
2776 
2777   PetscFunctionBegin;
2778   PetscCall((*submatj->destroy)(C));
2779   PetscCall(MatDestroySubMatrix_Private(submatj));
2780   PetscFunctionReturn(PETSC_SUCCESS);
2781 }
2782 
2783 /* Note this has code duplication with MatDestroySubMatrices_SeqBAIJ() */
2784 static PetscErrorCode MatDestroySubMatrices_SeqAIJ(PetscInt n, Mat *mat[])
2785 {
2786   PetscInt     i;
2787   Mat          C;
2788   Mat_SeqAIJ  *c;
2789   Mat_SubSppt *submatj;
2790 
2791   PetscFunctionBegin;
2792   for (i = 0; i < n; i++) {
2793     C       = (*mat)[i];
2794     c       = (Mat_SeqAIJ *)C->data;
2795     submatj = c->submatis1;
2796     if (submatj) {
2797       if (--((PetscObject)C)->refct <= 0) {
2798         PetscCall(PetscFree(C->factorprefix));
2799         PetscCall((*submatj->destroy)(C));
2800         PetscCall(MatDestroySubMatrix_Private(submatj));
2801         PetscCall(PetscFree(C->defaultvectype));
2802         PetscCall(PetscFree(C->defaultrandtype));
2803         PetscCall(PetscLayoutDestroy(&C->rmap));
2804         PetscCall(PetscLayoutDestroy(&C->cmap));
2805         PetscCall(PetscHeaderDestroy(&C));
2806       }
2807     } else {
2808       PetscCall(MatDestroy(&C));
2809     }
2810   }
2811 
2812   /* Destroy Dummy submatrices created for reuse */
2813   PetscCall(MatDestroySubMatrices_Dummy(n, mat));
2814 
2815   PetscCall(PetscFree(*mat));
2816   PetscFunctionReturn(PETSC_SUCCESS);
2817 }
2818 
2819 static PetscErrorCode MatCreateSubMatrices_SeqAIJ(Mat A, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *B[])
2820 {
2821   PetscInt i;
2822 
2823   PetscFunctionBegin;
2824   if (scall == MAT_INITIAL_MATRIX) PetscCall(PetscCalloc1(n + 1, B));
2825 
2826   for (i = 0; i < n; i++) PetscCall(MatCreateSubMatrix_SeqAIJ(A, irow[i], icol[i], PETSC_DECIDE, scall, &(*B)[i]));
2827   PetscFunctionReturn(PETSC_SUCCESS);
2828 }
2829 
2830 static PetscErrorCode MatIncreaseOverlap_SeqAIJ(Mat A, PetscInt is_max, IS is[], PetscInt ov)
2831 {
2832   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
2833   PetscInt        row, i, j, k, l, ll, m, n, *nidx, isz, val;
2834   const PetscInt *idx;
2835   PetscInt        start, end, *ai, *aj, bs = (A->rmap->bs > 0 && A->rmap->bs == A->cmap->bs) ? A->rmap->bs : 1;
2836   PetscBT         table;
2837 
2838   PetscFunctionBegin;
2839   m  = A->rmap->n / bs;
2840   ai = a->i;
2841   aj = a->j;
2842 
2843   PetscCheck(ov >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "illegal negative overlap value used");
2844 
2845   PetscCall(PetscMalloc1(m + 1, &nidx));
2846   PetscCall(PetscBTCreate(m, &table));
2847 
2848   for (i = 0; i < is_max; i++) {
2849     /* Initialize the two local arrays */
2850     isz = 0;
2851     PetscCall(PetscBTMemzero(m, table));
2852 
2853     /* Extract the indices, assume there can be duplicate entries */
2854     PetscCall(ISGetIndices(is[i], &idx));
2855     PetscCall(ISGetLocalSize(is[i], &n));
2856 
2857     if (bs > 1) {
2858       /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2859       for (j = 0; j < n; ++j) {
2860         if (!PetscBTLookupSet(table, idx[j] / bs)) nidx[isz++] = idx[j] / bs;
2861       }
2862       PetscCall(ISRestoreIndices(is[i], &idx));
2863       PetscCall(ISDestroy(&is[i]));
2864 
2865       k = 0;
2866       for (j = 0; j < ov; j++) { /* for each overlap */
2867         n = isz;
2868         for (; k < n; k++) { /* do only those rows in nidx[k], which are not done yet */
2869           for (ll = 0; ll < bs; ll++) {
2870             row   = bs * nidx[k] + ll;
2871             start = ai[row];
2872             end   = ai[row + 1];
2873             for (l = start; l < end; l++) {
2874               val = aj[l] / bs;
2875               if (!PetscBTLookupSet(table, val)) nidx[isz++] = val;
2876             }
2877           }
2878         }
2879       }
2880       PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, isz, nidx, PETSC_COPY_VALUES, (is + i)));
2881     } else {
2882       /* Enter these into the temp arrays. I.e., mark table[row], enter row into new index */
2883       for (j = 0; j < n; ++j) {
2884         if (!PetscBTLookupSet(table, idx[j])) nidx[isz++] = idx[j];
2885       }
2886       PetscCall(ISRestoreIndices(is[i], &idx));
2887       PetscCall(ISDestroy(&is[i]));
2888 
2889       k = 0;
2890       for (j = 0; j < ov; j++) { /* for each overlap */
2891         n = isz;
2892         for (; k < n; k++) { /* do only those rows in nidx[k], which are not done yet */
2893           row   = nidx[k];
2894           start = ai[row];
2895           end   = ai[row + 1];
2896           for (l = start; l < end; l++) {
2897             val = aj[l];
2898             if (!PetscBTLookupSet(table, val)) nidx[isz++] = val;
2899           }
2900         }
2901       }
2902       PetscCall(ISCreateGeneral(PETSC_COMM_SELF, isz, nidx, PETSC_COPY_VALUES, (is + i)));
2903     }
2904   }
2905   PetscCall(PetscBTDestroy(&table));
2906   PetscCall(PetscFree(nidx));
2907   PetscFunctionReturn(PETSC_SUCCESS);
2908 }
2909 
2910 static PetscErrorCode MatPermute_SeqAIJ(Mat A, IS rowp, IS colp, Mat *B)
2911 {
2912   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
2913   PetscInt        i, nz = 0, m = A->rmap->n, n = A->cmap->n;
2914   const PetscInt *row, *col;
2915   PetscInt       *cnew, j, *lens;
2916   IS              icolp, irowp;
2917   PetscInt       *cwork = NULL;
2918   PetscScalar    *vwork = NULL;
2919 
2920   PetscFunctionBegin;
2921   PetscCall(ISInvertPermutation(rowp, PETSC_DECIDE, &irowp));
2922   PetscCall(ISGetIndices(irowp, &row));
2923   PetscCall(ISInvertPermutation(colp, PETSC_DECIDE, &icolp));
2924   PetscCall(ISGetIndices(icolp, &col));
2925 
2926   /* determine lengths of permuted rows */
2927   PetscCall(PetscMalloc1(m + 1, &lens));
2928   for (i = 0; i < m; i++) lens[row[i]] = a->i[i + 1] - a->i[i];
2929   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), B));
2930   PetscCall(MatSetSizes(*B, m, n, m, n));
2931   PetscCall(MatSetBlockSizesFromMats(*B, A, A));
2932   PetscCall(MatSetType(*B, ((PetscObject)A)->type_name));
2933   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*B, 0, lens));
2934   PetscCall(PetscFree(lens));
2935 
2936   PetscCall(PetscMalloc1(n, &cnew));
2937   for (i = 0; i < m; i++) {
2938     PetscCall(MatGetRow_SeqAIJ(A, i, &nz, &cwork, &vwork));
2939     for (j = 0; j < nz; j++) cnew[j] = col[cwork[j]];
2940     PetscCall(MatSetValues_SeqAIJ(*B, 1, &row[i], nz, cnew, vwork, INSERT_VALUES));
2941     PetscCall(MatRestoreRow_SeqAIJ(A, i, &nz, &cwork, &vwork));
2942   }
2943   PetscCall(PetscFree(cnew));
2944 
2945   (*B)->assembled = PETSC_FALSE;
2946 
2947 #if defined(PETSC_HAVE_DEVICE)
2948   PetscCall(MatBindToCPU(*B, A->boundtocpu));
2949 #endif
2950   PetscCall(MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY));
2951   PetscCall(MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY));
2952   PetscCall(ISRestoreIndices(irowp, &row));
2953   PetscCall(ISRestoreIndices(icolp, &col));
2954   PetscCall(ISDestroy(&irowp));
2955   PetscCall(ISDestroy(&icolp));
2956   if (rowp == colp) PetscCall(MatPropagateSymmetryOptions(A, *B));
2957   PetscFunctionReturn(PETSC_SUCCESS);
2958 }
2959 
2960 PetscErrorCode MatCopy_SeqAIJ(Mat A, Mat B, MatStructure str)
2961 {
2962   PetscFunctionBegin;
2963   /* If the two matrices have the same copy implementation, use fast copy. */
2964   if (str == SAME_NONZERO_PATTERN && (A->ops->copy == B->ops->copy)) {
2965     Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
2966     Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;
2967     const PetscScalar *aa;
2968 
2969     PetscCall(MatSeqAIJGetArrayRead(A, &aa));
2970     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]);
2971     PetscCall(PetscArraycpy(b->a, aa, a->i[A->rmap->n]));
2972     PetscCall(PetscObjectStateIncrease((PetscObject)B));
2973     PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
2974   } else {
2975     PetscCall(MatCopy_Basic(A, B, str));
2976   }
2977   PetscFunctionReturn(PETSC_SUCCESS);
2978 }
2979 
2980 PETSC_INTERN PetscErrorCode MatSeqAIJGetArray_SeqAIJ(Mat A, PetscScalar *array[])
2981 {
2982   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
2983 
2984   PetscFunctionBegin;
2985   *array = a->a;
2986   PetscFunctionReturn(PETSC_SUCCESS);
2987 }
2988 
2989 PETSC_INTERN PetscErrorCode MatSeqAIJRestoreArray_SeqAIJ(Mat A, PetscScalar *array[])
2990 {
2991   PetscFunctionBegin;
2992   *array = NULL;
2993   PetscFunctionReturn(PETSC_SUCCESS);
2994 }
2995 
2996 /*
2997    Computes the number of nonzeros per row needed for preallocation when X and Y
2998    have different nonzero structure.
2999 */
3000 PetscErrorCode MatAXPYGetPreallocation_SeqX_private(PetscInt m, const PetscInt *xi, const PetscInt *xj, const PetscInt *yi, const PetscInt *yj, PetscInt *nnz)
3001 {
3002   PetscInt i, j, k, nzx, nzy;
3003 
3004   PetscFunctionBegin;
3005   /* Set the number of nonzeros in the new matrix */
3006   for (i = 0; i < m; i++) {
3007     const PetscInt *xjj = PetscSafePointerPlusOffset(xj, xi[i]), *yjj = PetscSafePointerPlusOffset(yj, yi[i]);
3008     nzx    = xi[i + 1] - xi[i];
3009     nzy    = yi[i + 1] - yi[i];
3010     nnz[i] = 0;
3011     for (j = 0, k = 0; j < nzx; j++) {                  /* Point in X */
3012       for (; k < nzy && yjj[k] < xjj[j]; k++) nnz[i]++; /* Catch up to X */
3013       if (k < nzy && yjj[k] == xjj[j]) k++;             /* Skip duplicate */
3014       nnz[i]++;
3015     }
3016     for (; k < nzy; k++) nnz[i]++;
3017   }
3018   PetscFunctionReturn(PETSC_SUCCESS);
3019 }
3020 
3021 PetscErrorCode MatAXPYGetPreallocation_SeqAIJ(Mat Y, Mat X, PetscInt *nnz)
3022 {
3023   PetscInt    m = Y->rmap->N;
3024   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data;
3025   Mat_SeqAIJ *y = (Mat_SeqAIJ *)Y->data;
3026 
3027   PetscFunctionBegin;
3028   /* Set the number of nonzeros in the new matrix */
3029   PetscCall(MatAXPYGetPreallocation_SeqX_private(m, x->i, x->j, y->i, y->j, nnz));
3030   PetscFunctionReturn(PETSC_SUCCESS);
3031 }
3032 
3033 PetscErrorCode MatAXPY_SeqAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
3034 {
3035   Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data, *y = (Mat_SeqAIJ *)Y->data;
3036 
3037   PetscFunctionBegin;
3038   if (str == UNKNOWN_NONZERO_PATTERN || (PetscDefined(USE_DEBUG) && str == SAME_NONZERO_PATTERN)) {
3039     PetscBool e = x->nz == y->nz ? PETSC_TRUE : PETSC_FALSE;
3040     if (e) {
3041       PetscCall(PetscArraycmp(x->i, y->i, Y->rmap->n + 1, &e));
3042       if (e) {
3043         PetscCall(PetscArraycmp(x->j, y->j, y->nz, &e));
3044         if (e) str = SAME_NONZERO_PATTERN;
3045       }
3046     }
3047     if (!e) PetscCheck(str != SAME_NONZERO_PATTERN, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MatStructure is not SAME_NONZERO_PATTERN");
3048   }
3049   if (str == SAME_NONZERO_PATTERN) {
3050     const PetscScalar *xa;
3051     PetscScalar       *ya, alpha = a;
3052     PetscBLASInt       one = 1, bnz;
3053 
3054     PetscCall(PetscBLASIntCast(x->nz, &bnz));
3055     PetscCall(MatSeqAIJGetArray(Y, &ya));
3056     PetscCall(MatSeqAIJGetArrayRead(X, &xa));
3057     PetscCallBLAS("BLASaxpy", BLASaxpy_(&bnz, &alpha, xa, &one, ya, &one));
3058     PetscCall(MatSeqAIJRestoreArrayRead(X, &xa));
3059     PetscCall(MatSeqAIJRestoreArray(Y, &ya));
3060     PetscCall(PetscLogFlops(2.0 * bnz));
3061     PetscCall(MatSeqAIJInvalidateDiagonal(Y));
3062     PetscCall(PetscObjectStateIncrease((PetscObject)Y));
3063   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
3064     PetscCall(MatAXPY_Basic(Y, a, X, str));
3065   } else {
3066     Mat       B;
3067     PetscInt *nnz;
3068     PetscCall(PetscMalloc1(Y->rmap->N, &nnz));
3069     PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
3070     PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
3071     PetscCall(MatSetLayouts(B, Y->rmap, Y->cmap));
3072     PetscCall(MatSetType(B, ((PetscObject)Y)->type_name));
3073     PetscCall(MatAXPYGetPreallocation_SeqAIJ(Y, X, nnz));
3074     PetscCall(MatSeqAIJSetPreallocation(B, 0, nnz));
3075     PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));
3076     PetscCall(MatHeaderMerge(Y, &B));
3077     PetscCall(MatSeqAIJCheckInode(Y));
3078     PetscCall(PetscFree(nnz));
3079   }
3080   PetscFunctionReturn(PETSC_SUCCESS);
3081 }
3082 
3083 PETSC_INTERN PetscErrorCode MatConjugate_SeqAIJ(Mat mat)
3084 {
3085 #if defined(PETSC_USE_COMPLEX)
3086   Mat_SeqAIJ  *aij = (Mat_SeqAIJ *)mat->data;
3087   PetscInt     i, nz;
3088   PetscScalar *a;
3089 
3090   PetscFunctionBegin;
3091   nz = aij->nz;
3092   PetscCall(MatSeqAIJGetArray(mat, &a));
3093   for (i = 0; i < nz; i++) a[i] = PetscConj(a[i]);
3094   PetscCall(MatSeqAIJRestoreArray(mat, &a));
3095 #else
3096   PetscFunctionBegin;
3097 #endif
3098   PetscFunctionReturn(PETSC_SUCCESS);
3099 }
3100 
3101 static PetscErrorCode MatGetRowMaxAbs_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3102 {
3103   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3104   PetscInt         i, j, m = A->rmap->n, *ai, *aj, ncols, n;
3105   PetscReal        atmp;
3106   PetscScalar     *x;
3107   const MatScalar *aa, *av;
3108 
3109   PetscFunctionBegin;
3110   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3111   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3112   aa = av;
3113   ai = a->i;
3114   aj = a->j;
3115 
3116   PetscCall(VecSet(v, 0.0));
3117   PetscCall(VecGetArrayWrite(v, &x));
3118   PetscCall(VecGetLocalSize(v, &n));
3119   PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
3120   for (i = 0; i < m; i++) {
3121     ncols = ai[1] - ai[0];
3122     ai++;
3123     for (j = 0; j < ncols; j++) {
3124       atmp = PetscAbsScalar(*aa);
3125       if (PetscAbsScalar(x[i]) < atmp) {
3126         x[i] = atmp;
3127         if (idx) idx[i] = *aj;
3128       }
3129       aa++;
3130       aj++;
3131     }
3132   }
3133   PetscCall(VecRestoreArrayWrite(v, &x));
3134   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
3135   PetscFunctionReturn(PETSC_SUCCESS);
3136 }
3137 
3138 static PetscErrorCode MatGetRowMax_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3139 {
3140   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3141   PetscInt         i, j, m = A->rmap->n, *ai, *aj, ncols, n;
3142   PetscScalar     *x;
3143   const MatScalar *aa, *av;
3144 
3145   PetscFunctionBegin;
3146   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3147   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3148   aa = av;
3149   ai = a->i;
3150   aj = a->j;
3151 
3152   PetscCall(VecSet(v, 0.0));
3153   PetscCall(VecGetArrayWrite(v, &x));
3154   PetscCall(VecGetLocalSize(v, &n));
3155   PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
3156   for (i = 0; i < m; i++) {
3157     ncols = ai[1] - ai[0];
3158     ai++;
3159     if (ncols == A->cmap->n) { /* row is dense */
3160       x[i] = *aa;
3161       if (idx) idx[i] = 0;
3162     } else { /* row is sparse so already KNOW maximum is 0.0 or higher */
3163       x[i] = 0.0;
3164       if (idx) {
3165         for (j = 0; j < ncols; j++) { /* find first implicit 0.0 in the row */
3166           if (aj[j] > j) {
3167             idx[i] = j;
3168             break;
3169           }
3170         }
3171         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3172         if (j == ncols && j < A->cmap->n) idx[i] = j;
3173       }
3174     }
3175     for (j = 0; j < ncols; j++) {
3176       if (PetscRealPart(x[i]) < PetscRealPart(*aa)) {
3177         x[i] = *aa;
3178         if (idx) idx[i] = *aj;
3179       }
3180       aa++;
3181       aj++;
3182     }
3183   }
3184   PetscCall(VecRestoreArrayWrite(v, &x));
3185   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
3186   PetscFunctionReturn(PETSC_SUCCESS);
3187 }
3188 
3189 static PetscErrorCode MatGetRowMinAbs_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3190 {
3191   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3192   PetscInt         i, j, m = A->rmap->n, *ai, *aj, ncols, n;
3193   PetscScalar     *x;
3194   const MatScalar *aa, *av;
3195 
3196   PetscFunctionBegin;
3197   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3198   aa = av;
3199   ai = a->i;
3200   aj = a->j;
3201 
3202   PetscCall(VecSet(v, 0.0));
3203   PetscCall(VecGetArrayWrite(v, &x));
3204   PetscCall(VecGetLocalSize(v, &n));
3205   PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector, %" PetscInt_FMT " vs. %" PetscInt_FMT " rows", m, n);
3206   for (i = 0; i < m; i++) {
3207     ncols = ai[1] - ai[0];
3208     ai++;
3209     if (ncols == A->cmap->n) { /* row is dense */
3210       x[i] = *aa;
3211       if (idx) idx[i] = 0;
3212     } else { /* row is sparse so already KNOW minimum is 0.0 or higher */
3213       x[i] = 0.0;
3214       if (idx) { /* find first implicit 0.0 in the row */
3215         for (j = 0; j < ncols; j++) {
3216           if (aj[j] > j) {
3217             idx[i] = j;
3218             break;
3219           }
3220         }
3221         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3222         if (j == ncols && j < A->cmap->n) idx[i] = j;
3223       }
3224     }
3225     for (j = 0; j < ncols; j++) {
3226       if (PetscAbsScalar(x[i]) > PetscAbsScalar(*aa)) {
3227         x[i] = *aa;
3228         if (idx) idx[i] = *aj;
3229       }
3230       aa++;
3231       aj++;
3232     }
3233   }
3234   PetscCall(VecRestoreArrayWrite(v, &x));
3235   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
3236   PetscFunctionReturn(PETSC_SUCCESS);
3237 }
3238 
3239 static PetscErrorCode MatGetRowMin_SeqAIJ(Mat A, Vec v, PetscInt idx[])
3240 {
3241   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
3242   PetscInt         i, j, m = A->rmap->n, ncols, n;
3243   const PetscInt  *ai, *aj;
3244   PetscScalar     *x;
3245   const MatScalar *aa, *av;
3246 
3247   PetscFunctionBegin;
3248   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3249   PetscCall(MatSeqAIJGetArrayRead(A, &av));
3250   aa = av;
3251   ai = a->i;
3252   aj = a->j;
3253 
3254   PetscCall(VecSet(v, 0.0));
3255   PetscCall(VecGetArrayWrite(v, &x));
3256   PetscCall(VecGetLocalSize(v, &n));
3257   PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
3258   for (i = 0; i < m; i++) {
3259     ncols = ai[1] - ai[0];
3260     ai++;
3261     if (ncols == A->cmap->n) { /* row is dense */
3262       x[i] = *aa;
3263       if (idx) idx[i] = 0;
3264     } else { /* row is sparse so already KNOW minimum is 0.0 or lower */
3265       x[i] = 0.0;
3266       if (idx) { /* find first implicit 0.0 in the row */
3267         for (j = 0; j < ncols; j++) {
3268           if (aj[j] > j) {
3269             idx[i] = j;
3270             break;
3271           }
3272         }
3273         /* in case first implicit 0.0 in the row occurs at ncols-th column */
3274         if (j == ncols && j < A->cmap->n) idx[i] = j;
3275       }
3276     }
3277     for (j = 0; j < ncols; j++) {
3278       if (PetscRealPart(x[i]) > PetscRealPart(*aa)) {
3279         x[i] = *aa;
3280         if (idx) idx[i] = *aj;
3281       }
3282       aa++;
3283       aj++;
3284     }
3285   }
3286   PetscCall(VecRestoreArrayWrite(v, &x));
3287   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));
3288   PetscFunctionReturn(PETSC_SUCCESS);
3289 }
3290 
3291 static PetscErrorCode MatInvertBlockDiagonal_SeqAIJ(Mat A, const PetscScalar **values)
3292 {
3293   Mat_SeqAIJ     *a = (Mat_SeqAIJ *)A->data;
3294   PetscInt        i, bs = PetscAbs(A->rmap->bs), mbs = A->rmap->n / bs, ipvt[5], bs2 = bs * bs, *v_pivots, ij[7], *IJ, j;
3295   MatScalar      *diag, work[25], *v_work;
3296   const PetscReal shift = 0.0;
3297   PetscBool       allowzeropivot, zeropivotdetected = PETSC_FALSE;
3298 
3299   PetscFunctionBegin;
3300   allowzeropivot = PetscNot(A->erroriffailure);
3301   if (a->ibdiagvalid) {
3302     if (values) *values = a->ibdiag;
3303     PetscFunctionReturn(PETSC_SUCCESS);
3304   }
3305   PetscCall(MatMarkDiagonal_SeqAIJ(A));
3306   if (!a->ibdiag) { PetscCall(PetscMalloc1(bs2 * mbs, &a->ibdiag)); }
3307   diag = a->ibdiag;
3308   if (values) *values = a->ibdiag;
3309   /* factor and invert each block */
3310   switch (bs) {
3311   case 1:
3312     for (i = 0; i < mbs; i++) {
3313       PetscCall(MatGetValues(A, 1, &i, 1, &i, diag + i));
3314       if (PetscAbsScalar(diag[i] + shift) < PETSC_MACHINE_EPSILON) {
3315         if (allowzeropivot) {
3316           A->factorerrortype             = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3317           A->factorerror_zeropivot_value = PetscAbsScalar(diag[i]);
3318           A->factorerror_zeropivot_row   = i;
3319           PetscCall(PetscInfo(A, "Zero pivot, row %" PetscInt_FMT " pivot %g tolerance %g\n", i, (double)PetscAbsScalar(diag[i]), (double)PETSC_MACHINE_EPSILON));
3320         } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_MAT_LU_ZRPVT, "Zero pivot, row %" PetscInt_FMT " pivot %g tolerance %g", i, (double)PetscAbsScalar(diag[i]), (double)PETSC_MACHINE_EPSILON);
3321       }
3322       diag[i] = (PetscScalar)1.0 / (diag[i] + shift);
3323     }
3324     break;
3325   case 2:
3326     for (i = 0; i < mbs; i++) {
3327       ij[0] = 2 * i;
3328       ij[1] = 2 * i + 1;
3329       PetscCall(MatGetValues(A, 2, ij, 2, ij, diag));
3330       PetscCall(PetscKernel_A_gets_inverse_A_2(diag, shift, allowzeropivot, &zeropivotdetected));
3331       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3332       PetscCall(PetscKernel_A_gets_transpose_A_2(diag));
3333       diag += 4;
3334     }
3335     break;
3336   case 3:
3337     for (i = 0; i < mbs; i++) {
3338       ij[0] = 3 * i;
3339       ij[1] = 3 * i + 1;
3340       ij[2] = 3 * i + 2;
3341       PetscCall(MatGetValues(A, 3, ij, 3, ij, diag));
3342       PetscCall(PetscKernel_A_gets_inverse_A_3(diag, shift, allowzeropivot, &zeropivotdetected));
3343       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3344       PetscCall(PetscKernel_A_gets_transpose_A_3(diag));
3345       diag += 9;
3346     }
3347     break;
3348   case 4:
3349     for (i = 0; i < mbs; i++) {
3350       ij[0] = 4 * i;
3351       ij[1] = 4 * i + 1;
3352       ij[2] = 4 * i + 2;
3353       ij[3] = 4 * i + 3;
3354       PetscCall(MatGetValues(A, 4, ij, 4, ij, diag));
3355       PetscCall(PetscKernel_A_gets_inverse_A_4(diag, shift, allowzeropivot, &zeropivotdetected));
3356       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3357       PetscCall(PetscKernel_A_gets_transpose_A_4(diag));
3358       diag += 16;
3359     }
3360     break;
3361   case 5:
3362     for (i = 0; i < mbs; i++) {
3363       ij[0] = 5 * i;
3364       ij[1] = 5 * i + 1;
3365       ij[2] = 5 * i + 2;
3366       ij[3] = 5 * i + 3;
3367       ij[4] = 5 * i + 4;
3368       PetscCall(MatGetValues(A, 5, ij, 5, ij, diag));
3369       PetscCall(PetscKernel_A_gets_inverse_A_5(diag, ipvt, work, shift, allowzeropivot, &zeropivotdetected));
3370       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3371       PetscCall(PetscKernel_A_gets_transpose_A_5(diag));
3372       diag += 25;
3373     }
3374     break;
3375   case 6:
3376     for (i = 0; i < mbs; i++) {
3377       ij[0] = 6 * i;
3378       ij[1] = 6 * i + 1;
3379       ij[2] = 6 * i + 2;
3380       ij[3] = 6 * i + 3;
3381       ij[4] = 6 * i + 4;
3382       ij[5] = 6 * i + 5;
3383       PetscCall(MatGetValues(A, 6, ij, 6, ij, diag));
3384       PetscCall(PetscKernel_A_gets_inverse_A_6(diag, shift, allowzeropivot, &zeropivotdetected));
3385       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3386       PetscCall(PetscKernel_A_gets_transpose_A_6(diag));
3387       diag += 36;
3388     }
3389     break;
3390   case 7:
3391     for (i = 0; i < mbs; i++) {
3392       ij[0] = 7 * i;
3393       ij[1] = 7 * i + 1;
3394       ij[2] = 7 * i + 2;
3395       ij[3] = 7 * i + 3;
3396       ij[4] = 7 * i + 4;
3397       ij[5] = 7 * i + 5;
3398       ij[6] = 7 * i + 6;
3399       PetscCall(MatGetValues(A, 7, ij, 7, ij, diag));
3400       PetscCall(PetscKernel_A_gets_inverse_A_7(diag, shift, allowzeropivot, &zeropivotdetected));
3401       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3402       PetscCall(PetscKernel_A_gets_transpose_A_7(diag));
3403       diag += 49;
3404     }
3405     break;
3406   default:
3407     PetscCall(PetscMalloc3(bs, &v_work, bs, &v_pivots, bs, &IJ));
3408     for (i = 0; i < mbs; i++) {
3409       for (j = 0; j < bs; j++) IJ[j] = bs * i + j;
3410       PetscCall(MatGetValues(A, bs, IJ, bs, IJ, diag));
3411       PetscCall(PetscKernel_A_gets_inverse_A(bs, diag, v_pivots, v_work, allowzeropivot, &zeropivotdetected));
3412       if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3413       PetscCall(PetscKernel_A_gets_transpose_A_N(diag, bs));
3414       diag += bs2;
3415     }
3416     PetscCall(PetscFree3(v_work, v_pivots, IJ));
3417   }
3418   a->ibdiagvalid = PETSC_TRUE;
3419   PetscFunctionReturn(PETSC_SUCCESS);
3420 }
3421 
3422 static PetscErrorCode MatSetRandom_SeqAIJ(Mat x, PetscRandom rctx)
3423 {
3424   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)x->data;
3425   PetscScalar a, *aa;
3426   PetscInt    m, n, i, j, col;
3427 
3428   PetscFunctionBegin;
3429   if (!x->assembled) {
3430     PetscCall(MatGetSize(x, &m, &n));
3431     for (i = 0; i < m; i++) {
3432       for (j = 0; j < aij->imax[i]; j++) {
3433         PetscCall(PetscRandomGetValue(rctx, &a));
3434         col = (PetscInt)(n * PetscRealPart(a));
3435         PetscCall(MatSetValues(x, 1, &i, 1, &col, &a, ADD_VALUES));
3436       }
3437     }
3438   } else {
3439     PetscCall(MatSeqAIJGetArrayWrite(x, &aa));
3440     for (i = 0; i < aij->nz; i++) PetscCall(PetscRandomGetValue(rctx, aa + i));
3441     PetscCall(MatSeqAIJRestoreArrayWrite(x, &aa));
3442   }
3443   PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
3444   PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
3445   PetscFunctionReturn(PETSC_SUCCESS);
3446 }
3447 
3448 /* Like MatSetRandom_SeqAIJ, but do not set values on columns in range of [low, high) */
3449 PetscErrorCode MatSetRandomSkipColumnRange_SeqAIJ_Private(Mat x, PetscInt low, PetscInt high, PetscRandom rctx)
3450 {
3451   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)x->data;
3452   PetscScalar a;
3453   PetscInt    m, n, i, j, col, nskip;
3454 
3455   PetscFunctionBegin;
3456   nskip = high - low;
3457   PetscCall(MatGetSize(x, &m, &n));
3458   n -= nskip; /* shrink number of columns where nonzeros can be set */
3459   for (i = 0; i < m; i++) {
3460     for (j = 0; j < aij->imax[i]; j++) {
3461       PetscCall(PetscRandomGetValue(rctx, &a));
3462       col = (PetscInt)(n * PetscRealPart(a));
3463       if (col >= low) col += nskip; /* shift col rightward to skip the hole */
3464       PetscCall(MatSetValues(x, 1, &i, 1, &col, &a, ADD_VALUES));
3465     }
3466   }
3467   PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
3468   PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
3469   PetscFunctionReturn(PETSC_SUCCESS);
3470 }
3471 
3472 static struct _MatOps MatOps_Values = {MatSetValues_SeqAIJ,
3473                                        MatGetRow_SeqAIJ,
3474                                        MatRestoreRow_SeqAIJ,
3475                                        MatMult_SeqAIJ,
3476                                        /*  4*/ MatMultAdd_SeqAIJ,
3477                                        MatMultTranspose_SeqAIJ,
3478                                        MatMultTransposeAdd_SeqAIJ,
3479                                        NULL,
3480                                        NULL,
3481                                        NULL,
3482                                        /* 10*/ NULL,
3483                                        MatLUFactor_SeqAIJ,
3484                                        NULL,
3485                                        MatSOR_SeqAIJ,
3486                                        MatTranspose_SeqAIJ,
3487                                        /*1 5*/ MatGetInfo_SeqAIJ,
3488                                        MatEqual_SeqAIJ,
3489                                        MatGetDiagonal_SeqAIJ,
3490                                        MatDiagonalScale_SeqAIJ,
3491                                        MatNorm_SeqAIJ,
3492                                        /* 20*/ NULL,
3493                                        MatAssemblyEnd_SeqAIJ,
3494                                        MatSetOption_SeqAIJ,
3495                                        MatZeroEntries_SeqAIJ,
3496                                        /* 24*/ MatZeroRows_SeqAIJ,
3497                                        NULL,
3498                                        NULL,
3499                                        NULL,
3500                                        NULL,
3501                                        /* 29*/ MatSetUp_Seq_Hash,
3502                                        NULL,
3503                                        NULL,
3504                                        NULL,
3505                                        NULL,
3506                                        /* 34*/ MatDuplicate_SeqAIJ,
3507                                        NULL,
3508                                        NULL,
3509                                        MatILUFactor_SeqAIJ,
3510                                        NULL,
3511                                        /* 39*/ MatAXPY_SeqAIJ,
3512                                        MatCreateSubMatrices_SeqAIJ,
3513                                        MatIncreaseOverlap_SeqAIJ,
3514                                        MatGetValues_SeqAIJ,
3515                                        MatCopy_SeqAIJ,
3516                                        /* 44*/ MatGetRowMax_SeqAIJ,
3517                                        MatScale_SeqAIJ,
3518                                        MatShift_SeqAIJ,
3519                                        MatDiagonalSet_SeqAIJ,
3520                                        MatZeroRowsColumns_SeqAIJ,
3521                                        /* 49*/ MatSetRandom_SeqAIJ,
3522                                        MatGetRowIJ_SeqAIJ,
3523                                        MatRestoreRowIJ_SeqAIJ,
3524                                        MatGetColumnIJ_SeqAIJ,
3525                                        MatRestoreColumnIJ_SeqAIJ,
3526                                        /* 54*/ MatFDColoringCreate_SeqXAIJ,
3527                                        NULL,
3528                                        NULL,
3529                                        MatPermute_SeqAIJ,
3530                                        NULL,
3531                                        /* 59*/ NULL,
3532                                        MatDestroy_SeqAIJ,
3533                                        MatView_SeqAIJ,
3534                                        NULL,
3535                                        NULL,
3536                                        /* 64*/ NULL,
3537                                        MatMatMatMultNumeric_SeqAIJ_SeqAIJ_SeqAIJ,
3538                                        NULL,
3539                                        NULL,
3540                                        NULL,
3541                                        /* 69*/ MatGetRowMaxAbs_SeqAIJ,
3542                                        MatGetRowMinAbs_SeqAIJ,
3543                                        NULL,
3544                                        NULL,
3545                                        NULL,
3546                                        /* 74*/ NULL,
3547                                        MatFDColoringApply_AIJ,
3548                                        NULL,
3549                                        NULL,
3550                                        NULL,
3551                                        /* 79*/ MatFindZeroDiagonals_SeqAIJ,
3552                                        NULL,
3553                                        NULL,
3554                                        NULL,
3555                                        MatLoad_SeqAIJ,
3556                                        /* 84*/ MatIsSymmetric_SeqAIJ,
3557                                        MatIsHermitian_SeqAIJ,
3558                                        NULL,
3559                                        NULL,
3560                                        NULL,
3561                                        /* 89*/ NULL,
3562                                        NULL,
3563                                        MatMatMultNumeric_SeqAIJ_SeqAIJ,
3564                                        NULL,
3565                                        NULL,
3566                                        /* 94*/ MatPtAPNumeric_SeqAIJ_SeqAIJ_SparseAxpy,
3567                                        NULL,
3568                                        NULL,
3569                                        MatMatTransposeMultNumeric_SeqAIJ_SeqAIJ,
3570                                        NULL,
3571                                        /* 99*/ MatProductSetFromOptions_SeqAIJ,
3572                                        NULL,
3573                                        NULL,
3574                                        MatConjugate_SeqAIJ,
3575                                        NULL,
3576                                        /*104*/ MatSetValuesRow_SeqAIJ,
3577                                        MatRealPart_SeqAIJ,
3578                                        MatImaginaryPart_SeqAIJ,
3579                                        NULL,
3580                                        NULL,
3581                                        /*109*/ MatMatSolve_SeqAIJ,
3582                                        NULL,
3583                                        MatGetRowMin_SeqAIJ,
3584                                        NULL,
3585                                        MatMissingDiagonal_SeqAIJ,
3586                                        /*114*/ NULL,
3587                                        NULL,
3588                                        NULL,
3589                                        NULL,
3590                                        NULL,
3591                                        /*119*/ NULL,
3592                                        NULL,
3593                                        NULL,
3594                                        NULL,
3595                                        MatGetMultiProcBlock_SeqAIJ,
3596                                        /*124*/ MatFindNonzeroRows_SeqAIJ,
3597                                        MatGetColumnReductions_SeqAIJ,
3598                                        MatInvertBlockDiagonal_SeqAIJ,
3599                                        MatInvertVariableBlockDiagonal_SeqAIJ,
3600                                        NULL,
3601                                        /*129*/ NULL,
3602                                        NULL,
3603                                        NULL,
3604                                        MatTransposeMatMultNumeric_SeqAIJ_SeqAIJ,
3605                                        MatTransposeColoringCreate_SeqAIJ,
3606                                        /*134*/ MatTransColoringApplySpToDen_SeqAIJ,
3607                                        MatTransColoringApplyDenToSp_SeqAIJ,
3608                                        NULL,
3609                                        NULL,
3610                                        MatRARtNumeric_SeqAIJ_SeqAIJ,
3611                                        /*139*/ NULL,
3612                                        NULL,
3613                                        NULL,
3614                                        MatFDColoringSetUp_SeqXAIJ,
3615                                        MatFindOffBlockDiagonalEntries_SeqAIJ,
3616                                        MatCreateMPIMatConcatenateSeqMat_SeqAIJ,
3617                                        /*145*/ MatDestroySubMatrices_SeqAIJ,
3618                                        NULL,
3619                                        NULL,
3620                                        MatCreateGraph_Simple_AIJ,
3621                                        NULL,
3622                                        /*150*/ MatTransposeSymbolic_SeqAIJ,
3623                                        MatEliminateZeros_SeqAIJ};
3624 
3625 static PetscErrorCode MatSeqAIJSetColumnIndices_SeqAIJ(Mat mat, PetscInt *indices)
3626 {
3627   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3628   PetscInt    i, nz, n;
3629 
3630   PetscFunctionBegin;
3631   nz = aij->maxnz;
3632   n  = mat->rmap->n;
3633   for (i = 0; i < nz; i++) aij->j[i] = indices[i];
3634   aij->nz = nz;
3635   for (i = 0; i < n; i++) aij->ilen[i] = aij->imax[i];
3636   PetscFunctionReturn(PETSC_SUCCESS);
3637 }
3638 
3639 /*
3640  * Given a sparse matrix with global column indices, compact it by using a local column space.
3641  * The result matrix helps saving memory in other algorithms, such as MatPtAPSymbolic_MPIAIJ_MPIAIJ_scalable()
3642  */
3643 PetscErrorCode MatSeqAIJCompactOutExtraColumns_SeqAIJ(Mat mat, ISLocalToGlobalMapping *mapping)
3644 {
3645   Mat_SeqAIJ   *aij = (Mat_SeqAIJ *)mat->data;
3646   PetscHMapI    gid1_lid1;
3647   PetscHashIter tpos;
3648   PetscInt      gid, lid, i, ec, nz = aij->nz;
3649   PetscInt     *garray, *jj = aij->j;
3650 
3651   PetscFunctionBegin;
3652   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3653   PetscAssertPointer(mapping, 2);
3654   /* use a table */
3655   PetscCall(PetscHMapICreateWithSize(mat->rmap->n, &gid1_lid1));
3656   ec = 0;
3657   for (i = 0; i < nz; i++) {
3658     PetscInt data, gid1 = jj[i] + 1;
3659     PetscCall(PetscHMapIGetWithDefault(gid1_lid1, gid1, 0, &data));
3660     if (!data) {
3661       /* one based table */
3662       PetscCall(PetscHMapISet(gid1_lid1, gid1, ++ec));
3663     }
3664   }
3665   /* form array of columns we need */
3666   PetscCall(PetscMalloc1(ec, &garray));
3667   PetscHashIterBegin(gid1_lid1, tpos);
3668   while (!PetscHashIterAtEnd(gid1_lid1, tpos)) {
3669     PetscHashIterGetKey(gid1_lid1, tpos, gid);
3670     PetscHashIterGetVal(gid1_lid1, tpos, lid);
3671     PetscHashIterNext(gid1_lid1, tpos);
3672     gid--;
3673     lid--;
3674     garray[lid] = gid;
3675   }
3676   PetscCall(PetscSortInt(ec, garray)); /* sort, and rebuild */
3677   PetscCall(PetscHMapIClear(gid1_lid1));
3678   for (i = 0; i < ec; i++) PetscCall(PetscHMapISet(gid1_lid1, garray[i] + 1, i + 1));
3679   /* compact out the extra columns in B */
3680   for (i = 0; i < nz; i++) {
3681     PetscInt gid1 = jj[i] + 1;
3682     PetscCall(PetscHMapIGetWithDefault(gid1_lid1, gid1, 0, &lid));
3683     lid--;
3684     jj[i] = lid;
3685   }
3686   PetscCall(PetscLayoutDestroy(&mat->cmap));
3687   PetscCall(PetscHMapIDestroy(&gid1_lid1));
3688   PetscCall(PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)mat), ec, ec, 1, &mat->cmap));
3689   PetscCall(ISLocalToGlobalMappingCreate(PETSC_COMM_SELF, mat->cmap->bs, mat->cmap->n, garray, PETSC_OWN_POINTER, mapping));
3690   PetscCall(ISLocalToGlobalMappingSetType(*mapping, ISLOCALTOGLOBALMAPPINGHASH));
3691   PetscFunctionReturn(PETSC_SUCCESS);
3692 }
3693 
3694 /*@
3695   MatSeqAIJSetColumnIndices - Set the column indices for all the rows
3696   in the matrix.
3697 
3698   Input Parameters:
3699 + mat     - the `MATSEQAIJ` matrix
3700 - indices - the column indices
3701 
3702   Level: advanced
3703 
3704   Notes:
3705   This can be called if you have precomputed the nonzero structure of the
3706   matrix and want to provide it to the matrix object to improve the performance
3707   of the `MatSetValues()` operation.
3708 
3709   You MUST have set the correct numbers of nonzeros per row in the call to
3710   `MatCreateSeqAIJ()`, and the columns indices MUST be sorted.
3711 
3712   MUST be called before any calls to `MatSetValues()`
3713 
3714   The indices should start with zero, not one.
3715 
3716 .seealso: [](ch_matrices), `Mat`, `MATSEQAIJ`
3717 @*/
3718 PetscErrorCode MatSeqAIJSetColumnIndices(Mat mat, PetscInt *indices)
3719 {
3720   PetscFunctionBegin;
3721   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3722   PetscAssertPointer(indices, 2);
3723   PetscUseMethod(mat, "MatSeqAIJSetColumnIndices_C", (Mat, PetscInt *), (mat, indices));
3724   PetscFunctionReturn(PETSC_SUCCESS);
3725 }
3726 
3727 static PetscErrorCode MatStoreValues_SeqAIJ(Mat mat)
3728 {
3729   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3730   size_t      nz  = aij->i[mat->rmap->n];
3731 
3732   PetscFunctionBegin;
3733   PetscCheck(aij->nonew, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");
3734 
3735   /* allocate space for values if not already there */
3736   if (!aij->saved_values) { PetscCall(PetscMalloc1(nz + 1, &aij->saved_values)); }
3737 
3738   /* copy values over */
3739   PetscCall(PetscArraycpy(aij->saved_values, aij->a, nz));
3740   PetscFunctionReturn(PETSC_SUCCESS);
3741 }
3742 
3743 /*@
3744   MatStoreValues - Stashes a copy of the matrix values; this allows reusing of the linear part of a Jacobian, while recomputing only the
3745   nonlinear portion.
3746 
3747   Logically Collect
3748 
3749   Input Parameter:
3750 . mat - the matrix (currently only `MATAIJ` matrices support this option)
3751 
3752   Level: advanced
3753 
3754   Example Usage:
3755 .vb
3756     Using SNES
3757     Create Jacobian matrix
3758     Set linear terms into matrix
3759     Apply boundary conditions to matrix, at this time matrix must have
3760       final nonzero structure (i.e. setting the nonlinear terms and applying
3761       boundary conditions again will not change the nonzero structure
3762     MatSetOption(mat, MAT_NEW_NONZERO_LOCATIONS, PETSC_FALSE);
3763     MatStoreValues(mat);
3764     Call SNESSetJacobian() with matrix
3765     In your Jacobian routine
3766       MatRetrieveValues(mat);
3767       Set nonlinear terms in matrix
3768 
3769     Without `SNESSolve()`, i.e. when you handle nonlinear solve yourself:
3770     // build linear portion of Jacobian
3771     MatSetOption(mat, MAT_NEW_NONZERO_LOCATIONS, PETSC_FALSE);
3772     MatStoreValues(mat);
3773     loop over nonlinear iterations
3774        MatRetrieveValues(mat);
3775        // call MatSetValues(mat,...) to set nonliner portion of Jacobian
3776        // call MatAssemblyBegin/End() on matrix
3777        Solve linear system with Jacobian
3778     endloop
3779 .ve
3780 
3781   Notes:
3782   Matrix must already be assembled before calling this routine
3783   Must set the matrix option `MatSetOption`(mat,`MAT_NEW_NONZERO_LOCATIONS`,`PETSC_FALSE`); before
3784   calling this routine.
3785 
3786   When this is called multiple times it overwrites the previous set of stored values
3787   and does not allocated additional space.
3788 
3789 .seealso: [](ch_matrices), `Mat`, `MatRetrieveValues()`
3790 @*/
3791 PetscErrorCode MatStoreValues(Mat mat)
3792 {
3793   PetscFunctionBegin;
3794   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3795   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3796   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3797   PetscUseMethod(mat, "MatStoreValues_C", (Mat), (mat));
3798   PetscFunctionReturn(PETSC_SUCCESS);
3799 }
3800 
3801 static PetscErrorCode MatRetrieveValues_SeqAIJ(Mat mat)
3802 {
3803   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
3804   PetscInt    nz  = aij->i[mat->rmap->n];
3805 
3806   PetscFunctionBegin;
3807   PetscCheck(aij->nonew, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");
3808   PetscCheck(aij->saved_values, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatStoreValues(A);first");
3809   /* copy values over */
3810   PetscCall(PetscArraycpy(aij->a, aij->saved_values, nz));
3811   PetscFunctionReturn(PETSC_SUCCESS);
3812 }
3813 
3814 /*@
3815   MatRetrieveValues - Retrieves the copy of the matrix values that was stored with `MatStoreValues()`
3816 
3817   Logically Collect
3818 
3819   Input Parameter:
3820 . mat - the matrix (currently only `MATAIJ` matrices support this option)
3821 
3822   Level: advanced
3823 
3824 .seealso: [](ch_matrices), `Mat`, `MatStoreValues()`
3825 @*/
3826 PetscErrorCode MatRetrieveValues(Mat mat)
3827 {
3828   PetscFunctionBegin;
3829   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3830   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3831   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3832   PetscUseMethod(mat, "MatRetrieveValues_C", (Mat), (mat));
3833   PetscFunctionReturn(PETSC_SUCCESS);
3834 }
3835 
3836 /*@C
3837   MatCreateSeqAIJ - Creates a sparse matrix in `MATSEQAIJ` (compressed row) format
3838   (the default parallel PETSc format).  For good matrix assembly performance
3839   the user should preallocate the matrix storage by setting the parameter `nz`
3840   (or the array `nnz`).
3841 
3842   Collective
3843 
3844   Input Parameters:
3845 + comm - MPI communicator, set to `PETSC_COMM_SELF`
3846 . m    - number of rows
3847 . n    - number of columns
3848 . nz   - number of nonzeros per row (same for all rows)
3849 - nnz  - array containing the number of nonzeros in the various rows
3850          (possibly different for each row) or NULL
3851 
3852   Output Parameter:
3853 . A - the matrix
3854 
3855   Options Database Keys:
3856 + -mat_no_inode            - Do not use inodes
3857 - -mat_inode_limit <limit> - Sets inode limit (max limit=5)
3858 
3859   Level: intermediate
3860 
3861   Notes:
3862   It is recommend to use `MatCreateFromOptions()` instead of this routine
3863 
3864   If `nnz` is given then `nz` is ignored
3865 
3866   The `MATSEQAIJ` format, also called
3867   compressed row storage, is fully compatible with standard Fortran
3868   storage.  That is, the stored row and column indices can begin at
3869   either one (as in Fortran) or zero.
3870 
3871   Specify the preallocated storage with either `nz` or `nnz` (not both).
3872   Set `nz` = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
3873   allocation.
3874 
3875   By default, this format uses inodes (identical nodes) when possible, to
3876   improve numerical efficiency of matrix-vector products and solves. We
3877   search for consecutive rows with the same nonzero structure, thereby
3878   reusing matrix information to achieve increased efficiency.
3879 
3880 .seealso: [](ch_matrices), `Mat`, [Sparse Matrix Creation](sec_matsparse), `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`
3881 @*/
3882 PetscErrorCode MatCreateSeqAIJ(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A)
3883 {
3884   PetscFunctionBegin;
3885   PetscCall(MatCreate(comm, A));
3886   PetscCall(MatSetSizes(*A, m, n, m, n));
3887   PetscCall(MatSetType(*A, MATSEQAIJ));
3888   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*A, nz, nnz));
3889   PetscFunctionReturn(PETSC_SUCCESS);
3890 }
3891 
3892 /*@C
3893   MatSeqAIJSetPreallocation - For good matrix assembly performance
3894   the user should preallocate the matrix storage by setting the parameter nz
3895   (or the array nnz).  By setting these parameters accurately, performance
3896   during matrix assembly can be increased by more than a factor of 50.
3897 
3898   Collective
3899 
3900   Input Parameters:
3901 + B   - The matrix
3902 . nz  - number of nonzeros per row (same for all rows)
3903 - nnz - array containing the number of nonzeros in the various rows
3904          (possibly different for each row) or NULL
3905 
3906   Options Database Keys:
3907 + -mat_no_inode            - Do not use inodes
3908 - -mat_inode_limit <limit> - Sets inode limit (max limit=5)
3909 
3910   Level: intermediate
3911 
3912   Notes:
3913   If `nnz` is given then `nz` is ignored
3914 
3915   The `MATSEQAIJ` format also called
3916   compressed row storage, is fully compatible with standard Fortran
3917   storage.  That is, the stored row and column indices can begin at
3918   either one (as in Fortran) or zero.  See the users' manual for details.
3919 
3920   Specify the preallocated storage with either `nz` or `nnz` (not both).
3921   Set nz = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
3922   allocation.
3923 
3924   You can call `MatGetInfo()` to get information on how effective the preallocation was;
3925   for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
3926   You can also run with the option -info and look for messages with the string
3927   malloc in them to see if additional memory allocation was needed.
3928 
3929   Developer Notes:
3930   Use nz of `MAT_SKIP_ALLOCATION` to not allocate any space for the matrix
3931   entries or columns indices
3932 
3933   By default, this format uses inodes (identical nodes) when possible, to
3934   improve numerical efficiency of matrix-vector products and solves. We
3935   search for consecutive rows with the same nonzero structure, thereby
3936   reusing matrix information to achieve increased efficiency.
3937 
3938 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`, `MatGetInfo()`,
3939           `MatSeqAIJSetTotalPreallocation()`
3940 @*/
3941 PetscErrorCode MatSeqAIJSetPreallocation(Mat B, PetscInt nz, const PetscInt nnz[])
3942 {
3943   PetscFunctionBegin;
3944   PetscValidHeaderSpecific(B, MAT_CLASSID, 1);
3945   PetscValidType(B, 1);
3946   PetscTryMethod(B, "MatSeqAIJSetPreallocation_C", (Mat, PetscInt, const PetscInt[]), (B, nz, nnz));
3947   PetscFunctionReturn(PETSC_SUCCESS);
3948 }
3949 
3950 PetscErrorCode MatSeqAIJSetPreallocation_SeqAIJ(Mat B, PetscInt nz, const PetscInt *nnz)
3951 {
3952   Mat_SeqAIJ *b              = (Mat_SeqAIJ *)B->data;
3953   PetscBool   skipallocation = PETSC_FALSE, realalloc = PETSC_FALSE;
3954   PetscInt    i;
3955 
3956   PetscFunctionBegin;
3957   if (B->hash_active) {
3958     B->ops[0] = b->cops;
3959     PetscCall(PetscHMapIJVDestroy(&b->ht));
3960     PetscCall(PetscFree(b->dnz));
3961     B->hash_active = PETSC_FALSE;
3962   }
3963   if (nz >= 0 || nnz) realalloc = PETSC_TRUE;
3964   if (nz == MAT_SKIP_ALLOCATION) {
3965     skipallocation = PETSC_TRUE;
3966     nz             = 0;
3967   }
3968   PetscCall(PetscLayoutSetUp(B->rmap));
3969   PetscCall(PetscLayoutSetUp(B->cmap));
3970 
3971   if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 5;
3972   PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nz cannot be less than 0: value %" PetscInt_FMT, nz);
3973   if (PetscUnlikelyDebug(nnz)) {
3974     for (i = 0; i < B->rmap->n; i++) {
3975       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]);
3976       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);
3977     }
3978   }
3979 
3980   B->preallocated = PETSC_TRUE;
3981   if (!skipallocation) {
3982     if (!b->imax) { PetscCall(PetscMalloc1(B->rmap->n, &b->imax)); }
3983     if (!b->ilen) {
3984       /* b->ilen will count nonzeros in each row so far. */
3985       PetscCall(PetscCalloc1(B->rmap->n, &b->ilen));
3986     } else {
3987       PetscCall(PetscMemzero(b->ilen, B->rmap->n * sizeof(PetscInt)));
3988     }
3989     if (!b->ipre) PetscCall(PetscMalloc1(B->rmap->n, &b->ipre));
3990     if (!nnz) {
3991       if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 10;
3992       else if (nz < 0) nz = 1;
3993       nz = PetscMin(nz, B->cmap->n);
3994       for (i = 0; i < B->rmap->n; i++) b->imax[i] = nz;
3995       PetscCall(PetscIntMultError(nz, B->rmap->n, &nz));
3996     } else {
3997       PetscInt64 nz64 = 0;
3998       for (i = 0; i < B->rmap->n; i++) {
3999         b->imax[i] = nnz[i];
4000         nz64 += nnz[i];
4001       }
4002       PetscCall(PetscIntCast(nz64, &nz));
4003     }
4004 
4005     /* allocate the matrix space */
4006     /* FIXME: should B's old memory be unlogged? */
4007     PetscCall(MatSeqXAIJFreeAIJ(B, &b->a, &b->j, &b->i));
4008     if (B->structure_only) {
4009       PetscCall(PetscMalloc1(nz, &b->j));
4010       PetscCall(PetscMalloc1(B->rmap->n + 1, &b->i));
4011     } else {
4012       PetscCall(PetscMalloc3(nz, &b->a, nz, &b->j, B->rmap->n + 1, &b->i));
4013     }
4014     b->i[0] = 0;
4015     for (i = 1; i < B->rmap->n + 1; i++) b->i[i] = b->i[i - 1] + b->imax[i - 1];
4016     if (B->structure_only) {
4017       b->singlemalloc = PETSC_FALSE;
4018       b->free_a       = PETSC_FALSE;
4019     } else {
4020       b->singlemalloc = PETSC_TRUE;
4021       b->free_a       = PETSC_TRUE;
4022     }
4023     b->free_ij = PETSC_TRUE;
4024   } else {
4025     b->free_a  = PETSC_FALSE;
4026     b->free_ij = PETSC_FALSE;
4027   }
4028 
4029   if (b->ipre && nnz != b->ipre && b->imax) {
4030     /* reserve user-requested sparsity */
4031     PetscCall(PetscArraycpy(b->ipre, b->imax, B->rmap->n));
4032   }
4033 
4034   b->nz               = 0;
4035   b->maxnz            = nz;
4036   B->info.nz_unneeded = (double)b->maxnz;
4037   if (realalloc) PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
4038   B->was_assembled = PETSC_FALSE;
4039   B->assembled     = PETSC_FALSE;
4040   /* We simply deem preallocation has changed nonzero state. Updating the state
4041      will give clients (like AIJKokkos) a chance to know something has happened.
4042   */
4043   B->nonzerostate++;
4044   PetscFunctionReturn(PETSC_SUCCESS);
4045 }
4046 
4047 static PetscErrorCode MatResetPreallocation_SeqAIJ(Mat A)
4048 {
4049   Mat_SeqAIJ *a;
4050   PetscInt    i;
4051   PetscBool   skipreset;
4052 
4053   PetscFunctionBegin;
4054   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
4055 
4056   /* Check local size. If zero, then return */
4057   if (!A->rmap->n) PetscFunctionReturn(PETSC_SUCCESS);
4058 
4059   a = (Mat_SeqAIJ *)A->data;
4060   /* if no saved info, we error out */
4061   PetscCheck(a->ipre, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "No saved preallocation info ");
4062 
4063   PetscCheck(a->i && a->imax && a->ilen, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Memory info is incomplete, and can not reset preallocation ");
4064 
4065   PetscCall(PetscArraycmp(a->ipre, a->ilen, A->rmap->n, &skipreset));
4066   if (!skipreset) {
4067     PetscCall(PetscArraycpy(a->imax, a->ipre, A->rmap->n));
4068     PetscCall(PetscArrayzero(a->ilen, A->rmap->n));
4069     a->i[0] = 0;
4070     for (i = 1; i < A->rmap->n + 1; i++) a->i[i] = a->i[i - 1] + a->imax[i - 1];
4071     A->preallocated     = PETSC_TRUE;
4072     a->nz               = 0;
4073     a->maxnz            = a->i[A->rmap->n];
4074     A->info.nz_unneeded = (double)a->maxnz;
4075     A->was_assembled    = PETSC_FALSE;
4076     A->assembled        = PETSC_FALSE;
4077   }
4078   PetscFunctionReturn(PETSC_SUCCESS);
4079 }
4080 
4081 /*@
4082   MatSeqAIJSetPreallocationCSR - Allocates memory for a sparse sequential matrix in `MATSEQAIJ` format.
4083 
4084   Input Parameters:
4085 + B - the matrix
4086 . i - the indices into j for the start of each row (starts with zero)
4087 . j - the column indices for each row (starts with zero) these must be sorted for each row
4088 - v - optional values in the matrix
4089 
4090   Level: developer
4091 
4092   Notes:
4093   The `i`,`j`,`v` values are COPIED with this routine; to avoid the copy use `MatCreateSeqAIJWithArrays()`
4094 
4095   This routine may be called multiple times with different nonzero patterns (or the same nonzero pattern). The nonzero
4096   structure will be the union of all the previous nonzero structures.
4097 
4098   Developer Notes:
4099   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
4100   then just copies the `v` values directly with `PetscMemcpy()`.
4101 
4102   This routine could also take a `PetscCopyMode` argument to allow sharing the values instead of always copying them.
4103 
4104 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatSeqAIJSetPreallocation()`, `MATSEQAIJ`, `MatResetPreallocation()`
4105 @*/
4106 PetscErrorCode MatSeqAIJSetPreallocationCSR(Mat B, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
4107 {
4108   PetscFunctionBegin;
4109   PetscValidHeaderSpecific(B, MAT_CLASSID, 1);
4110   PetscValidType(B, 1);
4111   PetscTryMethod(B, "MatSeqAIJSetPreallocationCSR_C", (Mat, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, i, j, v));
4112   PetscFunctionReturn(PETSC_SUCCESS);
4113 }
4114 
4115 static PetscErrorCode MatSeqAIJSetPreallocationCSR_SeqAIJ(Mat B, const PetscInt Ii[], const PetscInt J[], const PetscScalar v[])
4116 {
4117   PetscInt  i;
4118   PetscInt  m, n;
4119   PetscInt  nz;
4120   PetscInt *nnz;
4121 
4122   PetscFunctionBegin;
4123   PetscCheck(Ii[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Ii[0] must be 0 it is %" PetscInt_FMT, Ii[0]);
4124 
4125   PetscCall(PetscLayoutSetUp(B->rmap));
4126   PetscCall(PetscLayoutSetUp(B->cmap));
4127 
4128   PetscCall(MatGetSize(B, &m, &n));
4129   PetscCall(PetscMalloc1(m + 1, &nnz));
4130   for (i = 0; i < m; i++) {
4131     nz = Ii[i + 1] - Ii[i];
4132     PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Local row %" PetscInt_FMT " has a negative number of columns %" PetscInt_FMT, i, nz);
4133     nnz[i] = nz;
4134   }
4135   PetscCall(MatSeqAIJSetPreallocation(B, 0, nnz));
4136   PetscCall(PetscFree(nnz));
4137 
4138   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));
4139 
4140   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4141   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4142 
4143   PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
4144   PetscFunctionReturn(PETSC_SUCCESS);
4145 }
4146 
4147 /*@
4148   MatSeqAIJKron - Computes `C`, the Kronecker product of `A` and `B`.
4149 
4150   Input Parameters:
4151 + A     - left-hand side matrix
4152 . B     - right-hand side matrix
4153 - reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
4154 
4155   Output Parameter:
4156 . C - Kronecker product of `A` and `B`
4157 
4158   Level: intermediate
4159 
4160   Note:
4161   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the product matrix has not changed from that last call to `MatSeqAIJKron()`.
4162 
4163 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MATKAIJ`, `MatReuse`
4164 @*/
4165 PetscErrorCode MatSeqAIJKron(Mat A, Mat B, MatReuse reuse, Mat *C)
4166 {
4167   PetscFunctionBegin;
4168   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
4169   PetscValidType(A, 1);
4170   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
4171   PetscValidType(B, 2);
4172   PetscAssertPointer(C, 4);
4173   if (reuse == MAT_REUSE_MATRIX) {
4174     PetscValidHeaderSpecific(*C, MAT_CLASSID, 4);
4175     PetscValidType(*C, 4);
4176   }
4177   PetscTryMethod(A, "MatSeqAIJKron_C", (Mat, Mat, MatReuse, Mat *), (A, B, reuse, C));
4178   PetscFunctionReturn(PETSC_SUCCESS);
4179 }
4180 
4181 static PetscErrorCode MatSeqAIJKron_SeqAIJ(Mat A, Mat B, MatReuse reuse, Mat *C)
4182 {
4183   Mat                newmat;
4184   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data;
4185   Mat_SeqAIJ        *b = (Mat_SeqAIJ *)B->data;
4186   PetscScalar       *v;
4187   const PetscScalar *aa, *ba;
4188   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;
4189   PetscBool          flg;
4190 
4191   PetscFunctionBegin;
4192   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4193   PetscCheck(A->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4194   PetscCheck(!B->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4195   PetscCheck(B->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4196   PetscCall(PetscObjectTypeCompare((PetscObject)B, MATSEQAIJ, &flg));
4197   PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatType %s", ((PetscObject)B)->type_name);
4198   PetscCheck(reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatReuse %d", (int)reuse);
4199   if (reuse == MAT_INITIAL_MATRIX) {
4200     PetscCall(PetscMalloc2(am * bm + 1, &i, a->i[am] * b->i[bm], &j));
4201     PetscCall(MatCreate(PETSC_COMM_SELF, &newmat));
4202     PetscCall(MatSetSizes(newmat, am * bm, an * bn, am * bm, an * bn));
4203     PetscCall(MatSetType(newmat, MATAIJ));
4204     i[0] = 0;
4205     for (m = 0; m < am; ++m) {
4206       for (p = 0; p < bm; ++p) {
4207         i[m * bm + p + 1] = i[m * bm + p] + (a->i[m + 1] - a->i[m]) * (b->i[p + 1] - b->i[p]);
4208         for (n = a->i[m]; n < a->i[m + 1]; ++n) {
4209           for (q = b->i[p]; q < b->i[p + 1]; ++q) j[nnz++] = a->j[n] * bn + b->j[q];
4210         }
4211       }
4212     }
4213     PetscCall(MatSeqAIJSetPreallocationCSR(newmat, i, j, NULL));
4214     *C = newmat;
4215     PetscCall(PetscFree2(i, j));
4216     nnz = 0;
4217   }
4218   PetscCall(MatSeqAIJGetArray(*C, &v));
4219   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
4220   PetscCall(MatSeqAIJGetArrayRead(B, &ba));
4221   for (m = 0; m < am; ++m) {
4222     for (p = 0; p < bm; ++p) {
4223       for (n = a->i[m]; n < a->i[m + 1]; ++n) {
4224         for (q = b->i[p]; q < b->i[p + 1]; ++q) v[nnz++] = aa[n] * ba[q];
4225       }
4226     }
4227   }
4228   PetscCall(MatSeqAIJRestoreArray(*C, &v));
4229   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
4230   PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
4231   PetscFunctionReturn(PETSC_SUCCESS);
4232 }
4233 
4234 #include <../src/mat/impls/dense/seq/dense.h>
4235 #include <petsc/private/kernels/petscaxpy.h>
4236 
4237 /*
4238     Computes (B'*A')' since computing B*A directly is untenable
4239 
4240                n                       p                          p
4241         [             ]       [             ]         [                 ]
4242       m [      A      ]  *  n [       B     ]   =   m [         C       ]
4243         [             ]       [             ]         [                 ]
4244 
4245 */
4246 PetscErrorCode MatMatMultNumeric_SeqDense_SeqAIJ(Mat A, Mat B, Mat C)
4247 {
4248   Mat_SeqDense      *sub_a = (Mat_SeqDense *)A->data;
4249   Mat_SeqAIJ        *sub_b = (Mat_SeqAIJ *)B->data;
4250   Mat_SeqDense      *sub_c = (Mat_SeqDense *)C->data;
4251   PetscInt           i, j, n, m, q, p;
4252   const PetscInt    *ii, *idx;
4253   const PetscScalar *b, *a, *a_q;
4254   PetscScalar       *c, *c_q;
4255   PetscInt           clda = sub_c->lda;
4256   PetscInt           alda = sub_a->lda;
4257 
4258   PetscFunctionBegin;
4259   m = A->rmap->n;
4260   n = A->cmap->n;
4261   p = B->cmap->n;
4262   a = sub_a->v;
4263   b = sub_b->a;
4264   c = sub_c->v;
4265   if (clda == m) {
4266     PetscCall(PetscArrayzero(c, m * p));
4267   } else {
4268     for (j = 0; j < p; j++)
4269       for (i = 0; i < m; i++) c[j * clda + i] = 0.0;
4270   }
4271   ii  = sub_b->i;
4272   idx = sub_b->j;
4273   for (i = 0; i < n; i++) {
4274     q = ii[i + 1] - ii[i];
4275     while (q-- > 0) {
4276       c_q = c + clda * (*idx);
4277       a_q = a + alda * i;
4278       PetscKernelAXPY(c_q, *b, a_q, m);
4279       idx++;
4280       b++;
4281     }
4282   }
4283   PetscFunctionReturn(PETSC_SUCCESS);
4284 }
4285 
4286 PetscErrorCode MatMatMultSymbolic_SeqDense_SeqAIJ(Mat A, Mat B, PetscReal fill, Mat C)
4287 {
4288   PetscInt  m = A->rmap->n, n = B->cmap->n;
4289   PetscBool cisdense;
4290 
4291   PetscFunctionBegin;
4292   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);
4293   PetscCall(MatSetSizes(C, m, n, m, n));
4294   PetscCall(MatSetBlockSizesFromMats(C, A, B));
4295   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSECUDA, MATSEQDENSEHIP, ""));
4296   if (!cisdense) PetscCall(MatSetType(C, MATDENSE));
4297   PetscCall(MatSetUp(C));
4298 
4299   C->ops->matmultnumeric = MatMatMultNumeric_SeqDense_SeqAIJ;
4300   PetscFunctionReturn(PETSC_SUCCESS);
4301 }
4302 
4303 /*MC
4304    MATSEQAIJ - MATSEQAIJ = "seqaij" - A matrix type to be used for sequential sparse matrices,
4305    based on compressed sparse row format.
4306 
4307    Options Database Key:
4308 . -mat_type seqaij - sets the matrix type to "seqaij" during a call to MatSetFromOptions()
4309 
4310    Level: beginner
4311 
4312    Notes:
4313     `MatSetValues()` may be called for this matrix type with a `NULL` argument for the numerical values,
4314     in this case the values associated with the rows and columns one passes in are set to zero
4315     in the matrix
4316 
4317     `MatSetOptions`(,`MAT_STRUCTURE_ONLY`,`PETSC_TRUE`) may be called for this matrix type. In this no
4318     space is allocated for the nonzero entries and any entries passed with `MatSetValues()` are ignored
4319 
4320   Developer Note:
4321     It would be nice if all matrix formats supported passing `NULL` in for the numerical values
4322 
4323 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqAIJ()`, `MatSetFromOptions()`, `MatSetType()`, `MatCreate()`, `MatType`, `MATSELL`, `MATSEQSELL`, `MATMPISELL`
4324 M*/
4325 
4326 /*MC
4327    MATAIJ - MATAIJ = "aij" - A matrix type to be used for sparse matrices.
4328 
4329    This matrix type is identical to `MATSEQAIJ` when constructed with a single process communicator,
4330    and `MATMPIAIJ` otherwise.  As a result, for single process communicators,
4331    `MatSeqAIJSetPreallocation()` is supported, and similarly `MatMPIAIJSetPreallocation()` is supported
4332    for communicators controlling multiple processes.  It is recommended that you call both of
4333    the above preallocation routines for simplicity.
4334 
4335    Options Database Key:
4336 . -mat_type aij - sets the matrix type to "aij" during a call to `MatSetFromOptions()`
4337 
4338   Level: beginner
4339 
4340    Note:
4341    Subclasses include `MATAIJCUSPARSE`, `MATAIJPERM`, `MATAIJSELL`, `MATAIJMKL`, `MATAIJCRL`, and also automatically switches over to use inodes when
4342    enough exist.
4343 
4344 .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MATSEQAIJ`, `MATMPIAIJ`, `MATSELL`, `MATSEQSELL`, `MATMPISELL`
4345 M*/
4346 
4347 /*MC
4348    MATAIJCRL - MATAIJCRL = "aijcrl" - A matrix type to be used for sparse matrices.
4349 
4350    Options Database Key:
4351 . -mat_type aijcrl - sets the matrix type to "aijcrl" during a call to `MatSetFromOptions()`
4352 
4353   Level: beginner
4354 
4355    Note:
4356    This matrix type is identical to `MATSEQAIJCRL` when constructed with a single process communicator,
4357    and `MATMPIAIJCRL` otherwise.  As a result, for single process communicators,
4358    `MatSeqAIJSetPreallocation()` is supported, and similarly `MatMPIAIJSetPreallocation()` is supported
4359    for communicators controlling multiple processes.  It is recommended that you call both of
4360    the above preallocation routines for simplicity.
4361 
4362 .seealso: [](ch_matrices), `Mat`, `MatCreateMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`, `MATSEQAIJCRL`, `MATMPIAIJCRL`
4363 M*/
4364 
4365 PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCRL(Mat, MatType, MatReuse, Mat *);
4366 #if defined(PETSC_HAVE_ELEMENTAL)
4367 PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
4368 #endif
4369 #if defined(PETSC_HAVE_SCALAPACK)
4370 PETSC_INTERN PetscErrorCode MatConvert_AIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
4371 #endif
4372 #if defined(PETSC_HAVE_HYPRE)
4373 PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat A, MatType, MatReuse, Mat *);
4374 #endif
4375 
4376 PETSC_EXTERN PetscErrorCode MatConvert_SeqAIJ_SeqSELL(Mat, MatType, MatReuse, Mat *);
4377 PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat, MatType, MatReuse, Mat *);
4378 PETSC_INTERN PetscErrorCode MatProductSetFromOptions_IS_XAIJ(Mat);
4379 
4380 /*@C
4381   MatSeqAIJGetArray - gives read/write access to the array where the data for a `MATSEQAIJ` matrix is stored
4382 
4383   Not Collective
4384 
4385   Input Parameter:
4386 . A - a `MATSEQAIJ` matrix
4387 
4388   Output Parameter:
4389 . array - pointer to the data
4390 
4391   Level: intermediate
4392 
4393   Fortran Notes:
4394   `MatSeqAIJGetArray()` Fortran binding is deprecated (since PETSc 3.19), use `MatSeqAIJGetArrayF90()`
4395 
4396 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJRestoreArray()`, `MatSeqAIJGetArrayF90()`
4397 @*/
4398 PetscErrorCode MatSeqAIJGetArray(Mat A, PetscScalar **array)
4399 {
4400   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
4401 
4402   PetscFunctionBegin;
4403   if (aij->ops->getarray) {
4404     PetscCall((*aij->ops->getarray)(A, array));
4405   } else {
4406     *array = aij->a;
4407   }
4408   PetscFunctionReturn(PETSC_SUCCESS);
4409 }
4410 
4411 /*@C
4412   MatSeqAIJRestoreArray - returns access to the array where the data for a `MATSEQAIJ` matrix is stored obtained by `MatSeqAIJGetArray()`
4413 
4414   Not Collective
4415 
4416   Input Parameters:
4417 + A     - a `MATSEQAIJ` matrix
4418 - array - pointer to the data
4419 
4420   Level: intermediate
4421 
4422   Fortran Notes:
4423   `MatSeqAIJRestoreArray()` Fortran binding is deprecated (since PETSc 3.19), use `MatSeqAIJRestoreArrayF90()`
4424 
4425 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayF90()`
4426 @*/
4427 PetscErrorCode MatSeqAIJRestoreArray(Mat A, PetscScalar **array)
4428 {
4429   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
4430 
4431   PetscFunctionBegin;
4432   if (aij->ops->restorearray) {
4433     PetscCall((*aij->ops->restorearray)(A, array));
4434   } else {
4435     *array = NULL;
4436   }
4437   PetscCall(MatSeqAIJInvalidateDiagonal(A));
4438   PetscCall(PetscObjectStateIncrease((PetscObject)A));
4439   PetscFunctionReturn(PETSC_SUCCESS);
4440 }
4441 
4442 /*@C
4443   MatSeqAIJGetArrayRead - gives read-only access to the array where the data for a `MATSEQAIJ` matrix is stored
4444 
4445   Not Collective; No Fortran Support
4446 
4447   Input Parameter:
4448 . A - a `MATSEQAIJ` matrix
4449 
4450   Output Parameter:
4451 . array - pointer to the data
4452 
4453   Level: intermediate
4454 
4455 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayRead()`
4456 @*/
4457 PetscErrorCode MatSeqAIJGetArrayRead(Mat A, const PetscScalar **array)
4458 {
4459   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
4460 
4461   PetscFunctionBegin;
4462   if (aij->ops->getarrayread) {
4463     PetscCall((*aij->ops->getarrayread)(A, array));
4464   } else {
4465     *array = aij->a;
4466   }
4467   PetscFunctionReturn(PETSC_SUCCESS);
4468 }
4469 
4470 /*@C
4471   MatSeqAIJRestoreArrayRead - restore the read-only access array obtained from `MatSeqAIJGetArrayRead()`
4472 
4473   Not Collective; No Fortran Support
4474 
4475   Input Parameter:
4476 . A - a `MATSEQAIJ` matrix
4477 
4478   Output Parameter:
4479 . array - pointer to the data
4480 
4481   Level: intermediate
4482 
4483 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4484 @*/
4485 PetscErrorCode MatSeqAIJRestoreArrayRead(Mat A, const PetscScalar **array)
4486 {
4487   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
4488 
4489   PetscFunctionBegin;
4490   if (aij->ops->restorearrayread) {
4491     PetscCall((*aij->ops->restorearrayread)(A, array));
4492   } else {
4493     *array = NULL;
4494   }
4495   PetscFunctionReturn(PETSC_SUCCESS);
4496 }
4497 
4498 /*@C
4499   MatSeqAIJGetArrayWrite - gives write-only access to the array where the data for a `MATSEQAIJ` matrix is stored
4500 
4501   Not Collective; No Fortran Support
4502 
4503   Input Parameter:
4504 . A - a `MATSEQAIJ` matrix
4505 
4506   Output Parameter:
4507 . array - pointer to the data
4508 
4509   Level: intermediate
4510 
4511 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArrayRead()`
4512 @*/
4513 PetscErrorCode MatSeqAIJGetArrayWrite(Mat A, PetscScalar **array)
4514 {
4515   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
4516 
4517   PetscFunctionBegin;
4518   if (aij->ops->getarraywrite) {
4519     PetscCall((*aij->ops->getarraywrite)(A, array));
4520   } else {
4521     *array = aij->a;
4522   }
4523   PetscCall(MatSeqAIJInvalidateDiagonal(A));
4524   PetscCall(PetscObjectStateIncrease((PetscObject)A));
4525   PetscFunctionReturn(PETSC_SUCCESS);
4526 }
4527 
4528 /*@C
4529   MatSeqAIJRestoreArrayWrite - restore the read-only access array obtained from MatSeqAIJGetArrayRead
4530 
4531   Not Collective; No Fortran Support
4532 
4533   Input Parameter:
4534 . A - a MATSEQAIJ matrix
4535 
4536   Output Parameter:
4537 . array - pointer to the data
4538 
4539   Level: intermediate
4540 
4541 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4542 @*/
4543 PetscErrorCode MatSeqAIJRestoreArrayWrite(Mat A, PetscScalar **array)
4544 {
4545   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
4546 
4547   PetscFunctionBegin;
4548   if (aij->ops->restorearraywrite) {
4549     PetscCall((*aij->ops->restorearraywrite)(A, array));
4550   } else {
4551     *array = NULL;
4552   }
4553   PetscFunctionReturn(PETSC_SUCCESS);
4554 }
4555 
4556 /*@C
4557   MatSeqAIJGetCSRAndMemType - Get the CSR arrays and the memory type of the `MATSEQAIJ` matrix
4558 
4559   Not Collective; No Fortran Support
4560 
4561   Input Parameter:
4562 . mat - a matrix of type `MATSEQAIJ` or its subclasses
4563 
4564   Output Parameters:
4565 + i     - row map array of the matrix
4566 . j     - column index array of the matrix
4567 . a     - data array of the matrix
4568 - mtype - memory type of the arrays
4569 
4570   Level: developer
4571 
4572   Notes:
4573   Any of the output parameters can be `NULL`, in which case the corresponding value is not returned.
4574   If mat is a device matrix, the arrays are on the device. Otherwise, they are on the host.
4575 
4576   One can call this routine on a preallocated but not assembled matrix to just get the memory of the CSR underneath the matrix.
4577   If the matrix is assembled, the data array `a` is guaranteed to have the latest values of the matrix.
4578 
4579 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArray()`, `MatSeqAIJGetArrayRead()`
4580 @*/
4581 PetscErrorCode MatSeqAIJGetCSRAndMemType(Mat mat, const PetscInt **i, const PetscInt **j, PetscScalar **a, PetscMemType *mtype)
4582 {
4583   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)mat->data;
4584 
4585   PetscFunctionBegin;
4586   PetscCheck(mat->preallocated, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "matrix is not preallocated");
4587   if (aij->ops->getcsrandmemtype) {
4588     PetscCall((*aij->ops->getcsrandmemtype)(mat, i, j, a, mtype));
4589   } else {
4590     if (i) *i = aij->i;
4591     if (j) *j = aij->j;
4592     if (a) *a = aij->a;
4593     if (mtype) *mtype = PETSC_MEMTYPE_HOST;
4594   }
4595   PetscFunctionReturn(PETSC_SUCCESS);
4596 }
4597 
4598 /*@C
4599   MatSeqAIJGetMaxRowNonzeros - returns the maximum number of nonzeros in any row
4600 
4601   Not Collective
4602 
4603   Input Parameter:
4604 . A - a `MATSEQAIJ` matrix
4605 
4606   Output Parameter:
4607 . nz - the maximum number of nonzeros in any row
4608 
4609   Level: intermediate
4610 
4611 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJRestoreArray()`, `MatSeqAIJGetArrayF90()`
4612 @*/
4613 PetscErrorCode MatSeqAIJGetMaxRowNonzeros(Mat A, PetscInt *nz)
4614 {
4615   Mat_SeqAIJ *aij = (Mat_SeqAIJ *)A->data;
4616 
4617   PetscFunctionBegin;
4618   *nz = aij->rmax;
4619   PetscFunctionReturn(PETSC_SUCCESS);
4620 }
4621 
4622 static PetscErrorCode MatCOOStructDestroy_SeqAIJ(void *data)
4623 {
4624   MatCOOStruct_SeqAIJ *coo = (MatCOOStruct_SeqAIJ *)data;
4625   PetscFunctionBegin;
4626   PetscCall(PetscFree(coo->perm));
4627   PetscCall(PetscFree(coo->jmap));
4628   PetscCall(PetscFree(coo));
4629   PetscFunctionReturn(PETSC_SUCCESS);
4630 }
4631 
4632 PetscErrorCode MatSetPreallocationCOO_SeqAIJ(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
4633 {
4634   MPI_Comm             comm;
4635   PetscInt            *i, *j;
4636   PetscInt             M, N, row;
4637   PetscCount           k, p, q, nneg, nnz, start, end; /* Index the coo array, so use PetscCount as their type */
4638   PetscInt            *Ai;                             /* Change to PetscCount once we use it for row pointers */
4639   PetscInt            *Aj;
4640   PetscScalar         *Aa;
4641   Mat_SeqAIJ          *seqaij = (Mat_SeqAIJ *)(mat->data);
4642   MatType              rtype;
4643   PetscCount          *perm, *jmap;
4644   PetscContainer       container;
4645   MatCOOStruct_SeqAIJ *coo;
4646 
4647   PetscFunctionBegin;
4648   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
4649   PetscCall(MatGetSize(mat, &M, &N));
4650   i = coo_i;
4651   j = coo_j;
4652   PetscCall(PetscMalloc1(coo_n, &perm));
4653   for (k = 0; k < coo_n; k++) { /* Ignore entries with negative row or col indices */
4654     if (j[k] < 0) i[k] = -1;
4655     perm[k] = k;
4656   }
4657 
4658   /* Sort by row */
4659   PetscCall(PetscSortIntWithIntCountArrayPair(coo_n, i, j, perm));
4660 
4661   /* Advance k to the first row with a non-negative index */
4662   for (k = 0; k < coo_n; k++)
4663     if (i[k] >= 0) break;
4664   nneg = k;
4665   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 */
4666   nnz = 0;                                          /* Total number of unique nonzeros to be counted */
4667   jmap++;                                           /* Inc jmap by 1 for convenience */
4668 
4669   PetscCall(PetscCalloc1(M + 1, &Ai));        /* CSR of A */
4670   PetscCall(PetscMalloc1(coo_n - nneg, &Aj)); /* We have at most coo_n-nneg unique nonzeros */
4671 
4672   /* Support for HYPRE */
4673   PetscBool   hypre;
4674   const char *name;
4675   PetscCall(PetscObjectGetName((PetscObject)mat, &name));
4676   PetscCall(PetscStrcmp("_internal_COO_mat_for_hypre", name, &hypre));
4677 
4678   /* In each row, sort by column, then unique column indices to get row length */
4679   Ai++;  /* Inc by 1 for convenience */
4680   q = 0; /* q-th unique nonzero, with q starting from 0 */
4681   while (k < coo_n) {
4682     row   = i[k];
4683     start = k; /* [start,end) indices for this row */
4684     while (k < coo_n && i[k] == row) k++;
4685     end = k;
4686     /* hack for HYPRE: swap min column to diag so that diagonal values will go first */
4687     if (hypre) {
4688       PetscInt  minj    = PETSC_MAX_INT;
4689       PetscBool hasdiag = PETSC_FALSE;
4690       for (p = start; p < end; p++) {
4691         hasdiag = (PetscBool)(hasdiag || (j[p] == row));
4692         minj    = PetscMin(minj, j[p]);
4693       }
4694       if (hasdiag) {
4695         for (p = start; p < end; p++) {
4696           if (j[p] == minj) j[p] = row;
4697           else if (j[p] == row) j[p] = minj;
4698         }
4699       }
4700     }
4701     PetscCall(PetscSortIntWithCountArray(end - start, j + start, perm + start));
4702 
4703     /* Find number of unique col entries in this row */
4704     Aj[q]   = j[start]; /* Log the first nonzero in this row */
4705     jmap[q] = 1;        /* Number of repeats of this nonzero entry */
4706     Ai[row] = 1;
4707     nnz++;
4708 
4709     for (p = start + 1; p < end; p++) { /* Scan remaining nonzero in this row */
4710       if (j[p] != j[p - 1]) {           /* Meet a new nonzero */
4711         q++;
4712         jmap[q] = 1;
4713         Aj[q]   = j[p];
4714         Ai[row]++;
4715         nnz++;
4716       } else {
4717         jmap[q]++;
4718       }
4719     }
4720     q++; /* Move to next row and thus next unique nonzero */
4721   }
4722   Ai--; /* Back to the beginning of Ai[] */
4723   for (k = 0; k < M; k++) Ai[k + 1] += Ai[k];
4724   jmap--; /* Back to the beginning of jmap[] */
4725   jmap[0] = 0;
4726   for (k = 0; k < nnz; k++) jmap[k + 1] += jmap[k];
4727   if (nnz < coo_n - nneg) { /* Realloc with actual number of unique nonzeros */
4728     PetscCount *jmap_new;
4729     PetscInt   *Aj_new;
4730 
4731     PetscCall(PetscMalloc1(nnz + 1, &jmap_new));
4732     PetscCall(PetscArraycpy(jmap_new, jmap, nnz + 1));
4733     PetscCall(PetscFree(jmap));
4734     jmap = jmap_new;
4735 
4736     PetscCall(PetscMalloc1(nnz, &Aj_new));
4737     PetscCall(PetscArraycpy(Aj_new, Aj, nnz));
4738     PetscCall(PetscFree(Aj));
4739     Aj = Aj_new;
4740   }
4741 
4742   if (nneg) { /* Discard heading entries with negative indices in perm[], as we'll access it from index 0 in MatSetValuesCOO */
4743     PetscCount *perm_new;
4744 
4745     PetscCall(PetscMalloc1(coo_n - nneg, &perm_new));
4746     PetscCall(PetscArraycpy(perm_new, perm + nneg, coo_n - nneg));
4747     PetscCall(PetscFree(perm));
4748     perm = perm_new;
4749   }
4750 
4751   PetscCall(MatGetRootType_Private(mat, &rtype));
4752   PetscCall(PetscCalloc1(nnz, &Aa)); /* Zero the matrix */
4753   PetscCall(MatSetSeqAIJWithArrays_private(PETSC_COMM_SELF, M, N, Ai, Aj, Aa, rtype, mat));
4754 
4755   seqaij->singlemalloc = PETSC_FALSE;            /* Ai, Aj and Aa are not allocated in one big malloc */
4756   seqaij->free_a = seqaij->free_ij = PETSC_TRUE; /* Let newmat own Ai, Aj and Aa */
4757 
4758   // Put the COO struct in a container and then attach that to the matrix
4759   PetscCall(PetscMalloc1(1, &coo));
4760   coo->nz   = nnz;
4761   coo->n    = coo_n;
4762   coo->Atot = coo_n - nneg; // Annz is seqaij->nz, so no need to record that again
4763   coo->jmap = jmap;         // of length nnz+1
4764   coo->perm = perm;
4765   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
4766   PetscCall(PetscContainerSetPointer(container, coo));
4767   PetscCall(PetscContainerSetUserDestroy(container, MatCOOStructDestroy_SeqAIJ));
4768   PetscCall(PetscObjectCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject)container));
4769   PetscCall(PetscContainerDestroy(&container));
4770   PetscFunctionReturn(PETSC_SUCCESS);
4771 }
4772 
4773 static PetscErrorCode MatSetValuesCOO_SeqAIJ(Mat A, const PetscScalar v[], InsertMode imode)
4774 {
4775   Mat_SeqAIJ          *aseq = (Mat_SeqAIJ *)A->data;
4776   PetscCount           i, j, Annz = aseq->nz;
4777   PetscCount          *perm, *jmap;
4778   PetscScalar         *Aa;
4779   PetscContainer       container;
4780   MatCOOStruct_SeqAIJ *coo;
4781 
4782   PetscFunctionBegin;
4783   PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container));
4784   PetscCheck(container, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Not found MatCOOStruct on this matrix");
4785   PetscCall(PetscContainerGetPointer(container, (void **)&coo));
4786   perm = coo->perm;
4787   jmap = coo->jmap;
4788   PetscCall(MatSeqAIJGetArray(A, &Aa));
4789   for (i = 0; i < Annz; i++) {
4790     PetscScalar sum = 0.0;
4791     for (j = jmap[i]; j < jmap[i + 1]; j++) sum += v[perm[j]];
4792     Aa[i] = (imode == INSERT_VALUES ? 0.0 : Aa[i]) + sum;
4793   }
4794   PetscCall(MatSeqAIJRestoreArray(A, &Aa));
4795   PetscFunctionReturn(PETSC_SUCCESS);
4796 }
4797 
4798 #if defined(PETSC_HAVE_CUDA)
4799 PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJCUSPARSE(Mat, MatType, MatReuse, Mat *);
4800 #endif
4801 #if defined(PETSC_HAVE_HIP)
4802 PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);
4803 #endif
4804 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
4805 PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJKokkos(Mat, MatType, MatReuse, Mat *);
4806 #endif
4807 
4808 PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJ(Mat B)
4809 {
4810   Mat_SeqAIJ *b;
4811   PetscMPIInt size;
4812 
4813   PetscFunctionBegin;
4814   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
4815   PetscCheck(size <= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Comm must be of size 1");
4816 
4817   PetscCall(PetscNew(&b));
4818 
4819   B->data   = (void *)b;
4820   B->ops[0] = MatOps_Values;
4821   if (B->sortedfull) B->ops->setvalues = MatSetValues_SeqAIJ_SortedFull;
4822 
4823   b->row                = NULL;
4824   b->col                = NULL;
4825   b->icol               = NULL;
4826   b->reallocs           = 0;
4827   b->ignorezeroentries  = PETSC_FALSE;
4828   b->roworiented        = PETSC_TRUE;
4829   b->nonew              = 0;
4830   b->diag               = NULL;
4831   b->solve_work         = NULL;
4832   B->spptr              = NULL;
4833   b->saved_values       = NULL;
4834   b->idiag              = NULL;
4835   b->mdiag              = NULL;
4836   b->ssor_work          = NULL;
4837   b->omega              = 1.0;
4838   b->fshift             = 0.0;
4839   b->idiagvalid         = PETSC_FALSE;
4840   b->ibdiagvalid        = PETSC_FALSE;
4841   b->keepnonzeropattern = PETSC_FALSE;
4842 
4843   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATSEQAIJ));
4844 #if defined(PETSC_HAVE_MATLAB)
4845   PetscCall(PetscObjectComposeFunction((PetscObject)B, "PetscMatlabEnginePut_C", MatlabEnginePut_SeqAIJ));
4846   PetscCall(PetscObjectComposeFunction((PetscObject)B, "PetscMatlabEngineGet_C", MatlabEngineGet_SeqAIJ));
4847 #endif
4848   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetColumnIndices_C", MatSeqAIJSetColumnIndices_SeqAIJ));
4849   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_SeqAIJ));
4850   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_SeqAIJ));
4851   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqsbaij_C", MatConvert_SeqAIJ_SeqSBAIJ));
4852   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqbaij_C", MatConvert_SeqAIJ_SeqBAIJ));
4853   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijperm_C", MatConvert_SeqAIJ_SeqAIJPERM));
4854   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijsell_C", MatConvert_SeqAIJ_SeqAIJSELL));
4855 #if defined(PETSC_HAVE_MKL_SPARSE)
4856   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijmkl_C", MatConvert_SeqAIJ_SeqAIJMKL));
4857 #endif
4858 #if defined(PETSC_HAVE_CUDA)
4859   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijcusparse_C", MatConvert_SeqAIJ_SeqAIJCUSPARSE));
4860   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaijcusparse_seqaij_C", MatProductSetFromOptions_SeqAIJ));
4861   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaijcusparse_C", MatProductSetFromOptions_SeqAIJ));
4862 #endif
4863 #if defined(PETSC_HAVE_HIP)
4864   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijhipsparse_C", MatConvert_SeqAIJ_SeqAIJHIPSPARSE));
4865   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaijhipsparse_seqaij_C", MatProductSetFromOptions_SeqAIJ));
4866   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaijhipsparse_C", MatProductSetFromOptions_SeqAIJ));
4867 #endif
4868 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
4869   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijkokkos_C", MatConvert_SeqAIJ_SeqAIJKokkos));
4870 #endif
4871   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqaijcrl_C", MatConvert_SeqAIJ_SeqAIJCRL));
4872 #if defined(PETSC_HAVE_ELEMENTAL)
4873   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_elemental_C", MatConvert_SeqAIJ_Elemental));
4874 #endif
4875 #if defined(PETSC_HAVE_SCALAPACK)
4876   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_scalapack_C", MatConvert_AIJ_ScaLAPACK));
4877 #endif
4878 #if defined(PETSC_HAVE_HYPRE)
4879   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_hypre_C", MatConvert_AIJ_HYPRE));
4880   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_transpose_seqaij_seqaij_C", MatProductSetFromOptions_Transpose_AIJ_AIJ));
4881 #endif
4882   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqdense_C", MatConvert_SeqAIJ_SeqDense));
4883   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_seqsell_C", MatConvert_SeqAIJ_SeqSELL));
4884   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaij_is_C", MatConvert_XAIJ_IS));
4885   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsTranspose_C", MatIsTranspose_SeqAIJ));
4886   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatIsHermitianTranspose_C", MatIsHermitianTranspose_SeqAIJ));
4887   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetPreallocation_C", MatSeqAIJSetPreallocation_SeqAIJ));
4888   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatResetPreallocation_C", MatResetPreallocation_SeqAIJ));
4889   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJSetPreallocationCSR_C", MatSeqAIJSetPreallocationCSR_SeqAIJ));
4890   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatReorderForNonzeroDiagonal_C", MatReorderForNonzeroDiagonal_SeqAIJ));
4891   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_is_seqaij_C", MatProductSetFromOptions_IS_XAIJ));
4892   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdense_seqaij_C", MatProductSetFromOptions_SeqDense_SeqAIJ));
4893   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqaij_C", MatProductSetFromOptions_SeqAIJ));
4894   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqAIJKron_C", MatSeqAIJKron_SeqAIJ));
4895   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_SeqAIJ));
4896   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_SeqAIJ));
4897   PetscCall(MatCreate_SeqAIJ_Inode(B));
4898   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATSEQAIJ));
4899   PetscCall(MatSeqAIJSetTypeFromOptions(B)); /* this allows changing the matrix subtype to say MATSEQAIJPERM */
4900   PetscFunctionReturn(PETSC_SUCCESS);
4901 }
4902 
4903 /*
4904     Given a matrix generated with MatGetFactor() duplicates all the information in A into C
4905 */
4906 PetscErrorCode MatDuplicateNoCreate_SeqAIJ(Mat C, Mat A, MatDuplicateOption cpvalues, PetscBool mallocmatspace)
4907 {
4908   Mat_SeqAIJ *c = (Mat_SeqAIJ *)C->data, *a = (Mat_SeqAIJ *)A->data;
4909   PetscInt    m = A->rmap->n, i;
4910 
4911   PetscFunctionBegin;
4912   PetscCheck(A->assembled || cpvalues == MAT_DO_NOT_COPY_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot duplicate unassembled matrix");
4913 
4914   C->factortype    = A->factortype;
4915   c->row           = NULL;
4916   c->col           = NULL;
4917   c->icol          = NULL;
4918   c->reallocs      = 0;
4919   c->diagonaldense = a->diagonaldense;
4920 
4921   C->assembled = A->assembled;
4922 
4923   if (A->preallocated) {
4924     PetscCall(PetscLayoutReference(A->rmap, &C->rmap));
4925     PetscCall(PetscLayoutReference(A->cmap, &C->cmap));
4926 
4927     if (!A->hash_active) {
4928       PetscCall(PetscMalloc1(m, &c->imax));
4929       PetscCall(PetscMemcpy(c->imax, a->imax, m * sizeof(PetscInt)));
4930       PetscCall(PetscMalloc1(m, &c->ilen));
4931       PetscCall(PetscMemcpy(c->ilen, a->ilen, m * sizeof(PetscInt)));
4932 
4933       /* allocate the matrix space */
4934       if (mallocmatspace) {
4935         PetscCall(PetscMalloc3(a->i[m], &c->a, a->i[m], &c->j, m + 1, &c->i));
4936 
4937         c->singlemalloc = PETSC_TRUE;
4938 
4939         PetscCall(PetscArraycpy(c->i, a->i, m + 1));
4940         if (m > 0) {
4941           PetscCall(PetscArraycpy(c->j, a->j, a->i[m]));
4942           if (cpvalues == MAT_COPY_VALUES) {
4943             const PetscScalar *aa;
4944 
4945             PetscCall(MatSeqAIJGetArrayRead(A, &aa));
4946             PetscCall(PetscArraycpy(c->a, aa, a->i[m]));
4947             PetscCall(MatSeqAIJGetArrayRead(A, &aa));
4948           } else {
4949             PetscCall(PetscArrayzero(c->a, a->i[m]));
4950           }
4951         }
4952       }
4953       C->preallocated = PETSC_TRUE;
4954     } else {
4955       PetscCheck(mallocmatspace, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Cannot malloc matrix memory from a non-preallocated matrix");
4956       PetscCall(MatSetUp(C));
4957     }
4958 
4959     c->ignorezeroentries = a->ignorezeroentries;
4960     c->roworiented       = a->roworiented;
4961     c->nonew             = a->nonew;
4962     if (a->diag) {
4963       PetscCall(PetscMalloc1(m + 1, &c->diag));
4964       PetscCall(PetscMemcpy(c->diag, a->diag, m * sizeof(PetscInt)));
4965     } else c->diag = NULL;
4966 
4967     c->solve_work         = NULL;
4968     c->saved_values       = NULL;
4969     c->idiag              = NULL;
4970     c->ssor_work          = NULL;
4971     c->keepnonzeropattern = a->keepnonzeropattern;
4972     c->free_a             = PETSC_TRUE;
4973     c->free_ij            = PETSC_TRUE;
4974 
4975     c->rmax  = a->rmax;
4976     c->nz    = a->nz;
4977     c->maxnz = a->nz; /* Since we allocate exactly the right amount */
4978 
4979     c->compressedrow.use   = a->compressedrow.use;
4980     c->compressedrow.nrows = a->compressedrow.nrows;
4981     if (a->compressedrow.use) {
4982       i = a->compressedrow.nrows;
4983       PetscCall(PetscMalloc2(i + 1, &c->compressedrow.i, i, &c->compressedrow.rindex));
4984       PetscCall(PetscArraycpy(c->compressedrow.i, a->compressedrow.i, i + 1));
4985       PetscCall(PetscArraycpy(c->compressedrow.rindex, a->compressedrow.rindex, i));
4986     } else {
4987       c->compressedrow.use    = PETSC_FALSE;
4988       c->compressedrow.i      = NULL;
4989       c->compressedrow.rindex = NULL;
4990     }
4991     c->nonzerorowcnt = a->nonzerorowcnt;
4992     C->nonzerostate  = A->nonzerostate;
4993 
4994     PetscCall(MatDuplicate_SeqAIJ_Inode(A, cpvalues, &C));
4995   }
4996   PetscCall(PetscFunctionListDuplicate(((PetscObject)A)->qlist, &((PetscObject)C)->qlist));
4997   PetscFunctionReturn(PETSC_SUCCESS);
4998 }
4999 
5000 PetscErrorCode MatDuplicate_SeqAIJ(Mat A, MatDuplicateOption cpvalues, Mat *B)
5001 {
5002   PetscFunctionBegin;
5003   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), B));
5004   PetscCall(MatSetSizes(*B, A->rmap->n, A->cmap->n, A->rmap->n, A->cmap->n));
5005   if (!(A->rmap->n % A->rmap->bs) && !(A->cmap->n % A->cmap->bs)) PetscCall(MatSetBlockSizesFromMats(*B, A, A));
5006   PetscCall(MatSetType(*B, ((PetscObject)A)->type_name));
5007   PetscCall(MatDuplicateNoCreate_SeqAIJ(*B, A, cpvalues, PETSC_TRUE));
5008   PetscFunctionReturn(PETSC_SUCCESS);
5009 }
5010 
5011 PetscErrorCode MatLoad_SeqAIJ(Mat newMat, PetscViewer viewer)
5012 {
5013   PetscBool isbinary, ishdf5;
5014 
5015   PetscFunctionBegin;
5016   PetscValidHeaderSpecific(newMat, MAT_CLASSID, 1);
5017   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
5018   /* force binary viewer to load .info file if it has not yet done so */
5019   PetscCall(PetscViewerSetUp(viewer));
5020   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
5021   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
5022   if (isbinary) {
5023     PetscCall(MatLoad_SeqAIJ_Binary(newMat, viewer));
5024   } else if (ishdf5) {
5025 #if defined(PETSC_HAVE_HDF5)
5026     PetscCall(MatLoad_AIJ_HDF5(newMat, viewer));
5027 #else
5028     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
5029 #endif
5030   } else {
5031     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);
5032   }
5033   PetscFunctionReturn(PETSC_SUCCESS);
5034 }
5035 
5036 PetscErrorCode MatLoad_SeqAIJ_Binary(Mat mat, PetscViewer viewer)
5037 {
5038   Mat_SeqAIJ *a = (Mat_SeqAIJ *)mat->data;
5039   PetscInt    header[4], *rowlens, M, N, nz, sum, rows, cols, i;
5040 
5041   PetscFunctionBegin;
5042   PetscCall(PetscViewerSetUp(viewer));
5043 
5044   /* read in matrix header */
5045   PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
5046   PetscCheck(header[0] == MAT_FILE_CLASSID, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
5047   M  = header[1];
5048   N  = header[2];
5049   nz = header[3];
5050   PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
5051   PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
5052   PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Matrix stored in special format on disk, cannot load as SeqAIJ");
5053 
5054   /* set block sizes from the viewer's .info file */
5055   PetscCall(MatLoad_Binary_BlockSizes(mat, viewer));
5056   /* set local and global sizes if not set already */
5057   if (mat->rmap->n < 0) mat->rmap->n = M;
5058   if (mat->cmap->n < 0) mat->cmap->n = N;
5059   if (mat->rmap->N < 0) mat->rmap->N = M;
5060   if (mat->cmap->N < 0) mat->cmap->N = N;
5061   PetscCall(PetscLayoutSetUp(mat->rmap));
5062   PetscCall(PetscLayoutSetUp(mat->cmap));
5063 
5064   /* check if the matrix sizes are correct */
5065   PetscCall(MatGetSize(mat, &rows, &cols));
5066   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);
5067 
5068   /* read in row lengths */
5069   PetscCall(PetscMalloc1(M, &rowlens));
5070   PetscCall(PetscViewerBinaryRead(viewer, rowlens, M, NULL, PETSC_INT));
5071   /* check if sum(rowlens) is same as nz */
5072   sum = 0;
5073   for (i = 0; i < M; i++) sum += rowlens[i];
5074   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);
5075   /* preallocate and check sizes */
5076   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(mat, 0, rowlens));
5077   PetscCall(MatGetSize(mat, &rows, &cols));
5078   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);
5079   /* store row lengths */
5080   PetscCall(PetscArraycpy(a->ilen, rowlens, M));
5081   PetscCall(PetscFree(rowlens));
5082 
5083   /* fill in "i" row pointers */
5084   a->i[0] = 0;
5085   for (i = 0; i < M; i++) a->i[i + 1] = a->i[i] + a->ilen[i];
5086   /* read in "j" column indices */
5087   PetscCall(PetscViewerBinaryRead(viewer, a->j, nz, NULL, PETSC_INT));
5088   /* read in "a" nonzero values */
5089   PetscCall(PetscViewerBinaryRead(viewer, a->a, nz, NULL, PETSC_SCALAR));
5090 
5091   PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
5092   PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
5093   PetscFunctionReturn(PETSC_SUCCESS);
5094 }
5095 
5096 PetscErrorCode MatEqual_SeqAIJ(Mat A, Mat B, PetscBool *flg)
5097 {
5098   Mat_SeqAIJ        *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)B->data;
5099   const PetscScalar *aa, *ba;
5100 #if defined(PETSC_USE_COMPLEX)
5101   PetscInt k;
5102 #endif
5103 
5104   PetscFunctionBegin;
5105   /* If the  matrix dimensions are not equal,or no of nonzeros */
5106   if ((A->rmap->n != B->rmap->n) || (A->cmap->n != B->cmap->n) || (a->nz != b->nz)) {
5107     *flg = PETSC_FALSE;
5108     PetscFunctionReturn(PETSC_SUCCESS);
5109   }
5110 
5111   /* if the a->i are the same */
5112   PetscCall(PetscArraycmp(a->i, b->i, A->rmap->n + 1, flg));
5113   if (!*flg) PetscFunctionReturn(PETSC_SUCCESS);
5114 
5115   /* if a->j are the same */
5116   PetscCall(PetscArraycmp(a->j, b->j, a->nz, flg));
5117   if (!*flg) PetscFunctionReturn(PETSC_SUCCESS);
5118 
5119   PetscCall(MatSeqAIJGetArrayRead(A, &aa));
5120   PetscCall(MatSeqAIJGetArrayRead(B, &ba));
5121   /* if a->a are the same */
5122 #if defined(PETSC_USE_COMPLEX)
5123   for (k = 0; k < a->nz; k++) {
5124     if (PetscRealPart(aa[k]) != PetscRealPart(ba[k]) || PetscImaginaryPart(aa[k]) != PetscImaginaryPart(ba[k])) {
5125       *flg = PETSC_FALSE;
5126       PetscFunctionReturn(PETSC_SUCCESS);
5127     }
5128   }
5129 #else
5130   PetscCall(PetscArraycmp(aa, ba, a->nz, flg));
5131 #endif
5132   PetscCall(MatSeqAIJRestoreArrayRead(A, &aa));
5133   PetscCall(MatSeqAIJRestoreArrayRead(B, &ba));
5134   PetscFunctionReturn(PETSC_SUCCESS);
5135 }
5136 
5137 /*@
5138   MatCreateSeqAIJWithArrays - Creates an sequential `MATSEQAIJ` matrix using matrix elements (in CSR format)
5139   provided by the user.
5140 
5141   Collective
5142 
5143   Input Parameters:
5144 + comm - must be an MPI communicator of size 1
5145 . m    - number of rows
5146 . n    - number of columns
5147 . i    - row indices; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
5148 . j    - column indices
5149 - a    - matrix values
5150 
5151   Output Parameter:
5152 . mat - the matrix
5153 
5154   Level: intermediate
5155 
5156   Notes:
5157   The `i`, `j`, and `a` arrays are not copied by this routine, the user must free these arrays
5158   once the matrix is destroyed and not before
5159 
5160   You cannot set new nonzero locations into this matrix, that will generate an error.
5161 
5162   The `i` and `j` indices are 0 based
5163 
5164   The format which is used for the sparse matrix input, is equivalent to a
5165   row-major ordering.. i.e for the following matrix, the input data expected is
5166   as shown
5167 .vb
5168         1 0 0
5169         2 0 3
5170         4 5 6
5171 
5172         i =  {0,1,3,6}  [size = nrow+1  = 3+1]
5173         j =  {0,0,2,0,1,2}  [size = 6]; values must be sorted for each row
5174         v =  {1,2,3,4,5,6}  [size = 6]
5175 .ve
5176 
5177 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MatCreateMPIAIJWithArrays()`, `MatMPIAIJSetPreallocationCSR()`
5178 @*/
5179 PetscErrorCode MatCreateSeqAIJWithArrays(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt i[], PetscInt j[], PetscScalar a[], Mat *mat)
5180 {
5181   PetscInt    ii;
5182   Mat_SeqAIJ *aij;
5183   PetscInt    jj;
5184 
5185   PetscFunctionBegin;
5186   PetscCheck(m <= 0 || i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");
5187   PetscCall(MatCreate(comm, mat));
5188   PetscCall(MatSetSizes(*mat, m, n, m, n));
5189   /* PetscCall(MatSetBlockSizes(*mat,,)); */
5190   PetscCall(MatSetType(*mat, MATSEQAIJ));
5191   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*mat, MAT_SKIP_ALLOCATION, NULL));
5192   aij = (Mat_SeqAIJ *)(*mat)->data;
5193   PetscCall(PetscMalloc1(m, &aij->imax));
5194   PetscCall(PetscMalloc1(m, &aij->ilen));
5195 
5196   aij->i            = i;
5197   aij->j            = j;
5198   aij->a            = a;
5199   aij->singlemalloc = PETSC_FALSE;
5200   aij->nonew        = -1; /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
5201   aij->free_a       = PETSC_FALSE;
5202   aij->free_ij      = PETSC_FALSE;
5203 
5204   for (ii = 0, aij->nonzerorowcnt = 0, aij->rmax = 0; ii < m; ii++) {
5205     aij->ilen[ii] = aij->imax[ii] = i[ii + 1] - i[ii];
5206     if (PetscDefined(USE_DEBUG)) {
5207       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]);
5208       for (jj = i[ii] + 1; jj < i[ii + 1]; jj++) {
5209         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);
5210         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);
5211       }
5212     }
5213   }
5214   if (PetscDefined(USE_DEBUG)) {
5215     for (ii = 0; ii < aij->i[m]; ii++) {
5216       PetscCheck(j[ii] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative column index at location = %" PetscInt_FMT " index = %" PetscInt_FMT, ii, j[ii]);
5217       PetscCheck(j[ii] <= n - 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column index to large at location = %" PetscInt_FMT " index = %" PetscInt_FMT, ii, j[ii]);
5218     }
5219   }
5220 
5221   PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
5222   PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
5223   PetscFunctionReturn(PETSC_SUCCESS);
5224 }
5225 
5226 /*@
5227   MatCreateSeqAIJFromTriple - Creates an sequential `MATSEQAIJ` matrix using matrix elements (in COO format)
5228   provided by the user.
5229 
5230   Collective
5231 
5232   Input Parameters:
5233 + comm - must be an MPI communicator of size 1
5234 . m    - number of rows
5235 . n    - number of columns
5236 . i    - row indices
5237 . j    - column indices
5238 . a    - matrix values
5239 . nz   - number of nonzeros
5240 - idx  - if the `i` and `j` indices start with 1 use `PETSC_TRUE` otherwise use `PETSC_FALSE`
5241 
5242   Output Parameter:
5243 . mat - the matrix
5244 
5245   Level: intermediate
5246 
5247   Example:
5248   For the following matrix, the input data expected is as shown (using 0 based indexing)
5249 .vb
5250         1 0 0
5251         2 0 3
5252         4 5 6
5253 
5254         i =  {0,1,1,2,2,2}
5255         j =  {0,0,2,0,1,2}
5256         v =  {1,2,3,4,5,6}
5257 .ve
5258 
5259   Note:
5260   Instead of using this function, users should also consider `MatSetPreallocationCOO()` and `MatSetValuesCOO()`, which allow repeated or remote entries,
5261   and are particularly useful in iterative applications.
5262 
5263 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatCreateSeqAIJ()`, `MatCreateSeqAIJWithArrays()`, `MatMPIAIJSetPreallocationCSR()`, `MatSetValuesCOO()`, `MatSetPreallocationCOO()`
5264 @*/
5265 PetscErrorCode MatCreateSeqAIJFromTriple(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt i[], PetscInt j[], PetscScalar a[], Mat *mat, PetscInt nz, PetscBool idx)
5266 {
5267   PetscInt ii, *nnz, one = 1, row, col;
5268 
5269   PetscFunctionBegin;
5270   PetscCall(PetscCalloc1(m, &nnz));
5271   for (ii = 0; ii < nz; ii++) nnz[i[ii] - !!idx] += 1;
5272   PetscCall(MatCreate(comm, mat));
5273   PetscCall(MatSetSizes(*mat, m, n, m, n));
5274   PetscCall(MatSetType(*mat, MATSEQAIJ));
5275   PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*mat, 0, nnz));
5276   for (ii = 0; ii < nz; ii++) {
5277     if (idx) {
5278       row = i[ii] - 1;
5279       col = j[ii] - 1;
5280     } else {
5281       row = i[ii];
5282       col = j[ii];
5283     }
5284     PetscCall(MatSetValues(*mat, one, &row, one, &col, &a[ii], ADD_VALUES));
5285   }
5286   PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
5287   PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
5288   PetscCall(PetscFree(nnz));
5289   PetscFunctionReturn(PETSC_SUCCESS);
5290 }
5291 
5292 PetscErrorCode MatSeqAIJInvalidateDiagonal(Mat A)
5293 {
5294   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
5295 
5296   PetscFunctionBegin;
5297   a->idiagvalid  = PETSC_FALSE;
5298   a->ibdiagvalid = PETSC_FALSE;
5299 
5300   PetscCall(MatSeqAIJInvalidateDiagonal_Inode(A));
5301   PetscFunctionReturn(PETSC_SUCCESS);
5302 }
5303 
5304 PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
5305 {
5306   PetscFunctionBegin;
5307   PetscCall(MatCreateMPIMatConcatenateSeqMat_MPIAIJ(comm, inmat, n, scall, outmat));
5308   PetscFunctionReturn(PETSC_SUCCESS);
5309 }
5310 
5311 /*
5312  Permute A into C's *local* index space using rowemb,colemb.
5313  The embedding are supposed to be injections and the above implies that the range of rowemb is a subset
5314  of [0,m), colemb is in [0,n).
5315  If pattern == DIFFERENT_NONZERO_PATTERN, C is preallocated according to A.
5316  */
5317 PetscErrorCode MatSetSeqMat_SeqAIJ(Mat C, IS rowemb, IS colemb, MatStructure pattern, Mat B)
5318 {
5319   /* If making this function public, change the error returned in this function away from _PLIB. */
5320   Mat_SeqAIJ     *Baij;
5321   PetscBool       seqaij;
5322   PetscInt        m, n, *nz, i, j, count;
5323   PetscScalar     v;
5324   const PetscInt *rowindices, *colindices;
5325 
5326   PetscFunctionBegin;
5327   if (!B) PetscFunctionReturn(PETSC_SUCCESS);
5328   /* Check to make sure the target matrix (and embeddings) are compatible with C and each other. */
5329   PetscCall(PetscObjectBaseTypeCompare((PetscObject)B, MATSEQAIJ, &seqaij));
5330   PetscCheck(seqaij, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input matrix is of wrong type");
5331   if (rowemb) {
5332     PetscCall(ISGetLocalSize(rowemb, &m));
5333     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);
5334   } else {
5335     PetscCheck(C->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input matrix is row-incompatible with the target matrix");
5336   }
5337   if (colemb) {
5338     PetscCall(ISGetLocalSize(colemb, &n));
5339     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);
5340   } else {
5341     PetscCheck(C->cmap->n == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input matrix is col-incompatible with the target matrix");
5342   }
5343 
5344   Baij = (Mat_SeqAIJ *)(B->data);
5345   if (pattern == DIFFERENT_NONZERO_PATTERN) {
5346     PetscCall(PetscMalloc1(B->rmap->n, &nz));
5347     for (i = 0; i < B->rmap->n; i++) nz[i] = Baij->i[i + 1] - Baij->i[i];
5348     PetscCall(MatSeqAIJSetPreallocation(C, 0, nz));
5349     PetscCall(PetscFree(nz));
5350   }
5351   if (pattern == SUBSET_NONZERO_PATTERN) PetscCall(MatZeroEntries(C));
5352   count      = 0;
5353   rowindices = NULL;
5354   colindices = NULL;
5355   if (rowemb) PetscCall(ISGetIndices(rowemb, &rowindices));
5356   if (colemb) PetscCall(ISGetIndices(colemb, &colindices));
5357   for (i = 0; i < B->rmap->n; i++) {
5358     PetscInt row;
5359     row = i;
5360     if (rowindices) row = rowindices[i];
5361     for (j = Baij->i[i]; j < Baij->i[i + 1]; j++) {
5362       PetscInt col;
5363       col = Baij->j[count];
5364       if (colindices) col = colindices[col];
5365       v = Baij->a[count];
5366       PetscCall(MatSetValues(C, 1, &row, 1, &col, &v, INSERT_VALUES));
5367       ++count;
5368     }
5369   }
5370   /* FIXME: set C's nonzerostate correctly. */
5371   /* Assembly for C is necessary. */
5372   C->preallocated  = PETSC_TRUE;
5373   C->assembled     = PETSC_TRUE;
5374   C->was_assembled = PETSC_FALSE;
5375   PetscFunctionReturn(PETSC_SUCCESS);
5376 }
5377 
5378 PetscErrorCode MatEliminateZeros_SeqAIJ(Mat A, PetscBool keep)
5379 {
5380   Mat_SeqAIJ *a  = (Mat_SeqAIJ *)A->data;
5381   MatScalar  *aa = a->a;
5382   PetscInt    m = A->rmap->n, fshift = 0, fshift_prev = 0, i, k;
5383   PetscInt   *ailen = a->ilen, *imax = a->imax, *ai = a->i, *aj = a->j, rmax = 0;
5384 
5385   PetscFunctionBegin;
5386   PetscCheck(A->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot eliminate zeros for unassembled matrix");
5387   if (m) rmax = ailen[0]; /* determine row with most nonzeros */
5388   for (i = 1; i <= m; i++) {
5389     /* move each nonzero entry back by the amount of zero slots (fshift) before it*/
5390     for (k = ai[i - 1]; k < ai[i]; k++) {
5391       if (aa[k] == 0 && (aj[k] != i - 1 || !keep)) fshift++;
5392       else {
5393         if (aa[k] == 0 && aj[k] == i - 1) PetscCall(PetscInfo(A, "Keep the diagonal zero at row %" PetscInt_FMT "\n", i - 1));
5394         aa[k - fshift] = aa[k];
5395         aj[k - fshift] = aj[k];
5396       }
5397     }
5398     ai[i - 1] -= fshift_prev; // safe to update ai[i-1] now since it will not be used in the next iteration
5399     fshift_prev = fshift;
5400     /* reset ilen and imax for each row */
5401     ailen[i - 1] = imax[i - 1] = ai[i] - fshift - ai[i - 1];
5402     a->nonzerorowcnt += ((ai[i] - fshift - ai[i - 1]) > 0);
5403     rmax = PetscMax(rmax, ailen[i - 1]);
5404   }
5405   if (fshift) {
5406     if (m) {
5407       ai[m] -= fshift;
5408       a->nz = ai[m];
5409     }
5410     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));
5411     A->nonzerostate++;
5412     A->info.nz_unneeded += (PetscReal)fshift;
5413     a->rmax = rmax;
5414     if (a->inode.use && a->inode.checked) PetscCall(MatSeqAIJCheckInode(A));
5415     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
5416     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
5417   }
5418   PetscFunctionReturn(PETSC_SUCCESS);
5419 }
5420 
5421 PetscFunctionList MatSeqAIJList = NULL;
5422 
5423 /*@C
5424   MatSeqAIJSetType - Converts a `MATSEQAIJ` matrix to a subtype
5425 
5426   Collective
5427 
5428   Input Parameters:
5429 + mat    - the matrix object
5430 - matype - matrix type
5431 
5432   Options Database Key:
5433 . -mat_seqaij_type  <method> - for example seqaijcrl
5434 
5435   Level: intermediate
5436 
5437 .seealso: [](ch_matrices), `Mat`, `PCSetType()`, `VecSetType()`, `MatCreate()`, `MatType`
5438 @*/
5439 PetscErrorCode MatSeqAIJSetType(Mat mat, MatType matype)
5440 {
5441   PetscBool sametype;
5442   PetscErrorCode (*r)(Mat, MatType, MatReuse, Mat *);
5443 
5444   PetscFunctionBegin;
5445   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5446   PetscCall(PetscObjectTypeCompare((PetscObject)mat, matype, &sametype));
5447   if (sametype) PetscFunctionReturn(PETSC_SUCCESS);
5448 
5449   PetscCall(PetscFunctionListFind(MatSeqAIJList, matype, &r));
5450   PetscCheck(r, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown Mat type given: %s", matype);
5451   PetscCall((*r)(mat, matype, MAT_INPLACE_MATRIX, &mat));
5452   PetscFunctionReturn(PETSC_SUCCESS);
5453 }
5454 
5455 /*@C
5456   MatSeqAIJRegister -  - Adds a new sub-matrix type for sequential `MATSEQAIJ` matrices
5457 
5458   Not Collective
5459 
5460   Input Parameters:
5461 + sname    - name of a new user-defined matrix type, for example `MATSEQAIJCRL`
5462 - function - routine to convert to subtype
5463 
5464   Level: advanced
5465 
5466   Notes:
5467   `MatSeqAIJRegister()` may be called multiple times to add several user-defined solvers.
5468 
5469   Then, your matrix can be chosen with the procedural interface at runtime via the option
5470 $     -mat_seqaij_type my_mat
5471 
5472 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJRegisterAll()`
5473 @*/
5474 PetscErrorCode MatSeqAIJRegister(const char sname[], PetscErrorCode (*function)(Mat, MatType, MatReuse, Mat *))
5475 {
5476   PetscFunctionBegin;
5477   PetscCall(MatInitializePackage());
5478   PetscCall(PetscFunctionListAdd(&MatSeqAIJList, sname, function));
5479   PetscFunctionReturn(PETSC_SUCCESS);
5480 }
5481 
5482 PetscBool MatSeqAIJRegisterAllCalled = PETSC_FALSE;
5483 
5484 /*@C
5485   MatSeqAIJRegisterAll - Registers all of the matrix subtypes of `MATSSEQAIJ`
5486 
5487   Not Collective
5488 
5489   Level: advanced
5490 
5491   Note:
5492   This registers the versions of `MATSEQAIJ` for GPUs
5493 
5494 .seealso: [](ch_matrices), `Mat`, `MatRegisterAll()`, `MatSeqAIJRegister()`
5495 @*/
5496 PetscErrorCode MatSeqAIJRegisterAll(void)
5497 {
5498   PetscFunctionBegin;
5499   if (MatSeqAIJRegisterAllCalled) PetscFunctionReturn(PETSC_SUCCESS);
5500   MatSeqAIJRegisterAllCalled = PETSC_TRUE;
5501 
5502   PetscCall(MatSeqAIJRegister(MATSEQAIJCRL, MatConvert_SeqAIJ_SeqAIJCRL));
5503   PetscCall(MatSeqAIJRegister(MATSEQAIJPERM, MatConvert_SeqAIJ_SeqAIJPERM));
5504   PetscCall(MatSeqAIJRegister(MATSEQAIJSELL, MatConvert_SeqAIJ_SeqAIJSELL));
5505 #if defined(PETSC_HAVE_MKL_SPARSE)
5506   PetscCall(MatSeqAIJRegister(MATSEQAIJMKL, MatConvert_SeqAIJ_SeqAIJMKL));
5507 #endif
5508 #if defined(PETSC_HAVE_CUDA)
5509   PetscCall(MatSeqAIJRegister(MATSEQAIJCUSPARSE, MatConvert_SeqAIJ_SeqAIJCUSPARSE));
5510 #endif
5511 #if defined(PETSC_HAVE_HIP)
5512   PetscCall(MatSeqAIJRegister(MATSEQAIJHIPSPARSE, MatConvert_SeqAIJ_SeqAIJHIPSPARSE));
5513 #endif
5514 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
5515   PetscCall(MatSeqAIJRegister(MATSEQAIJKOKKOS, MatConvert_SeqAIJ_SeqAIJKokkos));
5516 #endif
5517 #if defined(PETSC_HAVE_VIENNACL) && defined(PETSC_HAVE_VIENNACL_NO_CUDA)
5518   PetscCall(MatSeqAIJRegister(MATMPIAIJVIENNACL, MatConvert_SeqAIJ_SeqAIJViennaCL));
5519 #endif
5520   PetscFunctionReturn(PETSC_SUCCESS);
5521 }
5522 
5523 /*
5524     Special version for direct calls from Fortran
5525 */
5526 #include <petsc/private/fortranimpl.h>
5527 #if defined(PETSC_HAVE_FORTRAN_CAPS)
5528   #define matsetvaluesseqaij_ MATSETVALUESSEQAIJ
5529 #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
5530   #define matsetvaluesseqaij_ matsetvaluesseqaij
5531 #endif
5532 
5533 /* Change these macros so can be used in void function */
5534 
5535 /* Change these macros so can be used in void function */
5536 /* Identical to PetscCallVoid, except it assigns to *_ierr */
5537 #undef PetscCall
5538 #define PetscCall(...) \
5539   do { \
5540     PetscErrorCode ierr_msv_mpiaij = __VA_ARGS__; \
5541     if (PetscUnlikely(ierr_msv_mpiaij)) { \
5542       *_ierr = PetscError(PETSC_COMM_SELF, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr_msv_mpiaij, PETSC_ERROR_REPEAT, " "); \
5543       return; \
5544     } \
5545   } while (0)
5546 
5547 #undef SETERRQ
5548 #define SETERRQ(comm, ierr, ...) \
5549   do { \
5550     *_ierr = PetscError(comm, __LINE__, PETSC_FUNCTION_NAME, __FILE__, ierr, PETSC_ERROR_INITIAL, __VA_ARGS__); \
5551     return; \
5552   } while (0)
5553 
5554 PETSC_EXTERN void matsetvaluesseqaij_(Mat *AA, PetscInt *mm, const PetscInt im[], PetscInt *nn, const PetscInt in[], const PetscScalar v[], InsertMode *isis, PetscErrorCode *_ierr)
5555 {
5556   Mat         A = *AA;
5557   PetscInt    m = *mm, n = *nn;
5558   InsertMode  is = *isis;
5559   Mat_SeqAIJ *a  = (Mat_SeqAIJ *)A->data;
5560   PetscInt   *rp, k, low, high, t, ii, row, nrow, i, col, l, rmax, N;
5561   PetscInt   *imax, *ai, *ailen;
5562   PetscInt   *aj, nonew = a->nonew, lastcol = -1;
5563   MatScalar  *ap, value, *aa;
5564   PetscBool   ignorezeroentries = a->ignorezeroentries;
5565   PetscBool   roworiented       = a->roworiented;
5566 
5567   PetscFunctionBegin;
5568   MatCheckPreallocated(A, 1);
5569   imax  = a->imax;
5570   ai    = a->i;
5571   ailen = a->ilen;
5572   aj    = a->j;
5573   aa    = a->a;
5574 
5575   for (k = 0; k < m; k++) { /* loop over added rows */
5576     row = im[k];
5577     if (row < 0) continue;
5578     PetscCheck(row < A->rmap->n, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Row too large");
5579     rp   = aj + ai[row];
5580     ap   = aa + ai[row];
5581     rmax = imax[row];
5582     nrow = ailen[row];
5583     low  = 0;
5584     high = nrow;
5585     for (l = 0; l < n; l++) { /* loop over added columns */
5586       if (in[l] < 0) continue;
5587       PetscCheck(in[l] < A->cmap->n, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Column too large");
5588       col = in[l];
5589       if (roworiented) value = v[l + k * n];
5590       else value = v[k + l * m];
5591 
5592       if (value == 0.0 && ignorezeroentries && (is == ADD_VALUES)) continue;
5593 
5594       if (col <= lastcol) low = 0;
5595       else high = nrow;
5596       lastcol = col;
5597       while (high - low > 5) {
5598         t = (low + high) / 2;
5599         if (rp[t] > col) high = t;
5600         else low = t;
5601       }
5602       for (i = low; i < high; i++) {
5603         if (rp[i] > col) break;
5604         if (rp[i] == col) {
5605           if (is == ADD_VALUES) ap[i] += value;
5606           else ap[i] = value;
5607           goto noinsert;
5608         }
5609       }
5610       if (value == 0.0 && ignorezeroentries) goto noinsert;
5611       if (nonew == 1) goto noinsert;
5612       PetscCheck(nonew != -1, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero in the matrix");
5613       MatSeqXAIJReallocateAIJ(A, A->rmap->n, 1, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
5614       N = nrow++ - 1;
5615       a->nz++;
5616       high++;
5617       /* shift up all the later entries in this row */
5618       for (ii = N; ii >= i; ii--) {
5619         rp[ii + 1] = rp[ii];
5620         ap[ii + 1] = ap[ii];
5621       }
5622       rp[i] = col;
5623       ap[i] = value;
5624       A->nonzerostate++;
5625     noinsert:;
5626       low = i + 1;
5627     }
5628     ailen[row] = nrow;
5629   }
5630   PetscFunctionReturnVoid();
5631 }
5632 /* Undefining these here since they were redefined from their original definition above! No
5633  * other PETSc functions should be defined past this point, as it is impossible to recover the
5634  * original definitions */
5635 #undef PetscCall
5636 #undef SETERRQ
5637