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 <algorithm>
14#include <array>
15#include <cassert>
16#include <cstdint>
17#include <dolfinx/common/petsc.h>
18#include <dolfinx/common/types.h>
19#include <functional>
20#include <iterator>
21#include <optional>
22#include <petscksp.h>
23#include <petscmat.h>
24#include <petscvec.h>
25#include <ranges>
26#include <span>
27#include <string>
28#include <string_view>
29#include <utility>
30#include <vector>
31
32namespace dolfinx::common
33{
34class IndexMap;
35} // namespace dolfinx::common
36
37namespace dolfinx::la
38{
39class SparsityPattern;
40
42namespace petsc
43{
52std::vector<Vec>
53create_vectors(MPI_Comm comm,
54 const std::vector<std::span<const PetscScalar>>& x);
55
61Vec create_vector(const common::IndexMap& map, int bs);
62
72Vec create_vector(MPI_Comm comm, std::array<std::int64_t, 2> range,
73 std::span<const std::int64_t> ghosts, int bs);
74
85Vec create_vector_wrap(const common::IndexMap& map, int bs,
86 std::span<const PetscScalar> x);
87
91template <class V>
93{
94 assert(x.index_map());
95 return create_vector_wrap(*x.index_map(), x.bs(), x.array());
96}
97
118std::vector<IS> create_index_sets(
119 const std::vector<
120 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
121
140std::vector<IS> create_global_index_sets(
141 const std::vector<
142 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
143
145std::vector<std::vector<PetscScalar>> get_local_vectors(
146 const Vec x,
147 const std::vector<
148 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
149
152 Vec x, const std::vector<std::span<const PetscScalar>>& x_b,
153 const std::vector<
154 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
155
179Mat create_matrix(MPI_Comm comm, const SparsityPattern& sp,
180 std::optional<std::string_view> type = std::nullopt,
181 std::optional<ISLocalToGlobalMapping> rlgmap = std::nullopt,
182 std::optional<ISLocalToGlobalMapping> clgmap = std::nullopt);
183
189MatNullSpace create_nullspace(MPI_Comm comm, std::span<const Vec> basis);
190
197{
198public:
203 Vector(const common::IndexMap& map, int bs);
204
205 // Delete copy constructor to avoid accidental copying of 'heavy' data
206 Vector(const Vector& x) = delete;
207
209 Vector(Vector&& x) noexcept;
210
222 Vector(Vec x, bool inc_ref_count);
223
225 ~Vector();
226
227 // Assignment operator (disabled)
228 Vector& operator=(const Vector& x) = delete;
229
231 Vector& operator=(Vector&& x) noexcept;
232
235 Vector copy() const;
236
238 std::int64_t size() const;
239
241 std::int32_t local_size() const;
242
244 std::array<std::int64_t, 2> local_range() const;
245
247 MPI_Comm comm() const;
248
250 void set_options_prefix(std::string_view options_prefix);
251
254 std::string get_options_prefix() const;
255
257 void set_from_options();
258
260 Vec vec() const;
261
262private:
263 // PETSc Vec pointer
264 Vec _x;
265};
266
273{
274public:
280 static auto set_fn(Mat A, InsertMode mode)
281 {
282 return [A, mode, cache = std::vector<PetscInt>()](
283 const common::LocalIndexRange auto& rows,
284 const common::LocalIndexRange auto& cols,
285 std::span<const PetscScalar> vals) mutable -> int
286 {
287 PetscErrorCode ierr;
288#ifdef PETSC_USE_64BIT_INDICES
289 cache.resize(std::ranges::size(rows) + std::ranges::size(cols));
290 std::ranges::copy(rows, cache.begin());
291 std::ranges::copy(cols,
292 std::next(cache.begin(), std::ranges::size(rows)));
293 const PetscInt* _rows = cache.data();
294 const PetscInt* _cols = cache.data() + std::ranges::size(rows);
295 ierr = MatSetValuesLocal(A, std::ranges::size(rows), _rows,
296 std::ranges::size(cols), _cols, vals.data(),
297 mode);
298#else
299 ierr = MatSetValuesLocal(A, std::ranges::size(rows),
300 std::ranges::data(rows), std::ranges::size(cols),
301 std::ranges::data(cols), vals.data(), mode);
302#endif
303
304#ifndef NDEBUG
305 common::petsc::check(ierr, "MatSetValuesLocal");
306#endif
307 return ierr;
308 };
309 }
310
316 static auto set_block_fn(Mat A, InsertMode mode)
317 {
318 return [A, mode, cache = std::vector<PetscInt>()](
319 const common::LocalIndexRange auto& rows,
320 const common::LocalIndexRange auto& cols,
321 std::span<const PetscScalar> vals) mutable -> int
322 {
323 PetscErrorCode ierr;
324#ifdef PETSC_USE_64BIT_INDICES
325 cache.resize(std::ranges::size(rows) + std::ranges::size(cols));
326 std::ranges::copy(rows, cache.begin());
327 std::ranges::copy(cols,
328 std::next(cache.begin(), std::ranges::size(rows)));
329 const PetscInt* _rows = cache.data();
330 const PetscInt* _cols = cache.data() + std::ranges::size(rows);
331 ierr = MatSetValuesBlockedLocal(A, std::ranges::size(rows), _rows,
332 std::ranges::size(cols), _cols,
333 vals.data(), mode);
334#else
335 ierr = MatSetValuesBlockedLocal(
336 A, std::ranges::size(rows), std::ranges::data(rows),
337 std::ranges::size(cols), std::ranges::data(cols), vals.data(), mode);
338#endif
339
340#ifndef NDEBUG
341 common::petsc::check(ierr, "MatSetValuesBlockedLocal");
342#endif
343 return ierr;
344 };
345 }
346
357 static auto set_block_expand_fn(Mat A, int bs0, int bs1, InsertMode mode)
358 {
359 return [A, bs0, bs1, mode, cache0 = std::vector<PetscInt>(),
360 cache1 = std::vector<PetscInt>()](
361 const common::LocalIndexRange auto& rows,
362 const common::LocalIndexRange auto& cols,
363 std::span<const PetscScalar> vals) mutable -> int
364 {
365 PetscErrorCode ierr;
366 const std::int32_t* _rows = std::ranges::data(rows);
367 const std::int32_t* _cols = std::ranges::data(cols);
368 const std::size_t num_rows = std::ranges::size(rows);
369 const std::size_t num_cols = std::ranges::size(cols);
370 cache0.resize(bs0 * num_rows);
371 cache1.resize(bs1 * num_cols);
372 for (std::size_t i = 0; i < num_rows; ++i)
373 for (int k = 0; k < bs0; ++k)
374 cache0[bs0 * i + k] = bs0 * _rows[i] + k;
375
376 for (std::size_t i = 0; i < num_cols; ++i)
377 for (int k = 0; k < bs1; ++k)
378 cache1[bs1 * i + k] = bs1 * _cols[i] + k;
379
380 ierr = MatSetValuesLocal(A, cache0.size(), cache0.data(), cache1.size(),
381 cache1.data(), vals.data(), mode);
382#ifndef NDEBUG
383 common::petsc::check(ierr, "MatSetValuesLocal");
384#endif
385 return ierr;
386 };
387 }
388
390 Matrix(MPI_Comm comm, const SparsityPattern& sp,
391 std::optional<std::string_view> type = std::nullopt);
392
400 Matrix(Mat A, bool inc_ref_count);
401
402 // Copy constructor (deleted)
403 Matrix(const Matrix& A) = delete;
404
406 Matrix(Matrix&& A) noexcept;
407
409 ~Matrix();
410
411 // Assignment operator (deleted)
412 Matrix& operator=(const Matrix& A) = delete;
413
415 Matrix& operator=(Matrix&& A) noexcept;
416
419 std::array<std::int64_t, 2> size() const;
420
427 Vec create_vector(std::size_t dim) const;
428
430 Mat mat() const;
431
432 //--- Special PETSc Functions ---
433
436 void set_options_prefix(std::string_view options_prefix);
437
440 std::string get_options_prefix() const;
441
443 void set_from_options();
444
445private:
446 // PETSc Mat pointer
447 Mat _matA;
448};
449
453{
454public:
457 explicit KrylovSolver(MPI_Comm comm);
458
465 KrylovSolver(KSP ksp, bool inc_ref_count);
466
467 // Copy constructor (deleted)
468 KrylovSolver(const KrylovSolver& solver) = delete;
469
471 KrylovSolver(KrylovSolver&& solver) noexcept;
472
475
476 // Assignment operator (deleted)
477 KrylovSolver& operator=(const KrylovSolver&) = delete;
478
480 KrylovSolver& operator=(KrylovSolver&& solver) noexcept;
481
483 void set_operator(const Mat A);
484
486 void set_operators(const Mat A, const Mat P);
487
496 [[nodiscard(
497 "check the converged reason - positive on convergence, negative on "
498 "divergence")]] KSPConvergedReason
499 solve(Vec x, const Vec b, bool transpose = false);
500
503 void set_options_prefix(std::string_view options_prefix);
504
507 std::string get_options_prefix() const;
508
510 void set_from_options() const;
511
513 KSP ksp() const;
514
515private:
516 // PETSc solver pointer
517 KSP _ksp;
518};
519} // namespace petsc
520} // namespace dolfinx::la
521
522#endif
Distribution of a global index range [0, N) across MPI ranks.
Definition IndexMap.h:191
Definition SparsityPattern.h:28
A vector that can be distributed across processes.
Definition Vector.h:53
std::shared_ptr< const common::IndexMap > index_map() const noexcept
Get IndexMap.
Definition Vector.h:465
constexpr int bs() const noexcept
Get block size.
Definition Vector.h:479
container_type & array() noexcept
Get the process-local part of the vector.
Definition Vector.h:484
void set_operator(const Mat A)
Set operator (Mat).
Definition petsc.cpp:672
KSP ksp() const
Return PETSc KSP pointer.
Definition petsc.cpp:746
std::string get_options_prefix() const
Definition petsc.cpp:731
void set_options_prefix(std::string_view options_prefix)
Definition petsc.cpp:722
void set_operators(const Mat A, const Mat P)
Set operator and preconditioner matrix (Mat).
Definition petsc.cpp:674
KrylovSolver(MPI_Comm comm)
Create a Krylov solver.
Definition petsc.cpp:631
void set_from_options() const
Set options from PETSc options database.
Definition petsc.cpp:740
~KrylovSolver()
Destructor.
Definition petsc.cpp:657
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:681
Definition petsc.h:273
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:316
~Matrix()
Destructor.
Definition petsc.cpp:562
void set_from_options()
Call PETSc function MatSetFromOptions on the PETSc Mat object.
Definition petsc.cpp:624
std::array< std::int64_t, 2 > size() const
Definition petsc.cpp:577
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:280
std::string get_options_prefix() const
Definition petsc.cpp:615
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:535
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:585
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:357
void set_options_prefix(std::string_view options_prefix)
Definition petsc.cpp:607
Mat mat() const
Return PETSc Mat pointer.
Definition petsc.cpp:605
void set_from_options()
Call PETSc function VecSetFromOptions on the underlying Vec object.
Definition petsc.cpp:526
std::int64_t size() const
Return global size of the vector.
Definition petsc.cpp:475
std::string get_options_prefix() const
Definition petsc.cpp:518
Vector copy() const
Create a copy of the vector.
Definition petsc.cpp:467
void set_options_prefix(std::string_view options_prefix)
Sets the prefix used by PETSc when searching the options database.
Definition petsc.cpp:510
~Vector()
Destructor.
Definition petsc.cpp:453
Vector(const common::IndexMap &map, int bs)
Create a vector.
Definition petsc.cpp:430
MPI_Comm comm() const
Return MPI communicator.
Definition petsc.cpp:501
std::array< std::int64_t, 2 > local_range() const
Return ownership range for calling rank.
Definition petsc.cpp:491
std::int32_t local_size() const
Return local size of vector (belonging to the call rank).
Definition petsc.cpp:483
Vec vec() const
Return pointer to PETSc Vec object.
Definition petsc.cpp:532
Concept for a contiguous list of process-local indices, e.g. the row or column indices passed to a ma...
Definition types.h:75
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:43
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:81
MatNullSpace create_nullspace(MPI_Comm comm, std::span< const Vec > basis)
Create PETSc MatNullSpace. Caller is responsible for destruction returned object.
Definition petsc.cpp:419
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:218
std::vector< IS > create_index_sets(const std::vector< std::pair< std::reference_wrapper< const common::IndexMap >, int > > &maps)
Index sets addressing a stack of index maps in the calling rank's local numbering.
Definition petsc.cpp:113
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:31
Mat create_matrix(MPI_Comm comm, const SparsityPattern &sp, std::optional< std::string_view > type=std::nullopt, std::optional< ISLocalToGlobalMapping > rlgmap=std::nullopt, std::optional< ISLocalToGlobalMapping > clgmap=std::nullopt)
Create a PETSc Mat. Caller is responsible for destroying the returned object.
Definition petsc.cpp:262
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:172
Vec create_vector(const common::IndexMap &map, int bs)
Create a ghosted PETSc Vec.
Definition petsc.cpp:49
std::vector< IS > create_global_index_sets(const std::vector< std::pair< std::reference_wrapper< const common::IndexMap >, int > > &maps)
Index sets describing each field of a stack of index maps in the global numbering of the stacked prob...
Definition petsc.cpp:133
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:134