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 <cassert>
14#include <cstdint>
15#include <dolfinx/common/petsc.h>
16#include <functional>
17#include <optional>
18#include <petscksp.h>
19#include <petscmat.h>
20#include <petscvec.h>
21#include <span>
22#include <string>
23#include <string_view>
24#include <utility>
25#include <vector>
26
27namespace dolfinx::common
28{
29class IndexMap;
30} // namespace dolfinx::common
31
32namespace dolfinx::la
33{
34class SparsityPattern;
35
37namespace petsc
38{
47std::vector<Vec>
48create_vectors(MPI_Comm comm,
49 const std::vector<std::span<const PetscScalar>>& x);
50
56Vec create_vector(const common::IndexMap& map, int bs);
57
67Vec create_vector(MPI_Comm comm, std::array<std::int64_t, 2> range,
68 std::span<const std::int64_t> ghosts, int bs);
69
80Vec create_vector_wrap(const common::IndexMap& map, int bs,
81 std::span<const PetscScalar> x);
82
86template <class V>
88{
89 assert(x.index_map());
90 return create_vector_wrap(*x.index_map(), x.bs(), x.array());
91}
92
105std::vector<IS> create_index_sets(
106 const std::vector<
107 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
108
110std::vector<std::vector<PetscScalar>> get_local_vectors(
111 const Vec x,
112 const std::vector<
113 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
114
117 Vec x, const std::vector<std::span<const PetscScalar>>& x_b,
118 const std::vector<
119 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
120
128Mat create_matrix(MPI_Comm comm, const SparsityPattern& sp,
129 std::optional<std::string_view> type = std::nullopt);
130
136MatNullSpace create_nullspace(MPI_Comm comm, std::span<const Vec> basis);
137
144{
145public:
150 Vector(const common::IndexMap& map, int bs);
151
152 // Delete copy constructor to avoid accidental copying of 'heavy' data
153 Vector(const Vector& x) = delete;
154
156 Vector(Vector&& x) noexcept;
157
169 Vector(Vec x, bool inc_ref_count);
170
172 virtual ~Vector();
173
174 // Assignment operator (disabled)
175 Vector& operator=(const Vector& x) = delete;
176
178 Vector& operator=(Vector&& x) noexcept;
179
182 Vector copy() const;
183
185 std::int64_t size() const;
186
188 std::int32_t local_size() const;
189
191 std::array<std::int64_t, 2> local_range() const;
192
194 MPI_Comm comm() const;
195
197 void set_options_prefix(std::string_view options_prefix);
198
201 std::string get_options_prefix() const;
202
204 void set_from_options();
205
207 Vec vec() const;
208
209private:
210 // PETSc Vec pointer
211 Vec _x;
212};
213
220{
221public:
227 static auto set_fn(Mat A, InsertMode mode)
228 {
229 return [A, mode, cache = std::vector<PetscInt>()](
230 std::span<const std::int32_t> rows,
231 std::span<const std::int32_t> cols,
232 std::span<const PetscScalar> vals) mutable -> int
233 {
234 PetscErrorCode ierr;
235#ifdef PETSC_USE_64BIT_INDICES
236 cache.resize(rows.size() + cols.size());
237 std::ranges::copy(rows, cache.begin());
238 std::ranges::copy(cols, std::next(cache.begin(), rows.size()));
239 const PetscInt* _rows = cache.data();
240 const PetscInt* _cols = cache.data() + rows.size();
241 ierr = MatSetValuesLocal(A, rows.size(), _rows, cols.size(), _cols,
242 vals.data(), mode);
243#else
244 ierr = MatSetValuesLocal(A, rows.size(), rows.data(), cols.size(),
245 cols.data(), vals.data(), mode);
246#endif
247
248#ifndef NDEBUG
249 common::petsc::check(ierr, "MatSetValuesLocal");
250#endif
251 return ierr;
252 };
253 }
254
260 static auto set_block_fn(Mat A, InsertMode mode)
261 {
262 return [A, mode, cache = std::vector<PetscInt>()](
263 std::span<const std::int32_t> rows,
264 std::span<const std::int32_t> cols,
265 std::span<const PetscScalar> vals) mutable -> int
266 {
267 PetscErrorCode ierr;
268#ifdef PETSC_USE_64BIT_INDICES
269 cache.resize(rows.size() + cols.size());
270 std::ranges::copy(rows, cache.begin());
271 std::ranges::copy(cols, std::next(cache.begin(), rows.size()));
272 const PetscInt* _rows = cache.data();
273 const PetscInt* _cols = cache.data() + rows.size();
274 ierr = MatSetValuesBlockedLocal(A, rows.size(), _rows, cols.size(), _cols,
275 vals.data(), mode);
276#else
277 ierr = MatSetValuesBlockedLocal(A, rows.size(), rows.data(), cols.size(),
278 cols.data(), vals.data(), mode);
279#endif
280
281#ifndef NDEBUG
282 common::petsc::check(ierr, "MatSetValuesBlockedLocal");
283#endif
284 return ierr;
285 };
286 }
287
298 static auto set_block_expand_fn(Mat A, int bs0, int bs1, InsertMode mode)
299 {
300 return [A, bs0, bs1, mode, cache0 = std::vector<PetscInt>(),
301 cache1 = std::vector<PetscInt>()](
302 std::span<const std::int32_t> rows,
303 std::span<const std::int32_t> cols,
304 std::span<const PetscScalar> vals) mutable -> int
305 {
306 PetscErrorCode ierr;
307 cache0.resize(bs0 * rows.size());
308 cache1.resize(bs1 * cols.size());
309 for (std::size_t i = 0; i < rows.size(); ++i)
310 for (int k = 0; k < bs0; ++k)
311 cache0[bs0 * i + k] = bs0 * rows[i] + k;
312
313 for (std::size_t i = 0; i < cols.size(); ++i)
314 for (int k = 0; k < bs1; ++k)
315 cache1[bs1 * i + k] = bs1 * cols[i] + k;
316
317 ierr = MatSetValuesLocal(A, cache0.size(), cache0.data(), cache1.size(),
318 cache1.data(), vals.data(), mode);
319#ifndef NDEBUG
320 common::petsc::check(ierr, "MatSetValuesLocal");
321#endif
322 return ierr;
323 };
324 }
325
327 Matrix(MPI_Comm comm, const SparsityPattern& sp,
328 std::optional<std::string_view> type = std::nullopt);
329
337 Matrix(Mat A, bool inc_ref_count);
338
339 // Copy constructor (deleted)
340 Matrix(const Matrix& A) = delete;
341
343 Matrix(Matrix&& A) noexcept;
344
346 ~Matrix();
347
348 // Assignment operator (deleted)
349 Matrix& operator=(const Matrix& A) = delete;
350
352 Matrix& operator=(Matrix&& A) noexcept;
353
356 std::array<std::int64_t, 2> size() const;
357
364 Vec create_vector(std::size_t dim) const;
365
367 Mat mat() const;
368
369 //--- Special PETSc Functions ---
370
373 void set_options_prefix(std::string_view options_prefix);
374
377 std::string get_options_prefix() const;
378
380 void set_from_options();
381
382private:
383 // PETSc Mat pointer
384 Mat _matA;
385};
386
390{
391public:
394 explicit KrylovSolver(MPI_Comm comm);
395
402 KrylovSolver(KSP ksp, bool inc_ref_count);
403
404 // Copy constructor (deleted)
405 KrylovSolver(const KrylovSolver& solver) = delete;
406
408 KrylovSolver(KrylovSolver&& solver) noexcept;
409
412
413 // Assignment operator (deleted)
414 KrylovSolver& operator=(const KrylovSolver&) = delete;
415
417 KrylovSolver& operator=(KrylovSolver&& solver) noexcept;
418
420 void set_operator(const Mat A);
421
423 void set_operators(const Mat A, const Mat P);
424
433 [[nodiscard(
434 "check the converged reason - positive on convergence, negative on "
435 "divergence")]] KSPConvergedReason
436 solve(Vec x, const Vec b, bool transpose = false);
437
440 void set_options_prefix(std::string_view options_prefix);
441
444 std::string get_options_prefix() const;
445
447 void set_from_options() const;
448
450 KSP ksp() const;
451
452private:
453 // PETSc solver pointer
454 KSP _ksp;
455};
456} // namespace petsc
457} // namespace dolfinx::la
458
459#endif
Definition IndexMap.h:95
Definition SparsityPattern.h:26
A vector that can be distributed across processes.
Definition Vector.h:50
container_type & array()
Get the process-local part of the vector.
Definition Vector.h:390
constexpr int bs() const
Get block size.
Definition Vector.h:385
std::shared_ptr< const common::IndexMap > index_map() const
Get IndexMap.
Definition Vector.h:382
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:220
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:260
~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:227
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:298
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
virtual ~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:38
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