Skip to content

Commit ba6996e

Browse files
committed
addOperatorSparsity implementation
Sets a sparsity pattern in a given Jacobian matrix, based on an operator matrix and the variable indices. Passes unit tests.
1 parent 729f86e commit ba6996e

2 files changed

Lines changed: 46 additions & 2 deletions

File tree

src/mesh/petsc_jacobian.cxx

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,48 @@
1+
#include "bout/build_defines.hxx"
2+
3+
#if BOUT_HAS_PETSC
4+
5+
#include "bout/assert.hxx"
16
#include "bout/petsc_jacobian.hxx"
7+
#include "bout/petsclib.hxx"
8+
9+
#include <petscmat.h>
10+
11+
void addOperatorSparsity(Mat Jfd, Mat sub, int out_var, int in_var) {
12+
// Infer nvars from global sizes
13+
PetscInt jfd_global{0}, sub_global{0};
14+
BOUT_DO_PETSC(MatGetSize(Jfd, &jfd_global, nullptr));
15+
BOUT_DO_PETSC(MatGetSize(sub, &sub_global, nullptr));
16+
17+
ASSERT1(sub_global > 0);
18+
ASSERT1(jfd_global % sub_global == 0);
19+
20+
const PetscInt nvars = jfd_global / sub_global;
21+
22+
ASSERT1(out_var >= 0 && out_var < static_cast<int>(nvars));
23+
ASSERT1(in_var >= 0 && in_var < static_cast<int>(nvars));
24+
25+
// Iterate over locally owned rows of sub and insert into Jfd
26+
PetscInt rstart{0}, rend{0};
27+
BOUT_DO_PETSC(MatGetOwnershipRange(sub, &rstart, &rend));
28+
29+
const PetscScalar one = 1.0;
30+
31+
for (PetscInt sub_row = rstart; sub_row < rend; ++sub_row) {
32+
PetscInt ncols{0};
33+
const PetscInt* sub_cols{nullptr};
34+
const PetscScalar* vals{nullptr};
35+
BOUT_DO_PETSC(MatGetRow(sub, sub_row, &ncols, &sub_cols, &vals));
36+
37+
const PetscInt jfd_row = (sub_row * nvars) + out_var;
38+
39+
for (PetscInt k = 0; k < ncols; ++k) {
40+
const PetscInt jfd_col = (sub_cols[k] * nvars) + in_var;
41+
BOUT_DO_PETSC(MatSetValues(Jfd, 1, &jfd_row, 1, &jfd_col, &one, INSERT_VALUES));
42+
}
43+
44+
BOUT_DO_PETSC(MatRestoreRow(sub, sub_row, &ncols, &sub_cols, &vals));
45+
}
46+
}
247

3-
void addOperatorSparsity(Mat Jfd, Mat sub, int out_var, int in_var) {}
48+
#endif // BOUT_HAS_PETSC

src/mesh/petsc_operators.cxx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
#include "bout/bout_types.hxx"
77
#include "bout/boutexception.hxx"
88
#include "bout/field3d.hxx"
9-
#include "bout/output.hxx"
109
#include "bout/output_bout_types.hxx"
1110
#include "bout/petsc_operators.hxx"
1211
#include "bout/region.hxx"

0 commit comments

Comments
 (0)