Actual source code: sbaij.c

  1: /*
  2:     Defines the basic matrix operations for the SBAIJ (compressed row)
  3:   matrix storage format.
  4: */
  5: #include <../src/mat/impls/baij/seq/baij.h>
  6: #include <../src/mat/impls/sbaij/seq/sbaij.h>
  7: #include <petsc/private/kernels/blocktranspose.h>
  8: #include <petscblaslapack.h>

 10: #include <../src/mat/impls/sbaij/seq/relax.h>
 11: #define USESHORT
 12: #include <../src/mat/impls/sbaij/seq/relax.h>

 14: /* defines MatSetValues_Seq_Hash(), MatAssemblyEnd_Seq_Hash(), MatSetUp_Seq_Hash() */
 15: #define TYPE SBAIJ
 16: #define TYPE_SBAIJ
 17: #define TYPE_BS
 18: #include "../src/mat/impls/aij/seq/seqhashmatsetvalues.h"
 19: #undef TYPE_BS
 20: #define TYPE_BS _BS
 21: #define TYPE_BS_ON
 22: #include "../src/mat/impls/aij/seq/seqhashmatsetvalues.h"
 23: #undef TYPE_BS
 24: #undef TYPE_SBAIJ
 25: #include "../src/mat/impls/aij/seq/seqhashmat.h"
 26: #undef TYPE
 27: #undef TYPE_BS_ON

 29: #if PetscDefined(HAVE_ELEMENTAL)
 30: PETSC_INTERN PetscErrorCode MatConvert_SeqSBAIJ_Elemental(Mat, MatType, MatReuse, Mat *);
 31: #endif
 32: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
 33: PETSC_INTERN PetscErrorCode MatConvert_SBAIJ_ScaLAPACK(Mat, MatType, MatReuse, Mat *);
 34: #endif
 35: PETSC_INTERN PetscErrorCode MatConvert_MPISBAIJ_Basic(Mat, MatType, MatReuse, Mat *);

 37: MatGetDiagonalMarkers(SeqSBAIJ, A->rmap->bs)

 39: static PetscErrorCode MatGetColumnReductions_SeqSBAIJ(Mat A, PetscInt type, PetscReal *reductions)
 40: {
 41:   Mat_SeqSBAIJ    *aij = (Mat_SeqSBAIJ *)A->data;
 42:   PetscInt         m, n, bs = A->rmap->bs, bs2 = aij->bs2;
 43:   PetscBool        implicit, hermitian;
 44:   const PetscInt  *ai = aij->i, *aj = aij->j;
 45:   const MatScalar *aa = aij->a;

 47:   PetscFunctionBegin;
 48:   PetscCall(MatGetSize(A, &m, &n));
 49:   PetscCheck(type == NORM_2 || type == NORM_1 || type == NORM_INFINITY || type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART || type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");
 50:   PetscCall(PetscArrayzero(reductions, n));
 51:   implicit  = (PetscBool)(m == n && (A->symmetric == PETSC_BOOL3_TRUE || A->hermitian == PETSC_BOOL3_TRUE));
 52:   hermitian = (PetscBool)(implicit && PetscDefined(USE_COMPLEX) && A->hermitian == PETSC_BOOL3_TRUE);
 53:   for (PetscInt i = 0; i < aij->mbs; i++) {
 54:     for (PetscInt k = ai[i]; k < ai[i + 1]; k++) {
 55:       const PetscBool offdiag = (PetscBool)(implicit && aj[k] != i);

 57:       for (PetscInt jb = 0; jb < bs; jb++) {
 58:         for (PetscInt ib = 0; ib < bs; ib++) {
 59:           const MatScalar value = aa[k * bs2 + jb * bs + ib];
 60:           const PetscInt  col = aj[k] * bs + jb, row = i * bs + ib;
 61:           PetscReal       reduction;

 63:           if (type == NORM_2) reduction = PetscAbsScalar(value * value);
 64:           else if (type == NORM_1 || type == NORM_INFINITY) reduction = PetscAbsScalar(value);
 65:           else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) reduction = PetscRealPart(value);
 66:           else reduction = PetscImaginaryPart(value);
 67:           if (type == NORM_INFINITY) reductions[col] = PetscMax(reduction, reductions[col]);
 68:           else reductions[col] += reduction;
 69:           if (offdiag) {
 70:             if (hermitian && (type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART)) reduction = -reduction;
 71:             if (type == NORM_INFINITY) reductions[row] = PetscMax(reduction, reductions[row]);
 72:             else reductions[row] += reduction;
 73:           }
 74:         }
 75:       }
 76:     }
 77:   }
 78:   if (type == NORM_2) {
 79:     for (PetscInt i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
 80:   } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
 81:     for (PetscInt i = 0; i < n; i++) reductions[i] /= m;
 82:   }
 83:   PetscFunctionReturn(PETSC_SUCCESS);
 84: }

 86: static PetscErrorCode MatGetRowIJ_SeqSBAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool blockcompressed, PetscInt *nn, const PetscInt *inia[], const PetscInt *inja[], PetscBool *done)
 87: {
 88:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
 89:   PetscInt      i, j, n = a->mbs, nz = a->i[n], *tia, *tja, bs = A->rmap->bs, k, l, cnt;
 90:   PetscInt    **ia = (PetscInt **)inia, **ja = (PetscInt **)inja;

 92:   PetscFunctionBegin;
 93:   *nn = n;
 94:   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);
 95:   if (symmetric) {
 96:     PetscCall(MatToSymmetricIJ_SeqAIJ(n, a->i, a->j, PETSC_FALSE, 0, 0, &tia, &tja));
 97:     nz = tia[n];
 98:   } else {
 99:     tia = a->i;
100:     tja = a->j;
101:   }

103:   if (!blockcompressed && bs > 1) {
104:     (*nn) *= bs;
105:     /* malloc & create the natural set of indices */
106:     PetscCall(PetscMalloc1((n + 1) * bs, ia));
107:     if (n) {
108:       (*ia)[0] = oshift;
109:       for (j = 1; j < bs; j++) (*ia)[j] = (tia[1] - tia[0]) * bs + (*ia)[j - 1];
110:     }

112:     for (i = 1; i < n; i++) {
113:       (*ia)[i * bs] = (tia[i] - tia[i - 1]) * bs + (*ia)[i * bs - 1];
114:       for (j = 1; j < bs; j++) (*ia)[i * bs + j] = (tia[i + 1] - tia[i]) * bs + (*ia)[i * bs + j - 1];
115:     }
116:     if (n) (*ia)[n * bs] = (tia[n] - tia[n - 1]) * bs + (*ia)[n * bs - 1];

118:     if (inja) {
119:       PetscCall(PetscMalloc1(nz * bs * bs, ja));
120:       cnt = 0;
121:       for (i = 0; i < n; i++) {
122:         for (j = 0; j < bs; j++) {
123:           for (k = tia[i]; k < tia[i + 1]; k++) {
124:             for (l = 0; l < bs; l++) (*ja)[cnt++] = bs * tja[k] + l;
125:           }
126:         }
127:       }
128:     }

130:     if (symmetric) { /* deallocate memory allocated in MatToSymmetricIJ_SeqAIJ() */
131:       PetscCall(PetscFree(tia));
132:       PetscCall(PetscFree(tja));
133:     }
134:   } else if (oshift == 1) {
135:     if (symmetric) {
136:       nz = tia[A->rmap->n / bs];
137:       /*  add 1 to i and j indices */
138:       for (i = 0; i < A->rmap->n / bs + 1; i++) tia[i] = tia[i] + 1;
139:       *ia = tia;
140:       if (ja) {
141:         for (i = 0; i < nz; i++) tja[i] = tja[i] + 1;
142:         *ja = tja;
143:       }
144:     } else {
145:       nz = a->i[A->rmap->n / bs];
146:       /* malloc space and  add 1 to i and j indices */
147:       PetscCall(PetscMalloc1(A->rmap->n / bs + 1, ia));
148:       for (i = 0; i < A->rmap->n / bs + 1; i++) (*ia)[i] = a->i[i] + 1;
149:       if (ja) {
150:         PetscCall(PetscMalloc1(nz, ja));
151:         for (i = 0; i < nz; i++) (*ja)[i] = a->j[i] + 1;
152:       }
153:     }
154:   } else {
155:     *ia = tia;
156:     if (ja) *ja = tja;
157:   }
158:   PetscFunctionReturn(PETSC_SUCCESS);
159: }

161: static PetscErrorCode MatRestoreRowIJ_SeqSBAIJ(Mat A, PetscInt oshift, PetscBool symmetric, PetscBool blockcompressed, PetscInt *nn, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
162: {
163:   PetscFunctionBegin;
164:   if (!ia) PetscFunctionReturn(PETSC_SUCCESS);
165:   if ((!blockcompressed && A->rmap->bs > 1) || (symmetric || oshift == 1)) {
166:     PetscCall(PetscFree(*ia));
167:     if (ja) PetscCall(PetscFree(*ja));
168:   }
169:   PetscFunctionReturn(PETSC_SUCCESS);
170: }

172: PetscErrorCode MatDestroy_SeqSBAIJ(Mat A)
173: {
174:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;

176:   PetscFunctionBegin;
177:   if (A->hash_active) {
178:     PetscInt bs;
179:     A->ops[0] = a->cops;
180:     PetscCall(PetscHMapIJVDestroy(&a->ht));
181:     PetscCall(MatGetBlockSize(A, &bs));
182:     if (bs > 1) PetscCall(PetscHSetIJDestroy(&a->bht));
183:     PetscCall(PetscFree(a->dnz));
184:     PetscCall(PetscFree(a->bdnz));
185:     A->hash_active = PETSC_FALSE;
186:   }
187:   PetscCall(PetscLogObjectState((PetscObject)A, "Rows=%" PetscInt_FMT ", NZ=%" PetscInt_FMT, A->rmap->N, a->nz));
188:   PetscCall(MatSeqXAIJFreeAIJ(A, &a->a, &a->j, &a->i));
189:   PetscCall(PetscFree(a->diag));
190:   PetscCall(ISDestroy(&a->row));
191:   PetscCall(ISDestroy(&a->col));
192:   PetscCall(ISDestroy(&a->icol));
193:   PetscCall(PetscFree(a->idiag));
194:   PetscCall(PetscFree(a->inode.size_csr));
195:   if (a->free_imax_ilen) PetscCall(PetscFree2(a->imax, a->ilen));
196:   PetscCall(PetscFree(a->solve_work));
197:   PetscCall(PetscFree(a->sor_work));
198:   PetscCall(PetscFree(a->solves_work));
199:   PetscCall(PetscFree(a->mult_work));
200:   PetscCall(PetscFree(a->saved_values));
201:   if (a->free_jshort) PetscCall(PetscFree(a->jshort));
202:   PetscCall(PetscFree(a->inew));
203:   PetscCall(MatDestroy(&a->parent));
204:   PetscCall(MatDestroySubMatrix_Private(a->submatis1));
205:   PetscCall(PetscFree(A->data));

207:   PetscCall(PetscObjectChangeTypeName((PetscObject)A, NULL));
208:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqSBAIJGetArray_C", NULL));
209:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqSBAIJRestoreArray_C", NULL));
210:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatStoreValues_C", NULL));
211:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatRetrieveValues_C", NULL));
212:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqSBAIJSetColumnIndices_C", NULL));
213:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqsbaij_seqaij_C", NULL));
214:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqsbaij_seqbaij_C", NULL));
215:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqSBAIJSetPreallocation_C", NULL));
216:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqSBAIJSetPreallocationCSR_C", NULL));
217: #if PetscDefined(HAVE_ELEMENTAL)
218:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqsbaij_elemental_C", NULL));
219: #endif
220: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
221:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqsbaij_scalapack_C", NULL));
222: #endif
223:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatFactorGetSolverType_C", NULL));
224:   PetscFunctionReturn(PETSC_SUCCESS);
225: }

227: static PetscErrorCode MatSetOption_SeqSBAIJ(Mat A, MatOption op, PetscBool flg)
228: {
229:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;

231:   PetscFunctionBegin;
232:   switch (op) {
233:   case MAT_ROW_ORIENTED:
234:     a->roworiented = flg;
235:     break;
236:   case MAT_KEEP_NONZERO_PATTERN:
237:     a->keepnonzeropattern = flg;
238:     break;
239:   case MAT_NEW_NONZERO_LOCATIONS:
240:     a->nonew = (flg ? 0 : 1);
241:     break;
242:   case MAT_NEW_NONZERO_LOCATION_ERR:
243:     a->nonew = (flg ? -1 : 0);
244:     break;
245:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
246:     a->nonew = (flg ? -2 : 0);
247:     break;
248:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
249:     a->nounused = (flg ? -1 : 0);
250:     break;
251:   case MAT_HERMITIAN:
252:     if (PetscDefined(USE_COMPLEX) && flg) { /* disable transpose ops */
253:       PetscInt bs;

255:       PetscCall(MatGetBlockSize(A, &bs));
256:       PetscCheck(bs <= 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for Hermitian with block size greater than 1");
257:       A->ops->multtranspose    = NULL;
258:       A->ops->multtransposeadd = NULL;
259:     }
260:     break;
261:   case MAT_SYMMETRIC:
262:   case MAT_SPD:
263:     if (PetscDefined(USE_COMPLEX) && flg) { /* An Hermitian and symmetric matrix has zero imaginary part (restore back transpose ops) */
264:       A->ops->multtranspose    = A->ops->mult;
265:       A->ops->multtransposeadd = A->ops->multadd;
266:     }
267:     break;
268:   case MAT_IGNORE_LOWER_TRIANGULAR:
269:   case MAT_ERROR_LOWER_TRIANGULAR:
270:     a->ignore_ltriangular = flg;
271:     break;
272:   case MAT_GETROW_UPPERTRIANGULAR:
273:     a->getrow_utriangular = flg;
274:     break;
275:   case MAT_STRUCTURE_ONLY:
276:     if (flg) {
277:       PetscCall(MatXAIJDeallocatea(A, &a->a));
278:       a->a = NULL;
279:     }
280:     break;
281:   default:
282:     break;
283:   }
284:   PetscFunctionReturn(PETSC_SUCCESS);
285: }

287: PetscErrorCode MatGetRow_SeqSBAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
288: {
289:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;

291:   PetscFunctionBegin;
292:   PetscCheck(!A || a->getrow_utriangular, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatGetRow is not supported for SBAIJ matrix format. Getting the upper triangular part of row, run with -mat_getrow_uppertriangular, call MatSetOption(mat,MAT_GETROW_UPPERTRIANGULAR,PETSC_TRUE) or MatGetRowUpperTriangular()");

294:   /* Get the upper triangular part of the row */
295:   PetscCall(MatGetRow_SeqBAIJ_private(A, row, nz, idx, v, a->i, a->j, a->a));
296:   PetscFunctionReturn(PETSC_SUCCESS);
297: }

299: PetscErrorCode MatRestoreRow_SeqSBAIJ(Mat A, PetscInt row, PetscInt *nz, PetscInt **idx, PetscScalar **v)
300: {
301:   PetscFunctionBegin;
302:   if (idx) PetscCall(PetscFree(*idx));
303:   if (v) PetscCall(PetscFree(*v));
304:   PetscFunctionReturn(PETSC_SUCCESS);
305: }

307: static PetscErrorCode MatGetRowUpperTriangular_SeqSBAIJ(Mat A)
308: {
309:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;

311:   PetscFunctionBegin;
312:   a->getrow_utriangular = PETSC_TRUE;
313:   PetscFunctionReturn(PETSC_SUCCESS);
314: }

316: static PetscErrorCode MatRestoreRowUpperTriangular_SeqSBAIJ(Mat A)
317: {
318:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;

320:   PetscFunctionBegin;
321:   a->getrow_utriangular = PETSC_FALSE;
322:   PetscFunctionReturn(PETSC_SUCCESS);
323: }

325: static PetscErrorCode MatTranspose_SeqSBAIJ(Mat A, MatReuse reuse, Mat *B)
326: {
327:   PetscFunctionBegin;
328:   if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *B));
329:   if (reuse == MAT_INITIAL_MATRIX) {
330:     PetscCall(MatDuplicate(A, MAT_COPY_VALUES, B));
331:   } else if (reuse == MAT_REUSE_MATRIX) {
332:     PetscCall(MatCopy(A, *B, SAME_NONZERO_PATTERN));
333:   }
334:   PetscFunctionReturn(PETSC_SUCCESS);
335: }

337: static PetscErrorCode MatView_SeqSBAIJ_ASCII(Mat A, PetscViewer viewer)
338: {
339:   Mat_SeqSBAIJ     *a = (Mat_SeqSBAIJ *)A->data;
340:   PetscInt          i, j, bs = A->rmap->bs, k, l, bs2 = a->bs2;
341:   PetscViewerFormat format;
342:   const PetscInt   *diag;
343:   const char       *matname;

345:   PetscFunctionBegin;
346:   if (A->structure_only) {
347:     PetscCall(MatView_SeqBAIJ(A, viewer));
348:     PetscFunctionReturn(PETSC_SUCCESS);
349:   }
350:   PetscCall(PetscViewerGetFormat(viewer, &format));
351:   if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
352:   } else if (format == PETSC_VIEWER_ASCII_MATLAB) {
353:     Mat aij;

355:     if (A->factortype && bs > 1) {
356:       PetscCall(PetscPrintf(PETSC_COMM_SELF, "Warning: matrix is factored with bs>1. MatView() with PETSC_VIEWER_ASCII_MATLAB is not supported and ignored!\n"));
357:       PetscFunctionReturn(PETSC_SUCCESS);
358:     }
359:     PetscCall(MatConvert(A, MATSEQAIJ, MAT_INITIAL_MATRIX, &aij));
360:     if (((PetscObject)A)->name) PetscCall(PetscObjectGetName((PetscObject)A, &matname));
361:     if (((PetscObject)A)->name) PetscCall(PetscObjectSetName((PetscObject)aij, matname));
362:     PetscCall(MatView_SeqAIJ(aij, viewer));
363:     PetscCall(MatDestroy(&aij));
364:   } else if (format == PETSC_VIEWER_ASCII_COMMON) {
365:     Mat B;

367:     PetscCall(MatConvert(A, MATSEQAIJ, MAT_INITIAL_MATRIX, &B));
368:     if (((PetscObject)A)->name) PetscCall(PetscObjectGetName((PetscObject)A, &matname));
369:     if (((PetscObject)A)->name) PetscCall(PetscObjectSetName((PetscObject)B, matname));
370:     PetscCall(MatView_SeqAIJ(B, viewer));
371:     PetscCall(MatDestroy(&B));
372:   } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
373:     PetscFunctionReturn(PETSC_SUCCESS);
374:   } else {
375:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
376:     if (A->factortype) { /* for factored matrix */
377:       PetscCheck(bs <= 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "matrix is factored with bs>1. Not implemented yet");
378:       PetscCall(MatGetDiagonalMarkers_SeqSBAIJ(A, &diag, NULL));
379:       for (i = 0; i < a->mbs; i++) { /* for row block i */
380:         PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
381:         /* diagonal entry */
382:         if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[diag[i]]) > 0.0) {
383:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i) ", a->j[diag[i]], (double)PetscRealPart(1.0 / a->a[diag[i]]), (double)PetscImaginaryPart(1.0 / a->a[diag[i]])));
384:         } else if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[diag[i]]) < 0.0) {
385:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i) ", a->j[diag[i]], (double)PetscRealPart(1.0 / a->a[diag[i]]), -(double)PetscImaginaryPart(1.0 / a->a[diag[i]])));
386:         } else {
387:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", a->j[diag[i]], (double)PetscRealPart(1.0 / a->a[diag[i]])));
388:         }
389:         /* off-diagonal entries */
390:         for (k = a->i[i]; k < a->i[i + 1] - 1; k++) {
391:           if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[k]) > 0.0) {
392:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i) ", bs * a->j[k], (double)PetscRealPart(a->a[k]), (double)PetscImaginaryPart(a->a[k])));
393:           } else if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[k]) < 0.0) {
394:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i) ", bs * a->j[k], (double)PetscRealPart(a->a[k]), -(double)PetscImaginaryPart(a->a[k])));
395:           } else {
396:             PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", bs * a->j[k], (double)PetscRealPart(a->a[k])));
397:           }
398:         }
399:         PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
400:       }

402:     } else {                         /* for non-factored matrix */
403:       for (i = 0; i < a->mbs; i++) { /* for row block i */
404:         for (j = 0; j < bs; j++) {   /* for row bs*i + j */
405:           PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i * bs + j));
406:           for (k = a->i[i]; k < a->i[i + 1]; k++) { /* for column block */
407:             for (l = 0; l < bs; l++) {              /* for column */
408:               if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[bs2 * k + l * bs + j]) > 0.0) {
409:                 PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i) ", bs * a->j[k] + l, (double)PetscRealPart(a->a[bs2 * k + l * bs + j]), (double)PetscImaginaryPart(a->a[bs2 * k + l * bs + j])));
410:               } else if (PetscDefined(USE_COMPLEX) && PetscImaginaryPart(a->a[bs2 * k + l * bs + j]) < 0.0) {
411:                 PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g - %g i) ", bs * a->j[k] + l, (double)PetscRealPart(a->a[bs2 * k + l * bs + j]), -(double)PetscImaginaryPart(a->a[bs2 * k + l * bs + j])));
412:               } else {
413:                 PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", bs * a->j[k] + l, (double)PetscRealPart(a->a[bs2 * k + l * bs + j])));
414:               }
415:             }
416:           }
417:           PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
418:         }
419:       }
420:     }
421:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
422:   }
423:   PetscCall(PetscViewerFlush(viewer));
424:   PetscFunctionReturn(PETSC_SUCCESS);
425: }

427: #include <petscdraw.h>
428: static PetscErrorCode MatView_SeqSBAIJ_Draw_Zoom(PetscDraw draw, void *Aa)
429: {
430:   Mat           A = (Mat)Aa;
431:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
432:   PetscInt      row, i, j, k, l, mbs = a->mbs, bs = A->rmap->bs, bs2 = a->bs2;
433:   PetscReal     xl, yl, xr, yr, x_l, x_r, y_l, y_r;
434:   MatScalar    *aa;
435:   PetscViewer   viewer;
436:   int           color;

438:   PetscFunctionBegin;
439:   PetscCall(PetscObjectQuery((PetscObject)A, "Zoomviewer", (PetscObject *)&viewer));
440:   PetscCall(PetscDrawGetCoordinates(draw, &xl, &yl, &xr, &yr));

442:   /* loop over matrix elements drawing boxes */

444:   PetscDrawCollectiveBegin(draw);
445:   PetscCall(PetscDrawString(draw, .3 * (xl + xr), .3 * (yl + yr), PETSC_DRAW_BLACK, "symmetric"));
446:   /* Blue for negative, Cyan for zero and  Red for positive */
447:   color = PETSC_DRAW_BLUE;
448:   for (i = 0, row = 0; i < mbs; i++, row += bs) {
449:     for (j = a->i[i]; j < a->i[i + 1]; j++) {
450:       y_l = A->rmap->N - row - 1.0;
451:       y_r = y_l + 1.0;
452:       x_l = a->j[j] * bs;
453:       x_r = x_l + 1.0;
454:       aa  = a->a + j * bs2;
455:       for (k = 0; k < bs; k++) {
456:         for (l = 0; l < bs; l++) {
457:           if (PetscRealPart(*aa++) >= 0.) continue;
458:           PetscCall(PetscDrawRectangle(draw, x_l + k, y_l - l, x_r + k, y_r - l, color, color, color, color));
459:         }
460:       }
461:     }
462:   }
463:   color = PETSC_DRAW_CYAN;
464:   for (i = 0, row = 0; i < mbs; i++, row += bs) {
465:     for (j = a->i[i]; j < a->i[i + 1]; j++) {
466:       y_l = A->rmap->N - row - 1.0;
467:       y_r = y_l + 1.0;
468:       x_l = a->j[j] * bs;
469:       x_r = x_l + 1.0;
470:       aa  = a->a + j * bs2;
471:       for (k = 0; k < bs; k++) {
472:         for (l = 0; l < bs; l++) {
473:           if (PetscRealPart(*aa++) != 0.) continue;
474:           PetscCall(PetscDrawRectangle(draw, x_l + k, y_l - l, x_r + k, y_r - l, color, color, color, color));
475:         }
476:       }
477:     }
478:   }
479:   color = PETSC_DRAW_RED;
480:   for (i = 0, row = 0; i < mbs; i++, row += bs) {
481:     for (j = a->i[i]; j < a->i[i + 1]; j++) {
482:       y_l = A->rmap->N - row - 1.0;
483:       y_r = y_l + 1.0;
484:       x_l = a->j[j] * bs;
485:       x_r = x_l + 1.0;
486:       aa  = a->a + j * bs2;
487:       for (k = 0; k < bs; k++) {
488:         for (l = 0; l < bs; l++) {
489:           if (PetscRealPart(*aa++) <= 0.) continue;
490:           PetscCall(PetscDrawRectangle(draw, x_l + k, y_l - l, x_r + k, y_r - l, color, color, color, color));
491:         }
492:       }
493:     }
494:   }
495:   PetscDrawCollectiveEnd(draw);
496:   PetscFunctionReturn(PETSC_SUCCESS);
497: }

499: static PetscErrorCode MatView_SeqSBAIJ_Draw(Mat A, PetscViewer viewer)
500: {
501:   PetscReal xl, yl, xr, yr, w, h;
502:   PetscDraw draw;
503:   PetscBool isnull;

505:   PetscFunctionBegin;
506:   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
507:   PetscCall(PetscDrawIsNull(draw, &isnull));
508:   if (isnull) PetscFunctionReturn(PETSC_SUCCESS);

510:   xr = A->rmap->N;
511:   yr = A->rmap->N;
512:   h  = yr / 10.0;
513:   w  = xr / 10.0;
514:   xr += w;
515:   yr += h;
516:   xl = -w;
517:   yl = -h;
518:   PetscCall(PetscDrawSetCoordinates(draw, xl, yl, xr, yr));
519:   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", (PetscObject)viewer));
520:   PetscCall(PetscDrawZoom(draw, MatView_SeqSBAIJ_Draw_Zoom, A));
521:   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", NULL));
522:   PetscCall(PetscDrawSave(draw));
523:   PetscFunctionReturn(PETSC_SUCCESS);
524: }

526: /* Used for both MPIBAIJ and MPISBAIJ matrices */
527: #define MatView_SeqSBAIJ_Binary MatView_SeqBAIJ_Binary

529: PetscErrorCode MatView_SeqSBAIJ(Mat A, PetscViewer viewer)
530: {
531:   PetscBool isascii, isbinary, isdraw;

533:   PetscFunctionBegin;
534:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
535:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
536:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
537:   if (isascii) {
538:     PetscCall(MatView_SeqSBAIJ_ASCII(A, viewer));
539:   } else if (isbinary) {
540:     PetscCall(MatView_SeqSBAIJ_Binary(A, viewer));
541:   } else if (isdraw) {
542:     PetscCall(MatView_SeqSBAIJ_Draw(A, viewer));
543:   } else {
544:     Mat         B;
545:     const char *matname;
546:     PetscCall(MatConvert(A, MATSEQAIJ, MAT_INITIAL_MATRIX, &B));
547:     if (((PetscObject)A)->name) PetscCall(PetscObjectGetName((PetscObject)A, &matname));
548:     if (((PetscObject)A)->name) PetscCall(PetscObjectSetName((PetscObject)B, matname));
549:     PetscCall(MatView(B, viewer));
550:     PetscCall(MatDestroy(&B));
551:   }
552:   PetscFunctionReturn(PETSC_SUCCESS);
553: }

555: PetscErrorCode MatGetValues_SeqSBAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], PetscScalar v[])
556: {
557:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
558:   PetscInt     *rp, k, low, high, t, row, nrow, i, col, l, *aj = a->j;
559:   PetscInt     *ai = a->i, *ailen = a->ilen;
560:   PetscInt      brow, bcol, ridx, cidx, bs = A->rmap->bs, bs2 = a->bs2;
561:   MatScalar    *ap, *aa = a->a;
562:   PetscBool     roworiented = a->roworiented;
563:   PetscScalar  *value;

565:   PetscFunctionBegin;
566:   for (k = 0; k < m; k++) { /* loop over rows */
567:     row = im[k];
568:     if (row < 0) continue; /* negative row */
569:     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);
570:     brow = row / bs;
571:     rp   = aj + ai[brow];
572:     ap   = aa + bs2 * ai[brow];
573:     nrow = ailen[brow];
574:     for (l = 0; l < n; l++) {  /* loop over columns */
575:       if (in[l] < 0) continue; /* negative column */
576:       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);
577:       value = roworiented ? &v[l + k * n] : &v[k + l * m];
578:       col   = in[l];
579:       bcol  = col / bs;
580:       cidx  = col % bs;
581:       ridx  = row % bs;
582:       high  = nrow;
583:       low   = 0; /* assume unsorted */
584:       while (high - low > 5) {
585:         t = (low + high) / 2;
586:         if (rp[t] > bcol) high = t;
587:         else low = t;
588:       }
589:       for (i = low; i < high; i++) {
590:         if (rp[i] > bcol) break;
591:         if (rp[i] == bcol) {
592:           *value = ap[bs2 * i + bs * cidx + ridx];
593:           goto finished;
594:         }
595:       }
596:       *value = 0.0;
597:     finished:;
598:     }
599:   }
600:   PetscFunctionReturn(PETSC_SUCCESS);
601: }

603: static PetscErrorCode MatPermute_SeqSBAIJ(Mat A, IS rowp, IS colp, Mat *B)
604: {
605:   Mat_SeqSBAIJ   *a = (Mat_SeqSBAIJ *)A->data, *b = NULL;
606:   Mat_SeqBAIJ    *c = NULL;
607:   Mat             C;
608:   IS              browp, bcolp;
609:   const PetscInt *row, *col;
610:   PetscInt       *irow, *icol, *lens, *bi, *bj, *bilen;
611:   MatScalar      *ba, *work;
612:   PetscInt        mbs, nbs, bs = A->rmap->bs, bs2 = a->bs2;
613:   PetscBool       same = (PetscBool)(rowp == colp), implicit = (PetscBool)(A->rmap->N == A->cmap->N && (A->symmetric == PETSC_BOOL3_TRUE || A->hermitian == PETSC_BOOL3_TRUE)), hermitian;

615:   PetscFunctionBegin;
616:   if (same == PETSC_FALSE) PetscCall(ISEqualUnsorted(rowp, colp, &same));
617:   hermitian = (PetscBool)(implicit == PETSC_TRUE && PetscDefined(USE_COMPLEX) && A->hermitian == PETSC_BOOL3_TRUE);
618:   same      = (PetscBool)(implicit == PETSC_TRUE && same == PETSC_TRUE);
619:   PetscCall(ISCompressIndicesGeneral(A->rmap->N, A->rmap->n, bs, 1, &rowp, &browp));
620:   if (rowp == colp) {
621:     bcolp = browp;
622:     PetscCall(PetscObjectReference((PetscObject)bcolp));
623:   } else PetscCall(ISCompressIndicesGeneral(A->cmap->N, A->cmap->n, bs, 1, &colp, &bcolp));
624:   PetscCall(ISGetLocalSize(browp, &mbs));
625:   PetscCall(ISGetLocalSize(bcolp, &nbs));
626:   PetscCheck(mbs == a->mbs && nbs == a->nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Row and column index sets must be block permutations");
627:   PetscCall(ISGetIndices(browp, &row));
628:   PetscCall(ISGetIndices(bcolp, &col));
629:   PetscCall(PetscMalloc2(mbs, &irow, nbs, &icol));
630:   for (PetscInt i = 0; i < mbs; i++) {
631:     PetscCheck(row[i] >= 0 && row[i] < mbs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Row index set is not a block permutation");
632:     irow[row[i]] = i;
633:   }
634:   for (PetscInt i = 0; i < nbs; i++) {
635:     PetscCheck(col[i] >= 0 && col[i] < nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Column index set is not a block permutation");
636:     icol[col[i]] = i;
637:   }
638:   PetscCall(PetscCalloc1(mbs, &lens));
639:   for (PetscInt i = 0; i < a->mbs; i++) {
640:     for (PetscInt k = a->i[i]; k < a->i[i + 1]; k++) {
641:       const PetscInt j = a->j[k];

643:       if (same == PETSC_TRUE) lens[PetscMin(irow[i], icol[j])]++;
644:       else {
645:         lens[irow[i]]++;
646:         if (implicit == PETSC_TRUE && i != j) lens[irow[j]]++;
647:       }
648:     }
649:   }
650:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &C));
651:   PetscCall(MatSetSizes(C, mbs * bs, nbs * bs, mbs * bs, nbs * bs));
652:   PetscCall(MatSetType(C, same == PETSC_TRUE ? ((PetscObject)A)->type_name : MATSEQBAIJ));
653:   if (same == PETSC_TRUE) {
654:     PetscCall(MatSeqSBAIJSetPreallocation(C, bs, 0, lens));
655:     b     = (Mat_SeqSBAIJ *)C->data;
656:     bi    = b->i;
657:     bj    = b->j;
658:     ba    = b->a;
659:     bilen = b->ilen;
660:   } else {
661:     PetscCall(MatSeqBAIJSetPreallocation(C, bs, 0, lens));
662:     c     = (Mat_SeqBAIJ *)C->data;
663:     bi    = c->i;
664:     bj    = c->j;
665:     ba    = c->a;
666:     bilen = c->ilen;
667:   }
668:   PetscCall(PetscFree(lens));
669:   for (PetscInt i = 0; i < a->mbs; i++) {
670:     for (PetscInt k = a->i[i]; k < a->i[i + 1]; k++) {
671:       const PetscInt j = a->j[k];
672:       PetscInt       r = irow[i], colidx = icol[j], pos;
673:       MatScalar     *block;

675:       if (same == PETSC_TRUE && r > colidx) {
676:         pos    = r;
677:         r      = colidx;
678:         colidx = pos;
679:       }
680:       pos     = bi[r] + bilen[r]++;
681:       bj[pos] = colidx;
682:       block   = ba + pos * bs2;
683:       PetscCall(PetscArraycpy(block, a->a + k * bs2, bs2));
684:       if (same == PETSC_TRUE && irow[i] > icol[j]) {
685:         PetscCall(PetscKernel_A_gets_transpose_A_N(block, bs));
686:         if (hermitian == PETSC_TRUE) {
687:           for (PetscInt q = 0; q < bs2; q++) block[q] = PetscConj(block[q]);
688:         }
689:       }
690:       if (same == PETSC_FALSE && implicit == PETSC_TRUE && i != j) {
691:         r       = irow[j];
692:         colidx  = icol[i];
693:         pos     = bi[r] + bilen[r]++;
694:         bj[pos] = colidx;
695:         block   = ba + pos * bs2;
696:         PetscCall(PetscArraycpy(block, a->a + k * bs2, bs2));
697:         PetscCall(PetscKernel_A_gets_transpose_A_N(block, bs));
698:         if (hermitian == PETSC_TRUE) {
699:           for (PetscInt q = 0; q < bs2; q++) block[q] = PetscConj(block[q]);
700:         }
701:       }
702:     }
703:   }
704:   PetscCall(PetscMalloc1(bs2, &work));
705:   for (PetscInt i = 0; i < mbs; i++) PetscCall(PetscSortIntWithDataArray(bilen[i], PetscSafePointerPlusOffset(bj, bi[i]), PetscSafePointerPlusOffset(ba, bi[i] * bs2), bs2 * sizeof(MatScalar), work));
706:   PetscCall(PetscFree(work));
707:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
708:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
709:   if (same == PETSC_TRUE) PetscCall(MatPropagateSymmetryOptions(A, C));
710:   PetscCall(PetscFree2(irow, icol));
711:   PetscCall(ISRestoreIndices(browp, &row));
712:   PetscCall(ISRestoreIndices(bcolp, &col));
713:   PetscCall(ISDestroy(&browp));
714:   PetscCall(ISDestroy(&bcolp));
715:   *B = C;
716:   PetscFunctionReturn(PETSC_SUCCESS);
717: }

719: PetscErrorCode MatSetValuesBlocked_SeqSBAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
720: {
721:   Mat_SeqSBAIJ      *a = (Mat_SeqSBAIJ *)A->data;
722:   PetscInt          *rp, k, low, high, t, ii, jj, row, nrow, i, col, l, rmax, N, lastcol = -1;
723:   PetscInt          *imax = a->imax, *ai = a->i, *ailen = a->ilen;
724:   PetscInt          *aj = a->j, nonew = a->nonew, bs2 = a->bs2, bs = A->rmap->bs, stepval;
725:   PetscBool          roworiented = a->roworiented;
726:   const PetscScalar *value       = v;
727:   MatScalar         *ap = NULL, *aa = a->a, *bap;

729:   PetscFunctionBegin;
730:   if (roworiented) stepval = (n - 1) * bs;
731:   else stepval = (m - 1) * bs;
732:   for (k = 0; k < m; k++) { /* loop over added rows */
733:     row = im[k];
734:     if (row < 0) continue;
735:     PetscCheck(row < a->mbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Block index row too large %" PetscInt_FMT " max %" PetscInt_FMT, row, a->mbs - 1);
736:     rp   = aj + ai[row];
737:     ap   = PetscSafePointerPlusOffset(aa, bs2 * ai[row]);
738:     rmax = imax[row];
739:     nrow = ailen[row];
740:     low  = 0;
741:     high = nrow;
742:     for (l = 0; l < n; l++) { /* loop over added columns */
743:       if (in[l] < 0) continue;
744:       col = in[l];
745:       PetscCheck(col < a->nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Block index column too large %" PetscInt_FMT " max %" PetscInt_FMT, col, a->nbs - 1);
746:       if (col < row) {
747:         PetscCheck(a->ignore_ltriangular, PETSC_COMM_SELF, PETSC_ERR_USER, "Lower triangular value cannot be set for sbaij format. Ignoring these values, run with -mat_ignore_lower_triangular or call MatSetOption(mat,MAT_IGNORE_LOWER_TRIANGULAR,PETSC_TRUE)");
748:         continue; /* ignore lower triangular block */
749:       }
750:       if (!A->structure_only) {
751:         if (roworiented) value = v + k * (stepval + bs) * bs + l * bs;
752:         else value = v + l * (stepval + bs) * bs + k * bs;
753:       }

755:       if (col <= lastcol) low = 0;
756:       else high = nrow;

758:       lastcol = col;
759:       while (high - low > 7) {
760:         t = (low + high) / 2;
761:         if (rp[t] > col) high = t;
762:         else low = t;
763:       }
764:       for (i = low; i < high; i++) {
765:         if (rp[i] > col) break;
766:         if (rp[i] == col) {
767:           if (A->structure_only) goto noinsert2;
768:           bap = ap + bs2 * i;
769:           if (roworiented) {
770:             if (is == ADD_VALUES) {
771:               for (ii = 0; ii < bs; ii++, value += stepval) {
772:                 for (jj = ii; jj < bs2; jj += bs) bap[jj] += *value++;
773:               }
774:             } else {
775:               for (ii = 0; ii < bs; ii++, value += stepval) {
776:                 for (jj = ii; jj < bs2; jj += bs) bap[jj] = *value++;
777:               }
778:             }
779:           } else {
780:             if (is == ADD_VALUES) {
781:               for (ii = 0; ii < bs; ii++, value += stepval) {
782:                 for (jj = 0; jj < bs; jj++) *bap++ += *value++;
783:               }
784:             } else {
785:               for (ii = 0; ii < bs; ii++, value += stepval) {
786:                 for (jj = 0; jj < bs; jj++) *bap++ = *value++;
787:               }
788:             }
789:           }
790:           goto noinsert2;
791:         }
792:       }
793:       if (nonew == 1) goto noinsert2;
794:       PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new block index nonzero block (%" PetscInt_FMT ", %" PetscInt_FMT ") in the matrix", row, col);
795:       if (A->structure_only) MatSeqXAIJReallocateAIJ_structure_only(A, a->mbs, bs2, nrow, row, col, rmax, ai, aj, rp, imax, nonew, MatScalar);
796:       else MatSeqXAIJReallocateAIJ(A, a->mbs, bs2, nrow, row, col, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);
797:       N = nrow++ - 1;
798:       high++;
799:       /* shift up all the later entries in this row */
800:       PetscCall(PetscArraymove(rp + i + 1, rp + i, N - i + 1));
801:       rp[i] = col;
802:       if (!A->structure_only) {
803:         PetscCall(PetscArraymove(ap + bs2 * (i + 1), ap + bs2 * i, bs2 * (N - i + 1)));
804:         PetscCall(PetscArrayzero(ap + bs2 * i, bs2));
805:         bap = ap + bs2 * i;
806:         if (roworiented) {
807:           for (ii = 0; ii < bs; ii++, value += stepval) {
808:             for (jj = ii; jj < bs2; jj += bs) bap[jj] = *value++;
809:           }
810:         } else {
811:           for (ii = 0; ii < bs; ii++, value += stepval) {
812:             for (jj = 0; jj < bs; jj++) *bap++ = *value++;
813:           }
814:         }
815:       }
816:     noinsert2:;
817:       low = i;
818:     }
819:     ailen[row] = nrow;
820:   }
821:   PetscFunctionReturn(PETSC_SUCCESS);
822: }

824: static PetscErrorCode MatAssemblyEnd_SeqSBAIJ(Mat A, MatAssemblyType mode)
825: {
826:   Mat_SeqSBAIJ *a      = (Mat_SeqSBAIJ *)A->data;
827:   PetscInt      fshift = 0, i, *ai = a->i, *aj = a->j, *imax = a->imax;
828:   PetscInt      m = A->rmap->N, *ip, N, *ailen = a->ilen;
829:   PetscInt      mbs = a->mbs, bs2 = a->bs2, rmax = 0;
830:   MatScalar    *aa = a->a, *ap;

832:   PetscFunctionBegin;
833:   if (mode == MAT_FLUSH_ASSEMBLY || (A->was_assembled && A->ass_nonzerostate == A->nonzerostate)) PetscFunctionReturn(PETSC_SUCCESS);

835:   if (m) rmax = ailen[0];
836:   for (i = 1; i < mbs; i++) {
837:     /* move each row back by the amount of empty slots (fshift) before it*/
838:     fshift += imax[i - 1] - ailen[i - 1];
839:     rmax = PetscMax(rmax, ailen[i]);
840:     if (fshift) {
841:       ip = aj + ai[i];
842:       N  = ailen[i];
843:       PetscCall(PetscArraymove(ip - fshift, ip, N));
844:       if (!A->structure_only) {
845:         ap = aa + bs2 * ai[i];
846:         PetscCall(PetscArraymove(ap - bs2 * fshift, ap, bs2 * N));
847:       }
848:     }
849:     ai[i] = ai[i - 1] + ailen[i - 1];
850:   }
851:   if (mbs) {
852:     fshift += imax[mbs - 1] - ailen[mbs - 1];
853:     ai[mbs] = ai[mbs - 1] + ailen[mbs - 1];
854:   }
855:   /* reset ilen and imax for each row */
856:   for (i = 0; i < mbs; i++) ailen[i] = imax[i] = ai[i + 1] - ai[i];
857:   a->nz = ai[mbs];

859:   PetscCheck(!fshift || a->nounused != -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Unused space detected in matrix: %" PetscInt_FMT " X %" PetscInt_FMT " block size %" PetscInt_FMT ", %" PetscInt_FMT " unneeded", m, A->cmap->n, A->rmap->bs, fshift * bs2);

861:   PetscCall(PetscInfo(A, "Matrix size: %" PetscInt_FMT " X %" PetscInt_FMT ", block size %" PetscInt_FMT "; storage space: %" PetscInt_FMT " unneeded, %" PetscInt_FMT " used\n", m, A->rmap->N, A->rmap->bs, fshift * bs2, a->nz * bs2));
862:   PetscCall(PetscInfo(A, "Number of mallocs during MatSetValues is %" PetscInt_FMT "\n", a->reallocs));
863:   PetscCall(PetscInfo(A, "Most nonzeros blocks in any row is %" PetscInt_FMT "\n", rmax));

865:   A->info.mallocs += a->reallocs;
866:   a->reallocs         = 0;
867:   A->info.nz_unneeded = (PetscReal)fshift * bs2;
868:   a->rmax             = rmax;

870:   if (!A->structure_only && A->cmap->n < 65536 && A->cmap->bs == 1) {
871:     if (a->jshort && a->free_jshort) {
872:       /* when matrix data structure is changed, previous jshort must be replaced */
873:       PetscCall(PetscFree(a->jshort));
874:     }
875:     PetscCall(PetscMalloc1(a->i[A->rmap->n], &a->jshort));
876:     for (i = 0; i < a->i[A->rmap->n]; i++) a->jshort[i] = (short)a->j[i];
877:     A->ops->mult   = MatMult_SeqSBAIJ_1_ushort;
878:     A->ops->sor    = MatSOR_SeqSBAIJ_ushort;
879:     a->free_jshort = PETSC_TRUE;
880:   }
881:   PetscFunctionReturn(PETSC_SUCCESS);
882: }

884: /* Only add/insert a(i,j) with i<=j (blocks).
885:    Any a(i,j) with i>j input by user is ignored.
886: */

888: PetscErrorCode MatSetValues_SeqSBAIJ(Mat A, PetscInt m, const PetscInt im[], PetscInt n, const PetscInt in[], const PetscScalar v[], InsertMode is)
889: {
890:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
891:   PetscInt     *rp, k, low, high, t, ii, row, nrow, i, col, l, rmax, N, lastcol = -1;
892:   PetscInt     *imax = a->imax, *ai = a->i, *ailen = a->ilen, roworiented = a->roworiented;
893:   PetscInt     *aj = a->j, nonew = a->nonew, bs = A->rmap->bs, brow, bcol;
894:   PetscInt      ridx, cidx, bs2                 = a->bs2;
895:   MatScalar    *ap, value = 0.0, *aa = a->a, *bap;

897:   PetscFunctionBegin;
898:   for (k = 0; k < m; k++) { /* loop over added rows */
899:     row  = im[k];           /* row number */
900:     brow = row / bs;        /* block row number */
901:     if (row < 0) continue;
902:     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);
903:     rp   = aj + ai[brow];                                  /*ptr to beginning of column value of the row block*/
904:     ap   = PetscSafePointerPlusOffset(aa, bs2 * ai[brow]); /*ptr to beginning of element value of the row block*/
905:     rmax = imax[brow];                                     /* maximum space allocated for this row */
906:     nrow = ailen[brow];                                    /* actual length of this row */
907:     low  = 0;
908:     high = nrow;
909:     for (l = 0; l < n; l++) { /* loop over added columns */
910:       if (in[l] < 0) continue;
911:       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);
912:       col  = in[l];
913:       bcol = col / bs; /* block col number */

915:       if (brow > bcol) {
916:         PetscCheck(a->ignore_ltriangular, PETSC_COMM_SELF, PETSC_ERR_USER, "Lower triangular value cannot be set for sbaij format. Ignoring these values, run with -mat_ignore_lower_triangular or call MatSetOption(mat,MAT_IGNORE_LOWER_TRIANGULAR,PETSC_TRUE)");
917:         continue; /* ignore lower triangular values */
918:       }

920:       ridx = row % bs;
921:       cidx = col % bs; /*row and col index inside the block */
922:       if ((brow == bcol && ridx <= cidx) || (brow < bcol)) {
923:         /* element value a(k,l) */
924:         if (!A->structure_only) {
925:           if (roworiented) value = v[l + k * n];
926:           else value = v[k + l * m];
927:         }

929:         /* move pointer bap to a(k,l) quickly and add/insert value */
930:         if (col <= lastcol) low = 0;
931:         else high = nrow;

933:         lastcol = col;
934:         while (high - low > 7) {
935:           t = (low + high) / 2;
936:           if (rp[t] > bcol) high = t;
937:           else low = t;
938:         }
939:         for (i = low; i < high; i++) {
940:           if (rp[i] > bcol) break;
941:           if (rp[i] == bcol) {
942:             if (A->structure_only) goto noinsert1;
943:             bap = ap + bs2 * i + bs * cidx + ridx;
944:             if (is == ADD_VALUES) *bap += value;
945:             else *bap = value;
946:             /* for diag block, add/insert its symmetric element a(cidx,ridx) */
947:             if (brow == bcol && ridx < cidx) {
948:               bap = ap + bs2 * i + bs * ridx + cidx;
949:               if (is == ADD_VALUES) *bap += value;
950:               else *bap = value;
951:             }
952:             goto noinsert1;
953:           }
954:         }

956:         if (nonew == 1) goto noinsert1;
957:         PetscCheck(nonew != -1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Inserting a new nonzero (%" PetscInt_FMT ", %" PetscInt_FMT ") in the matrix", row, col);
958:         if (A->structure_only) MatSeqXAIJReallocateAIJ_structure_only(A, a->mbs, bs2, nrow, brow, bcol, rmax, ai, aj, rp, imax, nonew, MatScalar);
959:         else MatSeqXAIJReallocateAIJ(A, a->mbs, bs2, nrow, brow, bcol, rmax, aa, ai, aj, rp, ap, imax, nonew, MatScalar);

961:         N = nrow++ - 1;
962:         high++;
963:         /* shift up all the later entries in this row */
964:         PetscCall(PetscArraymove(rp + i + 1, rp + i, N - i + 1));
965:         rp[i] = bcol;
966:         if (!A->structure_only) {
967:           PetscCall(PetscArraymove(ap + bs2 * (i + 1), ap + bs2 * i, bs2 * (N - i + 1)));
968:           PetscCall(PetscArrayzero(ap + bs2 * i, bs2));
969:           ap[bs2 * i + bs * cidx + ridx] = value;
970:           /* for diag block, add/insert its symmetric element a(cidx,ridx) */
971:           if (brow == bcol && ridx < cidx) ap[bs2 * i + bs * ridx + cidx] = value;
972:         }
973:       noinsert1:;
974:         low = i;
975:       }
976:     } /* end of loop over added columns */
977:     ailen[brow] = nrow;
978:   } /* end of loop over added rows */
979:   PetscFunctionReturn(PETSC_SUCCESS);
980: }

982: static PetscErrorCode MatICCFactor_SeqSBAIJ(Mat inA, IS row, const MatFactorInfo *info)
983: {
984:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)inA->data;
985:   Mat           outA;
986:   PetscBool     row_identity;

988:   PetscFunctionBegin;
989:   PetscCheck(info->levels == 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only levels=0 is supported for in-place icc");
990:   PetscCall(ISIdentity(row, &row_identity));
991:   PetscCheck(row_identity, PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix reordering is not supported");
992:   PetscCheck(inA->rmap->bs == 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix block size %" PetscInt_FMT " is not supported", inA->rmap->bs); /* Need to replace MatCholeskyFactorSymbolic_SeqSBAIJ_MSR()! */

994:   outA = inA;
995:   PetscCall(PetscFree(inA->solvertype));
996:   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &inA->solvertype));

998:   inA->factortype = MAT_FACTOR_ICC;
999:   PetscCall(MatSeqSBAIJSetNumericFactorization_inplace(inA, row_identity));

1001:   PetscCall(PetscObjectReference((PetscObject)row));
1002:   PetscCall(ISDestroy(&a->row));
1003:   a->row = row;
1004:   PetscCall(PetscObjectReference((PetscObject)row));
1005:   PetscCall(ISDestroy(&a->col));
1006:   a->col = row;

1008:   /* Create the invert permutation so that it can be used in MatCholeskyFactorNumeric() */
1009:   if (a->icol) PetscCall(ISInvertPermutation(row, PETSC_DECIDE, &a->icol));

1011:   if (!a->solve_work) PetscCall(PetscMalloc1(inA->rmap->N + inA->rmap->bs, &a->solve_work));

1013:   PetscCall(MatCholeskyFactorNumeric(outA, inA, info));
1014:   PetscFunctionReturn(PETSC_SUCCESS);
1015: }

1017: static PetscErrorCode MatSeqSBAIJSetColumnIndices_SeqSBAIJ(Mat mat, PetscInt *indices)
1018: {
1019:   Mat_SeqSBAIJ *baij = (Mat_SeqSBAIJ *)mat->data;
1020:   PetscInt      i, nz, n;

1022:   PetscFunctionBegin;
1023:   nz = baij->maxnz;
1024:   n  = mat->cmap->n;
1025:   for (i = 0; i < nz; i++) baij->j[i] = indices[i];

1027:   baij->nz = nz;
1028:   for (i = 0; i < n; i++) baij->ilen[i] = baij->imax[i];

1030:   PetscCall(MatSetOption(mat, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
1031:   PetscFunctionReturn(PETSC_SUCCESS);
1032: }

1034: /*@
1035:   MatSeqSBAIJSetColumnIndices - Set the column indices for all the rows
1036:   in a `MATSEQSBAIJ` matrix.

1038:   Input Parameters:
1039: + mat     - the `MATSEQSBAIJ` matrix
1040: - indices - the column indices

1042:   Level: advanced

1044:   Notes:
1045:   This can be called if you have precomputed the nonzero structure of the
1046:   matrix and want to provide it to the matrix object to improve the performance
1047:   of the `MatSetValues()` operation.

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

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

1054: .seealso: [](ch_matrices), `Mat`, `MATSEQSBAIJ`, `MatCreateSeqSBAIJ`
1055: @*/
1056: PetscErrorCode MatSeqSBAIJSetColumnIndices(Mat mat, PetscInt *indices)
1057: {
1058:   PetscFunctionBegin;
1060:   PetscAssertPointer(indices, 2);
1061:   PetscUseMethod(mat, "MatSeqSBAIJSetColumnIndices_C", (Mat, PetscInt *), (mat, indices));
1062:   PetscFunctionReturn(PETSC_SUCCESS);
1063: }

1065: static PetscErrorCode MatCopy_SeqSBAIJ(Mat A, Mat B, MatStructure str)
1066: {
1067:   PetscBool isbaij;

1069:   PetscFunctionBegin;
1070:   PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &isbaij, MATSEQSBAIJ, MATMPISBAIJ, ""));
1071:   PetscCheck(isbaij, PetscObjectComm((PetscObject)B), PETSC_ERR_SUP, "Not for matrix type %s", ((PetscObject)B)->type_name);
1072:   /* If the two matrices have the same copy implementation and nonzero pattern, use fast copy. */
1073:   if (str == SAME_NONZERO_PATTERN && A->ops->copy == B->ops->copy) {
1074:     Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
1075:     Mat_SeqSBAIJ *b = (Mat_SeqSBAIJ *)B->data;

1077:     PetscCheck(a->i[a->mbs] == b->i[b->mbs], PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Number of nonzeros in two matrices are different");
1078:     PetscCheck(a->mbs == b->mbs, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Number of rows in two matrices are different");
1079:     PetscCheck(a->bs2 == b->bs2, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Different block size");
1080:     PetscCall(PetscArraycpy(b->a, a->a, a->bs2 * a->i[a->mbs]));
1081:     PetscCall(PetscObjectStateIncrease((PetscObject)B));
1082:   } else {
1083:     PetscCall(MatGetRowUpperTriangular(A));
1084:     PetscCall(MatCopy_Basic(A, B, str));
1085:     PetscCall(MatRestoreRowUpperTriangular(A));
1086:   }
1087:   PetscFunctionReturn(PETSC_SUCCESS);
1088: }

1090: static PetscErrorCode MatSeqSBAIJGetArray_SeqSBAIJ(Mat A, PetscScalar *array[])
1091: {
1092:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;

1094:   PetscFunctionBegin;
1095:   *array = a->a;
1096:   PetscFunctionReturn(PETSC_SUCCESS);
1097: }

1099: static PetscErrorCode MatSeqSBAIJRestoreArray_SeqSBAIJ(Mat A, PetscScalar *array[])
1100: {
1101:   PetscFunctionBegin;
1102:   *array = NULL;
1103:   PetscFunctionReturn(PETSC_SUCCESS);
1104: }

1106: PetscErrorCode MatAXPYGetPreallocation_SeqSBAIJ(Mat Y, Mat X, PetscInt *nnz)
1107: {
1108:   PetscInt      bs = Y->rmap->bs, mbs = Y->rmap->N / bs;
1109:   Mat_SeqSBAIJ *x = (Mat_SeqSBAIJ *)X->data;
1110:   Mat_SeqSBAIJ *y = (Mat_SeqSBAIJ *)Y->data;

1112:   PetscFunctionBegin;
1113:   /* Set the number of nonzeros in the new matrix */
1114:   PetscCall(MatAXPYGetPreallocation_SeqX_private(mbs, x->i, x->j, y->i, y->j, nnz));
1115:   PetscFunctionReturn(PETSC_SUCCESS);
1116: }

1118: static PetscErrorCode MatAXPY_SeqSBAIJ(Mat Y, PetscScalar a, Mat X, MatStructure str)
1119: {
1120:   Mat_SeqSBAIJ *x = (Mat_SeqSBAIJ *)X->data, *y = (Mat_SeqSBAIJ *)Y->data;
1121:   PetscInt      bs = Y->rmap->bs, bs2 = bs * bs;
1122:   PetscBLASInt  one = 1;

1124:   PetscFunctionBegin;
1125:   if (str == UNKNOWN_NONZERO_PATTERN || (PetscDefined(USE_DEBUG) && str == SAME_NONZERO_PATTERN)) {
1126:     PetscBool e = x->nz == y->nz && x->mbs == y->mbs ? PETSC_TRUE : PETSC_FALSE;
1127:     if (e) {
1128:       PetscCall(PetscArraycmp(x->i, y->i, x->mbs + 1, &e));
1129:       if (e) {
1130:         PetscCall(PetscArraycmp(x->j, y->j, x->i[x->mbs], &e));
1131:         if (e) str = SAME_NONZERO_PATTERN;
1132:       }
1133:     }
1134:     if (!e) PetscCheck(str != SAME_NONZERO_PATTERN, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MatStructure is not SAME_NONZERO_PATTERN");
1135:   }
1136:   if (str == SAME_NONZERO_PATTERN) {
1137:     PetscScalar  alpha = a;
1138:     PetscBLASInt bnz;
1139:     PetscCall(PetscBLASIntCast(x->nz * bs2, &bnz));
1140:     PetscCallBLAS("BLASaxpy", BLASaxpy_(&bnz, &alpha, x->a, &one, y->a, &one));
1141:     PetscCall(PetscObjectStateIncrease((PetscObject)Y));
1142:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
1143:     const PetscBool getrow_utriangular = x->getrow_utriangular;

1145:     PetscCall(MatAXPY_Basic(Y, a, X, str));
1146:     PetscCall(MatSetOption(X, MAT_GETROW_UPPERTRIANGULAR, getrow_utriangular));
1147:   } else {
1148:     Mat       B;
1149:     PetscInt *nnz;
1150:     PetscCheck(bs == X->rmap->bs, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrices must have same block size");
1151:     PetscCall(MatGetRowUpperTriangular(X));
1152:     PetscCall(MatGetRowUpperTriangular(Y));
1153:     PetscCall(PetscMalloc1(Y->rmap->N, &nnz));
1154:     PetscCall(MatCreate(PetscObjectComm((PetscObject)Y), &B));
1155:     PetscCall(PetscObjectSetName((PetscObject)B, ((PetscObject)Y)->name));
1156:     PetscCall(MatSetSizes(B, Y->rmap->n, Y->cmap->n, Y->rmap->N, Y->cmap->N));
1157:     PetscCall(MatSetBlockSizesFromMats(B, Y, Y));
1158:     PetscCall(MatSetType(B, ((PetscObject)Y)->type_name));
1159:     PetscCall(MatAXPYGetPreallocation_SeqSBAIJ(Y, X, nnz));
1160:     PetscCall(MatSeqSBAIJSetPreallocation(B, bs, 0, nnz));

1162:     PetscCall(MatAXPY_BasicWithPreallocation(B, Y, a, X, str));

1164:     PetscCall(MatHeaderMerge(Y, &B));
1165:     PetscCall(PetscFree(nnz));
1166:     PetscCall(MatRestoreRowUpperTriangular(X));
1167:     PetscCall(MatRestoreRowUpperTriangular(Y));
1168:   }
1169:   PetscFunctionReturn(PETSC_SUCCESS);
1170: }

1172: static PetscErrorCode MatIsStructurallySymmetric_SeqSBAIJ(Mat A, PetscBool *flg)
1173: {
1174:   PetscFunctionBegin;
1175:   *flg = PETSC_TRUE;
1176:   PetscFunctionReturn(PETSC_SUCCESS);
1177: }

1179: static PetscErrorCode MatConjugate_SeqSBAIJ(Mat A)
1180: {
1181:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
1182:   PetscInt      i, nz = a->bs2 * a->i[a->mbs];
1183:   MatScalar    *aa = a->a;

1185:   PetscFunctionBegin;
1186:   for (i = 0; i < nz; i++) aa[i] = PetscConj(aa[i]);
1187:   PetscFunctionReturn(PETSC_SUCCESS);
1188: }

1190: static PetscErrorCode MatRealPart_SeqSBAIJ(Mat A)
1191: {
1192:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
1193:   PetscInt      i, nz = a->bs2 * a->i[a->mbs];
1194:   MatScalar    *aa = a->a;

1196:   PetscFunctionBegin;
1197:   for (i = 0; i < nz; i++) aa[i] = PetscRealPart(aa[i]);
1198:   PetscFunctionReturn(PETSC_SUCCESS);
1199: }

1201: static PetscErrorCode MatImaginaryPart_SeqSBAIJ(Mat A)
1202: {
1203:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ *)A->data;
1204:   PetscInt      i, nz = a->bs2 * a->i[a->mbs];
1205:   MatScalar    *aa = a->a;

1207:   PetscFunctionBegin;
1208:   for (i = 0; i < nz; i++) aa[i] = PetscImaginaryPart(aa[i]);
1209:   PetscFunctionReturn(PETSC_SUCCESS);
1210: }

1212: static PetscErrorCode MatZeroRowsColumns_SeqSBAIJ(Mat A, PetscInt is_n, const PetscInt is_idx[], PetscScalar diag, Vec x, Vec b)
1213: {
1214:   Mat_SeqSBAIJ      *baij = (Mat_SeqSBAIJ *)A->data;
1215:   PetscInt           i, j, k, count;
1216:   PetscInt           bs = A->rmap->bs, bs2 = baij->bs2, row, col;
1217:   PetscScalar        zero = 0.0;
1218:   MatScalar         *aa;
1219:   const PetscScalar *xx;
1220:   PetscScalar       *bb;
1221:   PetscBool         *zeroed, vecs = PETSC_FALSE;

1223:   PetscFunctionBegin;
1224:   /* fix right-hand side if needed */
1225:   if (x && b) {
1226:     PetscCall(VecGetArrayRead(x, &xx));
1227:     PetscCall(VecGetArray(b, &bb));
1228:     vecs = PETSC_TRUE;
1229:   }

1231:   /* zero the columns */
1232:   PetscCall(PetscCalloc1(A->rmap->n, &zeroed));
1233:   for (i = 0; i < is_n; i++) {
1234:     PetscCheck(is_idx[i] >= 0 && is_idx[i] < A->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "row %" PetscInt_FMT " out of range", is_idx[i]);
1235:     zeroed[is_idx[i]] = PETSC_TRUE;
1236:   }
1237:   if (vecs) {
1238:     for (i = 0; i < A->rmap->N; i++) {
1239:       row = i / bs;
1240:       for (j = baij->i[row]; j < baij->i[row + 1]; j++) {
1241:         for (k = 0; k < bs; k++) {
1242:           col = bs * baij->j[j] + k;
1243:           if (col <= i) continue;
1244:           aa = baij->a + j * bs2 + (i % bs) + bs * k;
1245:           if (!zeroed[i] && zeroed[col]) bb[i] -= aa[0] * xx[col];
1246:           if (zeroed[i] && !zeroed[col]) bb[col] -= aa[0] * xx[i];
1247:         }
1248:       }
1249:     }
1250:     for (i = 0; i < is_n; i++) bb[is_idx[i]] = diag * xx[is_idx[i]];
1251:   }

1253:   for (i = 0; i < A->rmap->N; i++) {
1254:     if (!zeroed[i]) {
1255:       row = i / bs;
1256:       for (j = baij->i[row]; j < baij->i[row + 1]; j++) {
1257:         for (k = 0; k < bs; k++) {
1258:           col = bs * baij->j[j] + k;
1259:           if (zeroed[col]) {
1260:             aa    = baij->a + j * bs2 + (i % bs) + bs * k;
1261:             aa[0] = 0.0;
1262:           }
1263:         }
1264:       }
1265:     }
1266:   }
1267:   PetscCall(PetscFree(zeroed));
1268:   if (vecs) {
1269:     PetscCall(VecRestoreArrayRead(x, &xx));
1270:     PetscCall(VecRestoreArray(b, &bb));
1271:   }

1273:   /* zero the rows */
1274:   for (i = 0; i < is_n; i++) {
1275:     row   = is_idx[i];
1276:     count = (baij->i[row / bs + 1] - baij->i[row / bs]) * bs;
1277:     aa    = PetscSafePointerPlusOffset(baij->a, baij->i[row / bs] * bs2 + (row % bs));
1278:     for (k = 0; k < count; k++) {
1279:       aa[0] = zero;
1280:       aa += bs;
1281:     }
1282:     if (diag != 0.0) PetscUseTypeMethod(A, setvalues, 1, &row, 1, &row, &diag, INSERT_VALUES);
1283:   }
1284:   PetscCall(MatAssemblyEnd_SeqSBAIJ(A, MAT_FINAL_ASSEMBLY));
1285:   PetscFunctionReturn(PETSC_SUCCESS);
1286: }

1288: static PetscErrorCode MatShift_SeqSBAIJ(Mat Y, PetscScalar a)
1289: {
1290:   Mat_SeqSBAIJ *aij = (Mat_SeqSBAIJ *)Y->data;

1292:   PetscFunctionBegin;
1293:   if (!Y->preallocated || !aij->nz) PetscCall(MatSeqSBAIJSetPreallocation(Y, Y->rmap->bs, 1, NULL));
1294:   PetscCall(MatShift_Basic(Y, a));
1295:   PetscFunctionReturn(PETSC_SUCCESS);
1296: }

1298: PetscErrorCode MatEliminateZeros_SeqSBAIJ(Mat A, PetscBool keep)
1299: {
1300:   Mat_SeqSBAIJ *a      = (Mat_SeqSBAIJ *)A->data;
1301:   PetscInt      fshift = 0, fshift_prev = 0, i, *ai = a->i, *aj = a->j, *imax = a->imax, j, k;
1302:   PetscInt      m = A->rmap->N, *ailen = a->ilen;
1303:   PetscInt      mbs = a->mbs, bs2 = a->bs2, rmax = 0;
1304:   MatScalar    *aa = a->a, *ap;
1305:   PetscBool     zero;

1307:   PetscFunctionBegin;
1308:   PetscCheck(A->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot eliminate zeros for unassembled matrix");
1309:   if (m) rmax = ailen[0];
1310:   for (i = 1, a->nonzerorowcnt = 0; i <= mbs; i++) {
1311:     for (k = ai[i - 1]; k < ai[i]; k++) {
1312:       zero = PETSC_TRUE;
1313:       ap   = aa + bs2 * k;
1314:       for (j = 0; j < bs2 && zero; j++) {
1315:         if (ap[j] != 0.0) zero = PETSC_FALSE;
1316:       }
1317:       if (zero && (aj[k] != i - 1 || !keep)) fshift++;
1318:       else {
1319:         if (zero && aj[k] == i - 1) PetscCall(PetscInfo(A, "Keep the diagonal block at row %" PetscInt_FMT "\n", i - 1));
1320:         aj[k - fshift] = aj[k];
1321:         PetscCall(PetscArraymove(ap - bs2 * fshift, ap, bs2));
1322:       }
1323:     }
1324:     ai[i - 1] -= fshift_prev;
1325:     fshift_prev  = fshift;
1326:     ailen[i - 1] = imax[i - 1] = ai[i] - fshift - ai[i - 1];
1327:     a->nonzerorowcnt += ((ai[i] - fshift - ai[i - 1]) > 0);
1328:     rmax = PetscMax(rmax, ailen[i - 1]);
1329:   }
1330:   if (fshift) {
1331:     if (mbs) {
1332:       ai[mbs] -= fshift;
1333:       a->nz = ai[mbs];
1334:     }
1335:     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));
1336:     A->nonzerostate++;
1337:     A->info.nz_unneeded += (PetscReal)fshift;
1338:     a->rmax = rmax;
1339:     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1340:     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1341:   }
1342:   PetscFunctionReturn(PETSC_SUCCESS);
1343: }

1345: static struct _MatOps MatOps_Values = {MatSetValues_SeqSBAIJ,
1346:                                        MatGetRow_SeqSBAIJ,
1347:                                        MatRestoreRow_SeqSBAIJ,
1348:                                        MatMult_SeqSBAIJ_N,
1349:                                        /*  4*/ MatMultAdd_SeqSBAIJ_N,
1350:                                        MatMult_SeqSBAIJ_N, /* transpose versions are same as non-transpose versions */
1351:                                        MatMultAdd_SeqSBAIJ_N,
1352:                                        NULL,
1353:                                        NULL,
1354:                                        NULL,
1355:                                        /* 10*/ NULL,
1356:                                        NULL,
1357:                                        MatCholeskyFactor_SeqSBAIJ,
1358:                                        MatSOR_SeqSBAIJ,
1359:                                        MatTranspose_SeqSBAIJ,
1360:                                        /* 15*/ MatGetInfo_SeqSBAIJ,
1361:                                        MatEqual_SeqSBAIJ,
1362:                                        MatGetDiagonal_SeqSBAIJ,
1363:                                        MatDiagonalScale_SeqSBAIJ,
1364:                                        MatNorm_SeqSBAIJ,
1365:                                        /* 20*/ NULL,
1366:                                        MatAssemblyEnd_SeqSBAIJ,
1367:                                        MatSetOption_SeqSBAIJ,
1368:                                        MatZeroEntries_SeqSBAIJ,
1369:                                        /* 24*/ NULL,
1370:                                        NULL,
1371:                                        NULL,
1372:                                        NULL,
1373:                                        NULL,
1374:                                        /* 29*/ MatSetUp_Seq_Hash,
1375:                                        NULL,
1376:                                        NULL,
1377:                                        NULL,
1378:                                        NULL,
1379:                                        /* 34*/ MatDuplicate_SeqSBAIJ,
1380:                                        NULL,
1381:                                        NULL,
1382:                                        NULL,
1383:                                        MatICCFactor_SeqSBAIJ,
1384:                                        /* 39*/ MatAXPY_SeqSBAIJ,
1385:                                        MatCreateSubMatrices_SeqSBAIJ,
1386:                                        MatIncreaseOverlap_SeqSBAIJ,
1387:                                        MatGetValues_SeqSBAIJ,
1388:                                        MatCopy_SeqSBAIJ,
1389:                                        /* 44*/ NULL,
1390:                                        MatScale_SeqSBAIJ,
1391:                                        MatShift_SeqSBAIJ,
1392:                                        NULL,
1393:                                        MatZeroRowsColumns_SeqSBAIJ,
1394:                                        /* 49*/ NULL,
1395:                                        MatGetRowIJ_SeqSBAIJ,
1396:                                        MatRestoreRowIJ_SeqSBAIJ,
1397:                                        NULL,
1398:                                        NULL,
1399:                                        /* 54*/ NULL,
1400:                                        NULL,
1401:                                        NULL,
1402:                                        MatPermute_SeqSBAIJ,
1403:                                        MatSetValuesBlocked_SeqSBAIJ,
1404:                                        /* 59*/ MatCreateSubMatrix_SeqSBAIJ,
1405:                                        NULL,
1406:                                        NULL,
1407:                                        NULL,
1408:                                        NULL,
1409:                                        /* 64*/ NULL,
1410:                                        NULL,
1411:                                        NULL,
1412:                                        NULL,
1413:                                        MatGetRowMaxAbs_SeqSBAIJ,
1414:                                        /* 69*/ NULL,
1415:                                        MatConvert_MPISBAIJ_Basic,
1416:                                        NULL,
1417:                                        NULL,
1418:                                        NULL,
1419:                                        /* 74*/ NULL,
1420:                                        NULL,
1421:                                        NULL,
1422:                                        MatGetInertia_SeqSBAIJ,
1423:                                        MatLoad_SeqSBAIJ,
1424:                                        /* 79*/ NULL,
1425:                                        NULL,
1426:                                        MatIsStructurallySymmetric_SeqSBAIJ,
1427:                                        NULL,
1428:                                        NULL,
1429:                                        /* 84*/ NULL,
1430:                                        NULL,
1431:                                        NULL,
1432:                                        NULL,
1433:                                        NULL,
1434:                                        /* 89*/ NULL,
1435:                                        NULL,
1436:                                        NULL,
1437:                                        NULL,
1438:                                        MatConjugate_SeqSBAIJ,
1439:                                        /* 94*/ NULL,
1440:                                        NULL,
1441:                                        MatRealPart_SeqSBAIJ,
1442:                                        MatImaginaryPart_SeqSBAIJ,
1443:                                        MatGetRowUpperTriangular_SeqSBAIJ,
1444:                                        /* 99*/ MatRestoreRowUpperTriangular_SeqSBAIJ,
1445:                                        NULL,
1446:                                        NULL,
1447:                                        NULL,
1448:                                        NULL,
1449:                                        /*104*/ NULL,
1450:                                        NULL,
1451:                                        NULL,
1452:                                        NULL,
1453:                                        NULL,
1454:                                        /*109*/ NULL,
1455:                                        NULL,
1456:                                        NULL,
1457:                                        NULL,
1458:                                        NULL,
1459:                                        /*114*/ NULL,
1460:                                        MatGetColumnReductions_SeqSBAIJ,
1461:                                        NULL,
1462:                                        NULL,
1463:                                        NULL,
1464:                                        /*119*/ NULL,
1465:                                        NULL,
1466:                                        NULL,
1467:                                        NULL,
1468:                                        NULL,
1469:                                        /*124*/ NULL,
1470:                                        MatSetBlockSizes_Default,
1471:                                        NULL,
1472:                                        NULL,
1473:                                        NULL,
1474:                                        /*129*/ MatCreateMPIMatConcatenateSeqMat_SeqSBAIJ,
1475:                                        MatDestroySubMatrices_SeqXAIJ,
1476:                                        NULL,
1477:                                        NULL,
1478:                                        NULL,
1479:                                        /*134*/ NULL,
1480:                                        MatEliminateZeros_SeqSBAIJ,
1481:                                        NULL,
1482:                                        NULL,
1483:                                        NULL,
1484:                                        /*139*/ NULL,
1485:                                        MatCopyHashToXAIJ_Seq_Hash,
1486:                                        NULL,
1487:                                        NULL,
1488:                                        NULL,
1489:                                        /*144*/ NULL,
1490:                                        NULL,
1491:                                        NULL,
1492:                                        NULL};

1494: static PetscErrorCode MatStoreValues_SeqSBAIJ(Mat mat)
1495: {
1496:   Mat_SeqSBAIJ *aij = (Mat_SeqSBAIJ *)mat->data;
1497:   PetscInt      nz  = aij->i[mat->rmap->N] * mat->rmap->bs * aij->bs2;

1499:   PetscFunctionBegin;
1500:   PetscCheck(aij->nonew == 1, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");

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

1505:   /* copy values over */
1506:   PetscCall(PetscArraycpy(aij->saved_values, aij->a, nz));
1507:   PetscFunctionReturn(PETSC_SUCCESS);
1508: }

1510: static PetscErrorCode MatRetrieveValues_SeqSBAIJ(Mat mat)
1511: {
1512:   Mat_SeqSBAIJ *aij = (Mat_SeqSBAIJ *)mat->data;
1513:   PetscInt      nz  = aij->i[mat->rmap->N] * mat->rmap->bs * aij->bs2;

1515:   PetscFunctionBegin;
1516:   PetscCheck(aij->nonew == 1, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatSetOption(A,MAT_NEW_NONZERO_LOCATIONS,PETSC_FALSE);first");
1517:   PetscCheck(aij->saved_values, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Must call MatStoreValues(A);first");

1519:   /* copy values over */
1520:   PetscCall(PetscArraycpy(aij->a, aij->saved_values, nz));
1521:   PetscFunctionReturn(PETSC_SUCCESS);
1522: }

1524: static PetscErrorCode MatSeqSBAIJSetPreallocation_SeqSBAIJ(Mat B, PetscInt bs, PetscInt nz, const PetscInt nnz[])
1525: {
1526:   Mat_SeqSBAIJ *b = (Mat_SeqSBAIJ *)B->data;
1527:   PetscInt      i, mbs, nbs, bs2;
1528:   PetscBool     skipallocation = PETSC_FALSE, flg = PETSC_FALSE, realalloc = PETSC_FALSE;

1530:   PetscFunctionBegin;
1531:   if (B->hash_active) {
1532:     PetscInt bs;
1533:     B->ops[0] = b->cops;
1534:     PetscCall(PetscHMapIJVDestroy(&b->ht));
1535:     PetscCall(MatGetBlockSize(B, &bs));
1536:     if (bs > 1) PetscCall(PetscHSetIJDestroy(&b->bht));
1537:     PetscCall(PetscFree(b->dnz));
1538:     PetscCall(PetscFree(b->bdnz));
1539:     B->hash_active = PETSC_FALSE;
1540:   }
1541:   if (nz >= 0 || nnz) realalloc = PETSC_TRUE;

1543:   PetscCall(MatSetBlockSize(B, bs));
1544:   PetscCall(PetscLayoutSetUp(B->rmap));
1545:   PetscCall(PetscLayoutSetUp(B->cmap));
1546:   PetscCheck(B->rmap->N <= B->cmap->N, PETSC_COMM_SELF, PETSC_ERR_SUP, "SEQSBAIJ matrix cannot have more rows %" PetscInt_FMT " than columns %" PetscInt_FMT, B->rmap->N, B->cmap->N);
1547:   PetscCall(PetscLayoutGetBlockSize(B->rmap, &bs));

1549:   B->preallocated = PETSC_TRUE;

1551:   mbs = B->rmap->N / bs;
1552:   nbs = B->cmap->n / bs;
1553:   bs2 = bs * bs;

1555:   PetscCheck(mbs * bs == B->rmap->N && nbs * bs == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number rows, cols must be divisible by blocksize");

1557:   if (nz == MAT_SKIP_ALLOCATION) {
1558:     skipallocation = PETSC_TRUE;
1559:     nz             = 0;
1560:   }

1562:   if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 3;
1563:   PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nz cannot be less than 0: value %" PetscInt_FMT, nz);
1564:   if (nnz) {
1565:     for (i = 0; i < mbs; i++) {
1566:       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]);
1567:       PetscCheck(nnz[i] <= nbs, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nnz cannot be greater than block row length: local row %" PetscInt_FMT " value %" PetscInt_FMT " block rowlength %" PetscInt_FMT, i, nnz[i], nbs);
1568:     }
1569:   }

1571:   B->ops->mult             = MatMult_SeqSBAIJ_N;
1572:   B->ops->multadd          = MatMultAdd_SeqSBAIJ_N;
1573:   B->ops->multtranspose    = MatMult_SeqSBAIJ_N;
1574:   B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_N;

1576:   PetscCall(PetscOptionsGetBool(((PetscObject)B)->options, ((PetscObject)B)->prefix, "-mat_no_unroll", &flg, NULL));
1577:   if (!flg) {
1578:     switch (bs) {
1579:     case 1:
1580:       B->ops->mult             = MatMult_SeqSBAIJ_1;
1581:       B->ops->multadd          = MatMultAdd_SeqSBAIJ_1;
1582:       B->ops->multtranspose    = MatMult_SeqSBAIJ_1;
1583:       B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_1;
1584:       break;
1585:     case 2:
1586:       B->ops->mult             = MatMult_SeqSBAIJ_2;
1587:       B->ops->multadd          = MatMultAdd_SeqSBAIJ_2;
1588:       B->ops->multtranspose    = MatMult_SeqSBAIJ_2;
1589:       B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_2;
1590:       break;
1591:     case 3:
1592:       B->ops->mult             = MatMult_SeqSBAIJ_3;
1593:       B->ops->multadd          = MatMultAdd_SeqSBAIJ_3;
1594:       B->ops->multtranspose    = MatMult_SeqSBAIJ_3;
1595:       B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_3;
1596:       break;
1597:     case 4:
1598:       B->ops->mult             = MatMult_SeqSBAIJ_4;
1599:       B->ops->multadd          = MatMultAdd_SeqSBAIJ_4;
1600:       B->ops->multtranspose    = MatMult_SeqSBAIJ_4;
1601:       B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_4;
1602:       break;
1603:     case 5:
1604:       B->ops->mult             = MatMult_SeqSBAIJ_5;
1605:       B->ops->multadd          = MatMultAdd_SeqSBAIJ_5;
1606:       B->ops->multtranspose    = MatMult_SeqSBAIJ_5;
1607:       B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_5;
1608:       break;
1609:     case 6:
1610:       B->ops->mult             = MatMult_SeqSBAIJ_6;
1611:       B->ops->multadd          = MatMultAdd_SeqSBAIJ_6;
1612:       B->ops->multtranspose    = MatMult_SeqSBAIJ_6;
1613:       B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_6;
1614:       break;
1615:     case 7:
1616:       B->ops->mult             = MatMult_SeqSBAIJ_7;
1617:       B->ops->multadd          = MatMultAdd_SeqSBAIJ_7;
1618:       B->ops->multtranspose    = MatMult_SeqSBAIJ_7;
1619:       B->ops->multtransposeadd = MatMultAdd_SeqSBAIJ_7;
1620:       break;
1621:     }
1622:   }

1624:   b->mbs = mbs;
1625:   b->nbs = nbs;
1626:   if (!skipallocation) {
1627:     if (!b->imax) {
1628:       PetscCall(PetscMalloc2(mbs, &b->imax, mbs, &b->ilen));
1629:       b->free_imax_ilen = PETSC_TRUE;
1630:     }
1631:     if (!nnz) {
1632:       if (nz == PETSC_DEFAULT || nz == PETSC_DECIDE) nz = 5;
1633:       else if (nz <= 0) nz = 1;
1634:       nz = PetscMin(nbs, nz);
1635:       for (i = 0; i < mbs; i++) b->imax[i] = nz;
1636:       PetscCall(PetscIntMultError(nz, mbs, &nz));
1637:     } else {
1638:       PetscInt64 nz64 = 0;
1639:       for (i = 0; i < mbs; i++) {
1640:         b->imax[i] = nnz[i];
1641:         nz64 += nnz[i];
1642:       }
1643:       PetscCall(PetscIntCast(nz64, &nz));
1644:     }
1645:     /* b->ilen will count nonzeros in each block row so far. */
1646:     for (i = 0; i < mbs; i++) b->ilen[i] = 0;
1647:     /* nz=(nz+mbs)/2; */ /* total diagonal and superdiagonal nonzero blocks */

1649:     /* allocate the matrix space */
1650:     PetscCall(MatSeqXAIJFreeAIJ(B, &b->a, &b->j, &b->i));
1651:     if (!B->structure_only) {
1652:       PetscCall(PetscShmgetAllocateArray(bs2 * nz, sizeof(PetscScalar), (void **)&b->a));
1653:       PetscCall(PetscArrayzero(b->a, nz * bs2));
1654:     }
1655:     PetscCall(PetscShmgetAllocateArray(nz, sizeof(PetscInt), (void **)&b->j));
1656:     PetscCall(PetscShmgetAllocateArray(B->rmap->n + 1, sizeof(PetscInt), (void **)&b->i));
1657:     PetscCall(PetscArrayzero(b->j, nz));
1658:     b->free_a  = PETSC_TRUE;
1659:     b->free_ij = PETSC_TRUE;

1661:     /* pointer to beginning of each row */
1662:     b->i[0] = 0;
1663:     for (i = 1; i < mbs + 1; i++) b->i[i] = b->i[i - 1] + b->imax[i - 1];
1664:   } else {
1665:     b->free_a  = PETSC_FALSE;
1666:     b->free_ij = PETSC_FALSE;
1667:   }

1669:   b->bs2     = bs2;
1670:   b->nz      = 0;
1671:   b->maxnz   = nz;
1672:   b->inew    = NULL;
1673:   b->jnew    = NULL;
1674:   b->anew    = NULL;
1675:   b->a2anew  = NULL;
1676:   b->permute = PETSC_FALSE;

1678:   B->was_assembled = PETSC_FALSE;
1679:   B->assembled     = PETSC_FALSE;
1680:   if (realalloc) PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
1681:   PetscFunctionReturn(PETSC_SUCCESS);
1682: }

1684: static PetscErrorCode MatSeqSBAIJSetPreallocationCSR_SeqSBAIJ(Mat B, PetscInt bs, const PetscInt ii[], const PetscInt jj[], const PetscScalar V[])
1685: {
1686:   PetscInt      i, j, m, nz, anz, nz_max = 0, *nnz;
1687:   PetscScalar  *values      = NULL;
1688:   Mat_SeqSBAIJ *b           = (Mat_SeqSBAIJ *)B->data;
1689:   PetscBool     roworiented = b->roworiented;
1690:   PetscBool     ilw         = b->ignore_ltriangular;

1692:   PetscFunctionBegin;
1693:   PetscCheck(bs >= 1, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_OUTOFRANGE, "Invalid block size specified, must be positive but it is %" PetscInt_FMT, bs);
1694:   PetscCall(PetscLayoutSetBlockSize(B->rmap, bs));
1695:   PetscCall(PetscLayoutSetBlockSize(B->cmap, bs));
1696:   PetscCall(PetscLayoutSetUp(B->rmap));
1697:   PetscCall(PetscLayoutSetUp(B->cmap));
1698:   PetscCall(PetscLayoutGetBlockSize(B->rmap, &bs));
1699:   m = B->rmap->n / bs;

1701:   PetscCheck(!ii[0], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "ii[0] must be 0 but it is %" PetscInt_FMT, ii[0]);
1702:   PetscCall(PetscMalloc1(m + 1, &nnz));
1703:   for (i = 0; i < m; i++) {
1704:     nz = ii[i + 1] - ii[i];
1705:     PetscCheck(nz >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row %" PetscInt_FMT " has a negative number of columns %" PetscInt_FMT, i, nz);
1706:     PetscCheckSorted(nz, jj + ii[i]);
1707:     anz = 0;
1708:     for (j = 0; j < nz; j++) {
1709:       /* count only values on the diagonal or above */
1710:       if (jj[ii[i] + j] >= i) {
1711:         anz = nz - j;
1712:         break;
1713:       }
1714:     }
1715:     nz_max = PetscMax(nz_max, nz);
1716:     nnz[i] = anz;
1717:   }
1718:   PetscCall(MatSeqSBAIJSetPreallocation(B, bs, 0, nnz));
1719:   PetscCall(PetscFree(nnz));

1721:   values = (PetscScalar *)V;
1722:   if (!values && !B->structure_only) PetscCall(PetscCalloc1(bs * bs * nz_max, &values));
1723:   b->ignore_ltriangular = PETSC_TRUE;
1724:   for (i = 0; i < m; i++) {
1725:     PetscInt        ncols = ii[i + 1] - ii[i];
1726:     const PetscInt *icols = jj + ii[i];

1728:     if (B->structure_only) PetscCall(MatSetValuesBlocked_SeqSBAIJ(B, 1, &i, ncols, icols, NULL, INSERT_VALUES));
1729:     else if (!roworiented || bs == 1) {
1730:       const PetscScalar *svals = values + (V ? (bs * bs * ii[i]) : 0);

1732:       PetscCall(MatSetValuesBlocked_SeqSBAIJ(B, 1, &i, ncols, icols, svals, INSERT_VALUES));
1733:     } else {
1734:       for (j = 0; j < ncols; j++) {
1735:         const PetscScalar *svals = values + (V ? (bs * bs * (ii[i] + j)) : 0);

1737:         PetscCall(MatSetValuesBlocked_SeqSBAIJ(B, 1, &i, 1, &icols[j], svals, INSERT_VALUES));
1738:       }
1739:     }
1740:   }
1741:   if (!V) PetscCall(PetscFree(values));
1742:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
1743:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
1744:   PetscCall(MatSetOption(B, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
1745:   b->ignore_ltriangular = ilw;
1746:   PetscFunctionReturn(PETSC_SUCCESS);
1747: }

1749: /*
1750:    This is used to set the numeric factorization for both Cholesky and ICC symbolic factorization
1751: */
1752: PetscErrorCode MatSeqSBAIJSetNumericFactorization_inplace(Mat B, PetscBool natural)
1753: {
1754:   PetscBool flg = PETSC_FALSE;
1755:   PetscInt  bs  = B->rmap->bs;

1757:   PetscFunctionBegin;
1758:   PetscCall(PetscOptionsGetBool(((PetscObject)B)->options, ((PetscObject)B)->prefix, "-mat_no_unroll", &flg, NULL));
1759:   if (flg) bs = 8;

1761:   if (!natural) {
1762:     switch (bs) {
1763:     case 1:
1764:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_1_inplace;
1765:       break;
1766:     case 2:
1767:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_2;
1768:       break;
1769:     case 3:
1770:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_3;
1771:       break;
1772:     case 4:
1773:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_4;
1774:       break;
1775:     case 5:
1776:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_5;
1777:       break;
1778:     case 6:
1779:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_6;
1780:       break;
1781:     case 7:
1782:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_7;
1783:       break;
1784:     default:
1785:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_N;
1786:       break;
1787:     }
1788:   } else {
1789:     switch (bs) {
1790:     case 1:
1791:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_1_NaturalOrdering_inplace;
1792:       break;
1793:     case 2:
1794:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_2_NaturalOrdering;
1795:       break;
1796:     case 3:
1797:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_3_NaturalOrdering;
1798:       break;
1799:     case 4:
1800:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_4_NaturalOrdering;
1801:       break;
1802:     case 5:
1803:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_5_NaturalOrdering;
1804:       break;
1805:     case 6:
1806:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_6_NaturalOrdering;
1807:       break;
1808:     case 7:
1809:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_7_NaturalOrdering;
1810:       break;
1811:     default:
1812:       B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqSBAIJ_N_NaturalOrdering;
1813:       break;
1814:     }
1815:   }
1816:   PetscFunctionReturn(PETSC_SUCCESS);
1817: }

1819: PETSC_INTERN PetscErrorCode MatConvert_SeqSBAIJ_SeqAIJ(Mat, MatType, MatReuse, Mat *);
1820: PETSC_INTERN PetscErrorCode MatConvert_SeqSBAIJ_SeqBAIJ(Mat, MatType, MatReuse, Mat *);
1821: static PetscErrorCode       MatFactorGetSolverType_petsc(Mat A, MatSolverType *type)
1822: {
1823:   PetscFunctionBegin;
1824:   *type = MATSOLVERPETSC;
1825:   PetscFunctionReturn(PETSC_SUCCESS);
1826: }

1828: PETSC_INTERN PetscErrorCode MatGetFactor_seqsbaij_petsc(Mat A, MatFactorType ftype, Mat *B)
1829: {
1830:   PetscInt n = A->rmap->n;

1832:   PetscFunctionBegin;
1833:   if (PetscDefined(USE_COMPLEX) && (ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC) && A->hermitian == PETSC_BOOL3_TRUE && A->symmetric != PETSC_BOOL3_TRUE) {
1834:     PetscCall(PetscInfo(A, "Hermitian MAT_FACTOR_CHOLESKY or MAT_FACTOR_ICC are not supported. Use MAT_FACTOR_LU instead.\n"));
1835:     *B = NULL;
1836:     PetscFunctionReturn(PETSC_SUCCESS);
1837:   }

1839:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), B));
1840:   PetscCall(MatSetSizes(*B, n, n, n, n));
1841:   PetscCheck(ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC, PETSC_COMM_SELF, PETSC_ERR_SUP, "Factor type not supported");
1842:   PetscCall(MatSetType(*B, MATSEQSBAIJ));
1843:   PetscCall(MatSeqSBAIJSetPreallocation(*B, A->rmap->bs, MAT_SKIP_ALLOCATION, NULL));

1845:   (*B)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqSBAIJ;
1846:   (*B)->ops->iccfactorsymbolic      = MatICCFactorSymbolic_SeqSBAIJ;
1847:   PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_CHOLESKY]));
1848:   PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ICC]));

1850:   (*B)->factortype     = ftype;
1851:   (*B)->canuseordering = PETSC_TRUE;
1852:   PetscCall(PetscFree((*B)->solvertype));
1853:   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &(*B)->solvertype));
1854:   PetscCall(PetscObjectComposeFunction((PetscObject)*B, "MatFactorGetSolverType_C", MatFactorGetSolverType_petsc));
1855:   PetscFunctionReturn(PETSC_SUCCESS);
1856: }

1858: /*@
1859:   MatSeqSBAIJGetArray - gives access to the array where the numerical data for a `MATSEQSBAIJ` matrix is stored

1861:   Not Collective

1863:   Input Parameter:
1864: . A - a `MATSEQSBAIJ` matrix

1866:   Output Parameter:
1867: . array - pointer to the data

1869:   Level: intermediate

1871: .seealso: [](ch_matrices), `Mat`, `MATSEQSBAIJ`, `MatSeqSBAIJRestoreArray()`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArray()`
1872: @*/
1873: PetscErrorCode MatSeqSBAIJGetArray(Mat A, PetscScalar *array[])
1874: {
1875:   PetscFunctionBegin;
1876:   PetscUseMethod(A, "MatSeqSBAIJGetArray_C", (Mat, PetscScalar **), (A, array));
1877:   PetscFunctionReturn(PETSC_SUCCESS);
1878: }

1880: /*@
1881:   MatSeqSBAIJRestoreArray - returns access to the array where the numerical data for a `MATSEQSBAIJ` matrix is stored obtained by `MatSeqSBAIJGetArray()`

1883:   Not Collective

1885:   Input Parameters:
1886: + A     - a `MATSEQSBAIJ` matrix
1887: - array - pointer to the data

1889:   Level: intermediate

1891: .seealso: [](ch_matrices), `Mat`, `MATSEQSBAIJ`, `MatSeqSBAIJGetArray()`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArray()`
1892: @*/
1893: PetscErrorCode MatSeqSBAIJRestoreArray(Mat A, PetscScalar *array[])
1894: {
1895:   PetscFunctionBegin;
1896:   PetscUseMethod(A, "MatSeqSBAIJRestoreArray_C", (Mat, PetscScalar **), (A, array));
1897:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
1898:   PetscFunctionReturn(PETSC_SUCCESS);
1899: }

1901: /*MC
1902:   MATSEQSBAIJ - MATSEQSBAIJ = "seqsbaij" - A matrix type to be used for sequential symmetric block sparse matrices,
1903:   based on block compressed sparse row format.  Only the upper triangular portion of the matrix is stored.

1905:   For complex numbers by default this matrix is symmetric, NOT Hermitian symmetric. To make it Hermitian symmetric you
1906:   can call `MatSetOption(A, MAT_HERMITIAN, PETSC_TRUE)`.

1908:   Options Database Key:
1909: . -mat_type seqsbaij - sets the matrix type to "seqsbaij" during a call to `MatSetFromOptions()`

1911:   Level: beginner

1913:   Notes:
1914:   Call `MatSetOption(A, MAT_STRUCTURE_ONLY, PETSC_TRUE)` before preallocation or `MatSetUp()` to store only the nonzero pattern.
1915:   The assembled matrix has no numerical value array. Row and column indices supplied during insertion are retained, while numerical values are ignored.
1916:   Such matrices can be used for structural operations, but not for numerical operations.

1918:   By default if you insert values into the lower triangular part of the matrix they are simply ignored (since they are not
1919:   stored and they are assumed to be symmetric to the upper triangular). If you call `MatSetOption(A, MAT_IGNORE_LOWER_TRIANGULAR, PETSC_FALSE)` or use
1920:   the options database `-mat_ignore_lower_triangular false` it will generate an error if you try to set a value in the lower triangular portion.

1922:   The number of rows in the matrix must be less than or equal to the number of columns

1924: .seealso: [](ch_matrices), `Mat`, `MATSEQSBAIJ`, `MatCreateSeqSBAIJ()`, `MatType`, `MATMPISBAIJ`
1925: M*/
1926: PETSC_EXTERN PetscErrorCode MatCreate_SeqSBAIJ(Mat B)
1927: {
1928:   Mat_SeqSBAIJ *b;
1929:   PetscMPIInt   size;
1930:   PetscBool     no_unroll = PETSC_FALSE, no_inode = PETSC_FALSE;

1932:   PetscFunctionBegin;
1933:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)B), &size));
1934:   PetscCheck(size <= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Comm must be of size 1");

1936:   PetscCall(PetscNew(&b));
1937:   B->data   = (void *)b;
1938:   B->ops[0] = MatOps_Values;

1940:   B->ops->destroy    = MatDestroy_SeqSBAIJ;
1941:   B->ops->view       = MatView_SeqSBAIJ;
1942:   b->row             = NULL;
1943:   b->icol            = NULL;
1944:   b->reallocs        = 0;
1945:   b->saved_values    = NULL;
1946:   b->inode.limit     = 5;
1947:   b->inode.max_limit = 5;

1949:   b->roworiented        = PETSC_TRUE;
1950:   b->nonew              = 0;
1951:   b->diag               = NULL;
1952:   b->solve_work         = NULL;
1953:   b->mult_work          = NULL;
1954:   B->spptr              = NULL;
1955:   B->info.nz_unneeded   = (PetscReal)b->maxnz * b->bs2;
1956:   b->keepnonzeropattern = PETSC_FALSE;

1958:   b->inew    = NULL;
1959:   b->jnew    = NULL;
1960:   b->anew    = NULL;
1961:   b->a2anew  = NULL;
1962:   b->permute = PETSC_FALSE;

1964:   b->ignore_ltriangular = PETSC_TRUE;

1966:   PetscCall(PetscOptionsGetBool(((PetscObject)B)->options, ((PetscObject)B)->prefix, "-mat_ignore_lower_triangular", &b->ignore_ltriangular, NULL));

1968:   b->getrow_utriangular = PETSC_FALSE;

1970:   PetscCall(PetscOptionsGetBool(((PetscObject)B)->options, ((PetscObject)B)->prefix, "-mat_getrow_uppertriangular", &b->getrow_utriangular, NULL));

1972:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqSBAIJGetArray_C", MatSeqSBAIJGetArray_SeqSBAIJ));
1973:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqSBAIJRestoreArray_C", MatSeqSBAIJRestoreArray_SeqSBAIJ));
1974:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatStoreValues_C", MatStoreValues_SeqSBAIJ));
1975:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatRetrieveValues_C", MatRetrieveValues_SeqSBAIJ));
1976:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqSBAIJSetColumnIndices_C", MatSeqSBAIJSetColumnIndices_SeqSBAIJ));
1977:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqsbaij_seqaij_C", MatConvert_SeqSBAIJ_SeqAIJ));
1978:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqsbaij_seqbaij_C", MatConvert_SeqSBAIJ_SeqBAIJ));
1979:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqSBAIJSetPreallocation_C", MatSeqSBAIJSetPreallocation_SeqSBAIJ));
1980:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqSBAIJSetPreallocationCSR_C", MatSeqSBAIJSetPreallocationCSR_SeqSBAIJ));
1981: #if PetscDefined(HAVE_ELEMENTAL)
1982:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqsbaij_elemental_C", MatConvert_SeqSBAIJ_Elemental));
1983: #endif
1984: #if PetscDefined(HAVE_SCALAPACK) && (PetscDefined(USE_REAL_SINGLE) || PetscDefined(USE_REAL_DOUBLE))
1985:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqsbaij_scalapack_C", MatConvert_SBAIJ_ScaLAPACK));
1986: #endif

1988:   B->symmetry_eternal            = PETSC_TRUE;
1989:   B->structural_symmetry_eternal = PETSC_TRUE;
1990:   B->symmetric                   = PETSC_BOOL3_TRUE;
1991:   B->structurally_symmetric      = PETSC_BOOL3_TRUE;
1992: #if !PetscDefined(USE_COMPLEX)
1993:   B->hermitian = PETSC_BOOL3_TRUE;
1994: #endif

1996:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATSEQSBAIJ));

1998:   PetscOptionsBegin(PetscObjectComm((PetscObject)B), ((PetscObject)B)->prefix, "Options for SEQSBAIJ matrix", "Mat");
1999:   PetscCall(PetscOptionsBool("-mat_no_unroll", "Do not optimize for inodes (slower)", NULL, no_unroll, &no_unroll, NULL));
2000:   if (no_unroll) PetscCall(PetscInfo(B, "Not using Inode routines due to -mat_no_unroll\n"));
2001:   PetscCall(PetscOptionsBool("-mat_no_inode", "Do not optimize for inodes (slower)", NULL, no_inode, &no_inode, NULL));
2002:   if (no_inode) PetscCall(PetscInfo(B, "Not using Inode routines due to -mat_no_inode\n"));
2003:   PetscCall(PetscOptionsInt("-mat_inode_limit", "Do not use inodes larger than this value", NULL, b->inode.limit, &b->inode.limit, NULL));
2004:   PetscOptionsEnd();
2005:   b->inode.use = (PetscBool)(!(no_unroll || no_inode));
2006:   if (b->inode.limit > b->inode.max_limit) b->inode.limit = b->inode.max_limit;
2007:   PetscFunctionReturn(PETSC_SUCCESS);
2008: }

2010: /*@
2011:   MatSeqSBAIJSetPreallocation - Creates a sparse symmetric matrix in block AIJ (block
2012:   compressed row) `MATSEQSBAIJ` format.  For good matrix assembly performance the
2013:   user should preallocate the matrix storage by setting the parameter `nz`
2014:   (or the array `nnz`).

2016:   Collective

2018:   Input Parameters:
2019: + B   - the symmetric matrix
2020: . bs  - size of block, the blocks are ALWAYS square. One can use `MatSetBlockSizes()` to set a different row and column blocksize but the row
2021:         blocksize always defines the size of the blocks. The column blocksize sets the blocksize of the vectors obtained with `MatCreateVecs()`
2022: . nz  - number of block nonzeros per block row (same for all rows)
2023: - nnz - array containing the number of block nonzeros in the upper triangular plus
2024:         diagonal portion of each block (possibly different for each block row) or `NULL`

2026:   Options Database Keys:
2027: + -mat_no_unroll (true|false) - uses code that does not unroll the loops in the block calculations (much slower)
2028: - -mat_block_size bs          - size of the blocks to use (only works if a negative bs is passed in)

2030:   Level: intermediate

2032:   Notes:
2033:   Specify the preallocated storage with either `nz` or `nnz` (not both).
2034:   Set `nz` = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
2035:   allocation.  See [Sparse Matrices](sec_matsparse) for details.

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

2042:   If the `nnz` parameter is given then the `nz` parameter is ignored

2044: .seealso: [](ch_matrices), `Mat`, [Sparse Matrices](sec_matsparse), `MATSEQSBAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatCreateSBAIJ()`
2045: @*/
2046: PetscErrorCode MatSeqSBAIJSetPreallocation(Mat B, PetscInt bs, PetscInt nz, const PetscInt nnz[])
2047: {
2048:   PetscFunctionBegin;
2052:   PetscTryMethod(B, "MatSeqSBAIJSetPreallocation_C", (Mat, PetscInt, PetscInt, const PetscInt[]), (B, bs, nz, nnz));
2053:   PetscFunctionReturn(PETSC_SUCCESS);
2054: }

2056: /*@
2057:   MatSeqSBAIJSetPreallocationCSR - Creates a sparse parallel matrix in `MATSEQSBAIJ` format using the given nonzero structure and (optional) numerical values

2059:   Input Parameters:
2060: + B  - the matrix
2061: . bs - size of block, the blocks are ALWAYS square.
2062: . i  - the indices into `j` for the start of each local row (indices start with zero)
2063: . j  - the column indices for each local row (indices start with zero) these must be sorted for each row
2064: - v  - optional values in the matrix, use `NULL` if not provided

2066:   Level: advanced

2068:   Notes:
2069:   The `i`,`j`,`v` values are COPIED with this routine; to avoid the copy use `MatCreateSeqSBAIJWithArrays()`

2071:   The order of the entries in values is specified by the `MatOption` `MAT_ROW_ORIENTED`.  For example, C programs
2072:   may want to use the default `MAT_ROW_ORIENTED` = `PETSC_TRUE` and use an array v[nnz][bs][bs] where the second index is
2073:   over rows within a block and the last index is over columns within a block row.  Fortran programs will likely set
2074:   `MAT_ROW_ORIENTED` = `PETSC_FALSE` and use a Fortran array v(bs,bs,nnz) in which the first index is over rows within a
2075:   block column and the second index is over columns within a block.

2077:   Any entries provided that lie below the diagonal are ignored

2079:   Though this routine has Preallocation() in the name it also sets the exact nonzero locations of the matrix entries
2080:   and usually the numerical values as well

2082: .seealso: [](ch_matrices), `Mat`, `MATSEQSBAIJ`, `MatCreate()`, `MatCreateSeqSBAIJ()`, `MatSetValuesBlocked()`, `MatSeqSBAIJSetPreallocation()`
2083: @*/
2084: PetscErrorCode MatSeqSBAIJSetPreallocationCSR(Mat B, PetscInt bs, const PetscInt i[], const PetscInt j[], const PetscScalar v[])
2085: {
2086:   PetscFunctionBegin;
2090:   PetscTryMethod(B, "MatSeqSBAIJSetPreallocationCSR_C", (Mat, PetscInt, const PetscInt[], const PetscInt[], const PetscScalar[]), (B, bs, i, j, v));
2091:   PetscFunctionReturn(PETSC_SUCCESS);
2092: }

2094: /*@
2095:   MatCreateSeqSBAIJ - Creates a sparse symmetric matrix in (block
2096:   compressed row) `MATSEQSBAIJ` format.  For good matrix assembly performance the
2097:   user should preallocate the matrix storage by setting the parameter `nz`
2098:   (or the array `nnz`).

2100:   Collective

2102:   Input Parameters:
2103: + comm - MPI communicator, set to `PETSC_COMM_SELF`
2104: . bs   - size of block, the blocks are ALWAYS square. One can use `MatSetBlockSizes()` to set a different row and column blocksize but the row
2105:           blocksize always defines the size of the blocks. The column blocksize sets the blocksize of the vectors obtained with MatCreateVecs()
2106: . m    - number of rows
2107: . n    - number of columns
2108: . nz   - number of block nonzeros per block row (same for all rows)
2109: - nnz  - array containing the number of block nonzeros in the upper triangular plus
2110:          diagonal portion of each block (possibly different for each block row) or `NULL`

2112:   Output Parameter:
2113: . A - the symmetric matrix

2115:   Options Database Keys:
2116: + -mat_no_unroll (true|false) - uses code that does not unroll the loops in the block calculations (much slower)
2117: - -mat_block_size bs          - size of the blocks to use

2119:   Level: intermediate

2121:   Notes:
2122:   It is recommended that one use `MatCreateFromOptions()` or the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
2123:   MatXXXXSetPreallocation() paradigm instead of this routine directly.
2124:   [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]

2126:   The number of rows and columns must be divisible by blocksize.
2127:   This matrix type does not support complex Hermitian operation.

2129:   Specify the preallocated storage with either `nz` or `nnz` (not both).
2130:   Set `nz` = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
2131:   allocation.  See [Sparse Matrices](sec_matsparse) for details.

2133:   If the `nnz` parameter is given then the `nz` parameter is ignored

2135: .seealso: [](ch_matrices), `Mat`, [Sparse Matrices](sec_matsparse), `MATSEQSBAIJ`, `MatCreate()`, `MatCreateSeqAIJ()`, `MatSetValues()`, `MatCreateSBAIJ()`
2136: @*/
2137: PetscErrorCode MatCreateSeqSBAIJ(MPI_Comm comm, PetscInt bs, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A)
2138: {
2139:   PetscFunctionBegin;
2140:   PetscCall(MatCreate(comm, A));
2141:   PetscCall(MatSetSizes(*A, m, n, m, n));
2142:   PetscCall(MatSetType(*A, MATSEQSBAIJ));
2143:   PetscCall(MatSeqSBAIJSetPreallocation(*A, bs, nz, (PetscInt *)nnz));
2144:   PetscFunctionReturn(PETSC_SUCCESS);
2145: }

2147: PetscErrorCode MatDuplicate_SeqSBAIJ(Mat A, MatDuplicateOption cpvalues, Mat *B)
2148: {
2149:   Mat           C;
2150:   Mat_SeqSBAIJ *c, *a  = (Mat_SeqSBAIJ *)A->data;
2151:   PetscInt      i, mbs = a->mbs, nz = a->nz, bs2 = a->bs2;

2153:   PetscFunctionBegin;
2154:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Cannot duplicate unassembled matrix");
2155:   PetscCheck(a->i[mbs] == nz, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Corrupt matrix");

2157:   *B = NULL;
2158:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &C));
2159:   PetscCall(MatSetSizes(C, A->rmap->N, A->cmap->n, A->rmap->N, A->cmap->n));
2160:   PetscCall(MatSetBlockSizesFromMats(C, A, A));
2161:   PetscCall(MatSetType(C, MATSEQSBAIJ));
2162:   PetscCall(MatSetOption(C, MAT_STRUCTURE_ONLY, A->structure_only));
2163:   c = (Mat_SeqSBAIJ *)C->data;

2165:   C->preallocated       = PETSC_TRUE;
2166:   C->factortype         = A->factortype;
2167:   c->row                = NULL;
2168:   c->icol               = NULL;
2169:   c->saved_values       = NULL;
2170:   c->keepnonzeropattern = a->keepnonzeropattern;
2171:   C->assembled          = PETSC_TRUE;

2173:   PetscCall(PetscLayoutReference(A->rmap, &C->rmap));
2174:   PetscCall(PetscLayoutReference(A->cmap, &C->cmap));
2175:   c->bs2 = a->bs2;
2176:   c->mbs = a->mbs;
2177:   c->nbs = a->nbs;

2179:   if (cpvalues == MAT_SHARE_NONZERO_PATTERN) {
2180:     c->imax           = a->imax;
2181:     c->ilen           = a->ilen;
2182:     c->free_imax_ilen = PETSC_FALSE;
2183:   } else {
2184:     PetscCall(PetscMalloc2(mbs + 1, &c->imax, mbs + 1, &c->ilen));
2185:     for (i = 0; i < mbs; i++) {
2186:       c->imax[i] = a->imax[i];
2187:       c->ilen[i] = a->ilen[i];
2188:     }
2189:     c->free_imax_ilen = PETSC_TRUE;
2190:   }

2192:   /* allocate the matrix space */
2193:   if (!A->structure_only) PetscCall(PetscShmgetAllocateArray(bs2 * nz, sizeof(PetscScalar), (void **)&c->a));
2194:   c->free_a = PETSC_TRUE;
2195:   if (cpvalues == MAT_SHARE_NONZERO_PATTERN) {
2196:     if (!A->structure_only) PetscCall(PetscArrayzero(c->a, bs2 * nz));
2197:     c->i       = a->i;
2198:     c->j       = a->j;
2199:     c->free_ij = PETSC_FALSE;
2200:     c->parent  = A;
2201:     PetscCall(PetscObjectReference((PetscObject)A));
2202:     PetscCall(MatSetOption(A, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
2203:     PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
2204:   } else {
2205:     PetscCall(PetscShmgetAllocateArray(nz, sizeof(PetscInt), (void **)&c->j));
2206:     PetscCall(PetscShmgetAllocateArray(mbs + 1, sizeof(PetscInt), (void **)&c->i));
2207:     PetscCall(PetscArraycpy(c->i, a->i, mbs + 1));
2208:     c->free_ij = PETSC_TRUE;
2209:   }
2210:   if (mbs > 0) {
2211:     if (cpvalues != MAT_SHARE_NONZERO_PATTERN) PetscCall(PetscArraycpy(c->j, a->j, nz));
2212:     if (!A->structure_only) {
2213:       if (cpvalues == MAT_COPY_VALUES) PetscCall(PetscArraycpy(c->a, a->a, bs2 * nz));
2214:       else PetscCall(PetscArrayzero(c->a, bs2 * nz));
2215:     }
2216:     if (a->jshort) {
2217:       /* cannot share jshort, it is reallocated in MatAssemblyEnd_SeqSBAIJ() */
2218:       /* if the parent matrix is reassembled, this child matrix will never notice */
2219:       PetscCall(PetscMalloc1(nz, &c->jshort));
2220:       PetscCall(PetscArraycpy(c->jshort, a->jshort, nz));

2222:       c->free_jshort = PETSC_TRUE;
2223:     }
2224:   }

2226:   c->nonzerorowcnt = a->nonzerorowcnt;
2227:   c->roworiented   = a->roworiented;
2228:   c->nonew         = a->nonew;
2229:   c->nz            = a->nz;
2230:   c->maxnz         = a->nz; /* Since we allocate exactly the right amount */
2231:   c->solve_work    = NULL;
2232:   c->mult_work     = NULL;

2234:   *B = C;
2235:   PetscCall(PetscFunctionListDuplicate(((PetscObject)A)->qlist, &((PetscObject)C)->qlist));
2236:   PetscFunctionReturn(PETSC_SUCCESS);
2237: }

2239: /* Used for both SeqBAIJ and SeqSBAIJ matrices */
2240: #define MatLoad_SeqSBAIJ_Binary MatLoad_SeqBAIJ_Binary

2242: PetscErrorCode MatLoad_SeqSBAIJ(Mat mat, PetscViewer viewer)
2243: {
2244:   PetscBool isbinary;

2246:   PetscFunctionBegin;
2247:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
2248:   PetscCheck(isbinary, PetscObjectComm((PetscObject)viewer), PETSC_ERR_SUP, "Viewer type %s not yet supported for reading %s matrices", ((PetscObject)viewer)->type_name, ((PetscObject)mat)->type_name);
2249:   PetscCall(MatLoad_SeqSBAIJ_Binary(mat, viewer));
2250:   PetscFunctionReturn(PETSC_SUCCESS);
2251: }

2253: /*@
2254:   MatCreateSeqSBAIJWithArrays - Creates an sequential `MATSEQSBAIJ` matrix using matrix elements
2255:   (upper triangular entries in CSR format) provided by the user.

2257:   Collective

2259:   Input Parameters:
2260: + comm - must be an MPI communicator of size 1
2261: . bs   - size of block
2262: . m    - number of rows
2263: . n    - number of columns
2264: . i    - row indices; that is i[0] = 0, i[row] = i[row-1] + number of block elements in that row block row of the matrix
2265: . j    - column indices
2266: - a    - matrix values

2268:   Output Parameter:
2269: . mat - the matrix

2271:   Level: advanced

2273:   Notes:
2274:   The `i`, `j`, and `a` arrays are not copied by this routine, the user must free these arrays
2275:   once the matrix is destroyed

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

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

2281:   When block size is greater than 1 the matrix values must be stored using the `MATSBAIJ` storage format. For block size of 1
2282:   it is the regular CSR format excluding the lower triangular elements.

2284: .seealso: [](ch_matrices), `Mat`, `MATSEQSBAIJ`, `MatCreate()`, `MatCreateSBAIJ()`, `MatCreateSeqSBAIJ()`
2285: @*/
2286: PetscErrorCode MatCreateSeqSBAIJWithArrays(MPI_Comm comm, PetscInt bs, PetscInt m, PetscInt n, PetscInt i[], PetscInt j[], PetscScalar a[], Mat *mat)
2287: {
2288:   Mat_SeqSBAIJ *sbaij;

2290:   PetscFunctionBegin;
2291:   PetscCheck(bs == 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "block size %" PetscInt_FMT " > 1 is not supported yet", bs);
2292:   PetscCheck(m == 0 || i[0] == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "i (row indices) must start with 0");

2294:   PetscCall(MatCreate(comm, mat));
2295:   PetscCall(MatSetSizes(*mat, m, n, m, n));
2296:   PetscCall(MatSetType(*mat, MATSEQSBAIJ));
2297:   PetscCall(MatSeqSBAIJSetPreallocation(*mat, bs, MAT_SKIP_ALLOCATION, NULL));
2298:   sbaij = (Mat_SeqSBAIJ *)(*mat)->data;
2299:   PetscCall(PetscMalloc2(m, &sbaij->imax, m, &sbaij->ilen));

2301:   sbaij->i = i;
2302:   sbaij->j = j;
2303:   sbaij->a = a;

2305:   sbaij->nonew          = -1; /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
2306:   sbaij->free_a         = PETSC_FALSE;
2307:   sbaij->free_ij        = PETSC_FALSE;
2308:   sbaij->free_imax_ilen = PETSC_TRUE;

2310:   for (PetscInt ii = 0; ii < m; ii++) {
2311:     sbaij->ilen[ii] = sbaij->imax[ii] = i[ii + 1] - i[ii];
2312:     PetscCheck(i[ii + 1] >= i[ii], 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]);
2313:   }
2314:   if (PetscDefined(USE_DEBUG)) {
2315:     for (PetscInt ii = 0; ii < sbaij->i[m]; ii++) {
2316:       PetscCheck(j[ii] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative column index at location = %" PetscInt_FMT " index = %" PetscInt_FMT, ii, j[ii]);
2317:       PetscCheck(j[ii] < n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column index too large at location = %" PetscInt_FMT " index = %" PetscInt_FMT, ii, j[ii]);
2318:     }
2319:   }

2321:   PetscCall(MatAssemblyBegin(*mat, MAT_FINAL_ASSEMBLY));
2322:   PetscCall(MatAssemblyEnd(*mat, MAT_FINAL_ASSEMBLY));
2323:   PetscFunctionReturn(PETSC_SUCCESS);
2324: }

2326: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqSBAIJ(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
2327: {
2328:   PetscFunctionBegin;
2329:   PetscCall(MatCreateMPIMatConcatenateSeqMat_MPISBAIJ(comm, inmat, n, scall, outmat));
2330:   PetscFunctionReturn(PETSC_SUCCESS);
2331: }