|
| 1 | +#include "bout/build_defines.hxx" |
| 2 | + |
| 3 | +#if BOUT_HAS_PETSC |
| 4 | + |
| 5 | +#include "bout/assert.hxx" |
1 | 6 | #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 | +} |
2 | 47 |
|
3 | | -void addOperatorSparsity(Mat Jfd, Mat sub, int out_var, int in_var) {} |
| 48 | +#endif // BOUT_HAS_PETSC |
0 commit comments