DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
petsc.h
1// Copyright (C) 2004-2026 Johan Hoffman, Johan Jansson, Anders Logg,
2// Garth N. Wells and Jack S. Hale
3//
4// This file is part of DOLFINx (https://www.fenicsproject.org)
5//
6// SPDX-License-Identifier: LGPL-3.0-or-later
7
8#pragma once
9
10#ifdef HAS_PETSC
11
12#include "Vector.h"
13#include <array>
14#include <cassert>
15#include <cstdint>
16#include <dolfinx/common/petsc.h>
17#include <functional>
18#include <optional>
19#include <petscksp.h>
20#include <petscmat.h>
21#include <petscvec.h>
22#include <span>
23#include <string>
24#include <string_view>
25#include <utility>
26#include <vector>
27
28namespace dolfinx::common
29{
30class IndexMap;
31} // namespace dolfinx::common
32
33namespace dolfinx::la
34{
35class SparsityPattern;
36
38namespace petsc
39{
48std::vector<Vec>
49create_vectors(MPI_Comm comm,
50 const std::vector<std::span<const PetscScalar>>& x);
51
57Vec create_vector(const common::IndexMap& map, int bs);
58
68Vec create_vector(MPI_Comm comm, std::array<std::int64_t, 2> range,
69 std::span<const std::int64_t> ghosts, int bs);
70
81Vec create_vector_wrap(const common::IndexMap& map, int bs,
82 std::span<const PetscScalar> x);
83
87template <class V>
89{
90 assert(x.index_map());
91 return create_vector_wrap(*x.index_map(), x.bs(), x.array());
92}
93
106std::vector<IS> create_index_sets(
107 const std::vector<
108 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
109
111std::vector<std::vector<PetscScalar>> get_local_vectors(
112 const Vec x,
113 const std::vector<
114 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
115
118 Vec x, const std::vector<std::span<const PetscScalar>>& x_b,
119 const std::vector<
120 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
121
137Mat create_matrix(MPI_Comm comm, const SparsityPattern& sp,
138 std::optional<std::string_view> type = std::nullopt);
139
145MatNullSpace create_nullspace(MPI_Comm comm, std::span<const Vec> basis);
146
153{
154public:
159 Vector(const common::IndexMap& map, int bs);
160
161 // Delete copy constructor to avoid accidental copying of 'heavy' data
162 Vector(const Vector& x) = delete;
163
165 Vector(Vector&& x) noexcept;
166
178 Vector(Vec x, bool inc_ref_count);
179
181 ~Vector();
182
183 // Assignment operator (disabled)
184 Vector& operator=(const Vector& x) = delete;
185
187 Vector& operator=(Vector&& x) noexcept;
188
191 Vector copy() const;
192
194 std::int64_t size() const;
195
197 std::int32_t local_size() const;
198
200 std::array<std::int64_t, 2> local_range() const;
201
203 MPI_Comm comm() const;
204
206 void set_options_prefix(std::string_view options_prefix);
207
210 std::string get_options_prefix() const;
211
213 void set_from_options();
214
216 Vec vec() const;
217
218private:
219 // PETSc Vec pointer
220 Vec _x;
221};
222
229{
230public:
236 static auto set_fn(Mat A, InsertMode mode)
237 {
238 return [A, mode, cache = std::vector<PetscInt>()](
239 std::span<const std::int32_t> rows,
240 std::span<const std::int32_t> cols,
241 std::span<const PetscScalar> vals) mutable -> int
242 {
243 PetscErrorCode ierr;
244#ifdef PETSC_USE_64BIT_INDICES
245 cache.resize(rows.size() + cols.size());
246 std::ranges::copy(rows, cache.begin());
247 std::ranges::copy(cols, std::next(cache.begin(), rows.size()));
248 const PetscInt* _rows = cache.data();
249 const PetscInt* _cols = cache.data() + rows.size();
250 ierr = MatSetValuesLocal(A, rows.size(), _rows, cols.size(), _cols,
251 vals.data(), mode);
252#else
253 ierr = MatSetValuesLocal(A, rows.size(), rows.data(), cols.size(),
254 cols.data(), vals.data(), mode);
255#endif
256
257#ifndef NDEBUG
258 common::petsc::check(ierr, "MatSetValuesLocal");
259#endif
260 return ierr;
261 };
262 }
263
269 static auto set_block_fn(Mat A, InsertMode mode)
270 {
271 return [A, mode, cache = std::vector<PetscInt>()](
272 std::span<const std::int32_t> rows,
273 std::span<const std::int32_t> cols,
274 std::span<const PetscScalar> vals) mutable -> int
275 {
276 PetscErrorCode ierr;
277#ifdef PETSC_USE_64BIT_INDICES
278 cache.resize(rows.size() + cols.size());
279 std::ranges::copy(rows, cache.begin());
280 std::ranges::copy(cols, std::next(cache.begin(), rows.size()));
281 const PetscInt* _rows = cache.data();
282 const PetscInt* _cols = cache.data() + rows.size();
283 ierr = MatSetValuesBlockedLocal(A, rows.size(), _rows, cols.size(), _cols,
284 vals.data(), mode);
285#else
286 ierr = MatSetValuesBlockedLocal(A, rows.size(), rows.data(), cols.size(),
287 cols.data(), vals.data(), mode);
288#endif
289
290#ifndef NDEBUG
291 common::petsc::check(ierr, "MatSetValuesBlockedLocal");
292#endif
293 return ierr;
294 };
295 }
296
307 static auto set_block_expand_fn(Mat A, int bs0, int bs1, InsertMode mode)
308 {
309 return [A, bs0, bs1, mode, cache0 = std::vector<PetscInt>(),
310 cache1 = std::vector<PetscInt>()](
311 std::span<const std::int32_t> rows,
312 std::span<const std::int32_t> cols,
313 std::span<const PetscScalar> vals) mutable -> int
314 {
315 PetscErrorCode ierr;
316 cache0.resize(bs0 * rows.size());
317 cache1.resize(bs1 * cols.size());
318 for (std::size_t i = 0; i < rows.size(); ++i)
319 for (int k = 0; k < bs0; ++k)
320 cache0[bs0 * i + k] = bs0 * rows[i] + k;
321
322 for (std::size_t i = 0; i < cols.size(); ++i)
323 for (int k = 0; k < bs1; ++k)
324 cache1[bs1 * i + k] = bs1 * cols[i] + k;
325
326 ierr = MatSetValuesLocal(A, cache0.size(), cache0.data(), cache1.size(),
327 cache1.data(), vals.data(), mode);
328#ifndef NDEBUG
329 common::petsc::check(ierr, "MatSetValuesLocal");
330#endif
331 return ierr;
332 };
333 }
334
336 Matrix(MPI_Comm comm, const SparsityPattern& sp,
337 std::optional<std::string_view> type = std::nullopt);
338
346 Matrix(Mat A, bool inc_ref_count);
347
348 // Copy constructor (deleted)
349 Matrix(const Matrix& A) = delete;
350
352 Matrix(Matrix&& A) noexcept;
353
355 ~Matrix();
356
357 // Assignment operator (deleted)
358 Matrix& operator=(const Matrix& A) = delete;
359
361 Matrix& operator=(Matrix&& A) noexcept;
362
365 std::array<std::int64_t, 2> size() const;
366
373 Vec create_vector(std::size_t dim) const;
374
376 Mat mat() const;
377
378 //--- Special PETSc Functions ---
379
382 void set_options_prefix(std::string_view options_prefix);
383
386 std::string get_options_prefix() const;
387
389 void set_from_options();
390
391private:
392 // PETSc Mat pointer
393 Mat _matA;
394};
395
399{
400public:
403 explicit KrylovSolver(MPI_Comm comm);
404
411 KrylovSolver(KSP ksp, bool inc_ref_count);
412
413 // Copy constructor (deleted)
414 KrylovSolver(const KrylovSolver& solver) = delete;
415
417 KrylovSolver(KrylovSolver&& solver) noexcept;
418
421
422 // Assignment operator (deleted)
423 KrylovSolver& operator=(const KrylovSolver&) = delete;
424
426 KrylovSolver& operator=(KrylovSolver&& solver) noexcept;
427
429 void set_operator(const Mat A);
430
432 void set_operators(const Mat A, const Mat P);
433
442 [[nodiscard(
443 "check the converged reason - positive on convergence, negative on "
444 "divergence")]] KSPConvergedReason
445 solve(Vec x, const Vec b, bool transpose = false);
446
449 void set_options_prefix(std::string_view options_prefix);
450
453 std::string get_options_prefix() const;
454
456 void set_from_options() const;
457
459 KSP ksp() const;
460
461private:
462 // PETSc solver pointer
463 KSP _ksp;
464};
465} // namespace petsc
466} // namespace dolfinx::la
467
468#endif
Distribution of a global index range [0, N) across MPI ranks.
Definition IndexMap.h:114
Definition SparsityPattern.h:28
A vector that can be distributed across processes.
Definition Vector.h:51
std::shared_ptr< const common::IndexMap > index_map() const noexcept
Get IndexMap.
Definition Vector.h:453
constexpr int bs() const noexcept
Get block size.
Definition Vector.h:467
container_type & array() noexcept
Get the process-local part of the vector.
Definition Vector.h:472
void set_operator(const Mat A)
Set operator (Mat).
Definition petsc.cpp:599
KSP ksp() const
Return PETSc KSP pointer.
Definition petsc.cpp:673
std::string get_options_prefix() const
Definition petsc.cpp:658
void set_options_prefix(std::string_view options_prefix)
Definition petsc.cpp:649
void set_operators(const Mat A, const Mat P)
Set operator and preconditioner matrix (Mat).
Definition petsc.cpp:601
KrylovSolver(MPI_Comm comm)
Create a Krylov solver.
Definition petsc.cpp:560
void set_from_options() const
Set options from PETSc options database.
Definition petsc.cpp:667
~KrylovSolver()
Destructor.
Definition petsc.cpp:584
KSPConvergedReason solve(Vec x, const Vec b, bool transpose=false)
Solve linear system Ax = b (A^t x = b if transpose is true).
Definition petsc.cpp:608
Definition petsc.h:229
static auto set_block_fn(Mat A, InsertMode mode)
Return a function with an interface for adding or inserting values into the matrix A using blocked in...
Definition petsc.h:269
~Matrix()
Destructor.
Definition petsc.cpp:491
void set_from_options()
Call PETSc function MatSetFromOptions on the PETSc Mat object.
Definition petsc.cpp:553
std::array< std::int64_t, 2 > size() const
Definition petsc.cpp:506
static auto set_fn(Mat A, InsertMode mode)
Return a function with an interface for adding or inserting values into the matrix A (calls MatSetVal...
Definition petsc.h:236
std::string get_options_prefix() const
Definition petsc.cpp:544
Matrix(MPI_Comm comm, const SparsityPattern &sp, std::optional< std::string_view > type=std::nullopt)
Create holder for a PETSc Mat object from a sparsity pattern.
Definition petsc.cpp:467
Vec create_vector(std::size_t dim) const
Initialize vector to be compatible with the matrix-vector product y = Ax. In the parallel case,...
Definition petsc.cpp:514
static auto set_block_expand_fn(Mat A, int bs0, int bs1, InsertMode mode)
Return a function with an interface for adding or inserting blocked values to the matrix A using non-...
Definition petsc.h:307
void set_options_prefix(std::string_view options_prefix)
Definition petsc.cpp:536
Mat mat() const
Return PETSc Mat pointer.
Definition petsc.cpp:534
void set_from_options()
Call PETSc function VecSetFromOptions on the underlying Vec object.
Definition petsc.cpp:458
std::int64_t size() const
Return global size of the vector.
Definition petsc.cpp:407
std::string get_options_prefix() const
Definition petsc.cpp:450
Vector copy() const
Create a copy of the vector.
Definition petsc.cpp:399
void set_options_prefix(std::string_view options_prefix)
Sets the prefix used by PETSc when searching the options database.
Definition petsc.cpp:442
~Vector()
Destructor.
Definition petsc.cpp:385
Vector(const common::IndexMap &map, int bs)
Create a vector.
Definition petsc.cpp:365
MPI_Comm comm() const
Return MPI communicator.
Definition petsc.cpp:433
std::array< std::int64_t, 2 > local_range() const
Return ownership range for calling rank.
Definition petsc.cpp:423
std::int32_t local_size() const
Return local size of vector (belonging to the call rank).
Definition petsc.cpp:415
Vec vec() const
Return pointer to PETSc Vec object.
Definition petsc.cpp:464
void check(PetscErrorCode ierr, std::string_view petsc_function, std::source_location loc=std::source_location::current())
Throw a std::runtime_error via error() if ierr indicates a PETSc call failed.
Definition petsc.h:41
Miscellaneous classes, functions and types.
Definition dolfinx_common.h:8
PETSc linear algebra functions.
Definition petsc.h:39
Vec create_vector_wrap(const common::IndexMap &map, int bs, std::span< const PetscScalar > x)
Create a PETSc Vec that wraps the data in an array.
Definition petsc.cpp:80
MatNullSpace create_nullspace(MPI_Comm comm, std::span< const Vec > basis)
Create PETSc MatNullSpace. Caller is responsible for destruction returned object.
Definition petsc.cpp:354
void scatter_local_vectors(Vec x, const std::vector< std::span< const PetscScalar > > &x_b, const std::vector< std::pair< std::reference_wrapper< const common::IndexMap >, int > > &maps)
Scatter local vectors to Vec.
Definition petsc.cpp:178
std::vector< IS > create_index_sets(const std::vector< std::pair< std::reference_wrapper< const common::IndexMap >, int > > &maps)
Compute PETSc IndexSets (IS) for a stack of index maps.
Definition petsc.cpp:112
std::vector< Vec > create_vectors(MPI_Comm comm, const std::vector< std::span< const PetscScalar > > &x)
Create PETSc vectors from the local data. The data is copied into the PETSc vectors and is not shared...
Definition petsc.cpp:29
Mat create_matrix(MPI_Comm comm, const SparsityPattern &sp, std::optional< std::string_view > type=std::nullopt)
Create a PETSc Mat. Caller is responsible for destroying the returned object.
Definition petsc.cpp:222
std::vector< std::vector< PetscScalar > > get_local_vectors(const Vec x, const std::vector< std::pair< std::reference_wrapper< const common::IndexMap >, int > > &maps)
Copy blocks from Vec into local arrays.
Definition petsc.cpp:132
Vec create_vector(const common::IndexMap &map, int bs)
Create a ghosted PETSc Vec.
Definition petsc.cpp:47
Linear algebra interface.
Definition dolfinx_la.h:7
dolfinx::la::MatrixCSR< T > transpose(const dolfinx::la::MatrixCSR< T > &A)
Compute the distributed transpose of a MatrixCSR.
Definition mattrans.h:128