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