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