DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
petsc.h
1// Copyright (C) 2004-2018 Johan Hoffman, Johan Jansson, Anders Logg and
2// Garth N. Wells
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 <format>
16#include <functional>
17#include <optional>
18#include <petscksp.h>
19#include <petscmat.h>
20#include <petscoptions.h>
21#include <petscvec.h>
22#include <span>
23#include <string>
24#include <string_view>
25#include <vector>
26
27namespace dolfinx::common
28{
29class IndexMap;
30} // namespace dolfinx::common
31
32namespace dolfinx::la
33{
34class SparsityPattern;
35enum class Norm : std::int8_t;
36
38namespace petsc
39{
41void error(PetscErrorCode error_code, std::string_view filename,
42 std::string_view petsc_function);
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
71Vec create_vector(MPI_Comm comm, std::array<std::int64_t, 2> range,
72 std::span<const std::int64_t> ghosts, int bs);
73
84Vec create_vector_wrap(const common::IndexMap& map, int bs,
85 std::span<const PetscScalar> x);
86
90template <class V>
92{
93 assert(x.index_map());
94 return create_vector_wrap(*x.index_map(), x.bs(), x.array());
95}
96
109std::vector<IS> create_index_sets(
110 const std::vector<
111 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
112
114std::vector<std::vector<PetscScalar>> get_local_vectors(
115 const Vec x,
116 const std::vector<
117 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
118
121 Vec x, const std::vector<std::span<const PetscScalar>>& x_b,
122 const std::vector<
123 std::pair<std::reference_wrapper<const common::IndexMap>, int>>& maps);
124
132Mat create_matrix(MPI_Comm comm, const SparsityPattern& sp,
133 std::optional<std::string_view> type = std::nullopt);
134
140MatNullSpace create_nullspace(MPI_Comm comm, std::span<const Vec> basis);
141
147namespace options
148{
150void set(std::string option);
151
153template <typename T>
154 requires requires(const T& value) { std::format("{}", value); }
155void set(std::string option, const T& value)
156{
157 if (option[0] != '-')
158 option = '-' + option;
159
160 PetscErrorCode ierr;
161 ierr = PetscOptionsSetValue(nullptr, option.c_str(),
162 std::format("{}", value).c_str());
163 if (ierr != 0)
164 petsc::error(ierr, __FILE__, "PetscOptionsSetValue");
165}
166
168void clear(std::string option);
169
171void clear();
172} // namespace options
173
180{
181public:
186 Vector(const common::IndexMap& map, int bs);
187
188 // Delete copy constructor to avoid accidental copying of 'heavy' data
189 Vector(const Vector& x) = delete;
190
192 Vector(Vector&& x) noexcept;
193
205 Vector(Vec x, bool inc_ref_count);
206
208 virtual ~Vector();
209
210 // Assignment operator (disabled)
211 Vector& operator=(const Vector& x) = delete;
212
214 Vector& operator=(Vector&& x) noexcept;
215
218 Vector copy() const;
219
221 std::int64_t size() const;
222
224 std::int32_t local_size() const;
225
227 std::array<std::int64_t, 2> local_range() const;
228
230 MPI_Comm comm() const;
231
233 void set_options_prefix(std::string_view options_prefix);
234
237 std::string get_options_prefix() const;
238
240 void set_from_options();
241
243 Vec vec() const;
244
245private:
246 // PETSc Vec pointer
247 Vec _x;
248};
249
253{
254public:
256 Operator(Mat A, bool inc_ref_count);
257
258 // Copy constructor (deleted)
259 Operator(const Operator& A) = delete;
260
262 Operator(Operator&& A) noexcept;
263
265 virtual ~Operator();
266
268 Operator& operator=(const Operator& A) = delete;
269
271 Operator& operator=(Operator&& A) noexcept;
272
275 std::array<std::int64_t, 2> size() const;
276
282 Vec create_vector(std::size_t dim) const;
283
285 Mat mat() const;
286
287protected:
288 // PETSc Mat pointer
289 Mat _matA;
290};
291
297class Matrix : public Operator
298{
299public:
304 static auto set_fn(Mat A, InsertMode mode)
305 {
306 return [A, mode, cache = std::vector<PetscInt>()](
307 std::span<const std::int32_t> rows,
308 std::span<const std::int32_t> cols,
309 std::span<const PetscScalar> vals) mutable -> int
310 {
311 PetscErrorCode ierr;
312#ifdef PETSC_USE_64BIT_INDICES
313 cache.resize(rows.size() + cols.size());
314 std::ranges::copy(rows, cache.begin());
315 std::ranges::copy(cols, std::next(cache.begin(), rows.size()));
316 const PetscInt* _rows = cache.data();
317 const PetscInt* _cols = cache.data() + rows.size();
318 ierr = MatSetValuesLocal(A, rows.size(), _rows, cols.size(), _cols,
319 vals.data(), mode);
320#else
321 ierr = MatSetValuesLocal(A, rows.size(), rows.data(), cols.size(),
322 cols.data(), vals.data(), mode);
323#endif
324
325#ifndef NDEBUG
326 if (ierr != 0)
327 petsc::error(ierr, __FILE__, "MatSetValuesLocal");
328#endif
329 return ierr;
330 };
331 }
332
338 static auto set_block_fn(Mat A, InsertMode mode)
339 {
340 return [A, mode, cache = std::vector<PetscInt>()](
341 std::span<const std::int32_t> rows,
342 std::span<const std::int32_t> cols,
343 std::span<const PetscScalar> vals) mutable -> int
344 {
345 PetscErrorCode ierr;
346#ifdef PETSC_USE_64BIT_INDICES
347 cache.resize(rows.size() + cols.size());
348 std::ranges::copy(rows, cache.begin());
349 std::ranges::copy(cols, std::next(cache.begin(), rows.size()));
350 const PetscInt* _rows = cache.data();
351 const PetscInt* _cols = cache.data() + rows.size();
352 ierr = MatSetValuesBlockedLocal(A, rows.size(), _rows, cols.size(), _cols,
353 vals.data(), mode);
354#else
355 ierr = MatSetValuesBlockedLocal(A, rows.size(), rows.data(), cols.size(),
356 cols.data(), vals.data(), mode);
357#endif
358
359#ifndef NDEBUG
360 if (ierr != 0)
361 petsc::error(ierr, __FILE__, "MatSetValuesBlockedLocal");
362#endif
363 return ierr;
364 };
365 }
366
375 static auto set_block_expand_fn(Mat A, int bs0, int bs1, InsertMode mode)
376 {
377 return [A, bs0, bs1, mode, cache0 = std::vector<PetscInt>(),
378 cache1 = std::vector<PetscInt>()](
379 std::span<const std::int32_t> rows,
380 std::span<const std::int32_t> cols,
381 std::span<const PetscScalar> vals) mutable -> int
382 {
383 PetscErrorCode ierr;
384 cache0.resize(bs0 * rows.size());
385 cache1.resize(bs1 * cols.size());
386 for (std::size_t i = 0; i < rows.size(); ++i)
387 for (int k = 0; k < bs0; ++k)
388 cache0[bs0 * i + k] = bs0 * rows[i] + k;
389
390 for (std::size_t i = 0; i < cols.size(); ++i)
391 for (int k = 0; k < bs1; ++k)
392 cache1[bs1 * i + k] = bs1 * cols[i] + k;
393
394 ierr = MatSetValuesLocal(A, cache0.size(), cache0.data(), cache1.size(),
395 cache1.data(), vals.data(), mode);
396#ifndef NDEBUG
397 if (ierr != 0)
398 petsc::error(ierr, __FILE__, "MatSetValuesLocal");
399#endif
400 return ierr;
401 };
402 }
403
405 Matrix(MPI_Comm comm, const SparsityPattern& sp,
406 std::optional<std::string_view> type = std::nullopt);
407
412 Matrix(Mat A, bool inc_ref_count);
413
414 // Copy constructor (deleted)
415 Matrix(const Matrix& A) = delete;
416
418 Matrix(Matrix&& A) = default;
419
421 ~Matrix() = default;
422
424 Matrix& operator=(const Matrix& A) = delete;
425
427 Matrix& operator=(Matrix&& A) = default;
428
432 enum class AssemblyType : std::int8_t
433 {
434 FINAL,
435 FLUSH
436 };
437
443 void apply(AssemblyType type);
444
446 double norm(Norm norm_type) const;
447
448 //--- Special PETSc Functions ---
449
452 void set_options_prefix(std::string_view options_prefix);
453
456 std::string get_options_prefix() const;
457
459 void set_from_options();
460};
461
465{
466public:
469 explicit KrylovSolver(MPI_Comm comm);
470
474 KrylovSolver(KSP ksp, bool inc_ref_count);
475
476 // Copy constructor (deleted)
477 KrylovSolver(const KrylovSolver& solver) = delete;
478
480 KrylovSolver(KrylovSolver&& solver) noexcept;
481
484
485 // Assignment operator (deleted)
486 KrylovSolver& operator=(const KrylovSolver&) = delete;
487
489 KrylovSolver& operator=(KrylovSolver&& solver) noexcept;
490
492 void set_operator(const Mat A);
493
495 void set_operators(const Mat A, const Mat P);
496
501 int solve(Vec x, const Vec b, bool transpose = false) const;
502
505 void set_options_prefix(std::string_view options_prefix);
506
509 std::string get_options_prefix() const;
510
512 void set_from_options() const;
513
515 KSP ksp() const;
516
517private:
518 // PETSc solver pointer
519 KSP _ksp;
520};
521} // namespace petsc
522} // namespace dolfinx::la
523
524#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:728
KSP ksp() const
Return PETSc KSP pointer.
Definition petsc.cpp:825
std::string get_options_prefix() const
Definition petsc.cpp:807
void set_options_prefix(std::string_view options_prefix)
Definition petsc.cpp:797
void set_operators(const Mat A, const Mat P)
Set operator and preconditioner matrix (Mat).
Definition petsc.cpp:730
KrylovSolver(MPI_Comm comm)
Definition petsc.cpp:690
void set_from_options() const
Set options from PETSc options database.
Definition petsc.cpp:817
~KrylovSolver()
Destructor.
Definition petsc.cpp:715
int solve(Vec x, const Vec b, bool transpose=false) const
Definition petsc.cpp:739
Definition petsc.h:298
static auto set_block_fn(Mat A, InsertMode mode)
Definition petsc.h:338
void set_from_options()
Call PETSc function MatSetFromOptions on the PETSc Mat object.
Definition petsc.cpp:683
double norm(Norm norm_type) const
Return norm of matrix.
Definition petsc.cpp:627
static auto set_fn(Mat A, InsertMode mode)
Definition petsc.h:304
Matrix(Matrix &&A)=default
Move constructor (falls through to base class move constructor).
std::string get_options_prefix() const
Definition petsc.cpp:675
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:615
Matrix & operator=(Matrix &&A)=default
Move assignment operator.
static auto set_block_expand_fn(Mat A, int bs0, int bs1, InsertMode mode)
Definition petsc.h:375
~Matrix()=default
Destructor.
void set_options_prefix(std::string_view options_prefix)
Definition petsc.cpp:669
AssemblyType
Definition petsc.h:433
Matrix & operator=(const Matrix &A)=delete
Assignment operator (deleted).
void apply(AssemblyType type)
Definition petsc.cpp:652
std::array< std::int64_t, 2 > size() const
Definition petsc.cpp:573
Operator & operator=(const Operator &A)=delete
Assignment operator (deleted).
Operator(Mat A, bool inc_ref_count)
Constructor.
Definition petsc.cpp:547
Vec create_vector(std::size_t dim) const
Definition petsc.cpp:583
Mat mat() const
Return PETSc Mat pointer.
Definition petsc.cpp:612
virtual ~Operator()
Destructor.
Definition petsc.cpp:559
void set_from_options()
Call PETSc function VecSetFromOptions on the underlying Vec object.
Definition petsc.cpp:537
std::int64_t size() const
Return global size of the vector.
Definition petsc.cpp:483
std::string get_options_prefix() const
Definition petsc.cpp:528
Vector copy() const
Definition petsc.cpp:473
void set_options_prefix(std::string_view options_prefix)
Sets the prefix used by PETSc when searching the options database.
Definition petsc.cpp:520
virtual ~Vector()
Destructor.
Definition petsc.cpp:461
Vector(const common::IndexMap &map, int bs)
Definition petsc.cpp:446
MPI_Comm comm() const
Return MPI communicator.
Definition petsc.cpp:511
std::array< std::int64_t, 2 > local_range() const
Return ownership range for calling rank.
Definition petsc.cpp:501
std::int32_t local_size() const
Return local size of vector (belonging to the call rank).
Definition petsc.cpp:492
Vec vec() const
Return pointer to PETSc Vec object.
Definition petsc.cpp:544
Miscellaneous classes, functions and types.
Definition dolfinx_common.h:8
Definition petsc.h:148
void clear()
Clear PETSc global options database.
Definition petsc.cpp:438
void set(std::string option)
Set PETSc option that takes no value.
Definition petsc.cpp:422
PETSc linear algebra functions.
Definition petsc.h:39
Vec create_vector_wrap(const common::IndexMap &map, int bs, std::span< const PetscScalar > x)
Definition petsc.cpp:110
MatNullSpace create_nullspace(MPI_Comm comm, std::span< const Vec > basis)
Definition petsc.cpp:410
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:212
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:143
std::vector< Vec > create_vectors(MPI_Comm comm, const std::vector< std::span< const PetscScalar > > &x)
Definition petsc.cpp:56
Mat create_matrix(MPI_Comm comm, const SparsityPattern &sp, std::optional< std::string_view > type=std::nullopt)
Definition petsc.cpp:260
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:163
void error(PetscErrorCode error_code, std::string_view filename, std::string_view petsc_function)
Print error message for PETSc calls that return an error.
Definition petsc.cpp:38
Vec create_vector(const common::IndexMap &map, int bs)
Definition petsc.cpp:76
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
Norm
Norm types.
Definition utils.h:17