Actual source code: dense.c

  1: /*
  2:      Defines the basic matrix operations for sequential dense.
  3:      Portions of this code are under:
  4:      Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
  5: */

  7: #include <../src/mat/impls/dense/seq/dense.h>
  8: #include <../src/mat/impls/dense/mpi/mpidense.h>
  9: #include <petscblaslapack.h>
 10: #include <../src/mat/impls/aij/seq/aij.h>
 11: #include <petsc/private/vecimpl.h>

 13: PetscErrorCode MatSeqDenseSymmetrize_Private(Mat A, PetscBool hermitian)
 14: {
 15:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
 16:   PetscInt      j, k, n = A->rmap->n;
 17:   PetscScalar  *v;

 19:   PetscFunctionBegin;
 20:   PetscCheck(A->rmap->n == A->cmap->n, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot symmetrize a rectangular matrix");
 21:   PetscCall(MatDenseGetArray(A, &v));
 22:   if (!hermitian) {
 23:     for (k = 0; k < n; k++) {
 24:       for (j = k; j < n; j++) v[j * mat->lda + k] = v[k * mat->lda + j];
 25:     }
 26:   } else {
 27:     for (k = 0; k < n; k++) {
 28:       for (j = k; j < n; j++) v[j * mat->lda + k] = PetscConj(v[k * mat->lda + j]);
 29:     }
 30:   }
 31:   PetscCall(MatDenseRestoreArray(A, &v));
 32:   PetscFunctionReturn(PETSC_SUCCESS);
 33: }

 35: PetscErrorCode MatSeqDenseInvertFactors_Private(Mat A)
 36: {
 37:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
 38:   PetscBLASInt  info, n;

 40:   PetscFunctionBegin;
 41:   if (!A->rmap->n || !A->cmap->n) PetscFunctionReturn(PETSC_SUCCESS);
 42:   PetscCall(PetscBLASIntCast(A->cmap->n, &n));
 43:   if (A->factortype == MAT_FACTOR_LU) {
 44:     PetscCheck(mat->pivots, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Pivots not present");
 45:     if (!mat->fwork) {
 46:       mat->lfwork = n;
 47:       PetscCall(PetscMalloc1(mat->lfwork, &mat->fwork));
 48:     }
 49:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
 50:     PetscCallBLAS("LAPACKgetri", LAPACKgetri_(&n, mat->v, &mat->lda, mat->pivots, mat->fwork, &mat->lfwork, &info));
 51:     PetscCall(PetscFPTrapPop());
 52:     PetscCall(PetscLogFlops((1.0 * A->cmap->n * A->cmap->n * A->cmap->n) / 3.0));
 53:   } else if (A->factortype == MAT_FACTOR_CHOLESKY) {
 54:     if (A->spd == PETSC_BOOL3_TRUE) {
 55:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
 56:       PetscCallBLAS("LAPACKpotri", LAPACKpotri_("L", &n, mat->v, &mat->lda, &info));
 57:       PetscCall(PetscFPTrapPop());
 58:       PetscCall(MatSeqDenseSymmetrize_Private(A, PETSC_TRUE));
 59: #if defined(PETSC_USE_COMPLEX)
 60:     } else if (A->hermitian == PETSC_BOOL3_TRUE) {
 61:       PetscCheck(mat->pivots, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Pivots not present");
 62:       PetscCheck(mat->fwork, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Fwork not present");
 63:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
 64:       PetscCallBLAS("LAPACKhetri", LAPACKhetri_("L", &n, mat->v, &mat->lda, mat->pivots, mat->fwork, &info));
 65:       PetscCall(PetscFPTrapPop());
 66:       PetscCall(MatSeqDenseSymmetrize_Private(A, PETSC_TRUE));
 67: #endif
 68:     } else { /* symmetric case */
 69:       PetscCheck(mat->pivots, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Pivots not present");
 70:       PetscCheck(mat->fwork, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Fwork not present");
 71:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
 72:       PetscCallBLAS("LAPACKsytri", LAPACKsytri_("L", &n, mat->v, &mat->lda, mat->pivots, mat->fwork, &info));
 73:       PetscCall(PetscFPTrapPop());
 74:       PetscCall(MatSeqDenseSymmetrize_Private(A, PETSC_FALSE));
 75:     }
 76:     PetscCheck(info >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Error in LAPACK argument %" PetscBLASInt_FMT, -info);
 77:     PetscCheck(info <= 0, PETSC_COMM_SELF, PETSC_ERR_MAT_CH_ZRPVT, "Bad Inversion: zero pivot in row %" PetscBLASInt_FMT, info - 1);
 78:     PetscCall(PetscLogFlops((1.0 * A->cmap->n * A->cmap->n * A->cmap->n) / 3.0));
 79:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix must be factored to solve");

 81:   A->ops->solve             = NULL;
 82:   A->ops->matsolve          = NULL;
 83:   A->ops->solvetranspose    = NULL;
 84:   A->ops->matsolvetranspose = NULL;
 85:   A->ops->solveadd          = NULL;
 86:   A->ops->solvetransposeadd = NULL;
 87:   A->factortype             = MAT_FACTOR_NONE;
 88:   PetscCall(PetscFree(A->solvertype));
 89:   PetscFunctionReturn(PETSC_SUCCESS);
 90: }

 92: static PetscErrorCode MatZeroRowsColumns_SeqDense(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
 93: {
 94:   Mat_SeqDense      *l = (Mat_SeqDense *)A->data;
 95:   PetscInt           m = l->lda, n = A->cmap->n, r = A->rmap->n, i, j;
 96:   PetscScalar       *slot, *bb, *v;
 97:   const PetscScalar *xx;

 99:   PetscFunctionBegin;
100:   if (PetscDefined(USE_DEBUG)) {
101:     for (i = 0; i < N; i++) {
102:       PetscCheck(rows[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative row requested to be zeroed");
103:       PetscCheck(rows[i] < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row %" PetscInt_FMT " requested to be zeroed greater than or equal number of rows %" PetscInt_FMT, rows[i], A->rmap->n);
104:       PetscCheck(rows[i] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Col %" PetscInt_FMT " requested to be zeroed greater than or equal number of cols %" PetscInt_FMT, rows[i], A->cmap->n);
105:     }
106:   }
107:   if (!N) PetscFunctionReturn(PETSC_SUCCESS);

109:   /* fix right-hand side if needed */
110:   if (x && b) {
111:     Vec xt;

113:     PetscCheck(A->rmap->n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only coded for square matrices");
114:     PetscCall(VecDuplicate(x, &xt));
115:     PetscCall(VecCopy(x, xt));
116:     PetscCall(VecScale(xt, -1.0));
117:     PetscCall(MatMultAdd(A, xt, b, b));
118:     PetscCall(VecDestroy(&xt));
119:     PetscCall(VecGetArrayRead(x, &xx));
120:     PetscCall(VecGetArray(b, &bb));
121:     for (i = 0; i < N; i++) bb[rows[i]] = diag * xx[rows[i]];
122:     PetscCall(VecRestoreArrayRead(x, &xx));
123:     PetscCall(VecRestoreArray(b, &bb));
124:   }

126:   PetscCall(MatDenseGetArray(A, &v));
127:   for (i = 0; i < N; i++) {
128:     slot = v + rows[i] * m;
129:     PetscCall(PetscArrayzero(slot, r));
130:   }
131:   for (i = 0; i < N; i++) {
132:     slot = v + rows[i];
133:     for (j = 0; j < n; j++) {
134:       *slot = 0.0;
135:       slot += m;
136:     }
137:   }
138:   if (diag != 0.0) {
139:     PetscCheck(A->rmap->n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only coded for square matrices");
140:     for (i = 0; i < N; i++) {
141:       slot  = v + (m + 1) * rows[i];
142:       *slot = diag;
143:     }
144:   }
145:   PetscCall(MatDenseRestoreArray(A, &v));
146:   PetscFunctionReturn(PETSC_SUCCESS);
147: }

149: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqDense(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
150: {
151:   Mat              B = NULL;
152:   Mat_SeqAIJ      *a = (Mat_SeqAIJ *)A->data;
153:   Mat_SeqDense    *b;
154:   PetscInt        *ai = a->i, *aj = a->j, m = A->rmap->N, n = A->cmap->N, i;
155:   const MatScalar *av;
156:   PetscBool        isseqdense;

158:   PetscFunctionBegin;
159:   if (reuse == MAT_REUSE_MATRIX) {
160:     PetscCall(PetscObjectTypeCompare((PetscObject)*newmat, MATSEQDENSE, &isseqdense));
161:     PetscCheck(isseqdense, PetscObjectComm((PetscObject)*newmat), PETSC_ERR_USER, "Cannot reuse matrix of type %s", ((PetscObject)*newmat)->type_name);
162:   }
163:   if (reuse != MAT_REUSE_MATRIX) {
164:     PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
165:     PetscCall(MatSetSizes(B, m, n, m, n));
166:     PetscCall(MatSetType(B, MATSEQDENSE));
167:     PetscCall(MatSeqDenseSetPreallocation(B, NULL));
168:     b = (Mat_SeqDense *)B->data;
169:   } else {
170:     b = (Mat_SeqDense *)((*newmat)->data);
171:     for (i = 0; i < n; i++) PetscCall(PetscArrayzero(b->v + i * b->lda, m));
172:   }
173:   PetscCall(MatSeqAIJGetArrayRead(A, &av));
174:   for (i = 0; i < m; i++) {
175:     PetscInt j;
176:     for (j = 0; j < ai[1] - ai[0]; j++) {
177:       b->v[*aj * b->lda + i] = *av;
178:       aj++;
179:       av++;
180:     }
181:     ai++;
182:   }
183:   PetscCall(MatSeqAIJRestoreArrayRead(A, &av));

185:   if (reuse == MAT_INPLACE_MATRIX) {
186:     PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
187:     PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
188:     PetscCall(MatHeaderReplace(A, &B));
189:   } else {
190:     if (B) *newmat = B;
191:     PetscCall(MatAssemblyBegin(*newmat, MAT_FINAL_ASSEMBLY));
192:     PetscCall(MatAssemblyEnd(*newmat, MAT_FINAL_ASSEMBLY));
193:   }
194:   PetscFunctionReturn(PETSC_SUCCESS);
195: }

197: PETSC_INTERN PetscErrorCode MatConvert_SeqDense_SeqAIJ(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
198: {
199:   Mat           B = NULL;
200:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;
201:   PetscInt      i, j;
202:   PetscInt     *rows, *nnz;
203:   MatScalar    *aa = a->v, *vals;

205:   PetscFunctionBegin;
206:   PetscCall(PetscCalloc3(A->rmap->n, &rows, A->rmap->n, &nnz, A->rmap->n, &vals));
207:   if (reuse != MAT_REUSE_MATRIX) {
208:     PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &B));
209:     PetscCall(MatSetSizes(B, A->rmap->n, A->cmap->n, A->rmap->N, A->cmap->N));
210:     PetscCall(MatSetType(B, MATSEQAIJ));
211:     for (j = 0; j < A->cmap->n; j++) {
212:       for (i = 0; i < A->rmap->n; i++)
213:         if (aa[i] != 0.0 || (i == j && A->cmap->n == A->rmap->n)) ++nnz[i];
214:       aa += a->lda;
215:     }
216:     PetscCall(MatSeqAIJSetPreallocation(B, PETSC_DETERMINE, nnz));
217:   } else B = *newmat;
218:   aa = a->v;
219:   for (j = 0; j < A->cmap->n; j++) {
220:     PetscInt numRows = 0;
221:     for (i = 0; i < A->rmap->n; i++)
222:       if (aa[i] != 0.0 || (i == j && A->cmap->n == A->rmap->n)) {
223:         rows[numRows]   = i;
224:         vals[numRows++] = aa[i];
225:       }
226:     PetscCall(MatSetValues(B, numRows, rows, 1, &j, vals, INSERT_VALUES));
227:     aa += a->lda;
228:   }
229:   PetscCall(PetscFree3(rows, nnz, vals));
230:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
231:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));

233:   if (reuse == MAT_INPLACE_MATRIX) PetscCall(MatHeaderReplace(A, &B));
234:   else if (reuse != MAT_REUSE_MATRIX) *newmat = B;
235:   PetscFunctionReturn(PETSC_SUCCESS);
236: }

238: PetscErrorCode MatAXPY_SeqDense(Mat Y, PetscScalar alpha, Mat X, MatStructure str)
239: {
240:   Mat_SeqDense      *x = (Mat_SeqDense *)X->data, *y = (Mat_SeqDense *)Y->data;
241:   const PetscScalar *xv;
242:   PetscScalar       *yv;
243:   PetscBLASInt       N, m, ldax = 0, lday = 0, one = 1;

245:   PetscFunctionBegin;
246:   PetscCall(MatDenseGetArrayRead(X, &xv));
247:   PetscCall(MatDenseGetArray(Y, &yv));
248:   PetscCall(PetscBLASIntCast(X->rmap->n * X->cmap->n, &N));
249:   PetscCall(PetscBLASIntCast(X->rmap->n, &m));
250:   PetscCall(PetscBLASIntCast(x->lda, &ldax));
251:   PetscCall(PetscBLASIntCast(y->lda, &lday));
252:   if (ldax > m || lday > m) {
253:     for (PetscInt j = 0; j < X->cmap->n; j++) PetscCallBLAS("BLASaxpy", BLASaxpy_(&m, &alpha, PetscSafePointerPlusOffset(xv, j * ldax), &one, PetscSafePointerPlusOffset(yv, j * lday), &one));
254:   } else {
255:     PetscCallBLAS("BLASaxpy", BLASaxpy_(&N, &alpha, xv, &one, yv, &one));
256:   }
257:   PetscCall(MatDenseRestoreArrayRead(X, &xv));
258:   PetscCall(MatDenseRestoreArray(Y, &yv));
259:   PetscCall(PetscLogFlops(PetscMax(2.0 * N - 1, 0)));
260:   PetscFunctionReturn(PETSC_SUCCESS);
261: }

263: static PetscErrorCode MatGetInfo_SeqDense(Mat A, MatInfoType flag, MatInfo *info)
264: {
265:   PetscLogDouble N = A->rmap->n * A->cmap->n;

267:   PetscFunctionBegin;
268:   info->block_size        = 1.0;
269:   info->nz_allocated      = N;
270:   info->nz_used           = N;
271:   info->nz_unneeded       = 0;
272:   info->assemblies        = A->num_ass;
273:   info->mallocs           = 0;
274:   info->memory            = 0; /* REVIEW ME */
275:   info->fill_ratio_given  = 0;
276:   info->fill_ratio_needed = 0;
277:   info->factor_mallocs    = 0;
278:   PetscFunctionReturn(PETSC_SUCCESS);
279: }

281: PetscErrorCode MatScale_SeqDense(Mat A, PetscScalar alpha)
282: {
283:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;
284:   PetscScalar  *v;
285:   PetscBLASInt  one = 1, j, nz, lda = 0;

287:   PetscFunctionBegin;
288:   PetscCall(MatDenseGetArray(A, &v));
289:   PetscCall(PetscBLASIntCast(a->lda, &lda));
290:   if (lda > A->rmap->n) {
291:     PetscCall(PetscBLASIntCast(A->rmap->n, &nz));
292:     for (j = 0; j < A->cmap->n; j++) PetscCallBLAS("BLASscal", BLASscal_(&nz, &alpha, v + j * lda, &one));
293:   } else {
294:     PetscCall(PetscBLASIntCast(A->rmap->n * A->cmap->n, &nz));
295:     PetscCallBLAS("BLASscal", BLASscal_(&nz, &alpha, v, &one));
296:   }
297:   PetscCall(PetscLogFlops(A->rmap->n * A->cmap->n));
298:   PetscCall(MatDenseRestoreArray(A, &v));
299:   PetscFunctionReturn(PETSC_SUCCESS);
300: }

302: PetscErrorCode MatShift_SeqDense(Mat A, PetscScalar alpha)
303: {
304:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;
305:   PetscScalar  *v;
306:   PetscInt      j, k;

308:   PetscFunctionBegin;
309:   PetscCall(MatDenseGetArray(A, &v));
310:   k = PetscMin(A->rmap->n, A->cmap->n);
311:   for (j = 0; j < k; j++) v[j + j * a->lda] += alpha;
312:   PetscCall(PetscLogFlops(k));
313:   PetscCall(MatDenseRestoreArray(A, &v));
314:   PetscFunctionReturn(PETSC_SUCCESS);
315: }

317: static PetscErrorCode MatIsHermitian_SeqDense(Mat A, PetscReal rtol, PetscBool *fl)
318: {
319:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data;
320:   PetscInt           i, j, m = A->rmap->n, N = a->lda;
321:   const PetscScalar *v;

323:   PetscFunctionBegin;
324:   *fl = PETSC_FALSE;
325:   if (A->rmap->n != A->cmap->n) PetscFunctionReturn(PETSC_SUCCESS);
326:   PetscCall(MatDenseGetArrayRead(A, &v));
327:   for (i = 0; i < m; i++) {
328:     for (j = i; j < m; j++) {
329:       if (PetscAbsScalar(v[i + j * N] - PetscConj(v[j + i * N])) > rtol) goto restore;
330:     }
331:   }
332:   *fl = PETSC_TRUE;
333: restore:
334:   PetscCall(MatDenseRestoreArrayRead(A, &v));
335:   PetscFunctionReturn(PETSC_SUCCESS);
336: }

338: static PetscErrorCode MatIsSymmetric_SeqDense(Mat A, PetscReal rtol, PetscBool *fl)
339: {
340:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data;
341:   PetscInt           i, j, m = A->rmap->n, N = a->lda;
342:   const PetscScalar *v;

344:   PetscFunctionBegin;
345:   *fl = PETSC_FALSE;
346:   if (A->rmap->n != A->cmap->n) PetscFunctionReturn(PETSC_SUCCESS);
347:   PetscCall(MatDenseGetArrayRead(A, &v));
348:   for (i = 0; i < m; i++) {
349:     for (j = i; j < m; j++) {
350:       if (PetscAbsScalar(v[i + j * N] - v[j + i * N]) > rtol) goto restore;
351:     }
352:   }
353:   *fl = PETSC_TRUE;
354: restore:
355:   PetscCall(MatDenseRestoreArrayRead(A, &v));
356:   PetscFunctionReturn(PETSC_SUCCESS);
357: }

359: PetscErrorCode MatDuplicateNoCreate_SeqDense(Mat newi, Mat A, MatDuplicateOption cpvalues)
360: {
361:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
362:   PetscInt      lda = mat->lda, j, m, nlda = lda;
363:   PetscBool     isdensecpu;

365:   PetscFunctionBegin;
366:   PetscCall(PetscLayoutReference(A->rmap, &newi->rmap));
367:   PetscCall(PetscLayoutReference(A->cmap, &newi->cmap));
368:   if (cpvalues == MAT_SHARE_NONZERO_PATTERN) { /* propagate LDA */
369:     PetscCall(MatDenseSetLDA(newi, lda));
370:   }
371:   PetscCall(PetscObjectTypeCompare((PetscObject)newi, MATSEQDENSE, &isdensecpu));
372:   if (isdensecpu) PetscCall(MatSeqDenseSetPreallocation(newi, NULL));
373:   if (cpvalues == MAT_COPY_VALUES) {
374:     const PetscScalar *av;
375:     PetscScalar       *v;

377:     PetscCall(MatDenseGetArrayRead(A, &av));
378:     PetscCall(MatDenseGetArrayWrite(newi, &v));
379:     PetscCall(MatDenseGetLDA(newi, &nlda));
380:     m = A->rmap->n;
381:     if (lda > m || nlda > m) {
382:       for (j = 0; j < A->cmap->n; j++) PetscCall(PetscArraycpy(PetscSafePointerPlusOffset(v, j * nlda), PetscSafePointerPlusOffset(av, j * lda), m));
383:     } else {
384:       PetscCall(PetscArraycpy(v, av, A->rmap->n * A->cmap->n));
385:     }
386:     PetscCall(MatDenseRestoreArrayWrite(newi, &v));
387:     PetscCall(MatDenseRestoreArrayRead(A, &av));
388:     PetscCall(MatPropagateSymmetryOptions(A, newi));
389:   }
390:   PetscFunctionReturn(PETSC_SUCCESS);
391: }

393: PetscErrorCode MatDuplicate_SeqDense(Mat A, MatDuplicateOption cpvalues, Mat *newmat)
394: {
395:   PetscFunctionBegin;
396:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), newmat));
397:   PetscCall(MatSetSizes(*newmat, A->rmap->n, A->cmap->n, A->rmap->n, A->cmap->n));
398:   PetscCall(MatSetType(*newmat, ((PetscObject)A)->type_name));
399:   PetscCall(MatDuplicateNoCreate_SeqDense(*newmat, A, cpvalues));
400:   PetscFunctionReturn(PETSC_SUCCESS);
401: }

403: static PetscErrorCode MatSolve_SeqDense_Internal_LU(Mat A, PetscScalar *x, PetscBLASInt ldx, PetscBLASInt m, PetscBLASInt nrhs, PetscBLASInt k, PetscBool T)
404: {
405:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;

407:   PetscFunctionBegin;
408:   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
409:   PetscCallLAPACKInfo("LAPACKgetrs", LAPACKgetrs_(T ? "T" : "N", &m, &nrhs, mat->v, &mat->lda, mat->pivots, x, &m, &info));
410:   PetscCall(PetscFPTrapPop());
411:   PetscCall(PetscLogFlops(nrhs * (2.0 * m * m - m)));
412:   PetscFunctionReturn(PETSC_SUCCESS);
413: }

415: static PetscErrorCode MatSolve_SeqDense_Internal_Cholesky(Mat A, PetscScalar *x, PetscBLASInt ldx, PetscBLASInt m, PetscBLASInt nrhs, PetscBLASInt k, PetscBool T)
416: {
417:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;

419:   PetscFunctionBegin;
420:   if (A->spd == PETSC_BOOL3_TRUE) {
421:     if (PetscDefined(USE_COMPLEX) && T) PetscCall(MatConjugate_SeqDense(A));
422:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
423:     PetscCallLAPACKInfo("LAPACKpotrs", LAPACKpotrs_("L", &m, &nrhs, mat->v, &mat->lda, x, &m, &info));
424:     PetscCall(PetscFPTrapPop());
425:     if (PetscDefined(USE_COMPLEX) && T) PetscCall(MatConjugate_SeqDense(A));
426: #if defined(PETSC_USE_COMPLEX)
427:   } else if (A->hermitian == PETSC_BOOL3_TRUE) {
428:     if (T) PetscCall(MatConjugate_SeqDense(A));
429:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
430:     PetscCallLAPACKInfo("LAPACKhetrs", LAPACKhetrs_("L", &m, &nrhs, mat->v, &mat->lda, mat->pivots, x, &m, &info));
431:     PetscCall(PetscFPTrapPop());
432:     if (T) PetscCall(MatConjugate_SeqDense(A));
433: #endif
434:   } else { /* symmetric case */
435:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
436:     PetscCallLAPACKInfo("LAPACKsytrs", LAPACKsytrs_("L", &m, &nrhs, mat->v, &mat->lda, mat->pivots, x, &m, &info));
437:     PetscCall(PetscFPTrapPop());
438:   }
439:   PetscCall(PetscLogFlops(nrhs * (2.0 * m * m - m)));
440:   PetscFunctionReturn(PETSC_SUCCESS);
441: }

443: static PetscErrorCode MatSolve_SeqDense_Internal_QR(Mat A, PetscScalar *x, PetscBLASInt ldx, PetscBLASInt m, PetscBLASInt nrhs, PetscBLASInt k)
444: {
445:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
446:   char          trans;

448:   PetscFunctionBegin;
449:   if (PetscDefined(USE_COMPLEX)) {
450:     trans = 'C';
451:   } else {
452:     trans = 'T';
453:   }
454:   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
455:   { /* lwork depends on the number of right-hand sides */
456:     PetscBLASInt nlfwork, lfwork = -1;
457:     PetscScalar  fwork;

459:     PetscCallLAPACKInfo("LAPACKormqr", LAPACKormqr_("L", &trans, &m, &nrhs, &mat->rank, mat->v, &mat->lda, mat->tau, x, &ldx, &fwork, &lfwork, &info));
460:     nlfwork = (PetscBLASInt)PetscRealPart(fwork);
461:     if (nlfwork > mat->lfwork) {
462:       mat->lfwork = nlfwork;
463:       PetscCall(PetscFree(mat->fwork));
464:       PetscCall(PetscMalloc1(mat->lfwork, &mat->fwork));
465:     }
466:   }
467:   PetscCallLAPACKInfo("LAPACKormqr", LAPACKormqr_("L", &trans, &m, &nrhs, &mat->rank, mat->v, &mat->lda, mat->tau, x, &ldx, mat->fwork, &mat->lfwork, &info));
468:   PetscCall(PetscFPTrapPop());
469:   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
470:   PetscCallLAPACKInfo("LAPACKtrtrs", LAPACKtrtrs_("U", "N", "N", &mat->rank, &nrhs, mat->v, &mat->lda, x, &ldx, &info));
471:   PetscCall(PetscFPTrapPop());
472:   for (PetscInt j = 0; j < nrhs; j++) {
473:     for (PetscInt i = mat->rank; i < k; i++) x[j * ldx + i] = 0.;
474:   }
475:   PetscCall(PetscLogFlops(nrhs * (4.0 * m * mat->rank - PetscSqr(mat->rank))));
476:   PetscFunctionReturn(PETSC_SUCCESS);
477: }

479: static PetscErrorCode MatSolveTranspose_SeqDense_Internal_QR(Mat A, PetscScalar *x, PetscBLASInt ldx, PetscBLASInt m, PetscBLASInt nrhs, PetscBLASInt k)
480: {
481:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;

483:   PetscFunctionBegin;
484:   if (A->rmap->n == A->cmap->n && mat->rank == A->rmap->n) {
485:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
486:     PetscCallLAPACKInfo("LAPACKtrtrs", LAPACKtrtrs_("U", "T", "N", &m, &nrhs, mat->v, &mat->lda, x, &ldx, &info));
487:     PetscCall(PetscFPTrapPop());
488:     if (PetscDefined(USE_COMPLEX)) PetscCall(MatConjugate_SeqDense(A));
489:     { /* lwork depends on the number of right-hand sides */
490:       PetscBLASInt nlfwork, lfwork = -1;
491:       PetscScalar  fwork;

493:       PetscCallLAPACKInfo("LAPACKormqr", LAPACKormqr_("L", "N", &m, &nrhs, &mat->rank, mat->v, &mat->lda, mat->tau, x, &ldx, &fwork, &lfwork, &info));
494:       nlfwork = (PetscBLASInt)PetscRealPart(fwork);
495:       if (nlfwork > mat->lfwork) {
496:         mat->lfwork = nlfwork;
497:         PetscCall(PetscFree(mat->fwork));
498:         PetscCall(PetscMalloc1(mat->lfwork, &mat->fwork));
499:       }
500:     }
501:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
502:     PetscCallLAPACKInfo("LAPACKormqr", LAPACKormqr_("L", "N", &m, &nrhs, &mat->rank, mat->v, &mat->lda, mat->tau, x, &ldx, mat->fwork, &mat->lfwork, &info));
503:     PetscCall(PetscFPTrapPop());
504:     if (PetscDefined(USE_COMPLEX)) PetscCall(MatConjugate_SeqDense(A));
505:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "QR factored matrix cannot be used for transpose solve");
506:   PetscCall(PetscLogFlops(nrhs * (4.0 * m * mat->rank - PetscSqr(mat->rank))));
507:   PetscFunctionReturn(PETSC_SUCCESS);
508: }

510: static PetscErrorCode MatSolve_SeqDense_SetUp(Mat A, Vec xx, Vec yy, PetscScalar **_y, PetscBLASInt *_m, PetscBLASInt *_k)
511: {
512:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
513:   PetscScalar  *y;
514:   PetscBLASInt  m = 0, k = 0;

516:   PetscFunctionBegin;
517:   PetscCall(PetscBLASIntCast(A->rmap->n, &m));
518:   PetscCall(PetscBLASIntCast(A->cmap->n, &k));
519:   if (k < m) {
520:     PetscCall(VecCopy(xx, mat->qrrhs));
521:     PetscCall(VecGetArray(mat->qrrhs, &y));
522:   } else {
523:     PetscCall(VecCopy(xx, yy));
524:     PetscCall(VecGetArray(yy, &y));
525:   }
526:   *_y = y;
527:   *_k = k;
528:   *_m = m;
529:   PetscFunctionReturn(PETSC_SUCCESS);
530: }

532: static PetscErrorCode MatSolve_SeqDense_TearDown(Mat A, Vec xx, Vec yy, PetscScalar **_y, PetscBLASInt *_m, PetscBLASInt *_k)
533: {
534:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
535:   PetscScalar  *y   = NULL;
536:   PetscBLASInt  m, k;

538:   PetscFunctionBegin;
539:   y   = *_y;
540:   *_y = NULL;
541:   k   = *_k;
542:   m   = *_m;
543:   if (k < m) {
544:     PetscScalar *yv;
545:     PetscCall(VecGetArray(yy, &yv));
546:     PetscCall(PetscArraycpy(yv, y, k));
547:     PetscCall(VecRestoreArray(yy, &yv));
548:     PetscCall(VecRestoreArray(mat->qrrhs, &y));
549:   } else {
550:     PetscCall(VecRestoreArray(yy, &y));
551:   }
552:   PetscFunctionReturn(PETSC_SUCCESS);
553: }

555: static PetscErrorCode MatSolve_SeqDense_LU(Mat A, Vec xx, Vec yy)
556: {
557:   PetscScalar *y = NULL;
558:   PetscBLASInt m = 0, k = 0;

560:   PetscFunctionBegin;
561:   PetscCall(MatSolve_SeqDense_SetUp(A, xx, yy, &y, &m, &k));
562:   PetscCall(MatSolve_SeqDense_Internal_LU(A, y, m, m, 1, k, PETSC_FALSE));
563:   PetscCall(MatSolve_SeqDense_TearDown(A, xx, yy, &y, &m, &k));
564:   PetscFunctionReturn(PETSC_SUCCESS);
565: }

567: static PetscErrorCode MatSolveTranspose_SeqDense_LU(Mat A, Vec xx, Vec yy)
568: {
569:   PetscScalar *y = NULL;
570:   PetscBLASInt m = 0, k = 0;

572:   PetscFunctionBegin;
573:   PetscCall(MatSolve_SeqDense_SetUp(A, xx, yy, &y, &m, &k));
574:   PetscCall(MatSolve_SeqDense_Internal_LU(A, y, m, m, 1, k, PETSC_TRUE));
575:   PetscCall(MatSolve_SeqDense_TearDown(A, xx, yy, &y, &m, &k));
576:   PetscFunctionReturn(PETSC_SUCCESS);
577: }

579: static PetscErrorCode MatSolve_SeqDense_Cholesky(Mat A, Vec xx, Vec yy)
580: {
581:   PetscScalar *y = NULL;
582:   PetscBLASInt m = 0, k = 0;

584:   PetscFunctionBegin;
585:   PetscCall(MatSolve_SeqDense_SetUp(A, xx, yy, &y, &m, &k));
586:   PetscCall(MatSolve_SeqDense_Internal_Cholesky(A, y, m, m, 1, k, PETSC_FALSE));
587:   PetscCall(MatSolve_SeqDense_TearDown(A, xx, yy, &y, &m, &k));
588:   PetscFunctionReturn(PETSC_SUCCESS);
589: }

591: static PetscErrorCode MatSolveTranspose_SeqDense_Cholesky(Mat A, Vec xx, Vec yy)
592: {
593:   PetscScalar *y = NULL;
594:   PetscBLASInt m = 0, k = 0;

596:   PetscFunctionBegin;
597:   PetscCall(MatSolve_SeqDense_SetUp(A, xx, yy, &y, &m, &k));
598:   PetscCall(MatSolve_SeqDense_Internal_Cholesky(A, y, m, m, 1, k, PETSC_TRUE));
599:   PetscCall(MatSolve_SeqDense_TearDown(A, xx, yy, &y, &m, &k));
600:   PetscFunctionReturn(PETSC_SUCCESS);
601: }

603: static PetscErrorCode MatSolve_SeqDense_QR(Mat A, Vec xx, Vec yy)
604: {
605:   PetscScalar *y = NULL;
606:   PetscBLASInt m = 0, k = 0;

608:   PetscFunctionBegin;
609:   PetscCall(MatSolve_SeqDense_SetUp(A, xx, yy, &y, &m, &k));
610:   PetscCall(MatSolve_SeqDense_Internal_QR(A, y, PetscMax(m, k), m, 1, k));
611:   PetscCall(MatSolve_SeqDense_TearDown(A, xx, yy, &y, &m, &k));
612:   PetscFunctionReturn(PETSC_SUCCESS);
613: }

615: static PetscErrorCode MatSolveTranspose_SeqDense_QR(Mat A, Vec xx, Vec yy)
616: {
617:   PetscScalar *y = NULL;
618:   PetscBLASInt m = 0, k = 0;

620:   PetscFunctionBegin;
621:   PetscCall(MatSolve_SeqDense_SetUp(A, xx, yy, &y, &m, &k));
622:   PetscCall(MatSolveTranspose_SeqDense_Internal_QR(A, y, PetscMax(m, k), m, 1, k));
623:   PetscCall(MatSolve_SeqDense_TearDown(A, xx, yy, &y, &m, &k));
624:   PetscFunctionReturn(PETSC_SUCCESS);
625: }

627: static PetscErrorCode MatMatSolve_SeqDense_SetUp(Mat A, Mat B, Mat X, PetscScalar **_y, PetscBLASInt *_ldy, PetscBLASInt *_m, PetscBLASInt *_nrhs, PetscBLASInt *_k)
628: {
629:   const PetscScalar *b;
630:   PetscScalar       *y;
631:   PetscInt           n, _ldb, _ldx;
632:   PetscBLASInt       nrhs = 0, m = 0, k = 0, ldb = 0, ldx = 0, ldy = 0;

634:   PetscFunctionBegin;
635:   *_ldy  = 0;
636:   *_m    = 0;
637:   *_nrhs = 0;
638:   *_k    = 0;
639:   *_y    = NULL;
640:   PetscCall(PetscBLASIntCast(A->rmap->n, &m));
641:   PetscCall(PetscBLASIntCast(A->cmap->n, &k));
642:   PetscCall(MatGetSize(B, NULL, &n));
643:   PetscCall(PetscBLASIntCast(n, &nrhs));
644:   PetscCall(MatDenseGetLDA(B, &_ldb));
645:   PetscCall(PetscBLASIntCast(_ldb, &ldb));
646:   PetscCall(MatDenseGetLDA(X, &_ldx));
647:   PetscCall(PetscBLASIntCast(_ldx, &ldx));
648:   if (ldx < m) {
649:     PetscCall(MatDenseGetArrayRead(B, &b));
650:     PetscCall(PetscMalloc1(nrhs * m, &y));
651:     if (ldb == m) {
652:       PetscCall(PetscArraycpy(y, b, ldb * nrhs));
653:     } else {
654:       for (PetscInt j = 0; j < nrhs; j++) PetscCall(PetscArraycpy(&y[j * m], &b[j * ldb], m));
655:     }
656:     ldy = m;
657:     PetscCall(MatDenseRestoreArrayRead(B, &b));
658:   } else {
659:     if (ldb == ldx) {
660:       PetscCall(MatCopy(B, X, SAME_NONZERO_PATTERN));
661:       PetscCall(MatDenseGetArray(X, &y));
662:     } else {
663:       PetscCall(MatDenseGetArray(X, &y));
664:       PetscCall(MatDenseGetArrayRead(B, &b));
665:       for (PetscInt j = 0; j < nrhs; j++) PetscCall(PetscArraycpy(&y[j * ldx], &b[j * ldb], m));
666:       PetscCall(MatDenseRestoreArrayRead(B, &b));
667:     }
668:     ldy = ldx;
669:   }
670:   *_y    = y;
671:   *_ldy  = ldy;
672:   *_k    = k;
673:   *_m    = m;
674:   *_nrhs = nrhs;
675:   PetscFunctionReturn(PETSC_SUCCESS);
676: }

678: static PetscErrorCode MatMatSolve_SeqDense_TearDown(Mat A, Mat B, Mat X, PetscScalar **_y, PetscBLASInt *_ldy, PetscBLASInt *_m, PetscBLASInt *_nrhs, PetscBLASInt *_k)
679: {
680:   PetscScalar *y;
681:   PetscInt     _ldx;
682:   PetscBLASInt k, ldy, nrhs, ldx = 0;

684:   PetscFunctionBegin;
685:   y    = *_y;
686:   *_y  = NULL;
687:   k    = *_k;
688:   ldy  = *_ldy;
689:   nrhs = *_nrhs;
690:   PetscCall(MatDenseGetLDA(X, &_ldx));
691:   PetscCall(PetscBLASIntCast(_ldx, &ldx));
692:   if (ldx != ldy) {
693:     PetscScalar *xv;
694:     PetscCall(MatDenseGetArray(X, &xv));
695:     for (PetscInt j = 0; j < nrhs; j++) PetscCall(PetscArraycpy(&xv[j * ldx], &y[j * ldy], k));
696:     PetscCall(MatDenseRestoreArray(X, &xv));
697:     PetscCall(PetscFree(y));
698:   } else {
699:     PetscCall(MatDenseRestoreArray(X, &y));
700:   }
701:   PetscFunctionReturn(PETSC_SUCCESS);
702: }

704: static PetscErrorCode MatMatSolve_SeqDense_LU(Mat A, Mat B, Mat X)
705: {
706:   PetscScalar *y;
707:   PetscBLASInt m, k, ldy, nrhs;

709:   PetscFunctionBegin;
710:   PetscCall(MatMatSolve_SeqDense_SetUp(A, B, X, &y, &ldy, &m, &nrhs, &k));
711:   PetscCall(MatSolve_SeqDense_Internal_LU(A, y, ldy, m, nrhs, k, PETSC_FALSE));
712:   PetscCall(MatMatSolve_SeqDense_TearDown(A, B, X, &y, &ldy, &m, &nrhs, &k));
713:   PetscFunctionReturn(PETSC_SUCCESS);
714: }

716: static PetscErrorCode MatMatSolveTranspose_SeqDense_LU(Mat A, Mat B, Mat X)
717: {
718:   PetscScalar *y;
719:   PetscBLASInt m, k, ldy, nrhs;

721:   PetscFunctionBegin;
722:   PetscCall(MatMatSolve_SeqDense_SetUp(A, B, X, &y, &ldy, &m, &nrhs, &k));
723:   PetscCall(MatSolve_SeqDense_Internal_LU(A, y, ldy, m, nrhs, k, PETSC_TRUE));
724:   PetscCall(MatMatSolve_SeqDense_TearDown(A, B, X, &y, &ldy, &m, &nrhs, &k));
725:   PetscFunctionReturn(PETSC_SUCCESS);
726: }

728: static PetscErrorCode MatMatSolve_SeqDense_Cholesky(Mat A, Mat B, Mat X)
729: {
730:   PetscScalar *y;
731:   PetscBLASInt m, k, ldy, nrhs;

733:   PetscFunctionBegin;
734:   PetscCall(MatMatSolve_SeqDense_SetUp(A, B, X, &y, &ldy, &m, &nrhs, &k));
735:   PetscCall(MatSolve_SeqDense_Internal_Cholesky(A, y, ldy, m, nrhs, k, PETSC_FALSE));
736:   PetscCall(MatMatSolve_SeqDense_TearDown(A, B, X, &y, &ldy, &m, &nrhs, &k));
737:   PetscFunctionReturn(PETSC_SUCCESS);
738: }

740: static PetscErrorCode MatMatSolveTranspose_SeqDense_Cholesky(Mat A, Mat B, Mat X)
741: {
742:   PetscScalar *y;
743:   PetscBLASInt m, k, ldy, nrhs;

745:   PetscFunctionBegin;
746:   PetscCall(MatMatSolve_SeqDense_SetUp(A, B, X, &y, &ldy, &m, &nrhs, &k));
747:   PetscCall(MatSolve_SeqDense_Internal_Cholesky(A, y, ldy, m, nrhs, k, PETSC_TRUE));
748:   PetscCall(MatMatSolve_SeqDense_TearDown(A, B, X, &y, &ldy, &m, &nrhs, &k));
749:   PetscFunctionReturn(PETSC_SUCCESS);
750: }

752: static PetscErrorCode MatMatSolve_SeqDense_QR(Mat A, Mat B, Mat X)
753: {
754:   PetscScalar *y;
755:   PetscBLASInt m, k, ldy, nrhs;

757:   PetscFunctionBegin;
758:   PetscCall(MatMatSolve_SeqDense_SetUp(A, B, X, &y, &ldy, &m, &nrhs, &k));
759:   PetscCall(MatSolve_SeqDense_Internal_QR(A, y, ldy, m, nrhs, k));
760:   PetscCall(MatMatSolve_SeqDense_TearDown(A, B, X, &y, &ldy, &m, &nrhs, &k));
761:   PetscFunctionReturn(PETSC_SUCCESS);
762: }

764: static PetscErrorCode MatMatSolveTranspose_SeqDense_QR(Mat A, Mat B, Mat X)
765: {
766:   PetscScalar *y;
767:   PetscBLASInt m, k, ldy, nrhs;

769:   PetscFunctionBegin;
770:   PetscCall(MatMatSolve_SeqDense_SetUp(A, B, X, &y, &ldy, &m, &nrhs, &k));
771:   PetscCall(MatSolveTranspose_SeqDense_Internal_QR(A, y, ldy, m, nrhs, k));
772:   PetscCall(MatMatSolve_SeqDense_TearDown(A, B, X, &y, &ldy, &m, &nrhs, &k));
773:   PetscFunctionReturn(PETSC_SUCCESS);
774: }

776: /* COMMENT: I have chosen to hide row permutation in the pivots,
777:    rather than put it in the Mat->row slot.*/
778: PetscErrorCode MatLUFactor_SeqDense(Mat A, IS row, IS col, PETSC_UNUSED const MatFactorInfo *minfo)
779: {
780:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
781:   PetscBLASInt  n, m, info;

783:   PetscFunctionBegin;
784:   PetscCall(PetscBLASIntCast(A->cmap->n, &n));
785:   PetscCall(PetscBLASIntCast(A->rmap->n, &m));
786:   if (!mat->pivots) PetscCall(PetscMalloc1(A->rmap->n, &mat->pivots));
787:   if (!A->rmap->n || !A->cmap->n) PetscFunctionReturn(PETSC_SUCCESS);
788:   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
789:   PetscCallBLAS("LAPACKgetrf", LAPACKgetrf_(&m, &n, mat->v, &mat->lda, mat->pivots, &info));
790:   PetscCheck(info >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Error in LAPACK argument %" PetscBLASInt_FMT, -info);
791:   PetscCheck(info <= 0, PETSC_COMM_SELF, PETSC_ERR_MAT_LU_ZRPVT, "Bad factorization: zero pivot in row %" PetscBLASInt_FMT, info - 1);
792:   PetscCall(PetscFPTrapPop());

794:   A->ops->solve             = MatSolve_SeqDense_LU;
795:   A->ops->matsolve          = MatMatSolve_SeqDense_LU;
796:   A->ops->solvetranspose    = MatSolveTranspose_SeqDense_LU;
797:   A->ops->matsolvetranspose = MatMatSolveTranspose_SeqDense_LU;
798:   A->factortype             = MAT_FACTOR_LU;

800:   PetscCall(PetscFree(A->solvertype));
801:   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &A->solvertype));

803:   PetscCall(PetscLogFlops((2.0 * A->cmap->n * A->cmap->n * A->cmap->n) / 3));
804:   PetscFunctionReturn(PETSC_SUCCESS);
805: }

807: static PetscErrorCode MatLUFactorNumeric_SeqDense(Mat fact, Mat A, const MatFactorInfo *info)
808: {
809:   PetscFunctionBegin;
810:   PetscCall(MatDuplicateNoCreate_SeqDense(fact, A, MAT_COPY_VALUES));
811:   PetscUseTypeMethod(fact, lufactor, NULL, NULL, info);
812:   PetscFunctionReturn(PETSC_SUCCESS);
813: }

815: PetscErrorCode MatLUFactorSymbolic_SeqDense(Mat fact, Mat A, IS row, IS col, PETSC_UNUSED const MatFactorInfo *info)
816: {
817:   PetscFunctionBegin;
818:   fact->preallocated         = PETSC_TRUE;
819:   fact->assembled            = PETSC_TRUE;
820:   fact->ops->lufactornumeric = MatLUFactorNumeric_SeqDense;
821:   PetscFunctionReturn(PETSC_SUCCESS);
822: }

824: /* Cholesky as L*L^T or L*D*L^T and the symmetric/hermitian complex variants */
825: PetscErrorCode MatCholeskyFactor_SeqDense(Mat A, IS perm, PETSC_UNUSED const MatFactorInfo *minfo)
826: {
827:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
828:   PetscBLASInt  info, n;

830:   PetscFunctionBegin;
831:   PetscCall(PetscBLASIntCast(A->cmap->n, &n));
832:   if (!A->rmap->n || !A->cmap->n) PetscFunctionReturn(PETSC_SUCCESS);
833:   if (A->spd == PETSC_BOOL3_TRUE) {
834:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
835:     PetscCallBLAS("LAPACKpotrf", LAPACKpotrf_("L", &n, mat->v, &mat->lda, &info));
836:     PetscCall(PetscFPTrapPop());
837: #if defined(PETSC_USE_COMPLEX)
838:   } else if (A->hermitian == PETSC_BOOL3_TRUE) {
839:     if (!mat->pivots) PetscCall(PetscMalloc1(A->rmap->n, &mat->pivots));
840:     if (!mat->fwork) {
841:       PetscScalar dummy;

843:       mat->lfwork = -1;
844:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
845:       PetscCallBLAS("LAPACKhetrf", LAPACKhetrf_("L", &n, mat->v, &mat->lda, mat->pivots, &dummy, &mat->lfwork, &info));
846:       PetscCall(PetscFPTrapPop());
847:       PetscCall(PetscBLASIntCast((PetscCount)(PetscRealPart(dummy)), &mat->lfwork));
848:       PetscCall(PetscMalloc1(mat->lfwork, &mat->fwork));
849:     }
850:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
851:     PetscCallBLAS("LAPACKhetrf", LAPACKhetrf_("L", &n, mat->v, &mat->lda, mat->pivots, mat->fwork, &mat->lfwork, &info));
852:     PetscCall(PetscFPTrapPop());
853: #endif
854:   } else { /* symmetric case */
855:     if (!mat->pivots) PetscCall(PetscMalloc1(A->rmap->n, &mat->pivots));
856:     if (!mat->fwork) {
857:       PetscScalar dummy;

859:       mat->lfwork = -1;
860:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
861:       PetscCallBLAS("LAPACKsytrf", LAPACKsytrf_("L", &n, mat->v, &mat->lda, mat->pivots, &dummy, &mat->lfwork, &info));
862:       PetscCall(PetscFPTrapPop());
863:       PetscCall(PetscBLASIntCast((PetscCount)(PetscRealPart(dummy)), &mat->lfwork));
864:       PetscCall(PetscMalloc1(mat->lfwork, &mat->fwork));
865:     }
866:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
867:     PetscCallBLAS("LAPACKsytrf", LAPACKsytrf_("L", &n, mat->v, &mat->lda, mat->pivots, mat->fwork, &mat->lfwork, &info));
868:     PetscCall(PetscFPTrapPop());
869:   }
870:   PetscCheck(info >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Error in LAPACK argument %" PetscBLASInt_FMT, -info);
871:   PetscCheck(info <= 0, PETSC_COMM_SELF, PETSC_ERR_MAT_CH_ZRPVT, "Bad factorization: zero pivot in row %" PetscBLASInt_FMT, info - 1);

873:   A->ops->solve             = MatSolve_SeqDense_Cholesky;
874:   A->ops->matsolve          = MatMatSolve_SeqDense_Cholesky;
875:   A->ops->solvetranspose    = MatSolveTranspose_SeqDense_Cholesky;
876:   A->ops->matsolvetranspose = MatMatSolveTranspose_SeqDense_Cholesky;
877:   A->factortype             = MAT_FACTOR_CHOLESKY;

879:   PetscCall(PetscFree(A->solvertype));
880:   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &A->solvertype));

882:   PetscCall(PetscLogFlops((1.0 * A->cmap->n * A->cmap->n * A->cmap->n) / 3.0));
883:   PetscFunctionReturn(PETSC_SUCCESS);
884: }

886: static PetscErrorCode MatCholeskyFactorNumeric_SeqDense(Mat fact, Mat A, const MatFactorInfo *info)
887: {
888:   PetscFunctionBegin;
889:   PetscCall(MatDuplicateNoCreate_SeqDense(fact, A, MAT_COPY_VALUES));
890:   PetscUseTypeMethod(fact, choleskyfactor, NULL, info);
891:   PetscFunctionReturn(PETSC_SUCCESS);
892: }

894: PetscErrorCode MatCholeskyFactorSymbolic_SeqDense(Mat fact, Mat A, IS row, const MatFactorInfo *info)
895: {
896:   PetscFunctionBegin;
897:   fact->assembled                  = PETSC_TRUE;
898:   fact->preallocated               = PETSC_TRUE;
899:   fact->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqDense;
900:   PetscFunctionReturn(PETSC_SUCCESS);
901: }

903: PetscErrorCode MatQRFactor_SeqDense(Mat A, IS col, PETSC_UNUSED const MatFactorInfo *minfo)
904: {
905:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
906:   PetscBLASInt  n, m, min, max;

908:   PetscFunctionBegin;
909:   PetscCall(PetscBLASIntCast(A->cmap->n, &n));
910:   PetscCall(PetscBLASIntCast(A->rmap->n, &m));
911:   max = PetscMax(m, n);
912:   min = PetscMin(m, n);
913:   if (!mat->tau) PetscCall(PetscMalloc1(min, &mat->tau));
914:   if (!mat->pivots) PetscCall(PetscMalloc1(n, &mat->pivots));
915:   if (!mat->qrrhs) PetscCall(MatCreateVecs(A, NULL, &mat->qrrhs));
916:   if (!A->rmap->n || !A->cmap->n) PetscFunctionReturn(PETSC_SUCCESS);
917:   if (!mat->fwork) {
918:     PetscScalar dummy;

920:     mat->lfwork = -1;
921:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
922:     PetscCallLAPACKInfo("LAPACKgeqrf", LAPACKgeqrf_(&m, &n, mat->v, &mat->lda, mat->tau, &dummy, &mat->lfwork, &info));
923:     PetscCall(PetscFPTrapPop());
924:     PetscCall(PetscBLASIntCast((PetscCount)(PetscRealPart(dummy)), &mat->lfwork));
925:     PetscCall(PetscMalloc1(mat->lfwork, &mat->fwork));
926:   }
927:   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
928:   PetscCallLAPACKInfo("LAPACKgeqrf", LAPACKgeqrf_(&m, &n, mat->v, &mat->lda, mat->tau, mat->fwork, &mat->lfwork, &info));
929:   PetscCall(PetscFPTrapPop());
930:   // TODO: try to estimate rank or test for and use geqp3 for rank revealing QR.  For now just say rank is min of m and n
931:   mat->rank = min;

933:   A->ops->solve    = MatSolve_SeqDense_QR;
934:   A->ops->matsolve = MatMatSolve_SeqDense_QR;
935:   A->factortype    = MAT_FACTOR_QR;
936:   if (m == n) {
937:     A->ops->solvetranspose    = MatSolveTranspose_SeqDense_QR;
938:     A->ops->matsolvetranspose = MatMatSolveTranspose_SeqDense_QR;
939:   }

941:   PetscCall(PetscFree(A->solvertype));
942:   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &A->solvertype));

944:   PetscCall(PetscLogFlops(2.0 * min * min * (max - min / 3.0)));
945:   PetscFunctionReturn(PETSC_SUCCESS);
946: }

948: static PetscErrorCode MatQRFactorNumeric_SeqDense(Mat fact, Mat A, const MatFactorInfo *info)
949: {
950:   PetscFunctionBegin;
951:   PetscCall(MatDuplicateNoCreate_SeqDense(fact, A, MAT_COPY_VALUES));
952:   PetscUseMethod(fact, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (fact, NULL, info));
953:   PetscFunctionReturn(PETSC_SUCCESS);
954: }

956: PetscErrorCode MatQRFactorSymbolic_SeqDense(Mat fact, Mat A, IS row, const MatFactorInfo *info)
957: {
958:   PetscFunctionBegin;
959:   fact->assembled    = PETSC_TRUE;
960:   fact->preallocated = PETSC_TRUE;
961:   PetscCall(PetscObjectComposeFunction((PetscObject)fact, "MatQRFactorNumeric_C", MatQRFactorNumeric_SeqDense));
962:   PetscFunctionReturn(PETSC_SUCCESS);
963: }

965: /* uses LAPACK */
966: PETSC_INTERN PetscErrorCode MatGetFactor_seqdense_petsc(Mat A, MatFactorType ftype, Mat *fact)
967: {
968:   PetscFunctionBegin;
969:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), fact));
970:   PetscCall(MatSetSizes(*fact, A->rmap->n, A->cmap->n, A->rmap->n, A->cmap->n));
971:   PetscCall(MatSetType(*fact, MATDENSE));
972:   (*fact)->trivialsymbolic = PETSC_TRUE;
973:   if (ftype == MAT_FACTOR_LU || ftype == MAT_FACTOR_ILU) {
974:     (*fact)->ops->lufactorsymbolic  = MatLUFactorSymbolic_SeqDense;
975:     (*fact)->ops->ilufactorsymbolic = MatLUFactorSymbolic_SeqDense;
976:   } else if (ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC) {
977:     (*fact)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqDense;
978:   } else if (ftype == MAT_FACTOR_QR) {
979:     PetscCall(PetscObjectComposeFunction((PetscObject)*fact, "MatQRFactorSymbolic_C", MatQRFactorSymbolic_SeqDense));
980:   }
981:   (*fact)->factortype = ftype;

983:   PetscCall(PetscFree((*fact)->solvertype));
984:   PetscCall(PetscStrallocpy(MATSOLVERPETSC, &(*fact)->solvertype));
985:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&(*fact)->preferredordering[MAT_FACTOR_LU]));
986:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&(*fact)->preferredordering[MAT_FACTOR_ILU]));
987:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&(*fact)->preferredordering[MAT_FACTOR_CHOLESKY]));
988:   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, (char **)&(*fact)->preferredordering[MAT_FACTOR_ICC]));
989:   PetscFunctionReturn(PETSC_SUCCESS);
990: }

992: static PetscErrorCode MatSOR_SeqDense(Mat A, Vec bb, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec xx)
993: {
994:   Mat_SeqDense      *mat = (Mat_SeqDense *)A->data;
995:   PetscScalar       *x, *v = mat->v, zero = 0.0, xt;
996:   const PetscScalar *b;
997:   PetscInt           m = A->rmap->n, i;
998:   PetscBLASInt       o = 1, bm = 0;

1000:   PetscFunctionBegin;
1001: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
1002:   PetscCheck(A->offloadmask != PETSC_OFFLOAD_GPU, PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
1003: #endif
1004:   if (shift == -1) shift = 0.0; /* negative shift indicates do not error on zero diagonal; this code never zeros on zero diagonal */
1005:   PetscCall(PetscBLASIntCast(m, &bm));
1006:   if (flag & SOR_ZERO_INITIAL_GUESS) {
1007:     /* this is a hack fix, should have another version without the second BLASdotu */
1008:     PetscCall(VecSet(xx, zero));
1009:   }
1010:   PetscCall(VecGetArray(xx, &x));
1011:   PetscCall(VecGetArrayRead(bb, &b));
1012:   its = its * lits;
1013:   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " and local its %" PetscInt_FMT " both positive", its, lits);
1014:   while (its--) {
1015:     if (flag & SOR_FORWARD_SWEEP || flag & SOR_LOCAL_FORWARD_SWEEP) {
1016:       for (i = 0; i < m; i++) {
1017:         PetscCallBLAS("BLASdotu", xt = b[i] - BLASdotu_(&bm, v + i, &bm, x, &o));
1018:         x[i] = (1. - omega) * x[i] + (xt + v[i + i * m] * x[i]) * omega / (v[i + i * m] + shift);
1019:       }
1020:     }
1021:     if (flag & SOR_BACKWARD_SWEEP || flag & SOR_LOCAL_BACKWARD_SWEEP) {
1022:       for (i = m - 1; i >= 0; i--) {
1023:         PetscCallBLAS("BLASdotu", xt = b[i] - BLASdotu_(&bm, v + i, &bm, x, &o));
1024:         x[i] = (1. - omega) * x[i] + (xt + v[i + i * m] * x[i]) * omega / (v[i + i * m] + shift);
1025:       }
1026:     }
1027:   }
1028:   PetscCall(VecRestoreArrayRead(bb, &b));
1029:   PetscCall(VecRestoreArray(xx, &x));
1030:   PetscFunctionReturn(PETSC_SUCCESS);
1031: }

1033: PETSC_INTERN PetscErrorCode MatMultColumnRangeKernel_SeqDense(Mat A, Vec xx, Vec yy, PetscInt c_start, PetscInt c_end, PetscBool trans, PetscBool herm)
1034: {
1035:   Mat_SeqDense      *mat = (Mat_SeqDense *)A->data;
1036:   PetscScalar       *y, _DOne = 1.0, _DZero = 0.0;
1037:   PetscBLASInt       m, n, _One             = 1;
1038:   const PetscScalar *v = mat->v, *x;

1040:   PetscFunctionBegin;
1041:   PetscCall(PetscBLASIntCast(A->rmap->n, &m));
1042:   PetscCall(PetscBLASIntCast(c_end - c_start, &n));
1043:   PetscCall(VecGetArrayRead(xx, &x));
1044:   PetscCall(VecGetArrayWrite(yy, &y));
1045:   if (!m || !n) {
1046:     PetscBLASInt i;
1047:     if (trans)
1048:       for (i = 0; i < n; i++) y[i] = 0.0;
1049:     else
1050:       for (i = 0; i < m; i++) y[i] = 0.0;
1051:   } else {
1052:     if (trans) {
1053:       if (herm) PetscCallBLAS("BLASgemv", BLASgemv_("C", &m, &n, &_DOne, v + c_start * mat->lda, &mat->lda, x, &_One, &_DZero, y + c_start, &_One));
1054:       else PetscCallBLAS("BLASgemv", BLASgemv_("T", &m, &n, &_DOne, v + c_start * mat->lda, &mat->lda, x, &_One, &_DZero, y + c_start, &_One));
1055:     } else {
1056:       PetscCallBLAS("BLASgemv", BLASgemv_("N", &m, &n, &_DOne, v + c_start * mat->lda, &mat->lda, x + c_start, &_One, &_DZero, y, &_One));
1057:     }
1058:     PetscCall(PetscLogFlops(2.0 * m * n - n));
1059:   }
1060:   PetscCall(VecRestoreArrayRead(xx, &x));
1061:   PetscCall(VecRestoreArrayWrite(yy, &y));
1062:   PetscFunctionReturn(PETSC_SUCCESS);
1063: }

1065: PetscErrorCode MatMultHermitianTransposeColumnRange_SeqDense(Mat A, Vec xx, Vec yy, PetscInt c_start, PetscInt c_end)
1066: {
1067:   PetscFunctionBegin;
1068:   PetscCall(MatMultColumnRangeKernel_SeqDense(A, xx, yy, c_start, c_end, PETSC_TRUE, PETSC_TRUE));
1069:   PetscFunctionReturn(PETSC_SUCCESS);
1070: }

1072: PetscErrorCode MatMult_SeqDense(Mat A, Vec xx, Vec yy)
1073: {
1074:   PetscFunctionBegin;
1075:   PetscCall(MatMultColumnRangeKernel_SeqDense(A, xx, yy, 0, A->cmap->n, PETSC_FALSE, PETSC_FALSE));
1076:   PetscFunctionReturn(PETSC_SUCCESS);
1077: }

1079: PetscErrorCode MatMultTranspose_SeqDense(Mat A, Vec xx, Vec yy)
1080: {
1081:   PetscFunctionBegin;
1082:   PetscCall(MatMultColumnRangeKernel_SeqDense(A, xx, yy, 0, A->cmap->n, PETSC_TRUE, PETSC_FALSE));
1083:   PetscFunctionReturn(PETSC_SUCCESS);
1084: }

1086: PetscErrorCode MatMultHermitianTranspose_SeqDense(Mat A, Vec xx, Vec yy)
1087: {
1088:   PetscFunctionBegin;
1089:   PetscCall(MatMultColumnRangeKernel_SeqDense(A, xx, yy, 0, A->cmap->n, PETSC_TRUE, PETSC_TRUE));
1090:   PetscFunctionReturn(PETSC_SUCCESS);
1091: }

1093: PETSC_INTERN PetscErrorCode MatMultAddColumnRangeKernel_SeqDense(Mat A, Vec xx, Vec zz, Vec yy, PetscInt c_start, PetscInt c_end, PetscBool trans, PetscBool herm)
1094: {
1095:   Mat_SeqDense      *mat = (Mat_SeqDense *)A->data;
1096:   const PetscScalar *v   = mat->v, *x;
1097:   PetscScalar       *y, _DOne = 1.0;
1098:   PetscBLASInt       m, n, _One = 1;

1100:   PetscFunctionBegin;
1101:   PetscCall(PetscBLASIntCast(A->rmap->n, &m));
1102:   PetscCall(PetscBLASIntCast(c_end - c_start, &n));
1103:   PetscCall(VecCopy(zz, yy));
1104:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
1105:   PetscCall(VecGetArray(yy, &y));
1106:   PetscCall(VecGetArrayRead(xx, &x));
1107:   if (trans) {
1108:     if (herm) PetscCallBLAS("BLASgemv", BLASgemv_("C", &m, &n, &_DOne, v + c_start * mat->lda, &mat->lda, x, &_One, &_DOne, y + c_start, &_One));
1109:     else PetscCallBLAS("BLASgemv", BLASgemv_("T", &m, &n, &_DOne, v + c_start * mat->lda, &mat->lda, x, &_One, &_DOne, y + c_start, &_One));
1110:   } else {
1111:     PetscCallBLAS("BLASgemv", BLASgemv_("N", &m, &n, &_DOne, v + c_start * mat->lda, &mat->lda, x + c_start, &_One, &_DOne, y, &_One));
1112:   }
1113:   PetscCall(VecRestoreArrayRead(xx, &x));
1114:   PetscCall(VecRestoreArray(yy, &y));
1115:   PetscCall(PetscLogFlops(2.0 * m * n));
1116:   PetscFunctionReturn(PETSC_SUCCESS);
1117: }

1119: PetscErrorCode MatMultColumnRange_SeqDense(Mat A, Vec xx, Vec yy, PetscInt c_start, PetscInt c_end)
1120: {
1121:   PetscFunctionBegin;
1122:   PetscCall(MatMultColumnRangeKernel_SeqDense(A, xx, yy, c_start, c_end, PETSC_FALSE, PETSC_FALSE));
1123:   PetscFunctionReturn(PETSC_SUCCESS);
1124: }

1126: PetscErrorCode MatMultAddColumnRange_SeqDense(Mat A, Vec xx, Vec zz, Vec yy, PetscInt c_start, PetscInt c_end)
1127: {
1128:   PetscFunctionBegin;
1129:   PetscCall(MatMultAddColumnRangeKernel_SeqDense(A, xx, zz, yy, c_start, c_end, PETSC_FALSE, PETSC_FALSE));
1130:   PetscFunctionReturn(PETSC_SUCCESS);
1131: }

1133: PetscErrorCode MatMultHermitianTransposeAddColumnRange_SeqDense(Mat A, Vec xx, Vec zz, Vec yy, PetscInt c_start, PetscInt c_end)
1134: {
1135:   PetscFunctionBegin;
1136:   PetscMPIInt rank;
1137:   PetscCallMPI(MPI_Comm_rank(MPI_COMM_WORLD, &rank));
1138:   PetscCall(MatMultAddColumnRangeKernel_SeqDense(A, xx, zz, yy, c_start, c_end, PETSC_TRUE, PETSC_TRUE));
1139:   PetscFunctionReturn(PETSC_SUCCESS);
1140: }

1142: PetscErrorCode MatMultAdd_SeqDense(Mat A, Vec xx, Vec zz, Vec yy)
1143: {
1144:   PetscFunctionBegin;
1145:   PetscCall(MatMultAddColumnRangeKernel_SeqDense(A, xx, zz, yy, 0, A->cmap->n, PETSC_FALSE, PETSC_FALSE));
1146:   PetscFunctionReturn(PETSC_SUCCESS);
1147: }

1149: PetscErrorCode MatMultTransposeAdd_SeqDense(Mat A, Vec xx, Vec zz, Vec yy)
1150: {
1151:   PetscFunctionBegin;
1152:   PetscCall(MatMultAddColumnRangeKernel_SeqDense(A, xx, zz, yy, 0, A->cmap->n, PETSC_TRUE, PETSC_FALSE));
1153:   PetscFunctionReturn(PETSC_SUCCESS);
1154: }

1156: PetscErrorCode MatMultHermitianTransposeAdd_SeqDense(Mat A, Vec xx, Vec zz, Vec yy)
1157: {
1158:   PetscFunctionBegin;
1159:   PetscCall(MatMultAddColumnRangeKernel_SeqDense(A, xx, zz, yy, 0, A->cmap->n, PETSC_TRUE, PETSC_TRUE));
1160:   PetscFunctionReturn(PETSC_SUCCESS);
1161: }

1163: static PetscErrorCode MatGetRow_SeqDense(Mat A, PetscInt row, PetscInt *ncols, PetscInt **cols, PetscScalar **vals)
1164: {
1165:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
1166:   PetscInt      i;

1168:   PetscFunctionBegin;
1169:   if (ncols) *ncols = A->cmap->n;
1170:   if (cols) {
1171:     PetscCall(PetscMalloc1(A->cmap->n, cols));
1172:     for (i = 0; i < A->cmap->n; i++) (*cols)[i] = i;
1173:   }
1174:   if (vals) {
1175:     const PetscScalar *v;

1177:     PetscCall(MatDenseGetArrayRead(A, &v));
1178:     PetscCall(PetscMalloc1(A->cmap->n, vals));
1179:     v += row;
1180:     for (i = 0; i < A->cmap->n; i++) {
1181:       (*vals)[i] = *v;
1182:       v += mat->lda;
1183:     }
1184:     PetscCall(MatDenseRestoreArrayRead(A, &v));
1185:   }
1186:   PetscFunctionReturn(PETSC_SUCCESS);
1187: }

1189: static PetscErrorCode MatRestoreRow_SeqDense(Mat A, PetscInt row, PetscInt *ncols, PetscInt **cols, PetscScalar **vals)
1190: {
1191:   PetscFunctionBegin;
1192:   if (cols) PetscCall(PetscFree(*cols));
1193:   if (vals) PetscCall(PetscFree(*vals));
1194:   PetscFunctionReturn(PETSC_SUCCESS);
1195: }

1197: static PetscErrorCode MatSetValues_SeqDense(Mat A, PetscInt m, const PetscInt indexm[], PetscInt n, const PetscInt indexn[], const PetscScalar v[], InsertMode addv)
1198: {
1199:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
1200:   PetscScalar  *av;
1201:   PetscInt      i, j, idx = 0;
1202: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
1203:   PetscOffloadMask oldf;
1204: #endif

1206:   PetscFunctionBegin;
1207:   PetscCall(MatDenseGetArray(A, &av));
1208:   if (!mat->roworiented) {
1209:     if (addv == INSERT_VALUES) {
1210:       for (j = 0; j < n; j++) {
1211:         if (indexn[j] < 0) {
1212:           idx += m;
1213:           continue;
1214:         }
1215:         PetscCheck(indexn[j] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, indexn[j], A->cmap->n - 1);
1216:         for (i = 0; i < m; i++) {
1217:           if (indexm[i] < 0) {
1218:             idx++;
1219:             continue;
1220:           }
1221:           PetscCheck(indexm[i] < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, indexm[i], A->rmap->n - 1);
1222:           av[indexn[j] * mat->lda + indexm[i]] = v ? v[idx++] : (idx++, 0.0);
1223:         }
1224:       }
1225:     } else {
1226:       for (j = 0; j < n; j++) {
1227:         if (indexn[j] < 0) {
1228:           idx += m;
1229:           continue;
1230:         }
1231:         PetscCheck(indexn[j] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, indexn[j], A->cmap->n - 1);
1232:         for (i = 0; i < m; i++) {
1233:           if (indexm[i] < 0) {
1234:             idx++;
1235:             continue;
1236:           }
1237:           PetscCheck(indexm[i] < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, indexm[i], A->rmap->n - 1);
1238:           av[indexn[j] * mat->lda + indexm[i]] += v ? v[idx++] : (idx++, 0.0);
1239:         }
1240:       }
1241:     }
1242:   } else {
1243:     if (addv == INSERT_VALUES) {
1244:       for (i = 0; i < m; i++) {
1245:         if (indexm[i] < 0) {
1246:           idx += n;
1247:           continue;
1248:         }
1249:         PetscCheck(indexm[i] < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, indexm[i], A->rmap->n - 1);
1250:         for (j = 0; j < n; j++) {
1251:           if (indexn[j] < 0) {
1252:             idx++;
1253:             continue;
1254:           }
1255:           PetscCheck(indexn[j] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, indexn[j], A->cmap->n - 1);
1256:           av[indexn[j] * mat->lda + indexm[i]] = v ? v[idx++] : (idx++, 0.0);
1257:         }
1258:       }
1259:     } else {
1260:       for (i = 0; i < m; i++) {
1261:         if (indexm[i] < 0) {
1262:           idx += n;
1263:           continue;
1264:         }
1265:         PetscCheck(indexm[i] < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, indexm[i], A->rmap->n - 1);
1266:         for (j = 0; j < n; j++) {
1267:           if (indexn[j] < 0) {
1268:             idx++;
1269:             continue;
1270:           }
1271:           PetscCheck(indexn[j] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column too large: col %" PetscInt_FMT " max %" PetscInt_FMT, indexn[j], A->cmap->n - 1);
1272:           av[indexn[j] * mat->lda + indexm[i]] += v ? v[idx++] : (idx++, 0.0);
1273:         }
1274:       }
1275:     }
1276:   }
1277:   /* hack to prevent unneeded copy to the GPU while returning the array */
1278: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
1279:   oldf           = A->offloadmask;
1280:   A->offloadmask = PETSC_OFFLOAD_GPU;
1281: #endif
1282:   PetscCall(MatDenseRestoreArray(A, &av));
1283: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
1284:   A->offloadmask = (oldf == PETSC_OFFLOAD_UNALLOCATED ? PETSC_OFFLOAD_UNALLOCATED : PETSC_OFFLOAD_CPU);
1285: #endif
1286:   PetscFunctionReturn(PETSC_SUCCESS);
1287: }

1289: static PetscErrorCode MatGetValues_SeqDense(Mat A, PetscInt m, const PetscInt indexm[], PetscInt n, const PetscInt indexn[], PetscScalar v[])
1290: {
1291:   Mat_SeqDense      *mat = (Mat_SeqDense *)A->data;
1292:   const PetscScalar *vv;
1293:   PetscInt           i, j;

1295:   PetscFunctionBegin;
1296:   PetscCall(MatDenseGetArrayRead(A, &vv));
1297:   /* row-oriented output */
1298:   for (i = 0; i < m; i++) {
1299:     if (indexm[i] < 0) {
1300:       v += n;
1301:       continue;
1302:     }
1303:     PetscCheck(indexm[i] < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row %" PetscInt_FMT " requested larger than number rows %" PetscInt_FMT, indexm[i], A->rmap->n);
1304:     for (j = 0; j < n; j++) {
1305:       if (indexn[j] < 0) {
1306:         v++;
1307:         continue;
1308:       }
1309:       PetscCheck(indexn[j] < A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column %" PetscInt_FMT " requested larger than number columns %" PetscInt_FMT, indexn[j], A->cmap->n);
1310:       *v++ = vv[indexn[j] * mat->lda + indexm[i]];
1311:     }
1312:   }
1313:   PetscCall(MatDenseRestoreArrayRead(A, &vv));
1314:   PetscFunctionReturn(PETSC_SUCCESS);
1315: }

1317: PetscErrorCode MatView_Dense_Binary(Mat mat, PetscViewer viewer)
1318: {
1319:   PetscBool          skipHeader;
1320:   PetscViewerFormat  format;
1321:   PetscInt           header[4], M, N, m, lda, i, j;
1322:   PetscCount         k;
1323:   const PetscScalar *v;
1324:   PetscScalar       *vwork;

1326:   PetscFunctionBegin;
1327:   PetscCall(PetscViewerSetUp(viewer));
1328:   PetscCall(PetscViewerBinaryGetSkipHeader(viewer, &skipHeader));
1329:   PetscCall(PetscViewerGetFormat(viewer, &format));
1330:   if (skipHeader) format = PETSC_VIEWER_NATIVE;

1332:   PetscCall(MatGetSize(mat, &M, &N));

1334:   /* write matrix header */
1335:   header[0] = MAT_FILE_CLASSID;
1336:   header[1] = M;
1337:   header[2] = N;
1338:   header[3] = (format == PETSC_VIEWER_NATIVE) ? MATRIX_BINARY_FORMAT_DENSE : M * N;
1339:   if (!skipHeader) PetscCall(PetscViewerBinaryWrite(viewer, header, 4, PETSC_INT));

1341:   PetscCall(MatGetLocalSize(mat, &m, NULL));
1342:   if (format != PETSC_VIEWER_NATIVE) {
1343:     PetscInt nnz = m * N, *iwork;
1344:     /* store row lengths for each row */
1345:     PetscCall(PetscMalloc1(nnz, &iwork));
1346:     for (i = 0; i < m; i++) iwork[i] = N;
1347:     PetscCall(PetscViewerBinaryWriteAll(viewer, iwork, m, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1348:     /* store column indices (zero start index) */
1349:     for (k = 0, i = 0; i < m; i++)
1350:       for (j = 0; j < N; j++, k++) iwork[k] = j;
1351:     PetscCall(PetscViewerBinaryWriteAll(viewer, iwork, nnz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1352:     PetscCall(PetscFree(iwork));
1353:   }
1354:   /* store matrix values as a dense matrix in row major order */
1355:   PetscCall(PetscMalloc1(m * N, &vwork));
1356:   PetscCall(MatDenseGetArrayRead(mat, &v));
1357:   PetscCall(MatDenseGetLDA(mat, &lda));
1358:   for (k = 0, i = 0; i < m; i++)
1359:     for (j = 0; j < N; j++, k++) vwork[k] = v[i + (size_t)lda * j];
1360:   PetscCall(MatDenseRestoreArrayRead(mat, &v));
1361:   PetscCall(PetscViewerBinaryWriteAll(viewer, vwork, m * N, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
1362:   PetscCall(PetscFree(vwork));
1363:   PetscFunctionReturn(PETSC_SUCCESS);
1364: }

1366: PetscErrorCode MatLoad_Dense_Binary(Mat mat, PetscViewer viewer)
1367: {
1368:   PetscBool    skipHeader;
1369:   PetscInt     header[4], M, N, m, nz, lda, i, j, k;
1370:   PetscInt     rows, cols;
1371:   PetscScalar *v, *vwork;

1373:   PetscFunctionBegin;
1374:   PetscCall(PetscViewerSetUp(viewer));
1375:   PetscCall(PetscViewerBinaryGetSkipHeader(viewer, &skipHeader));

1377:   if (!skipHeader) {
1378:     PetscCall(PetscViewerBinaryRead(viewer, header, 4, NULL, PETSC_INT));
1379:     PetscCheck(header[0] == MAT_FILE_CLASSID, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Not a matrix object in file");
1380:     M = header[1];
1381:     N = header[2];
1382:     PetscCheck(M >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix row size (%" PetscInt_FMT ") in file is negative", M);
1383:     PetscCheck(N >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix column size (%" PetscInt_FMT ") in file is negative", N);
1384:     nz = header[3];
1385:     PetscCheck(nz == MATRIX_BINARY_FORMAT_DENSE || nz >= 0, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Unknown matrix format %" PetscInt_FMT " in file", nz);
1386:   } else {
1387:     PetscCall(MatGetSize(mat, &M, &N));
1388:     PetscCheck(M >= 0 && N >= 0, PETSC_COMM_SELF, PETSC_ERR_USER, "Matrix binary file header was skipped, thus the user must specify the global sizes of input matrix");
1389:     nz = MATRIX_BINARY_FORMAT_DENSE;
1390:   }

1392:   /* setup global sizes if not set */
1393:   if (mat->rmap->N < 0) mat->rmap->N = M;
1394:   if (mat->cmap->N < 0) mat->cmap->N = N;
1395:   PetscCall(MatSetUp(mat));
1396:   /* check if global sizes are correct */
1397:   PetscCall(MatGetSize(mat, &rows, &cols));
1398:   PetscCheck(M == rows && N == cols, PetscObjectComm((PetscObject)viewer), PETSC_ERR_FILE_UNEXPECTED, "Matrix in file of different sizes (%" PetscInt_FMT ", %" PetscInt_FMT ") than the input matrix (%" PetscInt_FMT ", %" PetscInt_FMT ")", M, N, rows, cols);

1400:   PetscCall(MatGetSize(mat, NULL, &N));
1401:   PetscCall(MatGetLocalSize(mat, &m, NULL));
1402:   PetscCall(MatDenseGetArray(mat, &v));
1403:   PetscCall(MatDenseGetLDA(mat, &lda));
1404:   if (nz == MATRIX_BINARY_FORMAT_DENSE) { /* matrix in file is dense format */
1405:     PetscCount nnz = (size_t)m * N;
1406:     /* read in matrix values */
1407:     PetscCall(PetscMalloc1(nnz, &vwork));
1408:     PetscCall(PetscViewerBinaryReadAll(viewer, vwork, nnz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
1409:     /* store values in column major order */
1410:     for (j = 0; j < N; j++)
1411:       for (i = 0; i < m; i++) v[i + (size_t)lda * j] = vwork[(size_t)i * N + j];
1412:     PetscCall(PetscFree(vwork));
1413:   } else { /* matrix in file is sparse format */
1414:     PetscInt nnz = 0, *rlens, *icols;
1415:     /* read in row lengths */
1416:     PetscCall(PetscMalloc1(m, &rlens));
1417:     PetscCall(PetscViewerBinaryReadAll(viewer, rlens, m, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1418:     for (i = 0; i < m; i++) nnz += rlens[i];
1419:     /* read in column indices and values */
1420:     PetscCall(PetscMalloc2(nnz, &icols, nnz, &vwork));
1421:     PetscCall(PetscViewerBinaryReadAll(viewer, icols, nnz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_INT));
1422:     PetscCall(PetscViewerBinaryReadAll(viewer, vwork, nnz, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_SCALAR));
1423:     /* store values in column major order */
1424:     for (k = 0, i = 0; i < m; i++)
1425:       for (j = 0; j < rlens[i]; j++, k++) v[i + lda * icols[k]] = vwork[k];
1426:     PetscCall(PetscFree(rlens));
1427:     PetscCall(PetscFree2(icols, vwork));
1428:   }
1429:   PetscCall(MatDenseRestoreArray(mat, &v));
1430:   PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
1431:   PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
1432:   PetscFunctionReturn(PETSC_SUCCESS);
1433: }

1435: static PetscErrorCode MatLoad_SeqDense(Mat newMat, PetscViewer viewer)
1436: {
1437:   PetscBool isbinary, ishdf5;

1439:   PetscFunctionBegin;
1442:   /* force binary viewer to load .info file if it has not yet done so */
1443:   PetscCall(PetscViewerSetUp(viewer));
1444:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1445:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
1446:   if (isbinary) {
1447:     PetscCall(MatLoad_Dense_Binary(newMat, viewer));
1448:   } else if (ishdf5) {
1449: #if defined(PETSC_HAVE_HDF5)
1450:     PetscCall(MatLoad_Dense_HDF5(newMat, viewer));
1451: #else
1452:     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
1453: #endif
1454:   } else {
1455:     SETERRQ(PetscObjectComm((PetscObject)newMat), PETSC_ERR_SUP, "Viewer type %s not yet supported for reading %s matrices", ((PetscObject)viewer)->type_name, ((PetscObject)newMat)->type_name);
1456:   }
1457:   PetscFunctionReturn(PETSC_SUCCESS);
1458: }

1460: static PetscErrorCode MatView_SeqDense_ASCII(Mat A, PetscViewer viewer)
1461: {
1462:   Mat_SeqDense     *a = (Mat_SeqDense *)A->data;
1463:   PetscInt          i, j;
1464:   const char       *name;
1465:   PetscScalar      *v, *av;
1466:   PetscViewerFormat format;
1467: #if defined(PETSC_USE_COMPLEX)
1468:   PetscBool allreal = PETSC_TRUE;
1469: #endif

1471:   PetscFunctionBegin;
1472:   PetscCall(MatDenseGetArrayRead(A, (const PetscScalar **)&av));
1473:   PetscCall(PetscViewerGetFormat(viewer, &format));
1474:   if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1475:     PetscFunctionReturn(PETSC_SUCCESS); /* do nothing for now */
1476:   } else if (format == PETSC_VIEWER_ASCII_COMMON) {
1477:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1478:     for (i = 0; i < A->rmap->n; i++) {
1479:       v = av + i;
1480:       PetscCall(PetscViewerASCIIPrintf(viewer, "row %" PetscInt_FMT ":", i));
1481:       for (j = 0; j < A->cmap->n; j++) {
1482: #if defined(PETSC_USE_COMPLEX)
1483:         if (PetscRealPart(*v) != 0.0 && PetscImaginaryPart(*v) != 0.0) {
1484:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g + %g i) ", j, (double)PetscRealPart(*v), (double)PetscImaginaryPart(*v)));
1485:         } else if (PetscRealPart(*v)) {
1486:           PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", j, (double)PetscRealPart(*v)));
1487:         }
1488: #else
1489:         if (*v) PetscCall(PetscViewerASCIIPrintf(viewer, " (%" PetscInt_FMT ", %g) ", j, (double)*v));
1490: #endif
1491:         v += a->lda;
1492:       }
1493:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
1494:     }
1495:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1496:   } else {
1497:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1498: #if defined(PETSC_USE_COMPLEX)
1499:     /* determine if matrix has all real values */
1500:     for (j = 0; j < A->cmap->n; j++) {
1501:       v = av + j * a->lda;
1502:       for (i = 0; i < A->rmap->n; i++) {
1503:         if (PetscImaginaryPart(v[i])) {
1504:           allreal = PETSC_FALSE;
1505:           break;
1506:         }
1507:       }
1508:     }
1509: #endif
1510:     if (format == PETSC_VIEWER_ASCII_MATLAB) {
1511:       PetscCall(PetscObjectGetName((PetscObject)A, &name));
1512:       PetscCall(PetscViewerASCIIPrintf(viewer, "%% Size = %" PetscInt_FMT " %" PetscInt_FMT " \n", A->rmap->n, A->cmap->n));
1513:       PetscCall(PetscViewerASCIIPrintf(viewer, "%s = zeros(%" PetscInt_FMT ",%" PetscInt_FMT ");\n", name, A->rmap->n, A->cmap->n));
1514:       PetscCall(PetscViewerASCIIPrintf(viewer, "%s = [\n", name));
1515:     }

1517:     for (i = 0; i < A->rmap->n; i++) {
1518:       v = av + i;
1519:       for (j = 0; j < A->cmap->n; j++) {
1520: #if defined(PETSC_USE_COMPLEX)
1521:         if (allreal) {
1522:           PetscCall(PetscViewerASCIIPrintf(viewer, "%18.16e ", (double)PetscRealPart(*v)));
1523:         } else {
1524:           PetscCall(PetscViewerASCIIPrintf(viewer, "%18.16e + %18.16ei ", (double)PetscRealPart(*v), (double)PetscImaginaryPart(*v)));
1525:         }
1526: #else
1527:         PetscCall(PetscViewerASCIIPrintf(viewer, "%18.16e ", (double)*v));
1528: #endif
1529:         v += a->lda;
1530:       }
1531:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
1532:     }
1533:     if (format == PETSC_VIEWER_ASCII_MATLAB) PetscCall(PetscViewerASCIIPrintf(viewer, "];\n"));
1534:     PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1535:   }
1536:   PetscCall(MatDenseRestoreArrayRead(A, (const PetscScalar **)&av));
1537:   PetscCall(PetscViewerFlush(viewer));
1538:   PetscFunctionReturn(PETSC_SUCCESS);
1539: }

1541: #include <petscdraw.h>
1542: static PetscErrorCode MatView_SeqDense_Draw_Zoom(PetscDraw draw, void *Aa)
1543: {
1544:   Mat                A = (Mat)Aa;
1545:   PetscInt           m = A->rmap->n, n = A->cmap->n, i, j;
1546:   int                color = PETSC_DRAW_WHITE;
1547:   const PetscScalar *v;
1548:   PetscViewer        viewer;
1549:   PetscReal          xl, yl, xr, yr, x_l, x_r, y_l, y_r;
1550:   PetscViewerFormat  format;

1552:   PetscFunctionBegin;
1553:   PetscCall(PetscObjectQuery((PetscObject)A, "Zoomviewer", (PetscObject *)&viewer));
1554:   PetscCall(PetscViewerGetFormat(viewer, &format));
1555:   PetscCall(PetscDrawGetCoordinates(draw, &xl, &yl, &xr, &yr));

1557:   /* Loop over matrix elements drawing boxes */
1558:   PetscCall(MatDenseGetArrayRead(A, &v));
1559:   if (format != PETSC_VIEWER_DRAW_CONTOUR) {
1560:     PetscDrawCollectiveBegin(draw);
1561:     /* Blue for negative and Red for positive */
1562:     for (j = 0; j < n; j++) {
1563:       x_l = j;
1564:       x_r = x_l + 1.0;
1565:       for (i = 0; i < m; i++) {
1566:         y_l = m - i - 1.0;
1567:         y_r = y_l + 1.0;
1568:         if (PetscRealPart(v[j * m + i]) > 0.) color = PETSC_DRAW_RED;
1569:         else if (PetscRealPart(v[j * m + i]) < 0.) color = PETSC_DRAW_BLUE;
1570:         else continue;
1571:         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
1572:       }
1573:     }
1574:     PetscDrawCollectiveEnd(draw);
1575:   } else {
1576:     /* use contour shading to indicate magnitude of values */
1577:     /* first determine max of all nonzero values */
1578:     PetscReal minv = 0.0, maxv = 0.0;
1579:     PetscDraw popup;

1581:     for (i = 0; i < m * n; i++) {
1582:       if (PetscAbsScalar(v[i]) > maxv) maxv = PetscAbsScalar(v[i]);
1583:     }
1584:     if (minv >= maxv) maxv = minv + PETSC_SMALL;
1585:     PetscCall(PetscDrawGetPopup(draw, &popup));
1586:     PetscCall(PetscDrawScalePopup(popup, minv, maxv));

1588:     PetscDrawCollectiveBegin(draw);
1589:     for (j = 0; j < n; j++) {
1590:       x_l = j;
1591:       x_r = x_l + 1.0;
1592:       for (i = 0; i < m; i++) {
1593:         y_l   = m - i - 1.0;
1594:         y_r   = y_l + 1.0;
1595:         color = PetscDrawRealToColor(PetscAbsScalar(v[j * m + i]), minv, maxv);
1596:         PetscCall(PetscDrawRectangle(draw, x_l, y_l, x_r, y_r, color, color, color, color));
1597:       }
1598:     }
1599:     PetscDrawCollectiveEnd(draw);
1600:   }
1601:   PetscCall(MatDenseRestoreArrayRead(A, &v));
1602:   PetscFunctionReturn(PETSC_SUCCESS);
1603: }

1605: static PetscErrorCode MatView_SeqDense_Draw(Mat A, PetscViewer viewer)
1606: {
1607:   PetscDraw draw;
1608:   PetscBool isnull;
1609:   PetscReal xr, yr, xl, yl, h, w;

1611:   PetscFunctionBegin;
1612:   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1613:   PetscCall(PetscDrawIsNull(draw, &isnull));
1614:   if (isnull) PetscFunctionReturn(PETSC_SUCCESS);

1616:   xr = A->cmap->n;
1617:   yr = A->rmap->n;
1618:   h  = yr / 10.0;
1619:   w  = xr / 10.0;
1620:   xr += w;
1621:   yr += h;
1622:   xl = -w;
1623:   yl = -h;
1624:   PetscCall(PetscDrawSetCoordinates(draw, xl, yl, xr, yr));
1625:   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", (PetscObject)viewer));
1626:   PetscCall(PetscDrawZoom(draw, MatView_SeqDense_Draw_Zoom, A));
1627:   PetscCall(PetscObjectCompose((PetscObject)A, "Zoomviewer", NULL));
1628:   PetscCall(PetscDrawSave(draw));
1629:   PetscFunctionReturn(PETSC_SUCCESS);
1630: }

1632: PetscErrorCode MatView_SeqDense(Mat A, PetscViewer viewer)
1633: {
1634:   PetscBool isascii, isbinary, isdraw;

1636:   PetscFunctionBegin;
1637:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1638:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1639:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1640:   if (isascii) PetscCall(MatView_SeqDense_ASCII(A, viewer));
1641:   else if (isbinary) PetscCall(MatView_Dense_Binary(A, viewer));
1642:   else if (isdraw) PetscCall(MatView_SeqDense_Draw(A, viewer));
1643:   PetscFunctionReturn(PETSC_SUCCESS);
1644: }

1646: static PetscErrorCode MatDensePlaceArray_SeqDense(Mat A, const PetscScalar *array)
1647: {
1648:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

1650:   PetscFunctionBegin;
1651:   PetscCheck(!a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1652:   PetscCheck(!a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1653:   PetscCheck(!a->unplacedarray, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseResetArray() first");
1654:   a->unplacedarray       = a->v;
1655:   a->unplaced_user_alloc = a->user_alloc;
1656:   a->v                   = (PetscScalar *)array;
1657:   a->user_alloc          = PETSC_TRUE;
1658: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
1659:   A->offloadmask = PETSC_OFFLOAD_CPU;
1660: #endif
1661:   PetscFunctionReturn(PETSC_SUCCESS);
1662: }

1664: static PetscErrorCode MatDenseResetArray_SeqDense(Mat A)
1665: {
1666:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

1668:   PetscFunctionBegin;
1669:   PetscCheck(!a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1670:   PetscCheck(!a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1671:   a->v             = a->unplacedarray;
1672:   a->user_alloc    = a->unplaced_user_alloc;
1673:   a->unplacedarray = NULL;
1674: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
1675:   A->offloadmask = PETSC_OFFLOAD_CPU;
1676: #endif
1677:   PetscFunctionReturn(PETSC_SUCCESS);
1678: }

1680: static PetscErrorCode MatDenseReplaceArray_SeqDense(Mat A, const PetscScalar *array)
1681: {
1682:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

1684:   PetscFunctionBegin;
1685:   PetscCheck(!a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1686:   PetscCheck(!a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1687:   if (!a->user_alloc) PetscCall(PetscFree(a->v));
1688:   a->v          = (PetscScalar *)array;
1689:   a->user_alloc = PETSC_FALSE;
1690: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
1691:   A->offloadmask = PETSC_OFFLOAD_CPU;
1692: #endif
1693:   PetscFunctionReturn(PETSC_SUCCESS);
1694: }

1696: PetscErrorCode MatDestroy_SeqDense(Mat mat)
1697: {
1698:   Mat_SeqDense *l = (Mat_SeqDense *)mat->data;

1700:   PetscFunctionBegin;
1701:   PetscCall(PetscLogObjectState((PetscObject)mat, "Rows %" PetscInt_FMT " Cols %" PetscInt_FMT, mat->rmap->n, mat->cmap->n));
1702:   PetscCall(VecDestroy(&l->qrrhs));
1703:   PetscCall(PetscFree(l->tau));
1704:   PetscCall(PetscFree(l->pivots));
1705:   PetscCall(PetscFree(l->fwork));
1706:   if (!l->user_alloc) PetscCall(PetscFree(l->v));
1707:   if (!l->unplaced_user_alloc) PetscCall(PetscFree(l->unplacedarray));
1708:   PetscCheck(!l->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1709:   PetscCheck(!l->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1710:   PetscCall(VecDestroy(&l->cvec));
1711:   PetscCall(MatDestroy(&l->cmat));
1712:   PetscCall(PetscFree(mat->data));

1714:   PetscCall(PetscObjectChangeTypeName((PetscObject)mat, NULL));
1715:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatQRFactor_C", NULL));
1716:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatQRFactorSymbolic_C", NULL));
1717:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatQRFactorNumeric_C", NULL));
1718:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetLDA_C", NULL));
1719:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseSetLDA_C", NULL));
1720:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetArray_C", NULL));
1721:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreArray_C", NULL));
1722:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDensePlaceArray_C", NULL));
1723:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseResetArray_C", NULL));
1724:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseReplaceArray_C", NULL));
1725:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetArrayRead_C", NULL));
1726:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreArrayRead_C", NULL));
1727:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetArrayWrite_C", NULL));
1728:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreArrayWrite_C", NULL));
1729:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_seqdense_seqaij_C", NULL));
1730: #if defined(PETSC_HAVE_ELEMENTAL)
1731:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_seqdense_elemental_C", NULL));
1732: #endif
1733: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
1734:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_seqdense_scalapack_C", NULL));
1735: #endif
1736: #if defined(PETSC_HAVE_CUDA)
1737:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_seqdense_seqdensecuda_C", NULL));
1738:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqdensecuda_seqdensecuda_C", NULL));
1739:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqdensecuda_seqdense_C", NULL));
1740:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqdense_seqdensecuda_C", NULL));
1741: #endif
1742: #if defined(PETSC_HAVE_HIP)
1743:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatConvert_seqdense_seqdensehip_C", NULL));
1744:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqdensehip_seqdensehip_C", NULL));
1745:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqdensehip_seqdense_C", NULL));
1746:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqdense_seqdensehip_C", NULL));
1747: #endif
1748:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatSeqDenseSetPreallocation_C", NULL));
1749:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqaij_seqdense_C", NULL));
1750:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqdense_seqdense_C", NULL));
1751:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqbaij_seqdense_C", NULL));
1752:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatProductSetFromOptions_seqsbaij_seqdense_C", NULL));

1754:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetColumn_C", NULL));
1755:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreColumn_C", NULL));
1756:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetColumnVec_C", NULL));
1757:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreColumnVec_C", NULL));
1758:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetColumnVecRead_C", NULL));
1759:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreColumnVecRead_C", NULL));
1760:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetColumnVecWrite_C", NULL));
1761:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreColumnVecWrite_C", NULL));
1762:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseGetSubMatrix_C", NULL));
1763:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatDenseRestoreSubMatrix_C", NULL));
1764:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMultColumnRange_C", NULL));
1765:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMultAddColumnRange_C", NULL));
1766:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMultHermitianTransposeColumnRange_C", NULL));
1767:   PetscCall(PetscObjectComposeFunction((PetscObject)mat, "MatMultHermitianTransposeAddColumnRange_C", NULL));
1768:   PetscFunctionReturn(PETSC_SUCCESS);
1769: }

1771: static PetscErrorCode MatTranspose_SeqDense(Mat A, MatReuse reuse, Mat *matout)
1772: {
1773:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
1774:   PetscInt      k, j, m = A->rmap->n, M = mat->lda, n = A->cmap->n;
1775:   PetscScalar  *v, tmp;

1777:   PetscFunctionBegin;
1778:   if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *matout));
1779:   if (reuse == MAT_INPLACE_MATRIX) {
1780:     if (m == n) { /* in place transpose */
1781:       PetscCall(MatDenseGetArray(A, &v));
1782:       for (j = 0; j < m; j++) {
1783:         for (k = 0; k < j; k++) {
1784:           tmp          = v[j + k * M];
1785:           v[j + k * M] = v[k + j * M];
1786:           v[k + j * M] = tmp;
1787:         }
1788:       }
1789:       PetscCall(MatDenseRestoreArray(A, &v));
1790:     } else { /* reuse memory, temporary allocates new memory */
1791:       PetscScalar *v2;
1792:       PetscLayout  tmplayout;

1794:       PetscCall(PetscMalloc1((size_t)m * n, &v2));
1795:       PetscCall(MatDenseGetArray(A, &v));
1796:       for (j = 0; j < n; j++) {
1797:         for (k = 0; k < m; k++) v2[j + (size_t)k * n] = v[k + (size_t)j * M];
1798:       }
1799:       PetscCall(PetscArraycpy(v, v2, (size_t)m * n));
1800:       PetscCall(PetscFree(v2));
1801:       PetscCall(MatDenseRestoreArray(A, &v));
1802:       /* cleanup size dependent quantities */
1803:       PetscCall(VecDestroy(&mat->cvec));
1804:       PetscCall(MatDestroy(&mat->cmat));
1805:       PetscCall(PetscFree(mat->pivots));
1806:       PetscCall(PetscFree(mat->fwork));
1807:       /* swap row/col layouts */
1808:       PetscCall(PetscBLASIntCast(n, &mat->lda));
1809:       tmplayout = A->rmap;
1810:       A->rmap   = A->cmap;
1811:       A->cmap   = tmplayout;
1812:     }
1813:   } else { /* out-of-place transpose */
1814:     Mat           tmat;
1815:     Mat_SeqDense *tmatd;
1816:     PetscScalar  *v2;
1817:     PetscInt      M2;

1819:     if (reuse == MAT_INITIAL_MATRIX) {
1820:       PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &tmat));
1821:       PetscCall(MatSetSizes(tmat, A->cmap->n, A->rmap->n, A->cmap->n, A->rmap->n));
1822:       PetscCall(MatSetType(tmat, ((PetscObject)A)->type_name));
1823:       PetscCall(MatSeqDenseSetPreallocation(tmat, NULL));
1824:     } else tmat = *matout;

1826:     PetscCall(MatDenseGetArrayRead(A, (const PetscScalar **)&v));
1827:     PetscCall(MatDenseGetArray(tmat, &v2));
1828:     tmatd = (Mat_SeqDense *)tmat->data;
1829:     M2    = tmatd->lda;
1830:     for (j = 0; j < n; j++) {
1831:       for (k = 0; k < m; k++) v2[j + k * M2] = v[k + j * M];
1832:     }
1833:     PetscCall(MatDenseRestoreArray(tmat, &v2));
1834:     PetscCall(MatDenseRestoreArrayRead(A, (const PetscScalar **)&v));
1835:     PetscCall(MatAssemblyBegin(tmat, MAT_FINAL_ASSEMBLY));
1836:     PetscCall(MatAssemblyEnd(tmat, MAT_FINAL_ASSEMBLY));
1837:     *matout = tmat;
1838:   }
1839:   PetscFunctionReturn(PETSC_SUCCESS);
1840: }

1842: static PetscErrorCode MatEqual_SeqDense(Mat A1, Mat A2, PetscBool *flg)
1843: {
1844:   Mat_SeqDense      *mat1 = (Mat_SeqDense *)A1->data;
1845:   Mat_SeqDense      *mat2 = (Mat_SeqDense *)A2->data;
1846:   PetscInt           i;
1847:   const PetscScalar *v1, *v2;

1849:   PetscFunctionBegin;
1850:   if (A1->rmap->n != A2->rmap->n) {
1851:     *flg = PETSC_FALSE;
1852:     PetscFunctionReturn(PETSC_SUCCESS);
1853:   }
1854:   if (A1->cmap->n != A2->cmap->n) {
1855:     *flg = PETSC_FALSE;
1856:     PetscFunctionReturn(PETSC_SUCCESS);
1857:   }
1858:   PetscCall(MatDenseGetArrayRead(A1, &v1));
1859:   PetscCall(MatDenseGetArrayRead(A2, &v2));
1860:   for (i = 0; i < A1->cmap->n; i++) {
1861:     PetscCall(PetscArraycmp(v1, v2, A1->rmap->n, flg));
1862:     if (*flg == PETSC_FALSE) PetscFunctionReturn(PETSC_SUCCESS);
1863:     v1 += mat1->lda;
1864:     v2 += mat2->lda;
1865:   }
1866:   PetscCall(MatDenseRestoreArrayRead(A1, &v1));
1867:   PetscCall(MatDenseRestoreArrayRead(A2, &v2));
1868:   *flg = PETSC_TRUE;
1869:   PetscFunctionReturn(PETSC_SUCCESS);
1870: }

1872: PetscErrorCode MatGetDiagonal_SeqDense(Mat A, Vec v)
1873: {
1874:   Mat_SeqDense      *mat = (Mat_SeqDense *)A->data;
1875:   PetscInt           i, n, len;
1876:   PetscScalar       *x;
1877:   const PetscScalar *vv;

1879:   PetscFunctionBegin;
1880:   PetscCall(VecGetSize(v, &n));
1881:   PetscCall(VecGetArray(v, &x));
1882:   len = PetscMin(A->rmap->n, A->cmap->n);
1883:   PetscCall(MatDenseGetArrayRead(A, &vv));
1884:   PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming mat and vec");
1885:   for (i = 0; i < len; i++) x[i] = vv[i * mat->lda + i];
1886:   PetscCall(MatDenseRestoreArrayRead(A, &vv));
1887:   PetscCall(VecRestoreArray(v, &x));
1888:   PetscFunctionReturn(PETSC_SUCCESS);
1889: }

1891: PetscErrorCode MatDiagonalScale_SeqDense(Mat A, Vec ll, Vec rr)
1892: {
1893:   Mat_SeqDense      *mat = (Mat_SeqDense *)A->data;
1894:   const PetscScalar *l, *r;
1895:   PetscScalar        x, *v, *vv;
1896:   PetscInt           i, j, m = A->rmap->n, n = A->cmap->n;

1898:   PetscFunctionBegin;
1899:   PetscCall(MatDenseGetArray(A, &vv));
1900:   if (ll) {
1901:     PetscCall(VecGetSize(ll, &m));
1902:     PetscCall(VecGetArrayRead(ll, &l));
1903:     PetscCheck(m == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Left scaling vec wrong size");
1904:     for (i = 0; i < m; i++) {
1905:       x = l[i];
1906:       v = vv + i;
1907:       for (j = 0; j < n; j++) {
1908:         (*v) *= x;
1909:         v += mat->lda;
1910:       }
1911:     }
1912:     PetscCall(VecRestoreArrayRead(ll, &l));
1913:     PetscCall(PetscLogFlops(1.0 * n * m));
1914:   }
1915:   if (rr) {
1916:     PetscCall(VecGetSize(rr, &n));
1917:     PetscCall(VecGetArrayRead(rr, &r));
1918:     PetscCheck(n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Right scaling vec wrong size");
1919:     for (i = 0; i < n; i++) {
1920:       x = r[i];
1921:       v = vv + i * mat->lda;
1922:       for (j = 0; j < m; j++) (*v++) *= x;
1923:     }
1924:     PetscCall(VecRestoreArrayRead(rr, &r));
1925:     PetscCall(PetscLogFlops(1.0 * n * m));
1926:   }
1927:   PetscCall(MatDenseRestoreArray(A, &vv));
1928:   PetscFunctionReturn(PETSC_SUCCESS);
1929: }

1931: PetscErrorCode MatNorm_SeqDense(Mat A, NormType type, PetscReal *nrm)
1932: {
1933:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
1934:   PetscScalar  *v, *vv, *work, *av = NULL;
1935:   PetscReal     sum = 0.0;
1936:   PetscInt      lda, m = A->rmap->n, i, j;

1938:   PetscFunctionBegin;
1939:   PetscCall(MatDenseGetArrayRead(A, (const PetscScalar **)&vv));
1940:   PetscCall(MatDenseGetLDA(A, &lda));
1941:   v = vv;
1942:   if (type == NORM_FROBENIUS) {
1943:     if (lda > m) {
1944:       for (j = 0; j < A->cmap->n; j++) {
1945:         v = vv + j * lda;
1946:         for (i = 0; i < m; i++) {
1947:           sum += PetscRealPart(PetscConj(*v) * (*v));
1948:           v++;
1949:         }
1950:       }
1951:     } else {
1952: #if defined(PETSC_USE_REAL___FP16)
1953:       PetscBLASInt one = 1, cnt = A->cmap->n * A->rmap->n;
1954:       PetscCallBLAS("BLASnrm2", *nrm = BLASnrm2_(&cnt, v, &one));
1955:     }
1956: #else
1957:       for (i = 0; i < A->cmap->n * A->rmap->n; i++) {
1958:         sum += PetscRealPart(PetscConj(*v) * (*v));
1959:         v++;
1960:       }
1961:     }
1962:     *nrm = PetscSqrtReal(sum);
1963: #endif
1964:     PetscCall(PetscLogFlops(2.0 * A->cmap->n * A->rmap->n));
1965:   } else if (type == NORM_1) {
1966:     *nrm = 0.0;
1967:     for (j = 0; j < A->cmap->n; j++) {
1968:       v   = vv + j * mat->lda;
1969:       sum = 0.0;
1970:       for (i = 0; i < A->rmap->n; i++) {
1971:         sum += PetscAbsScalar(*v);
1972:         v++;
1973:       }
1974:       if (sum > *nrm) *nrm = sum;
1975:     }
1976:     PetscCall(PetscLogFlops(1.0 * A->cmap->n * A->rmap->n));
1977:   } else if (type == NORM_INFINITY) {
1978:     *nrm = 0.0;
1979:     for (j = 0; j < A->rmap->n; j++) {
1980:       v   = vv + j;
1981:       sum = 0.0;
1982:       for (i = 0; i < A->cmap->n; i++) {
1983:         sum += PetscAbsScalar(*v);
1984:         v += mat->lda;
1985:       }
1986:       if (sum > *nrm) *nrm = sum;
1987:     }
1988:     PetscCall(PetscLogFlops(1.0 * A->cmap->n * A->rmap->n));
1989:   } else if (type == NORM_2) {
1990:     PetscReal   *s;
1991:     PetscBLASInt bm, bn, blda, min, lwork;

1993:     PetscCall(PetscBLASIntCast(A->rmap->n, &bm));
1994:     PetscCall(PetscBLASIntCast(A->cmap->n, &bn));
1995:     PetscCall(PetscBLASIntCast(PetscMax(A->rmap->n, 1), &blda));
1996:     min = PetscMin(bm, bn);
1997:     if (!min) {
1998:       *nrm = 0.0;
1999:       PetscCall(MatDenseRestoreArrayRead(A, (const PetscScalar **)&vv));
2000:       PetscFunctionReturn(PETSC_SUCCESS);
2001:     }
2002:     PetscCall(PetscMalloc2(A->rmap->n * A->cmap->n, &av, min, &s));
2003:     for (j = 0; j < A->cmap->n; j++) PetscCall(PetscArraycpy(av + j * A->rmap->n, vv + j * lda, A->rmap->n));

2005:     lwork = -1;
2006:     {
2007:       PetscScalar workquery;
2008: #if defined(PETSC_USE_COMPLEX)
2009:       PetscReal *rwork;

2011:       PetscCall(PetscMalloc1(5 * min, &rwork));
2012:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2013:       PetscCallLAPACKInfo("LAPACKgesvd", LAPACKgesvd_("N", "N", &bm, &bn, av, &blda, s, NULL, &bm, NULL, &min, &workquery, &lwork, rwork, &info));
2014:       lwork = (PetscBLASInt)PetscRealPart(workquery);
2015:       PetscCall(PetscMalloc1(lwork, &work));
2016:       PetscCallLAPACKInfo("LAPACKgesvd", LAPACKgesvd_("N", "N", &bm, &bn, av, &blda, s, NULL, &bm, NULL, &min, work, &lwork, rwork, &info));
2017:       PetscCall(PetscFPTrapPop());
2018:       PetscCall(PetscFree(rwork));
2019: #else
2020:       PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2021:       PetscCallLAPACKInfo("LAPACKgesvd", LAPACKgesvd_("N", "N", &bm, &bn, av, &blda, s, NULL, &bm, NULL, &min, &workquery, &lwork, &info));
2022:       lwork = (PetscBLASInt)PetscRealPart(workquery);
2023:       PetscCall(PetscMalloc1(lwork, &work));
2024:       PetscCallLAPACKInfo("LAPACKgesvd", LAPACKgesvd_("N", "N", &bm, &bn, av, &blda, s, NULL, &bm, NULL, &min, work, &lwork, &info));
2025:       PetscCall(PetscFPTrapPop());
2026: #endif
2027:     }
2028:     *nrm = s[0];
2029:     PetscCall(PetscFree(work));
2030:     PetscCall(PetscFree2(av, s));
2031:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Unsupported norm type %s", NormTypes[type]);
2032:   PetscCall(MatDenseRestoreArrayRead(A, (const PetscScalar **)&vv));
2033:   PetscFunctionReturn(PETSC_SUCCESS);
2034: }

2036: static PetscErrorCode MatSetOption_SeqDense(Mat A, MatOption op, PetscBool flg)
2037: {
2038:   Mat_SeqDense *aij = (Mat_SeqDense *)A->data;

2040:   PetscFunctionBegin;
2041:   switch (op) {
2042:   case MAT_ROW_ORIENTED:
2043:     aij->roworiented = flg;
2044:     break;
2045:   default:
2046:     break;
2047:   }
2048:   PetscFunctionReturn(PETSC_SUCCESS);
2049: }

2051: PetscErrorCode MatZeroEntries_SeqDense(Mat A)
2052: {
2053:   Mat_SeqDense *l   = (Mat_SeqDense *)A->data;
2054:   PetscInt      lda = l->lda, m = A->rmap->n, n = A->cmap->n, j;
2055:   PetscScalar  *v;

2057:   PetscFunctionBegin;
2058:   PetscCall(MatDenseGetArrayWrite(A, &v));
2059:   if (lda > m) {
2060:     for (j = 0; j < n; j++) PetscCall(PetscArrayzero(v + j * lda, m));
2061:   } else {
2062:     PetscCall(PetscArrayzero(v, PetscInt64Mult(m, n)));
2063:   }
2064:   PetscCall(MatDenseRestoreArrayWrite(A, &v));
2065:   PetscFunctionReturn(PETSC_SUCCESS);
2066: }

2068: static PetscErrorCode MatZeroRows_SeqDense(Mat A, PetscInt N, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
2069: {
2070:   Mat_SeqDense      *l = (Mat_SeqDense *)A->data;
2071:   PetscInt           m = l->lda, n = A->cmap->n, i, j;
2072:   PetscScalar       *slot, *bb, *v;
2073:   const PetscScalar *xx;

2075:   PetscFunctionBegin;
2076:   if (PetscDefined(USE_DEBUG)) {
2077:     for (i = 0; i < N; i++) {
2078:       PetscCheck(rows[i] >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Negative row requested to be zeroed");
2079:       PetscCheck(rows[i] < A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row %" PetscInt_FMT " requested to be zeroed greater than or equal number of rows %" PetscInt_FMT, rows[i], A->rmap->n);
2080:     }
2081:   }
2082:   if (!N) PetscFunctionReturn(PETSC_SUCCESS);

2084:   /* fix right-hand side if needed */
2085:   if (x && b) {
2086:     PetscCall(VecGetArrayRead(x, &xx));
2087:     PetscCall(VecGetArray(b, &bb));
2088:     for (i = 0; i < N; i++) bb[rows[i]] = diag * xx[rows[i]];
2089:     PetscCall(VecRestoreArrayRead(x, &xx));
2090:     PetscCall(VecRestoreArray(b, &bb));
2091:   }

2093:   PetscCall(MatDenseGetArray(A, &v));
2094:   for (i = 0; i < N; i++) {
2095:     slot = v + rows[i];
2096:     for (j = 0; j < n; j++) {
2097:       *slot = 0.0;
2098:       slot += m;
2099:     }
2100:   }
2101:   if (diag != 0.0) {
2102:     PetscCheck(A->rmap->n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only coded for square matrices");
2103:     for (i = 0; i < N; i++) {
2104:       slot  = v + (m + 1) * rows[i];
2105:       *slot = diag;
2106:     }
2107:   }
2108:   PetscCall(MatDenseRestoreArray(A, &v));
2109:   PetscFunctionReturn(PETSC_SUCCESS);
2110: }

2112: static PetscErrorCode MatDenseGetLDA_SeqDense(Mat A, PetscInt *lda)
2113: {
2114:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;

2116:   PetscFunctionBegin;
2117:   *lda = mat->lda;
2118:   PetscFunctionReturn(PETSC_SUCCESS);
2119: }

2121: PetscErrorCode MatDenseGetArray_SeqDense(Mat A, PetscScalar **array)
2122: {
2123:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;

2125:   PetscFunctionBegin;
2126:   PetscCheck(!mat->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
2127:   *array = mat->v;
2128:   PetscFunctionReturn(PETSC_SUCCESS);
2129: }

2131: PetscErrorCode MatDenseRestoreArray_SeqDense(Mat A, PetscScalar **array)
2132: {
2133:   PetscFunctionBegin;
2134:   if (array) *array = NULL;
2135:   PetscFunctionReturn(PETSC_SUCCESS);
2136: }

2138: /*@
2139:   MatDenseGetLDA - gets the leading dimension of the array returned from `MatDenseGetArray()`

2141:   Not Collective

2143:   Input Parameter:
2144: . A - a `MATDENSE` or `MATDENSECUDA` matrix

2146:   Output Parameter:
2147: . lda - the leading dimension

2149:   Level: intermediate

2151: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseSetLDA()`
2152: @*/
2153: PetscErrorCode MatDenseGetLDA(Mat A, PetscInt *lda)
2154: {
2155:   PetscFunctionBegin;
2157:   PetscAssertPointer(lda, 2);
2158:   MatCheckPreallocated(A, 1);
2159:   PetscUseMethod(A, "MatDenseGetLDA_C", (Mat, PetscInt *), (A, lda));
2160:   PetscFunctionReturn(PETSC_SUCCESS);
2161: }

2163: /*@
2164:   MatDenseSetLDA - Sets the leading dimension of the array used by the `MATDENSE` matrix

2166:   Collective if the matrix layouts have not yet been setup

2168:   Input Parameters:
2169: + A   - a `MATDENSE` or `MATDENSECUDA` matrix
2170: - lda - the leading dimension

2172:   Level: intermediate

2174: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseGetLDA()`
2175: @*/
2176: PetscErrorCode MatDenseSetLDA(Mat A, PetscInt lda)
2177: {
2178:   PetscFunctionBegin;
2180:   PetscTryMethod(A, "MatDenseSetLDA_C", (Mat, PetscInt), (A, lda));
2181:   PetscFunctionReturn(PETSC_SUCCESS);
2182: }

2184: /*@C
2185:   MatDenseGetArray - gives read-write access to the array where the data for a `MATDENSE` matrix is stored

2187:   Logically Collective

2189:   Input Parameter:
2190: . A - a dense matrix

2192:   Output Parameter:
2193: . array - pointer to the data

2195:   Level: intermediate

2197: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseRestoreArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`
2198: @*/
2199: PetscErrorCode MatDenseGetArray(Mat A, PetscScalar *array[]) PeNS
2200: {
2201:   PetscFunctionBegin;
2203:   PetscAssertPointer(array, 2);
2204:   PetscUseMethod(A, "MatDenseGetArray_C", (Mat, PetscScalar **), (A, array));
2205:   PetscFunctionReturn(PETSC_SUCCESS);
2206: }

2208: /*@C
2209:   MatDenseRestoreArray - returns access to the array where the data for a `MATDENSE` matrix is stored obtained by `MatDenseGetArray()`

2211:   Logically Collective

2213:   Input Parameters:
2214: + A     - a dense matrix
2215: - array - pointer to the data (may be `NULL`)

2217:   Level: intermediate

2219: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseGetArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`
2220: @*/
2221: PetscErrorCode MatDenseRestoreArray(Mat A, PetscScalar *array[]) PeNS
2222: {
2223:   PetscFunctionBegin;
2225:   if (array) PetscAssertPointer(array, 2);
2226:   PetscUseMethod(A, "MatDenseRestoreArray_C", (Mat, PetscScalar **), (A, array));
2227:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
2228: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2229:   A->offloadmask = PETSC_OFFLOAD_CPU;
2230: #endif
2231:   PetscFunctionReturn(PETSC_SUCCESS);
2232: }

2234: /*@C
2235:   MatDenseGetArrayRead - gives read-only access to the array where the data for a `MATDENSE` matrix is stored

2237:   Not Collective

2239:   Input Parameter:
2240: . A - a dense matrix

2242:   Output Parameter:
2243: . array - pointer to the data

2245:   Level: intermediate

2247: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseRestoreArrayRead()`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`
2248: @*/
2249: PetscErrorCode MatDenseGetArrayRead(Mat A, const PetscScalar *array[]) PeNS
2250: {
2251:   PetscFunctionBegin;
2253:   PetscAssertPointer(array, 2);
2254:   PetscUseMethod(A, "MatDenseGetArrayRead_C", (Mat, PetscScalar **), (A, (PetscScalar **)array));
2255:   PetscFunctionReturn(PETSC_SUCCESS);
2256: }

2258: /*@C
2259:   MatDenseRestoreArrayRead - returns access to the array where the data for a `MATDENSE` matrix is stored obtained by `MatDenseGetArrayRead()`

2261:   Not Collective

2263:   Input Parameters:
2264: + A     - a dense matrix
2265: - array - pointer to the data (may be `NULL`)

2267:   Level: intermediate

2269: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseGetArrayRead()`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`
2270: @*/
2271: PetscErrorCode MatDenseRestoreArrayRead(Mat A, const PetscScalar *array[]) PeNS
2272: {
2273:   PetscFunctionBegin;
2275:   if (array) PetscAssertPointer(array, 2);
2276:   PetscUseMethod(A, "MatDenseRestoreArrayRead_C", (Mat, PetscScalar **), (A, (PetscScalar **)array));
2277:   PetscFunctionReturn(PETSC_SUCCESS);
2278: }

2280: /*@C
2281:   MatDenseGetArrayWrite - gives write-only access to the array where the data for a `MATDENSE` matrix is stored

2283:   Not Collective

2285:   Input Parameter:
2286: . A - a dense matrix

2288:   Output Parameter:
2289: . array - pointer to the data

2291:   Level: intermediate

2293: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseRestoreArrayWrite()`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`
2294: @*/
2295: PetscErrorCode MatDenseGetArrayWrite(Mat A, PetscScalar *array[]) PeNS
2296: {
2297:   PetscFunctionBegin;
2299:   PetscAssertPointer(array, 2);
2300:   PetscUseMethod(A, "MatDenseGetArrayWrite_C", (Mat, PetscScalar **), (A, array));
2301:   PetscFunctionReturn(PETSC_SUCCESS);
2302: }

2304: /*@C
2305:   MatDenseRestoreArrayWrite - returns access to the array where the data for a `MATDENSE` matrix is stored obtained by `MatDenseGetArrayWrite()`

2307:   Not Collective

2309:   Input Parameters:
2310: + A     - a dense matrix
2311: - array - pointer to the data (may be `NULL`)

2313:   Level: intermediate

2315: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseGetArrayWrite()`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`
2316: @*/
2317: PetscErrorCode MatDenseRestoreArrayWrite(Mat A, PetscScalar *array[]) PeNS
2318: {
2319:   PetscFunctionBegin;
2321:   if (array) PetscAssertPointer(array, 2);
2322:   PetscUseMethod(A, "MatDenseRestoreArrayWrite_C", (Mat, PetscScalar **), (A, array));
2323:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
2324: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2325:   A->offloadmask = PETSC_OFFLOAD_CPU;
2326: #endif
2327:   PetscFunctionReturn(PETSC_SUCCESS);
2328: }

2330: /*@C
2331:   MatDenseGetArrayAndMemType - gives read-write access to the array where the data for a `MATDENSE` matrix is stored

2333:   Logically Collective

2335:   Input Parameter:
2336: . A - a dense matrix

2338:   Output Parameters:
2339: + array - pointer to the data
2340: - mtype - memory type of the returned pointer

2342:   Level: intermediate

2344:   Note:
2345:   If the matrix is of a device type such as `MATDENSECUDA`, `MATDENSEHIP`, etc.,
2346:   an array on device is always returned and is guaranteed to contain the matrix's latest data.

2348: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseRestoreArrayAndMemType()`, `MatDenseGetArrayReadAndMemType()`, `MatDenseGetArrayWriteAndMemType()`, `MatDenseGetArrayRead()`,
2349:    `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`, `MatSeqAIJGetCSRAndMemType()`
2350: @*/
2351: PetscErrorCode MatDenseGetArrayAndMemType(Mat A, PetscScalar *array[], PetscMemType *mtype)
2352: {
2353:   PetscBool isMPI;

2355:   PetscFunctionBegin;
2357:   PetscAssertPointer(array, 2);
2358:   PetscCall(MatBindToCPU(A, PETSC_FALSE)); /* We want device matrices to always return device arrays, so we unbind the matrix if it is bound to CPU */
2359:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIDENSE, &isMPI));
2360:   if (isMPI) {
2361:     /* Dispatch here so that the code can be reused for all subclasses of MATDENSE */
2362:     PetscCall(MatDenseGetArrayAndMemType(((Mat_MPIDense *)A->data)->A, array, mtype));
2363:   } else {
2364:     PetscErrorCode (*fptr)(Mat, PetscScalar **, PetscMemType *);

2366:     PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatDenseGetArrayAndMemType_C", &fptr));
2367:     if (fptr) {
2368:       PetscCall((*fptr)(A, array, mtype));
2369:     } else {
2370:       PetscUseMethod(A, "MatDenseGetArray_C", (Mat, PetscScalar **), (A, array));
2371:       if (mtype) *mtype = PETSC_MEMTYPE_HOST;
2372:     }
2373:   }
2374:   PetscFunctionReturn(PETSC_SUCCESS);
2375: }

2377: /*@C
2378:   MatDenseRestoreArrayAndMemType - returns access to the array that is obtained by `MatDenseGetArrayAndMemType()`

2380:   Logically Collective

2382:   Input Parameters:
2383: + A     - a dense matrix
2384: - array - pointer to the data

2386:   Level: intermediate

2388: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseGetArrayAndMemType()`, `MatDenseGetArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`
2389: @*/
2390: PetscErrorCode MatDenseRestoreArrayAndMemType(Mat A, PetscScalar *array[])
2391: {
2392:   PetscBool isMPI;

2394:   PetscFunctionBegin;
2396:   if (array) PetscAssertPointer(array, 2);
2397:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIDENSE, &isMPI));
2398:   if (isMPI) {
2399:     PetscCall(MatDenseRestoreArrayAndMemType(((Mat_MPIDense *)A->data)->A, array));
2400:   } else {
2401:     PetscErrorCode (*fptr)(Mat, PetscScalar **);

2403:     PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatDenseRestoreArrayAndMemType_C", &fptr));
2404:     if (fptr) {
2405:       PetscCall((*fptr)(A, array));
2406:     } else {
2407:       PetscUseMethod(A, "MatDenseRestoreArray_C", (Mat, PetscScalar **), (A, array));
2408:     }
2409:     if (array) *array = NULL;
2410:   }
2411:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
2412:   PetscFunctionReturn(PETSC_SUCCESS);
2413: }

2415: /*@C
2416:   MatDenseGetArrayReadAndMemType - gives read-only access to the array where the data for a `MATDENSE` matrix is stored

2418:   Logically Collective

2420:   Input Parameter:
2421: . A - a dense matrix

2423:   Output Parameters:
2424: + array - pointer to the data
2425: - mtype - memory type of the returned pointer

2427:   Level: intermediate

2429:   Note:
2430:   If the matrix is of a device type such as `MATDENSECUDA`, `MATDENSEHIP`, etc.,
2431:   an array on device is always returned and is guaranteed to contain the matrix's latest data.

2433: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseRestoreArrayReadAndMemType()`, `MatDenseGetArrayWriteAndMemType()`,
2434:    `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`, `MatSeqAIJGetCSRAndMemType()`
2435: @*/
2436: PetscErrorCode MatDenseGetArrayReadAndMemType(Mat A, const PetscScalar *array[], PetscMemType *mtype)
2437: {
2438:   PetscBool isMPI;

2440:   PetscFunctionBegin;
2442:   PetscAssertPointer(array, 2);
2443:   PetscCall(MatBindToCPU(A, PETSC_FALSE)); /* We want device matrices to always return device arrays, so we unbind the matrix if it is bound to CPU */
2444:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIDENSE, &isMPI));
2445:   if (isMPI) { /* Dispatch here so that the code can be reused for all subclasses of MATDENSE */
2446:     PetscCall(MatDenseGetArrayReadAndMemType(((Mat_MPIDense *)A->data)->A, array, mtype));
2447:   } else {
2448:     PetscErrorCode (*fptr)(Mat, const PetscScalar **, PetscMemType *);

2450:     PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatDenseGetArrayReadAndMemType_C", &fptr));
2451:     if (fptr) {
2452:       PetscCall((*fptr)(A, array, mtype));
2453:     } else {
2454:       PetscUseMethod(A, "MatDenseGetArrayRead_C", (Mat, PetscScalar **), (A, (PetscScalar **)array));
2455:       if (mtype) *mtype = PETSC_MEMTYPE_HOST;
2456:     }
2457:   }
2458:   PetscFunctionReturn(PETSC_SUCCESS);
2459: }

2461: /*@C
2462:   MatDenseRestoreArrayReadAndMemType - returns access to the array that is obtained by `MatDenseGetArrayReadAndMemType()`

2464:   Logically Collective

2466:   Input Parameters:
2467: + A     - a dense matrix
2468: - array - pointer to the data

2470:   Level: intermediate

2472: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseGetArrayReadAndMemType()`, `MatDenseGetArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`
2473: @*/
2474: PetscErrorCode MatDenseRestoreArrayReadAndMemType(Mat A, const PetscScalar *array[])
2475: {
2476:   PetscBool isMPI;

2478:   PetscFunctionBegin;
2480:   if (array) PetscAssertPointer(array, 2);
2481:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIDENSE, &isMPI));
2482:   if (isMPI) {
2483:     PetscCall(MatDenseRestoreArrayReadAndMemType(((Mat_MPIDense *)A->data)->A, array));
2484:   } else {
2485:     PetscErrorCode (*fptr)(Mat, const PetscScalar **);

2487:     PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatDenseRestoreArrayReadAndMemType_C", &fptr));
2488:     if (fptr) {
2489:       PetscCall((*fptr)(A, array));
2490:     } else {
2491:       PetscUseMethod(A, "MatDenseRestoreArrayRead_C", (Mat, PetscScalar **), (A, (PetscScalar **)array));
2492:     }
2493:     if (array) *array = NULL;
2494:   }
2495:   PetscFunctionReturn(PETSC_SUCCESS);
2496: }

2498: /*@C
2499:   MatDenseGetArrayWriteAndMemType - gives write-only access to the array where the data for a `MATDENSE` matrix is stored

2501:   Logically Collective

2503:   Input Parameter:
2504: . A - a dense matrix

2506:   Output Parameters:
2507: + array - pointer to the data
2508: - mtype - memory type of the returned pointer

2510:   Level: intermediate

2512:   Note:
2513:   If the matrix is of a device type such as `MATDENSECUDA`, `MATDENSEHIP`, etc.,
2514:   an array on device is always returned and is guaranteed to contain the matrix's latest data.

2516: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseRestoreArrayWriteAndMemType()`, `MatDenseGetArrayReadAndMemType()`, `MatDenseGetArrayRead()`,
2517:   `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`, `MatSeqAIJGetCSRAndMemType()`
2518: @*/
2519: PetscErrorCode MatDenseGetArrayWriteAndMemType(Mat A, PetscScalar *array[], PetscMemType *mtype)
2520: {
2521:   PetscBool isMPI;

2523:   PetscFunctionBegin;
2525:   PetscAssertPointer(array, 2);
2526:   PetscCall(MatBindToCPU(A, PETSC_FALSE)); /* We want device matrices to always return device arrays, so we unbind the matrix if it is bound to CPU */
2527:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIDENSE, &isMPI));
2528:   if (isMPI) {
2529:     PetscCall(MatDenseGetArrayWriteAndMemType(((Mat_MPIDense *)A->data)->A, array, mtype));
2530:   } else {
2531:     PetscErrorCode (*fptr)(Mat, PetscScalar **, PetscMemType *);

2533:     PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatDenseGetArrayWriteAndMemType_C", &fptr));
2534:     if (fptr) {
2535:       PetscCall((*fptr)(A, array, mtype));
2536:     } else {
2537:       PetscUseMethod(A, "MatDenseGetArrayWrite_C", (Mat, PetscScalar **), (A, array));
2538:       if (mtype) *mtype = PETSC_MEMTYPE_HOST;
2539:     }
2540:   }
2541:   PetscFunctionReturn(PETSC_SUCCESS);
2542: }

2544: /*@C
2545:   MatDenseRestoreArrayWriteAndMemType - returns access to the array that is obtained by `MatDenseGetArrayReadAndMemType()`

2547:   Logically Collective

2549:   Input Parameters:
2550: + A     - a dense matrix
2551: - array - pointer to the data

2553:   Level: intermediate

2555: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseGetArrayWriteAndMemType()`, `MatDenseGetArray()`, `MatDenseGetArrayRead()`, `MatDenseRestoreArrayRead()`, `MatDenseGetArrayWrite()`, `MatDenseRestoreArrayWrite()`
2556: @*/
2557: PetscErrorCode MatDenseRestoreArrayWriteAndMemType(Mat A, PetscScalar *array[])
2558: {
2559:   PetscBool isMPI;

2561:   PetscFunctionBegin;
2563:   if (array) PetscAssertPointer(array, 2);
2564:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)A, MATMPIDENSE, &isMPI));
2565:   if (isMPI) {
2566:     PetscCall(MatDenseRestoreArrayWriteAndMemType(((Mat_MPIDense *)A->data)->A, array));
2567:   } else {
2568:     PetscErrorCode (*fptr)(Mat, PetscScalar **);

2570:     PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatDenseRestoreArrayWriteAndMemType_C", &fptr));
2571:     if (fptr) {
2572:       PetscCall((*fptr)(A, array));
2573:     } else {
2574:       PetscUseMethod(A, "MatDenseRestoreArrayWrite_C", (Mat, PetscScalar **), (A, array));
2575:     }
2576:     if (array) *array = NULL;
2577:   }
2578:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
2579:   PetscFunctionReturn(PETSC_SUCCESS);
2580: }

2582: static PetscErrorCode MatCreateSubMatrix_SeqDense(Mat A, IS isrow, IS iscol, MatReuse scall, Mat *B)
2583: {
2584:   Mat_SeqDense   *mat = (Mat_SeqDense *)A->data;
2585:   PetscInt        i, j, nrows, ncols, ldb;
2586:   const PetscInt *irow, *icol;
2587:   PetscScalar    *av, *bv, *v = mat->v;
2588:   Mat             newmat;

2590:   PetscFunctionBegin;
2591:   PetscCall(ISGetIndices(isrow, &irow));
2592:   PetscCall(ISGetIndices(iscol, &icol));
2593:   PetscCall(ISGetLocalSize(isrow, &nrows));
2594:   PetscCall(ISGetLocalSize(iscol, &ncols));

2596:   /* Check submatrixcall */
2597:   if (scall == MAT_REUSE_MATRIX) {
2598:     PetscInt n_cols, n_rows;
2599:     PetscCall(MatGetSize(*B, &n_rows, &n_cols));
2600:     if (n_rows != nrows || n_cols != ncols) {
2601:       /* resize the result matrix to match number of requested rows/columns */
2602:       PetscCall(MatSetSizes(*B, nrows, ncols, nrows, ncols));
2603:     }
2604:     newmat = *B;
2605:   } else {
2606:     /* Create and fill new matrix */
2607:     PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &newmat));
2608:     PetscCall(MatSetSizes(newmat, nrows, ncols, nrows, ncols));
2609:     PetscCall(MatSetType(newmat, ((PetscObject)A)->type_name));
2610:     PetscCall(MatSeqDenseSetPreallocation(newmat, NULL));
2611:   }

2613:   /* Now extract the data pointers and do the copy,column at a time */
2614:   PetscCall(MatDenseGetArray(newmat, &bv));
2615:   PetscCall(MatDenseGetLDA(newmat, &ldb));
2616:   for (i = 0; i < ncols; i++) {
2617:     av = v + mat->lda * icol[i];
2618:     for (j = 0; j < nrows; j++) bv[j] = av[irow[j]];
2619:     bv += ldb;
2620:   }
2621:   PetscCall(MatDenseRestoreArray(newmat, &bv));

2623:   /* Assemble the matrices so that the correct flags are set */
2624:   PetscCall(MatAssemblyBegin(newmat, MAT_FINAL_ASSEMBLY));
2625:   PetscCall(MatAssemblyEnd(newmat, MAT_FINAL_ASSEMBLY));

2627:   /* Free work space */
2628:   PetscCall(ISRestoreIndices(isrow, &irow));
2629:   PetscCall(ISRestoreIndices(iscol, &icol));
2630:   *B = newmat;
2631:   PetscFunctionReturn(PETSC_SUCCESS);
2632: }

2634: static PetscErrorCode MatCreateSubMatrices_SeqDense(Mat A, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *B[])
2635: {
2636:   PetscInt i;

2638:   PetscFunctionBegin;
2639:   if (scall == MAT_INITIAL_MATRIX) PetscCall(PetscCalloc1(n, B));

2641:   for (i = 0; i < n; i++) PetscCall(MatCreateSubMatrix_SeqDense(A, irow[i], icol[i], scall, &(*B)[i]));
2642:   PetscFunctionReturn(PETSC_SUCCESS);
2643: }

2645: PetscErrorCode MatCopy_SeqDense(Mat A, Mat B, MatStructure str)
2646: {
2647:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data, *b = (Mat_SeqDense *)B->data;
2648:   const PetscScalar *va;
2649:   PetscScalar       *vb;
2650:   PetscInt           lda1 = a->lda, lda2 = b->lda, m = A->rmap->n, n = A->cmap->n, j;

2652:   PetscFunctionBegin;
2653:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2654:   if (A->ops->copy != B->ops->copy) {
2655:     PetscCall(MatCopy_Basic(A, B, str));
2656:     PetscFunctionReturn(PETSC_SUCCESS);
2657:   }
2658:   PetscCheck(m == B->rmap->n && n == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "size(B) != size(A)");
2659:   PetscCall(MatDenseGetArrayRead(A, &va));
2660:   PetscCall(MatDenseGetArray(B, &vb));
2661:   if (lda1 > m || lda2 > m) {
2662:     for (j = 0; j < n; j++) PetscCall(PetscArraycpy(vb + j * lda2, va + j * lda1, m));
2663:   } else {
2664:     PetscCall(PetscArraycpy(vb, va, A->rmap->n * A->cmap->n));
2665:   }
2666:   PetscCall(MatDenseRestoreArray(B, &vb));
2667:   PetscCall(MatDenseRestoreArrayRead(A, &va));
2668:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
2669:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
2670:   PetscFunctionReturn(PETSC_SUCCESS);
2671: }

2673: PetscErrorCode MatSetUp_SeqDense(Mat A)
2674: {
2675:   PetscFunctionBegin;
2676:   PetscCall(PetscLayoutSetUp(A->rmap));
2677:   PetscCall(PetscLayoutSetUp(A->cmap));
2678:   if (!A->preallocated) PetscCall(MatSeqDenseSetPreallocation(A, NULL));
2679:   PetscFunctionReturn(PETSC_SUCCESS);
2680: }

2682: PetscErrorCode MatConjugate_SeqDense(Mat A)
2683: {
2684:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
2685:   PetscInt      i, j;
2686:   PetscInt      min = PetscMin(A->rmap->n, A->cmap->n);
2687:   PetscScalar  *aa;

2689:   PetscFunctionBegin;
2690:   PetscCall(MatDenseGetArray(A, &aa));
2691:   for (j = 0; j < A->cmap->n; j++)
2692:     for (i = 0; i < A->rmap->n; i++) aa[i + j * mat->lda] = PetscConj(aa[i + j * mat->lda]);
2693:   PetscCall(MatDenseRestoreArray(A, &aa));
2694:   if (mat->tau)
2695:     for (i = 0; i < min; i++) mat->tau[i] = PetscConj(mat->tau[i]);
2696:   PetscFunctionReturn(PETSC_SUCCESS);
2697: }

2699: static PetscErrorCode MatRealPart_SeqDense(Mat A)
2700: {
2701:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
2702:   PetscInt      i, j;
2703:   PetscScalar  *aa;

2705:   PetscFunctionBegin;
2706:   PetscCall(MatDenseGetArray(A, &aa));
2707:   for (j = 0; j < A->cmap->n; j++) {
2708:     for (i = 0; i < A->rmap->n; i++) aa[i + j * mat->lda] = PetscRealPart(aa[i + j * mat->lda]);
2709:   }
2710:   PetscCall(MatDenseRestoreArray(A, &aa));
2711:   PetscFunctionReturn(PETSC_SUCCESS);
2712: }

2714: static PetscErrorCode MatImaginaryPart_SeqDense(Mat A)
2715: {
2716:   Mat_SeqDense *mat = (Mat_SeqDense *)A->data;
2717:   PetscInt      i, j;
2718:   PetscScalar  *aa;

2720:   PetscFunctionBegin;
2721:   PetscCall(MatDenseGetArray(A, &aa));
2722:   for (j = 0; j < A->cmap->n; j++) {
2723:     for (i = 0; i < A->rmap->n; i++) aa[i + j * mat->lda] = PetscImaginaryPart(aa[i + j * mat->lda]);
2724:   }
2725:   PetscCall(MatDenseRestoreArray(A, &aa));
2726:   PetscFunctionReturn(PETSC_SUCCESS);
2727: }

2729: PetscErrorCode MatMatMultSymbolic_SeqDense_SeqDense(Mat A, Mat B, PetscReal fill, Mat C)
2730: {
2731:   PetscInt  m = A->rmap->n, n = B->cmap->n;
2732:   PetscBool cisdense = PETSC_FALSE;

2734:   PetscFunctionBegin;
2735:   PetscCall(MatSetSizes(C, m, n, m, n));
2736: #if defined(PETSC_HAVE_CUDA)
2737:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSECUDA, ""));
2738: #endif
2739: #if defined(PETSC_HAVE_HIP)
2740:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSEHIP, ""));
2741: #endif
2742:   if (!cisdense) {
2743:     PetscBool flg;

2745:     PetscCall(PetscObjectTypeCompare((PetscObject)B, ((PetscObject)A)->type_name, &flg));
2746:     PetscCall(MatSetType(C, flg ? ((PetscObject)A)->type_name : MATDENSE));
2747:   }
2748:   PetscCall(MatSetUp(C));
2749:   PetscFunctionReturn(PETSC_SUCCESS);
2750: }

2752: PetscErrorCode MatMatMultNumeric_SeqDense_SeqDense(Mat A, Mat B, Mat C)
2753: {
2754:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data, *b = (Mat_SeqDense *)B->data, *c = (Mat_SeqDense *)C->data;
2755:   const PetscScalar *av, *bv;
2756:   PetscScalar       *cv;
2757:   PetscBLASInt       m, n, k;
2758:   PetscScalar        _DOne = 1.0, _DZero = 0.0;

2760:   PetscFunctionBegin;
2761:   PetscCall(PetscBLASIntCast(C->rmap->n, &m));
2762:   PetscCall(PetscBLASIntCast(C->cmap->n, &n));
2763:   PetscCall(PetscBLASIntCast(A->cmap->n, &k));
2764:   if (!m || !n || !k) {
2765:     PetscCall(MatZeroEntries(C));
2766:     PetscFunctionReturn(PETSC_SUCCESS);
2767:   }
2768:   PetscCall(MatDenseGetArrayRead(A, &av));
2769:   PetscCall(MatDenseGetArrayRead(B, &bv));
2770:   PetscCall(MatDenseGetArrayWrite(C, &cv));
2771:   PetscCallBLAS("BLASgemm", BLASgemm_("N", "N", &m, &n, &k, &_DOne, av, &a->lda, bv, &b->lda, &_DZero, cv, &c->lda));
2772:   PetscCall(MatDenseRestoreArrayRead(A, &av));
2773:   PetscCall(MatDenseRestoreArrayRead(B, &bv));
2774:   PetscCall(MatDenseRestoreArrayWrite(C, &cv));
2775:   PetscCall(PetscLogFlops(1.0 * m * n * k + 1.0 * m * n * (k - 1)));
2776:   PetscFunctionReturn(PETSC_SUCCESS);
2777: }

2779: PetscErrorCode MatMatTransposeMultSymbolic_SeqDense_SeqDense(Mat A, Mat B, PetscReal fill, Mat C)
2780: {
2781:   PetscInt  m = A->rmap->n, n = B->rmap->n;
2782:   PetscBool cisdense = PETSC_FALSE;

2784:   PetscFunctionBegin;
2785:   PetscCall(MatSetSizes(C, m, n, m, n));
2786: #if defined(PETSC_HAVE_CUDA)
2787:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSECUDA, ""));
2788: #endif
2789: #if defined(PETSC_HAVE_HIP)
2790:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSEHIP, ""));
2791: #endif
2792:   if (!cisdense) {
2793:     PetscBool flg;

2795:     PetscCall(PetscObjectTypeCompare((PetscObject)B, ((PetscObject)A)->type_name, &flg));
2796:     PetscCall(MatSetType(C, flg ? ((PetscObject)A)->type_name : MATDENSE));
2797:   }
2798:   PetscCall(MatSetUp(C));
2799:   PetscFunctionReturn(PETSC_SUCCESS);
2800: }

2802: PetscErrorCode MatMatTransposeMultNumeric_SeqDense_SeqDense(Mat A, Mat B, Mat C)
2803: {
2804:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data, *b = (Mat_SeqDense *)B->data, *c = (Mat_SeqDense *)C->data;
2805:   const PetscScalar *av, *bv;
2806:   PetscScalar       *cv;
2807:   PetscBLASInt       m, n, k;
2808:   PetscScalar        _DOne = 1.0, _DZero = 0.0;

2810:   PetscFunctionBegin;
2811:   PetscCall(PetscBLASIntCast(C->rmap->n, &m));
2812:   PetscCall(PetscBLASIntCast(C->cmap->n, &n));
2813:   PetscCall(PetscBLASIntCast(A->cmap->n, &k));
2814:   if (!m || !n || !k) {
2815:     PetscCall(MatZeroEntries(C));
2816:     PetscFunctionReturn(PETSC_SUCCESS);
2817:   }
2818:   PetscCall(MatDenseGetArrayRead(A, &av));
2819:   PetscCall(MatDenseGetArrayRead(B, &bv));
2820:   PetscCall(MatDenseGetArrayWrite(C, &cv));
2821:   PetscCallBLAS("BLASgemm", BLASgemm_("N", "T", &m, &n, &k, &_DOne, av, &a->lda, bv, &b->lda, &_DZero, cv, &c->lda));
2822:   PetscCall(MatDenseRestoreArrayRead(A, &av));
2823:   PetscCall(MatDenseRestoreArrayRead(B, &bv));
2824:   PetscCall(MatDenseRestoreArrayWrite(C, &cv));
2825:   PetscCall(PetscLogFlops(1.0 * m * n * k + 1.0 * m * n * (k - 1)));
2826:   PetscFunctionReturn(PETSC_SUCCESS);
2827: }

2829: PetscErrorCode MatTransposeMatMultSymbolic_SeqDense_SeqDense(Mat A, Mat B, PetscReal fill, Mat C)
2830: {
2831:   PetscInt  m = A->cmap->n, n = B->cmap->n;
2832:   PetscBool cisdense = PETSC_FALSE;

2834:   PetscFunctionBegin;
2835:   PetscCall(MatSetSizes(C, m, n, m, n));
2836: #if defined(PETSC_HAVE_CUDA)
2837:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSECUDA, ""));
2838: #endif
2839: #if defined(PETSC_HAVE_HIP)
2840:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATSEQDENSEHIP, ""));
2841: #endif
2842:   if (!cisdense) {
2843:     PetscBool flg;

2845:     PetscCall(PetscObjectTypeCompare((PetscObject)B, ((PetscObject)A)->type_name, &flg));
2846:     PetscCall(MatSetType(C, flg ? ((PetscObject)A)->type_name : MATDENSE));
2847:   }
2848:   PetscCall(MatSetUp(C));
2849:   PetscFunctionReturn(PETSC_SUCCESS);
2850: }

2852: PetscErrorCode MatTransposeMatMultNumeric_SeqDense_SeqDense(Mat A, Mat B, Mat C)
2853: {
2854:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data, *b = (Mat_SeqDense *)B->data, *c = (Mat_SeqDense *)C->data;
2855:   const PetscScalar *av, *bv;
2856:   PetscScalar       *cv;
2857:   PetscBLASInt       m, n, k;
2858:   PetscScalar        _DOne = 1.0, _DZero = 0.0;

2860:   PetscFunctionBegin;
2861:   PetscCall(PetscBLASIntCast(C->rmap->n, &m));
2862:   PetscCall(PetscBLASIntCast(C->cmap->n, &n));
2863:   PetscCall(PetscBLASIntCast(A->rmap->n, &k));
2864:   if (!m || !n || !k) {
2865:     PetscCall(MatZeroEntries(C));
2866:     PetscFunctionReturn(PETSC_SUCCESS);
2867:   }
2868:   PetscCall(MatDenseGetArrayRead(A, &av));
2869:   PetscCall(MatDenseGetArrayRead(B, &bv));
2870:   PetscCall(MatDenseGetArrayWrite(C, &cv));
2871:   PetscCallBLAS("BLASgemm", BLASgemm_("T", "N", &m, &n, &k, &_DOne, av, &a->lda, bv, &b->lda, &_DZero, cv, &c->lda));
2872:   PetscCall(MatDenseRestoreArrayRead(A, &av));
2873:   PetscCall(MatDenseRestoreArrayRead(B, &bv));
2874:   PetscCall(MatDenseRestoreArrayWrite(C, &cv));
2875:   PetscCall(PetscLogFlops(1.0 * m * n * k + 1.0 * m * n * (k - 1)));
2876:   PetscFunctionReturn(PETSC_SUCCESS);
2877: }

2879: static PetscErrorCode MatProductSetFromOptions_SeqDense_AB(Mat C)
2880: {
2881:   PetscFunctionBegin;
2882:   C->ops->matmultsymbolic = MatMatMultSymbolic_SeqDense_SeqDense;
2883:   C->ops->productsymbolic = MatProductSymbolic_AB;
2884:   PetscFunctionReturn(PETSC_SUCCESS);
2885: }

2887: static PetscErrorCode MatProductSetFromOptions_SeqDense_AtB(Mat C)
2888: {
2889:   PetscFunctionBegin;
2890:   C->ops->transposematmultsymbolic = MatTransposeMatMultSymbolic_SeqDense_SeqDense;
2891:   C->ops->productsymbolic          = MatProductSymbolic_AtB;
2892:   PetscFunctionReturn(PETSC_SUCCESS);
2893: }

2895: static PetscErrorCode MatProductSetFromOptions_SeqDense_ABt(Mat C)
2896: {
2897:   PetscFunctionBegin;
2898:   C->ops->mattransposemultsymbolic = MatMatTransposeMultSymbolic_SeqDense_SeqDense;
2899:   C->ops->productsymbolic          = MatProductSymbolic_ABt;
2900:   PetscFunctionReturn(PETSC_SUCCESS);
2901: }

2903: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_SeqDense(Mat C)
2904: {
2905:   Mat_Product *product = C->product;

2907:   PetscFunctionBegin;
2908:   switch (product->type) {
2909:   case MATPRODUCT_AB:
2910:     PetscCall(MatProductSetFromOptions_SeqDense_AB(C));
2911:     break;
2912:   case MATPRODUCT_AtB:
2913:     PetscCall(MatProductSetFromOptions_SeqDense_AtB(C));
2914:     break;
2915:   case MATPRODUCT_ABt:
2916:     PetscCall(MatProductSetFromOptions_SeqDense_ABt(C));
2917:     break;
2918:   default:
2919:     break;
2920:   }
2921:   PetscFunctionReturn(PETSC_SUCCESS);
2922: }

2924: static PetscErrorCode MatGetRowMax_SeqDense(Mat A, Vec v, PetscInt idx[])
2925: {
2926:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data;
2927:   PetscInt           i, j, m = A->rmap->n, n = A->cmap->n, p;
2928:   PetscScalar       *x;
2929:   const PetscScalar *aa;

2931:   PetscFunctionBegin;
2932:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2933:   PetscCall(VecGetArray(v, &x));
2934:   PetscCall(VecGetLocalSize(v, &p));
2935:   PetscCall(MatDenseGetArrayRead(A, &aa));
2936:   PetscCheck(p == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
2937:   for (i = 0; i < m; i++) {
2938:     x[i] = aa[i];
2939:     if (idx) idx[i] = 0;
2940:     for (j = 1; j < n; j++) {
2941:       if (PetscRealPart(x[i]) < PetscRealPart(aa[i + a->lda * j])) {
2942:         x[i] = aa[i + a->lda * j];
2943:         if (idx) idx[i] = j;
2944:       }
2945:     }
2946:   }
2947:   PetscCall(MatDenseRestoreArrayRead(A, &aa));
2948:   PetscCall(VecRestoreArray(v, &x));
2949:   PetscFunctionReturn(PETSC_SUCCESS);
2950: }

2952: static PetscErrorCode MatGetRowMaxAbs_SeqDense(Mat A, Vec v, PetscInt idx[])
2953: {
2954:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data;
2955:   PetscInt           i, j, m = A->rmap->n, n = A->cmap->n, p;
2956:   PetscScalar       *x;
2957:   PetscReal          atmp;
2958:   const PetscScalar *aa;

2960:   PetscFunctionBegin;
2961:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2962:   PetscCall(VecGetArray(v, &x));
2963:   PetscCall(VecGetLocalSize(v, &p));
2964:   PetscCall(MatDenseGetArrayRead(A, &aa));
2965:   PetscCheck(p == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
2966:   for (i = 0; i < m; i++) {
2967:     x[i] = PetscAbsScalar(aa[i]);
2968:     for (j = 1; j < n; j++) {
2969:       atmp = PetscAbsScalar(aa[i + a->lda * j]);
2970:       if (PetscAbsScalar(x[i]) < atmp) {
2971:         x[i] = atmp;
2972:         if (idx) idx[i] = j;
2973:       }
2974:     }
2975:   }
2976:   PetscCall(MatDenseRestoreArrayRead(A, &aa));
2977:   PetscCall(VecRestoreArray(v, &x));
2978:   PetscFunctionReturn(PETSC_SUCCESS);
2979: }

2981: static PetscErrorCode MatGetRowMin_SeqDense(Mat A, Vec v, PetscInt idx[])
2982: {
2983:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data;
2984:   PetscInt           i, j, m = A->rmap->n, n = A->cmap->n, p;
2985:   PetscScalar       *x;
2986:   const PetscScalar *aa;

2988:   PetscFunctionBegin;
2989:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2990:   PetscCall(MatDenseGetArrayRead(A, &aa));
2991:   PetscCall(VecGetArray(v, &x));
2992:   PetscCall(VecGetLocalSize(v, &p));
2993:   PetscCheck(p == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
2994:   for (i = 0; i < m; i++) {
2995:     x[i] = aa[i];
2996:     if (idx) idx[i] = 0;
2997:     for (j = 1; j < n; j++) {
2998:       if (PetscRealPart(x[i]) > PetscRealPart(aa[i + a->lda * j])) {
2999:         x[i] = aa[i + a->lda * j];
3000:         if (idx) idx[i] = j;
3001:       }
3002:     }
3003:   }
3004:   PetscCall(VecRestoreArray(v, &x));
3005:   PetscCall(MatDenseRestoreArrayRead(A, &aa));
3006:   PetscFunctionReturn(PETSC_SUCCESS);
3007: }

3009: PetscErrorCode MatGetColumnVector_SeqDense(Mat A, Vec v, PetscInt col)
3010: {
3011:   Mat_SeqDense      *a = (Mat_SeqDense *)A->data;
3012:   PetscScalar       *x;
3013:   const PetscScalar *aa;

3015:   PetscFunctionBegin;
3016:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3017:   PetscCall(MatDenseGetArrayRead(A, &aa));
3018:   PetscCall(VecGetArray(v, &x));
3019:   PetscCall(PetscArraycpy(x, aa + col * a->lda, A->rmap->n));
3020:   PetscCall(VecRestoreArray(v, &x));
3021:   PetscCall(MatDenseRestoreArrayRead(A, &aa));
3022:   PetscFunctionReturn(PETSC_SUCCESS);
3023: }

3025: PETSC_INTERN PetscErrorCode MatGetColumnReductions_SeqDense(Mat A, PetscInt type, PetscReal *reductions)
3026: {
3027:   PetscInt           i, j, m, n;
3028:   const PetscScalar *a;

3030:   PetscFunctionBegin;
3031:   PetscCall(MatGetSize(A, &m, &n));
3032:   PetscCall(PetscArrayzero(reductions, n));
3033:   PetscCall(MatDenseGetArrayRead(A, &a));
3034:   if (type == NORM_2) {
3035:     for (i = 0; i < n; i++) {
3036:       for (j = 0; j < m; j++) reductions[i] += PetscAbsScalar(a[j] * a[j]);
3037:       a = PetscSafePointerPlusOffset(a, m);
3038:     }
3039:   } else if (type == NORM_1) {
3040:     for (i = 0; i < n; i++) {
3041:       for (j = 0; j < m; j++) reductions[i] += PetscAbsScalar(a[j]);
3042:       a = PetscSafePointerPlusOffset(a, m);
3043:     }
3044:   } else if (type == NORM_INFINITY) {
3045:     for (i = 0; i < n; i++) {
3046:       for (j = 0; j < m; j++) reductions[i] = PetscMax(PetscAbsScalar(a[j]), reductions[i]);
3047:       a = PetscSafePointerPlusOffset(a, m);
3048:     }
3049:   } else if (type == REDUCTION_SUM_REALPART || type == REDUCTION_MEAN_REALPART) {
3050:     for (i = 0; i < n; i++) {
3051:       for (j = 0; j < m; j++) reductions[i] += PetscRealPart(a[j]);
3052:       a = PetscSafePointerPlusOffset(a, m);
3053:     }
3054:   } else if (type == REDUCTION_SUM_IMAGINARYPART || type == REDUCTION_MEAN_IMAGINARYPART) {
3055:     for (i = 0; i < n; i++) {
3056:       for (j = 0; j < m; j++) reductions[i] += PetscImaginaryPart(a[j]);
3057:       a = PetscSafePointerPlusOffset(a, m);
3058:     }
3059:   } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Unknown reduction type");
3060:   PetscCall(MatDenseRestoreArrayRead(A, &a));
3061:   if (type == NORM_2) {
3062:     for (i = 0; i < n; i++) reductions[i] = PetscSqrtReal(reductions[i]);
3063:   } else if (type == REDUCTION_MEAN_REALPART || type == REDUCTION_MEAN_IMAGINARYPART) {
3064:     for (i = 0; i < n; i++) reductions[i] /= m;
3065:   }
3066:   PetscFunctionReturn(PETSC_SUCCESS);
3067: }

3069: PetscErrorCode MatSetRandom_SeqDense(Mat x, PetscRandom rctx)
3070: {
3071:   PetscScalar *a;
3072:   PetscInt     lda, m, n, i, j;

3074:   PetscFunctionBegin;
3075:   PetscCall(MatGetSize(x, &m, &n));
3076:   PetscCall(MatDenseGetLDA(x, &lda));
3077:   PetscCall(MatDenseGetArrayWrite(x, &a));
3078:   for (j = 0; j < n; j++) {
3079:     for (i = 0; i < m; i++) PetscCall(PetscRandomGetValue(rctx, a + j * lda + i));
3080:   }
3081:   PetscCall(MatDenseRestoreArrayWrite(x, &a));
3082:   PetscFunctionReturn(PETSC_SUCCESS);
3083: }

3085: /* vals is not const */
3086: static PetscErrorCode MatDenseGetColumn_SeqDense(Mat A, PetscInt col, PetscScalar **vals)
3087: {
3088:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;
3089:   PetscScalar  *v;

3091:   PetscFunctionBegin;
3092:   PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3093:   PetscCall(MatDenseGetArray(A, &v));
3094:   *vals = v + col * a->lda;
3095:   PetscCall(MatDenseRestoreArray(A, &v));
3096:   PetscFunctionReturn(PETSC_SUCCESS);
3097: }

3099: static PetscErrorCode MatDenseRestoreColumn_SeqDense(Mat A, PetscScalar **vals)
3100: {
3101:   PetscFunctionBegin;
3102:   if (vals) *vals = NULL; /* user cannot accidentally use the array later */
3103:   PetscFunctionReturn(PETSC_SUCCESS);
3104: }

3106: static struct _MatOps MatOps_Values = {MatSetValues_SeqDense,
3107:                                        MatGetRow_SeqDense,
3108:                                        MatRestoreRow_SeqDense,
3109:                                        MatMult_SeqDense,
3110:                                        /*  4*/ MatMultAdd_SeqDense,
3111:                                        MatMultTranspose_SeqDense,
3112:                                        MatMultTransposeAdd_SeqDense,
3113:                                        NULL,
3114:                                        NULL,
3115:                                        NULL,
3116:                                        /* 10*/ NULL,
3117:                                        MatLUFactor_SeqDense,
3118:                                        MatCholeskyFactor_SeqDense,
3119:                                        MatSOR_SeqDense,
3120:                                        MatTranspose_SeqDense,
3121:                                        /* 15*/ MatGetInfo_SeqDense,
3122:                                        MatEqual_SeqDense,
3123:                                        MatGetDiagonal_SeqDense,
3124:                                        MatDiagonalScale_SeqDense,
3125:                                        MatNorm_SeqDense,
3126:                                        /* 20*/ NULL,
3127:                                        NULL,
3128:                                        MatSetOption_SeqDense,
3129:                                        MatZeroEntries_SeqDense,
3130:                                        /* 24*/ MatZeroRows_SeqDense,
3131:                                        NULL,
3132:                                        NULL,
3133:                                        NULL,
3134:                                        NULL,
3135:                                        /* 29*/ MatSetUp_SeqDense,
3136:                                        NULL,
3137:                                        NULL,
3138:                                        NULL,
3139:                                        NULL,
3140:                                        /* 34*/ MatDuplicate_SeqDense,
3141:                                        NULL,
3142:                                        NULL,
3143:                                        NULL,
3144:                                        NULL,
3145:                                        /* 39*/ MatAXPY_SeqDense,
3146:                                        MatCreateSubMatrices_SeqDense,
3147:                                        NULL,
3148:                                        MatGetValues_SeqDense,
3149:                                        MatCopy_SeqDense,
3150:                                        /* 44*/ MatGetRowMax_SeqDense,
3151:                                        MatScale_SeqDense,
3152:                                        MatShift_SeqDense,
3153:                                        NULL,
3154:                                        MatZeroRowsColumns_SeqDense,
3155:                                        /* 49*/ MatSetRandom_SeqDense,
3156:                                        NULL,
3157:                                        NULL,
3158:                                        NULL,
3159:                                        NULL,
3160:                                        /* 54*/ NULL,
3161:                                        NULL,
3162:                                        NULL,
3163:                                        NULL,
3164:                                        NULL,
3165:                                        /* 59*/ MatCreateSubMatrix_SeqDense,
3166:                                        MatDestroy_SeqDense,
3167:                                        MatView_SeqDense,
3168:                                        NULL,
3169:                                        NULL,
3170:                                        /* 64*/ NULL,
3171:                                        NULL,
3172:                                        NULL,
3173:                                        NULL,
3174:                                        MatGetRowMaxAbs_SeqDense,
3175:                                        /* 69*/ NULL,
3176:                                        NULL,
3177:                                        NULL,
3178:                                        NULL,
3179:                                        NULL,
3180:                                        /* 74*/ NULL,
3181:                                        NULL,
3182:                                        NULL,
3183:                                        NULL,
3184:                                        MatLoad_SeqDense,
3185:                                        /* 79*/ MatIsSymmetric_SeqDense,
3186:                                        MatIsHermitian_SeqDense,
3187:                                        NULL,
3188:                                        NULL,
3189:                                        NULL,
3190:                                        /* 84*/ NULL,
3191:                                        MatMatMultNumeric_SeqDense_SeqDense,
3192:                                        NULL,
3193:                                        NULL,
3194:                                        MatMatTransposeMultNumeric_SeqDense_SeqDense,
3195:                                        /* 89*/ NULL,
3196:                                        MatProductSetFromOptions_SeqDense,
3197:                                        NULL,
3198:                                        NULL,
3199:                                        MatConjugate_SeqDense,
3200:                                        /* 94*/ NULL,
3201:                                        NULL,
3202:                                        MatRealPart_SeqDense,
3203:                                        MatImaginaryPart_SeqDense,
3204:                                        NULL,
3205:                                        /* 99*/ NULL,
3206:                                        NULL,
3207:                                        NULL,
3208:                                        MatGetRowMin_SeqDense,
3209:                                        MatGetColumnVector_SeqDense,
3210:                                        /*104*/ NULL,
3211:                                        NULL,
3212:                                        NULL,
3213:                                        NULL,
3214:                                        NULL,
3215:                                        /*109*/ NULL,
3216:                                        NULL,
3217:                                        MatMultHermitianTranspose_SeqDense,
3218:                                        MatMultHermitianTransposeAdd_SeqDense,
3219:                                        NULL,
3220:                                        /*114*/ NULL,
3221:                                        MatGetColumnReductions_SeqDense,
3222:                                        NULL,
3223:                                        NULL,
3224:                                        NULL,
3225:                                        /*119*/ NULL,
3226:                                        MatTransposeMatMultNumeric_SeqDense_SeqDense,
3227:                                        NULL,
3228:                                        NULL,
3229:                                        NULL,
3230:                                        /*124*/ NULL,
3231:                                        NULL,
3232:                                        NULL,
3233:                                        NULL,
3234:                                        NULL,
3235:                                        /*129*/ MatCreateMPIMatConcatenateSeqMat_SeqDense,
3236:                                        NULL,
3237:                                        NULL,
3238:                                        NULL,
3239:                                        NULL,
3240:                                        /*134*/ NULL,
3241:                                        NULL,
3242:                                        NULL,
3243:                                        NULL,
3244:                                        NULL,
3245:                                        /*139*/ NULL,
3246:                                        NULL,
3247:                                        NULL,
3248:                                        NULL,
3249:                                        MatADot_Default,
3250:                                        /*144*/ MatANorm_Default,
3251:                                        NULL,
3252:                                        NULL,
3253:                                        NULL};

3255: /*@
3256:   MatCreateSeqDense - Creates a `MATSEQDENSE` that
3257:   is stored in column major order (the usual Fortran format).

3259:   Collective

3261:   Input Parameters:
3262: + comm - MPI communicator, set to `PETSC_COMM_SELF`
3263: . m    - number of rows
3264: . n    - number of columns
3265: - data - optional location of matrix data in column major order.  Use `NULL` for PETSc
3266:          to control all matrix memory allocation.

3268:   Output Parameter:
3269: . A - the matrix

3271:   Level: intermediate

3273:   Note:
3274:   The data input variable is intended primarily for Fortran programmers
3275:   who wish to allocate their own matrix memory space.  Most users should
3276:   set `data` = `NULL`.

3278:   Developer Note:
3279:   Many of the matrix operations for this variant use the BLAS and LAPACK routines.

3281: .seealso: [](ch_matrices), `Mat`, `MATSEQDENSE`, `MatCreate()`, `MatCreateDense()`, `MatSetValues()`
3282: @*/
3283: PetscErrorCode MatCreateSeqDense(MPI_Comm comm, PetscInt m, PetscInt n, PetscScalar data[], Mat *A)
3284: {
3285:   PetscFunctionBegin;
3286:   PetscCall(MatCreate(comm, A));
3287:   PetscCall(MatSetSizes(*A, m, n, m, n));
3288:   PetscCall(MatSetType(*A, MATSEQDENSE));
3289:   PetscCall(MatSeqDenseSetPreallocation(*A, data));
3290:   PetscFunctionReturn(PETSC_SUCCESS);
3291: }

3293: /*@
3294:   MatSeqDenseSetPreallocation - Sets the array used for storing the matrix elements of a `MATSEQDENSE` matrix

3296:   Collective

3298:   Input Parameters:
3299: + B    - the matrix
3300: - data - the array (or `NULL`)

3302:   Level: intermediate

3304:   Note:
3305:   The data input variable is intended primarily for Fortran programmers
3306:   who wish to allocate their own matrix memory space.  Most users should
3307:   need not call this routine.

3309: .seealso: [](ch_matrices), `Mat`, `MATSEQDENSE`, `MatCreate()`, `MatCreateDense()`, `MatSetValues()`, `MatDenseSetLDA()`
3310: @*/
3311: PetscErrorCode MatSeqDenseSetPreallocation(Mat B, PetscScalar data[])
3312: {
3313:   PetscFunctionBegin;
3315:   PetscTryMethod(B, "MatSeqDenseSetPreallocation_C", (Mat, PetscScalar[]), (B, data));
3316:   PetscFunctionReturn(PETSC_SUCCESS);
3317: }

3319: PetscErrorCode MatSeqDenseSetPreallocation_SeqDense(Mat B, PetscScalar *data)
3320: {
3321:   Mat_SeqDense *b = (Mat_SeqDense *)B->data;

3323:   PetscFunctionBegin;
3324:   PetscCheck(!b->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
3325:   B->preallocated = PETSC_TRUE;

3327:   PetscCall(PetscLayoutSetUp(B->rmap));
3328:   PetscCall(PetscLayoutSetUp(B->cmap));

3330:   if (b->lda <= 0) PetscCall(PetscBLASIntCast(B->rmap->n, &b->lda));

3332:   if (!data) { /* petsc-allocated storage */
3333:     if (!b->user_alloc) PetscCall(PetscFree(b->v));
3334:     PetscCall(PetscCalloc1((size_t)b->lda * B->cmap->n, &b->v));

3336:     b->user_alloc = PETSC_FALSE;
3337:   } else { /* user-allocated storage */
3338:     if (!b->user_alloc) PetscCall(PetscFree(b->v));
3339:     b->v          = data;
3340:     b->user_alloc = PETSC_TRUE;
3341:   }
3342:   B->assembled = PETSC_TRUE;
3343:   PetscFunctionReturn(PETSC_SUCCESS);
3344: }

3346: #if defined(PETSC_HAVE_ELEMENTAL)
3347: PETSC_INTERN PetscErrorCode MatConvert_SeqDense_Elemental(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
3348: {
3349:   Mat                mat_elemental;
3350:   const PetscScalar *array;
3351:   PetscScalar       *v_colwise;
3352:   PetscInt           M = A->rmap->N, N = A->cmap->N, i, j, k, *rows, *cols;

3354:   PetscFunctionBegin;
3355:   PetscCall(PetscMalloc3(M * N, &v_colwise, M, &rows, N, &cols));
3356:   PetscCall(MatDenseGetArrayRead(A, &array));
3357:   /* convert column-wise array into row-wise v_colwise, see MatSetValues_Elemental() */
3358:   k = 0;
3359:   for (j = 0; j < N; j++) {
3360:     cols[j] = j;
3361:     for (i = 0; i < M; i++) v_colwise[j * M + i] = array[k++];
3362:   }
3363:   for (i = 0; i < M; i++) rows[i] = i;
3364:   PetscCall(MatDenseRestoreArrayRead(A, &array));

3366:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &mat_elemental));
3367:   PetscCall(MatSetSizes(mat_elemental, PETSC_DECIDE, PETSC_DECIDE, M, N));
3368:   PetscCall(MatSetType(mat_elemental, MATELEMENTAL));
3369:   PetscCall(MatSetUp(mat_elemental));

3371:   /* PETSc-Elemental interaface uses axpy for setting off-processor entries, only ADD_VALUES is allowed */
3372:   PetscCall(MatSetValues(mat_elemental, M, rows, N, cols, v_colwise, ADD_VALUES));
3373:   PetscCall(MatAssemblyBegin(mat_elemental, MAT_FINAL_ASSEMBLY));
3374:   PetscCall(MatAssemblyEnd(mat_elemental, MAT_FINAL_ASSEMBLY));
3375:   PetscCall(PetscFree3(v_colwise, rows, cols));

3377:   if (reuse == MAT_INPLACE_MATRIX) {
3378:     PetscCall(MatHeaderReplace(A, &mat_elemental));
3379:   } else {
3380:     *newmat = mat_elemental;
3381:   }
3382:   PetscFunctionReturn(PETSC_SUCCESS);
3383: }
3384: #endif

3386: PetscErrorCode MatDenseSetLDA_SeqDense(Mat B, PetscInt lda)
3387: {
3388:   Mat_SeqDense *b = (Mat_SeqDense *)B->data;
3389:   PetscBool     data;

3391:   PetscFunctionBegin;
3392:   data = (B->rmap->n > 0 && B->cmap->n > 0) ? (b->v ? PETSC_TRUE : PETSC_FALSE) : PETSC_FALSE;
3393:   PetscCheck(b->user_alloc || !data || b->lda == lda, PETSC_COMM_SELF, PETSC_ERR_ORDER, "LDA cannot be changed after allocation of internal storage");
3394:   PetscCheck(lda >= B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "LDA %" PetscInt_FMT " must be at least matrix dimension %" PetscInt_FMT, lda, B->rmap->n);
3395:   PetscCall(PetscBLASIntCast(lda, &b->lda));
3396:   PetscFunctionReturn(PETSC_SUCCESS);
3397: }

3399: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_SeqDense(MPI_Comm comm, Mat inmat, PetscInt n, MatReuse scall, Mat *outmat)
3400: {
3401:   PetscFunctionBegin;
3402:   PetscCall(MatCreateMPIMatConcatenateSeqMat_MPIDense(comm, inmat, n, scall, outmat));
3403:   PetscFunctionReturn(PETSC_SUCCESS);
3404: }

3406: PetscErrorCode MatDenseCreateColumnVec_Private(Mat A, Vec *v)
3407: {
3408:   PetscBool   isstd, iskok, iscuda, iship;
3409:   PetscMPIInt size;
3410: #if PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
3411:   /* we pass the data of A, to prevent allocating needless GPU memory the first time VecCUPMPlaceArray is called. */
3412:   const PetscScalar *a;
3413: #endif

3415:   PetscFunctionBegin;
3416:   *v = NULL;
3417:   PetscCall(PetscStrcmpAny(A->defaultvectype, &isstd, VECSTANDARD, VECSEQ, VECMPI, ""));
3418:   PetscCall(PetscStrcmpAny(A->defaultvectype, &iskok, VECKOKKOS, VECSEQKOKKOS, VECMPIKOKKOS, ""));
3419:   PetscCall(PetscStrcmpAny(A->defaultvectype, &iscuda, VECCUDA, VECSEQCUDA, VECMPICUDA, ""));
3420:   PetscCall(PetscStrcmpAny(A->defaultvectype, &iship, VECHIP, VECSEQHIP, VECMPIHIP, ""));
3421:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
3422:   if (isstd) {
3423:     if (size > 1) PetscCall(VecCreateMPIWithArray(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, A->rmap->N, NULL, v));
3424:     else PetscCall(VecCreateSeqWithArray(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, NULL, v));
3425:   } else if (iskok) {
3426:     PetscCheck(PetscDefined(HAVE_KOKKOS_KERNELS), PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Reconfigure using KOKKOS kernels support");
3427: #if PetscDefined(HAVE_KOKKOS_KERNELS)
3428:     if (size > 1) PetscCall(VecCreateMPIKokkosWithArray(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, A->rmap->N, NULL, v));
3429:     else PetscCall(VecCreateSeqKokkosWithArray(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, NULL, v));
3430: #endif
3431:   } else if (iscuda) {
3432:     PetscCheck(PetscDefined(HAVE_CUDA), PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Reconfigure using CUDA support");
3433: #if PetscDefined(HAVE_CUDA)
3434:     PetscCall(MatDenseCUDAGetArrayRead(A, &a));
3435:     if (size > 1) PetscCall(VecCreateMPICUDAWithArrays(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, A->rmap->N, NULL, a, v));
3436:     else PetscCall(VecCreateSeqCUDAWithArrays(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, NULL, a, v));
3437: #endif
3438:   } else if (iship) {
3439:     PetscCheck(PetscDefined(HAVE_HIP), PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Reconfigure using HIP support");
3440: #if PetscDefined(HAVE_HIP)
3441:     PetscCall(MatDenseHIPGetArrayRead(A, &a));
3442:     if (size > 1) PetscCall(VecCreateMPIHIPWithArrays(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, A->rmap->N, NULL, a, v));
3443:     else PetscCall(VecCreateSeqHIPWithArrays(PetscObjectComm((PetscObject)A), A->rmap->bs, A->rmap->n, NULL, a, v));
3444: #endif
3445:   }
3446:   PetscCheck(*v, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not coded for type %s", A->defaultvectype);
3447:   PetscFunctionReturn(PETSC_SUCCESS);
3448: }

3450: PetscErrorCode MatDenseGetColumnVec_SeqDense(Mat A, PetscInt col, Vec *v)
3451: {
3452:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3454:   PetscFunctionBegin;
3455:   PetscCheck(!a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
3456:   PetscCheck(!a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
3457:   if (!a->cvec) PetscCall(MatDenseCreateColumnVec_Private(A, &a->cvec));
3458:   a->vecinuse = col + 1;
3459:   PetscCall(MatDenseGetArray(A, (PetscScalar **)&a->ptrinuse));
3460:   PetscCall(VecPlaceArray(a->cvec, a->ptrinuse + (size_t)col * (size_t)a->lda));
3461:   *v = a->cvec;
3462:   PetscFunctionReturn(PETSC_SUCCESS);
3463: }

3465: PetscErrorCode MatDenseRestoreColumnVec_SeqDense(Mat A, PetscInt col, Vec *v)
3466: {
3467:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3469:   PetscFunctionBegin;
3470:   PetscCheck(a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseGetColumnVec() first");
3471:   PetscCheck(a->cvec, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing internal column vector");
3472:   VecCheckAssembled(a->cvec);
3473:   a->vecinuse = 0;
3474:   PetscCall(MatDenseRestoreArray(A, (PetscScalar **)&a->ptrinuse));
3475:   PetscCall(VecResetArray(a->cvec));
3476:   if (v) *v = NULL;
3477:   PetscFunctionReturn(PETSC_SUCCESS);
3478: }

3480: PetscErrorCode MatDenseGetColumnVecRead_SeqDense(Mat A, PetscInt col, Vec *v)
3481: {
3482:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3484:   PetscFunctionBegin;
3485:   PetscCheck(!a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
3486:   PetscCheck(!a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
3487:   if (!a->cvec) PetscCall(MatDenseCreateColumnVec_Private(A, &a->cvec));
3488:   a->vecinuse = col + 1;
3489:   PetscCall(MatDenseGetArrayRead(A, &a->ptrinuse));
3490:   PetscCall(VecPlaceArray(a->cvec, PetscSafePointerPlusOffset(a->ptrinuse, (size_t)col * (size_t)a->lda)));
3491:   PetscCall(VecLockReadPush(a->cvec));
3492:   *v = a->cvec;
3493:   PetscFunctionReturn(PETSC_SUCCESS);
3494: }

3496: PetscErrorCode MatDenseRestoreColumnVecRead_SeqDense(Mat A, PetscInt col, Vec *v)
3497: {
3498:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3500:   PetscFunctionBegin;
3501:   PetscCheck(a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseGetColumnVec() first");
3502:   PetscCheck(a->cvec, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing internal column vector");
3503:   VecCheckAssembled(a->cvec);
3504:   a->vecinuse = 0;
3505:   PetscCall(MatDenseRestoreArrayRead(A, &a->ptrinuse));
3506:   PetscCall(VecLockReadPop(a->cvec));
3507:   PetscCall(VecResetArray(a->cvec));
3508:   if (v) *v = NULL;
3509:   PetscFunctionReturn(PETSC_SUCCESS);
3510: }

3512: PetscErrorCode MatDenseGetColumnVecWrite_SeqDense(Mat A, PetscInt col, Vec *v)
3513: {
3514:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3516:   PetscFunctionBegin;
3517:   PetscCheck(!a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
3518:   PetscCheck(!a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
3519:   if (!a->cvec) PetscCall(MatDenseCreateColumnVec_Private(A, &a->cvec));
3520:   a->vecinuse = col + 1;
3521:   PetscCall(MatDenseGetArrayWrite(A, (PetscScalar **)&a->ptrinuse));
3522:   PetscCall(VecPlaceArray(a->cvec, PetscSafePointerPlusOffset(a->ptrinuse, (size_t)col * (size_t)a->lda)));
3523:   *v = a->cvec;
3524:   PetscFunctionReturn(PETSC_SUCCESS);
3525: }

3527: PetscErrorCode MatDenseRestoreColumnVecWrite_SeqDense(Mat A, PetscInt col, Vec *v)
3528: {
3529:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3531:   PetscFunctionBegin;
3532:   PetscCheck(a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseGetColumnVec() first");
3533:   PetscCheck(a->cvec, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing internal column vector");
3534:   VecCheckAssembled(a->cvec);
3535:   a->vecinuse = 0;
3536:   PetscCall(MatDenseRestoreArrayWrite(A, (PetscScalar **)&a->ptrinuse));
3537:   PetscCall(VecResetArray(a->cvec));
3538:   if (v) *v = NULL;
3539:   PetscFunctionReturn(PETSC_SUCCESS);
3540: }

3542: PetscErrorCode MatDenseGetSubMatrix_SeqDense(Mat A, PetscInt rbegin, PetscInt rend, PetscInt cbegin, PetscInt cend, Mat *v)
3543: {
3544:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3546:   PetscFunctionBegin;
3547:   PetscCheck(!a->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
3548:   PetscCheck(!a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
3549:   if (a->cmat && (cend - cbegin != a->cmat->cmap->N || rend - rbegin != a->cmat->rmap->N)) PetscCall(MatDestroy(&a->cmat));
3550:   if (!a->cmat) {
3551:     PetscCall(MatCreateDense(PetscObjectComm((PetscObject)A), rend - rbegin, PETSC_DECIDE, rend - rbegin, cend - cbegin, PetscSafePointerPlusOffset(a->v, rbegin + (size_t)cbegin * a->lda), &a->cmat));
3552:   } else {
3553:     PetscCall(MatDensePlaceArray(a->cmat, PetscSafePointerPlusOffset(a->v, rbegin + (size_t)cbegin * a->lda)));
3554:   }
3555:   PetscCall(MatDenseSetLDA(a->cmat, a->lda));
3556:   a->matinuse = cbegin + 1;
3557:   *v          = a->cmat;
3558: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
3559:   A->offloadmask = PETSC_OFFLOAD_CPU;
3560: #endif
3561:   PetscFunctionReturn(PETSC_SUCCESS);
3562: }

3564: PetscErrorCode MatDenseRestoreSubMatrix_SeqDense(Mat A, Mat *v)
3565: {
3566:   Mat_SeqDense *a = (Mat_SeqDense *)A->data;

3568:   PetscFunctionBegin;
3569:   PetscCheck(a->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseGetSubMatrix() first");
3570:   PetscCheck(a->cmat, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing internal column matrix");
3571:   PetscCheck(*v == a->cmat, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Not the matrix obtained from MatDenseGetSubMatrix()");
3572:   a->matinuse = 0;
3573:   PetscCall(MatDenseResetArray(a->cmat));
3574:   *v = NULL;
3575: #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
3576:   A->offloadmask = PETSC_OFFLOAD_CPU;
3577: #endif
3578:   PetscFunctionReturn(PETSC_SUCCESS);
3579: }

3581: /*MC
3582:    MATSEQDENSE - MATSEQDENSE = "seqdense" - A matrix type to be used for sequential dense matrices.

3584:    Options Database Key:
3585: . -mat_type seqdense - sets the matrix type to `MATSEQDENSE` during a call to `MatSetFromOptions()`

3587:   Level: beginner

3589: .seealso: [](ch_matrices), `Mat`, `MATSEQDENSE`, `MatCreateSeqDense()`
3590: M*/
3591: PetscErrorCode MatCreate_SeqDense(Mat B)
3592: {
3593:   Mat_SeqDense *b;
3594:   PetscMPIInt   size;

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

3600:   PetscCall(PetscNew(&b));
3601:   B->data   = (void *)b;
3602:   B->ops[0] = MatOps_Values;

3604:   b->roworiented = PETSC_TRUE;

3606:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatQRFactor_C", MatQRFactor_SeqDense));
3607:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetLDA_C", MatDenseGetLDA_SeqDense));
3608:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseSetLDA_C", MatDenseSetLDA_SeqDense));
3609:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetArray_C", MatDenseGetArray_SeqDense));
3610:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreArray_C", MatDenseRestoreArray_SeqDense));
3611:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDensePlaceArray_C", MatDensePlaceArray_SeqDense));
3612:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseResetArray_C", MatDenseResetArray_SeqDense));
3613:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseReplaceArray_C", MatDenseReplaceArray_SeqDense));
3614:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetArrayRead_C", MatDenseGetArray_SeqDense));
3615:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreArrayRead_C", MatDenseRestoreArray_SeqDense));
3616:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetArrayWrite_C", MatDenseGetArray_SeqDense));
3617:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreArrayWrite_C", MatDenseRestoreArray_SeqDense));
3618:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqdense_seqaij_C", MatConvert_SeqDense_SeqAIJ));
3619: #if defined(PETSC_HAVE_ELEMENTAL)
3620:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqdense_elemental_C", MatConvert_SeqDense_Elemental));
3621: #endif
3622: #if defined(PETSC_HAVE_SCALAPACK) && (defined(PETSC_USE_REAL_SINGLE) || defined(PETSC_USE_REAL_DOUBLE))
3623:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqdense_scalapack_C", MatConvert_Dense_ScaLAPACK));
3624: #endif
3625: #if defined(PETSC_HAVE_CUDA)
3626:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqdense_seqdensecuda_C", MatConvert_SeqDense_SeqDenseCUDA));
3627:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdensecuda_seqdensecuda_C", MatProductSetFromOptions_SeqDense));
3628:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdensecuda_seqdense_C", MatProductSetFromOptions_SeqDense));
3629:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdense_seqdensecuda_C", MatProductSetFromOptions_SeqDense));
3630: #endif
3631: #if defined(PETSC_HAVE_HIP)
3632:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqdense_seqdensehip_C", MatConvert_SeqDense_SeqDenseHIP));
3633:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdensehip_seqdensehip_C", MatProductSetFromOptions_SeqDense));
3634:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdensehip_seqdense_C", MatProductSetFromOptions_SeqDense));
3635:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdense_seqdensehip_C", MatProductSetFromOptions_SeqDense));
3636: #endif
3637:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSeqDenseSetPreallocation_C", MatSeqDenseSetPreallocation_SeqDense));
3638:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqaij_seqdense_C", MatProductSetFromOptions_SeqAIJ_SeqDense));
3639:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqdense_seqdense_C", MatProductSetFromOptions_SeqDense));
3640:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqbaij_seqdense_C", MatProductSetFromOptions_SeqXBAIJ_SeqDense));
3641:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_seqsbaij_seqdense_C", MatProductSetFromOptions_SeqXBAIJ_SeqDense));

3643:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetColumn_C", MatDenseGetColumn_SeqDense));
3644:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreColumn_C", MatDenseRestoreColumn_SeqDense));
3645:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetColumnVec_C", MatDenseGetColumnVec_SeqDense));
3646:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreColumnVec_C", MatDenseRestoreColumnVec_SeqDense));
3647:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetColumnVecRead_C", MatDenseGetColumnVecRead_SeqDense));
3648:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreColumnVecRead_C", MatDenseRestoreColumnVecRead_SeqDense));
3649:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetColumnVecWrite_C", MatDenseGetColumnVecWrite_SeqDense));
3650:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreColumnVecWrite_C", MatDenseRestoreColumnVecWrite_SeqDense));
3651:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseGetSubMatrix_C", MatDenseGetSubMatrix_SeqDense));
3652:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatDenseRestoreSubMatrix_C", MatDenseRestoreSubMatrix_SeqDense));
3653:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMultColumnRange_C", MatMultColumnRange_SeqDense));
3654:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMultAddColumnRange_C", MatMultAddColumnRange_SeqDense));
3655:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMultHermitianTransposeColumnRange_C", MatMultHermitianTransposeColumnRange_SeqDense));
3656:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMultHermitianTransposeAddColumnRange_C", MatMultHermitianTransposeAddColumnRange_SeqDense));
3657:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATSEQDENSE));
3658:   PetscFunctionReturn(PETSC_SUCCESS);
3659: }

3661: /*@C
3662:   MatDenseGetColumn - gives access to a column of a dense matrix. This is only the local part of the column. You MUST call `MatDenseRestoreColumn()` to avoid memory bleeding.

3664:   Not Collective

3666:   Input Parameters:
3667: + A   - a `MATSEQDENSE` or `MATMPIDENSE` matrix
3668: - col - column index

3670:   Output Parameter:
3671: . vals - pointer to the data

3673:   Level: intermediate

3675:   Note:
3676:   Use `MatDenseGetColumnVec()` to get access to a column of a `MATDENSE` treated as a `Vec`

3678: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseRestoreColumn()`, `MatDenseGetColumnVec()`
3679: @*/
3680: PetscErrorCode MatDenseGetColumn(Mat A, PetscInt col, PetscScalar *vals[])
3681: {
3682:   PetscFunctionBegin;
3685:   PetscAssertPointer(vals, 3);
3686:   PetscUseMethod(A, "MatDenseGetColumn_C", (Mat, PetscInt, PetscScalar **), (A, col, vals));
3687:   PetscFunctionReturn(PETSC_SUCCESS);
3688: }

3690: /*@C
3691:   MatDenseRestoreColumn - returns access to a column of a `MATDENSE` matrix which is returned by `MatDenseGetColumn()`.

3693:   Not Collective

3695:   Input Parameters:
3696: + A    - a `MATSEQDENSE` or `MATMPIDENSE` matrix
3697: - vals - pointer to the data (may be `NULL`)

3699:   Level: intermediate

3701: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MatDenseGetColumn()`
3702: @*/
3703: PetscErrorCode MatDenseRestoreColumn(Mat A, PetscScalar *vals[])
3704: {
3705:   PetscFunctionBegin;
3707:   PetscAssertPointer(vals, 2);
3708:   PetscUseMethod(A, "MatDenseRestoreColumn_C", (Mat, PetscScalar **), (A, vals));
3709:   PetscFunctionReturn(PETSC_SUCCESS);
3710: }

3712: /*@
3713:   MatDenseGetColumnVec - Gives read-write access to a column of a `MATDENSE` matrix, represented as a `Vec`.

3715:   Collective

3717:   Input Parameters:
3718: + A   - the `Mat` object
3719: - col - the column index

3721:   Output Parameter:
3722: . v - the vector

3724:   Level: intermediate

3726:   Notes:
3727:   The vector is owned by PETSc. Users need to call `MatDenseRestoreColumnVec()` when the vector is no longer needed.

3729:   Use `MatDenseGetColumnVecRead()` to obtain read-only access or `MatDenseGetColumnVecWrite()` for write-only access.

3731: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVecRead()`, `MatDenseGetColumnVecWrite()`, `MatDenseRestoreColumnVec()`, `MatDenseRestoreColumnVecRead()`, `MatDenseRestoreColumnVecWrite()`, `MatDenseGetColumn()`
3732: @*/
3733: PetscErrorCode MatDenseGetColumnVec(Mat A, PetscInt col, Vec *v)
3734: {
3735:   PetscFunctionBegin;
3739:   PetscAssertPointer(v, 3);
3740:   PetscCheck(A->preallocated, PetscObjectComm((PetscObject)A), PETSC_ERR_ORDER, "Matrix not preallocated");
3741:   PetscCheck(col >= 0 && col < A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid col %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT ")", col, A->cmap->N);
3742:   PetscUseMethod(A, "MatDenseGetColumnVec_C", (Mat, PetscInt, Vec *), (A, col, v));
3743:   PetscFunctionReturn(PETSC_SUCCESS);
3744: }

3746: /*@
3747:   MatDenseRestoreColumnVec - Returns access to a column of a dense matrix obtained from `MatDenseGetColumnVec()`.

3749:   Collective

3751:   Input Parameters:
3752: + A   - the `Mat` object
3753: . col - the column index
3754: - v   - the `Vec` object (may be `NULL`)

3756:   Level: intermediate

3758: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVec()`, `MatDenseGetColumnVecRead()`, `MatDenseGetColumnVecWrite()`, `MatDenseRestoreColumnVecRead()`, `MatDenseRestoreColumnVecWrite()`
3759: @*/
3760: PetscErrorCode MatDenseRestoreColumnVec(Mat A, PetscInt col, Vec *v)
3761: {
3762:   PetscFunctionBegin;
3767:   PetscCheck(A->preallocated, PetscObjectComm((PetscObject)A), PETSC_ERR_ORDER, "Matrix not preallocated");
3768:   PetscCheck(col >= 0 && col < A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid col %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT ")", col, A->cmap->N);
3769:   PetscUseMethod(A, "MatDenseRestoreColumnVec_C", (Mat, PetscInt, Vec *), (A, col, v));
3770:   PetscFunctionReturn(PETSC_SUCCESS);
3771: }

3773: /*@
3774:   MatDenseGetColumnVecRead - Gives read-only access to a column of a dense matrix, represented as a `Vec`.

3776:   Collective

3778:   Input Parameters:
3779: + A   - the `Mat` object
3780: - col - the column index

3782:   Output Parameter:
3783: . v - the vector

3785:   Level: intermediate

3787:   Notes:
3788:   The vector is owned by PETSc and users cannot modify it.

3790:   Users need to call `MatDenseRestoreColumnVecRead()` when the vector is no longer needed.

3792:   Use `MatDenseGetColumnVec()` to obtain read-write access or `MatDenseGetColumnVecWrite()` for write-only access.

3794: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVec()`, `MatDenseGetColumnVecWrite()`, `MatDenseRestoreColumnVec()`, `MatDenseRestoreColumnVecRead()`, `MatDenseRestoreColumnVecWrite()`
3795: @*/
3796: PetscErrorCode MatDenseGetColumnVecRead(Mat A, PetscInt col, Vec *v)
3797: {
3798:   PetscFunctionBegin;
3802:   PetscAssertPointer(v, 3);
3803:   PetscCheck(A->preallocated, PetscObjectComm((PetscObject)A), PETSC_ERR_ORDER, "Matrix not preallocated");
3804:   PetscCheck(col >= 0 && col < A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid col %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT ")", col, A->cmap->N);
3805:   PetscUseMethod(A, "MatDenseGetColumnVecRead_C", (Mat, PetscInt, Vec *), (A, col, v));
3806:   PetscFunctionReturn(PETSC_SUCCESS);
3807: }

3809: /*@
3810:   MatDenseRestoreColumnVecRead - Returns access to a column of a dense matrix obtained from `MatDenseGetColumnVecRead()`.

3812:   Collective

3814:   Input Parameters:
3815: + A   - the `Mat` object
3816: . col - the column index
3817: - v   - the `Vec` object (may be `NULL`)

3819:   Level: intermediate

3821: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVec()`, `MatDenseGetColumnVecRead()`, `MatDenseGetColumnVecWrite()`, `MatDenseRestoreColumnVec()`, `MatDenseRestoreColumnVecWrite()`
3822: @*/
3823: PetscErrorCode MatDenseRestoreColumnVecRead(Mat A, PetscInt col, Vec *v)
3824: {
3825:   PetscFunctionBegin;
3830:   PetscCheck(A->preallocated, PetscObjectComm((PetscObject)A), PETSC_ERR_ORDER, "Matrix not preallocated");
3831:   PetscCheck(col >= 0 && col < A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid col %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT ")", col, A->cmap->N);
3832:   PetscUseMethod(A, "MatDenseRestoreColumnVecRead_C", (Mat, PetscInt, Vec *), (A, col, v));
3833:   PetscFunctionReturn(PETSC_SUCCESS);
3834: }

3836: /*@
3837:   MatDenseGetColumnVecWrite - Gives write-only access to a column of a dense matrix, represented as a `Vec`.

3839:   Collective

3841:   Input Parameters:
3842: + A   - the `Mat` object
3843: - col - the column index

3845:   Output Parameter:
3846: . v - the vector

3848:   Level: intermediate

3850:   Notes:
3851:   The vector is owned by PETSc. Users need to call `MatDenseRestoreColumnVecWrite()` when the vector is no longer needed.

3853:   Use `MatDenseGetColumnVec()` to obtain read-write access or `MatDenseGetColumnVecRead()` for read-only access.

3855: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVec()`, `MatDenseGetColumnVecRead()`, `MatDenseRestoreColumnVec()`, `MatDenseRestoreColumnVecRead()`, `MatDenseRestoreColumnVecWrite()`
3856: @*/
3857: PetscErrorCode MatDenseGetColumnVecWrite(Mat A, PetscInt col, Vec *v)
3858: {
3859:   PetscFunctionBegin;
3863:   PetscAssertPointer(v, 3);
3864:   PetscCheck(A->preallocated, PetscObjectComm((PetscObject)A), PETSC_ERR_ORDER, "Matrix not preallocated");
3865:   PetscCheck(col >= 0 && col < A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid col %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT ")", col, A->cmap->N);
3866:   PetscUseMethod(A, "MatDenseGetColumnVecWrite_C", (Mat, PetscInt, Vec *), (A, col, v));
3867:   PetscFunctionReturn(PETSC_SUCCESS);
3868: }

3870: /*@
3871:   MatDenseRestoreColumnVecWrite - Returns access to a column of a dense matrix obtained from `MatDenseGetColumnVecWrite()`.

3873:   Collective

3875:   Input Parameters:
3876: + A   - the `Mat` object
3877: . col - the column index
3878: - v   - the `Vec` object (may be `NULL`)

3880:   Level: intermediate

3882: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVec()`, `MatDenseGetColumnVecRead()`, `MatDenseGetColumnVecWrite()`, `MatDenseRestoreColumnVec()`, `MatDenseRestoreColumnVecRead()`
3883: @*/
3884: PetscErrorCode MatDenseRestoreColumnVecWrite(Mat A, PetscInt col, Vec *v)
3885: {
3886:   PetscFunctionBegin;
3891:   PetscCheck(A->preallocated, PetscObjectComm((PetscObject)A), PETSC_ERR_ORDER, "Matrix not preallocated");
3892:   PetscCheck(col >= 0 && col < A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid col %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT ")", col, A->cmap->N);
3893:   PetscUseMethod(A, "MatDenseRestoreColumnVecWrite_C", (Mat, PetscInt, Vec *), (A, col, v));
3894:   PetscFunctionReturn(PETSC_SUCCESS);
3895: }

3897: /*@
3898:   MatDenseGetSubMatrix - Gives access to a block of rows and columns of a dense matrix, represented as a `Mat`.

3900:   Collective

3902:   Input Parameters:
3903: + A      - the `Mat` object
3904: . rbegin - the first global row index in the block (if `PETSC_DECIDE`, is 0)
3905: . rend   - the global row index past the last one in the block (if `PETSC_DECIDE`, is `M`)
3906: . cbegin - the first global column index in the block (if `PETSC_DECIDE`, is 0)
3907: - cend   - the global column index past the last one in the block (if `PETSC_DECIDE`, is `N`)

3909:   Output Parameter:
3910: . v - the matrix

3912:   Level: intermediate

3914:   Notes:
3915:   The matrix is owned by PETSc. Users need to call `MatDenseRestoreSubMatrix()` when the matrix is no longer needed.

3917:   The output matrix is not redistributed by PETSc, so depending on the values of `rbegin` and `rend`, some processes may have no local rows.

3919: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVec()`, `MatDenseRestoreColumnVec()`, `MatDenseRestoreSubMatrix()`
3920: @*/
3921: PetscErrorCode MatDenseGetSubMatrix(Mat A, PetscInt rbegin, PetscInt rend, PetscInt cbegin, PetscInt cend, Mat *v)
3922: {
3923:   PetscFunctionBegin;
3930:   PetscAssertPointer(v, 6);
3931:   if (rbegin == PETSC_DECIDE) rbegin = 0;
3932:   if (rend == PETSC_DECIDE) rend = A->rmap->N;
3933:   if (cbegin == PETSC_DECIDE) cbegin = 0;
3934:   if (cend == PETSC_DECIDE) cend = A->cmap->N;
3935:   PetscCheck(A->preallocated, PetscObjectComm((PetscObject)A), PETSC_ERR_ORDER, "Matrix not preallocated");
3936:   PetscCheck(rbegin >= 0 && rbegin <= A->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid rbegin %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT "]", rbegin, A->rmap->N);
3937:   PetscCheck(rend >= rbegin && rend <= A->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid rend %" PetscInt_FMT ", should be in [%" PetscInt_FMT ",%" PetscInt_FMT "]", rend, rbegin, A->rmap->N);
3938:   PetscCheck(cbegin >= 0 && cbegin <= A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid cbegin %" PetscInt_FMT ", should be in [0,%" PetscInt_FMT "]", cbegin, A->cmap->N);
3939:   PetscCheck(cend >= cbegin && cend <= A->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Invalid cend %" PetscInt_FMT ", should be in [%" PetscInt_FMT ",%" PetscInt_FMT "]", cend, cbegin, A->cmap->N);
3940:   PetscUseMethod(A, "MatDenseGetSubMatrix_C", (Mat, PetscInt, PetscInt, PetscInt, PetscInt, Mat *), (A, rbegin, rend, cbegin, cend, v));
3941:   PetscFunctionReturn(PETSC_SUCCESS);
3942: }

3944: /*@
3945:   MatDenseRestoreSubMatrix - Returns access to a block of columns of a dense matrix obtained from `MatDenseGetSubMatrix()`.

3947:   Collective

3949:   Input Parameters:
3950: + A - the `Mat` object
3951: - v - the `Mat` object (cannot be `NULL`)

3953:   Level: intermediate

3955: .seealso: [](ch_matrices), `Mat`, `MATDENSE`, `MATDENSECUDA`, `MATDENSEHIP`, `MatDenseGetColumnVec()`, `MatDenseRestoreColumnVec()`, `MatDenseGetSubMatrix()`
3956: @*/
3957: PetscErrorCode MatDenseRestoreSubMatrix(Mat A, Mat *v)
3958: {
3959:   PetscFunctionBegin;
3962:   PetscAssertPointer(v, 2);
3964:   PetscUseMethod(A, "MatDenseRestoreSubMatrix_C", (Mat, Mat *), (A, v));
3965:   PetscFunctionReturn(PETSC_SUCCESS);
3966: }

3968: #include <petscblaslapack.h>
3969: #include <petsc/private/kernels/blockinvert.h>

3971: PetscErrorCode MatSeqDenseInvert(Mat A)
3972: {
3973:   PetscInt        m;
3974:   const PetscReal shift = 0.0;
3975:   PetscBool       allowzeropivot, zeropivotdetected = PETSC_FALSE;
3976:   PetscScalar    *values;

3978:   PetscFunctionBegin;
3980:   PetscCall(MatDenseGetArray(A, &values));
3981:   PetscCall(MatGetLocalSize(A, &m, NULL));
3982:   allowzeropivot = PetscNot(A->erroriffailure);
3983:   /* factor and invert each block */
3984:   switch (m) {
3985:   case 1:
3986:     values[0] = (PetscScalar)1.0 / (values[0] + shift);
3987:     break;
3988:   case 2:
3989:     PetscCall(PetscKernel_A_gets_inverse_A_2(values, shift, allowzeropivot, &zeropivotdetected));
3990:     if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3991:     break;
3992:   case 3:
3993:     PetscCall(PetscKernel_A_gets_inverse_A_3(values, shift, allowzeropivot, &zeropivotdetected));
3994:     if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3995:     break;
3996:   case 4:
3997:     PetscCall(PetscKernel_A_gets_inverse_A_4(values, shift, allowzeropivot, &zeropivotdetected));
3998:     if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
3999:     break;
4000:   case 5: {
4001:     PetscScalar work[25];
4002:     PetscInt    ipvt[5];

4004:     PetscCall(PetscKernel_A_gets_inverse_A_5(values, ipvt, work, shift, allowzeropivot, &zeropivotdetected));
4005:     if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
4006:   } break;
4007:   case 6:
4008:     PetscCall(PetscKernel_A_gets_inverse_A_6(values, shift, allowzeropivot, &zeropivotdetected));
4009:     if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
4010:     break;
4011:   case 7:
4012:     PetscCall(PetscKernel_A_gets_inverse_A_7(values, shift, allowzeropivot, &zeropivotdetected));
4013:     if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
4014:     break;
4015:   default: {
4016:     PetscInt    *v_pivots, *IJ, j;
4017:     PetscScalar *v_work;

4019:     PetscCall(PetscMalloc3(m, &v_work, m, &v_pivots, m, &IJ));
4020:     for (j = 0; j < m; j++) IJ[j] = j;
4021:     PetscCall(PetscKernel_A_gets_inverse_A(m, values, v_pivots, v_work, allowzeropivot, &zeropivotdetected));
4022:     if (zeropivotdetected) A->factorerrortype = MAT_FACTOR_NUMERIC_ZEROPIVOT;
4023:     PetscCall(PetscFree3(v_work, v_pivots, IJ));
4024:   }
4025:   }
4026:   PetscCall(MatDenseRestoreArray(A, &values));
4027:   PetscFunctionReturn(PETSC_SUCCESS);
4028: }

4030: /*@
4031:   MatDenseReplaceArrayWithMemType - Allows one to replace the array in a `MATDENSE`, `MATDENSECUDA`, or `MATDENSEHIP`
4032:   with an array provided by the user and a matching `PetscMemType`. This is useful to avoid copying an array into a matrix.

4034:   Not Collective

4036:   Input Parameters:
4037: + mat   - the matrix
4038: . mtype - the `PetscMemType` of the array
4039: - array - the array in column major order

4041:   Level: developer

4043:   Note:
4044:   Adding `const` to `array` was an oversight, see notes in `VecPlaceArray()`.

4046:   This permanently replaces the GPU array and frees the memory associated with the old GPU
4047:   array. The memory passed in CANNOT be freed by the user. It will be freed when the matrix is
4048:   destroyed. The array should respect the matrix leading dimension.

4050: .seealso: `MatDenseReplaceArray()`, `MatDenseCUDAReplaceArray()`, `MatDenseHIPReplaceArray()`
4051: @*/
4052: PetscErrorCode MatDenseReplaceArrayWithMemType(Mat mat, PetscMemType mtype, const PetscScalar array[])
4053: {
4054:   const char *type = PetscMemTypeToString(mtype) + 14; /* skip "PETSC_MEMTYPE_" */
4055:   char        buffer[256];

4057:   PetscFunctionBegin;
4059:   PetscAssertPointer(array, 3);
4060:   PetscCall(PetscSNPrintf(buffer, sizeof(buffer), "MatDense%sReplaceArray_C", PetscMemTypeHost(mtype) ? "" : type));
4061:   PetscUseMethod(mat, buffer, (Mat, const PetscScalar[]), (mat, array));
4062:   PetscFunctionReturn(PETSC_SUCCESS);
4063: }