Vulpes  0.1.0
Versatile and parallel compUtational Library for high-order discontinuous Polytopal Element Simulations
Loading...
Searching...
No Matches
sparse_matrix.hpp
Go to the documentation of this file.
1// ----------------------------------------------------------------------
2//
3// Copyright (C) 2024 - 2026 by the Vulpes authors.
4// This file is part of Vulpes.
5//
6// Vulpes is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// Vulpes is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14// General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Vulpes. If not, see <http://www.gnu.org/licenses/>.
18//
19// ----------------------------------------------------------------------
20
21// Author: Francesco Daniele <francesco.daniele@polimi.it>
22// Author: Matteo Caldana <matteo.caldana@polimi.it>
23// Author: Nicola De March <nicola.demarch@polimi.it>
24// Author: Pedro Peixoto <ppeixoto@usp.br>
25
26#ifndef VULPES_LA_SPARSE_MATRIX_HPP_
27#define VULPES_LA_SPARSE_MATRIX_HPP_
28
29#include <petscmat.h>
30#include <petscsys.h>
31
32#include <cstddef>
33#include <iostream>
34#include <memory>
35#include <string>
36#include <utility>
37#include <vector>
38
39#include <Eigen/Dense>
40
43#include "vulpes/la/vector.hpp"
46
47namespace vulpes {
48namespace la {
49
51
53 static_assert(std::is_same_v<double, PetscScalar>);
54
55 public:
57
68 template <typename DofHandler>
69 explicit SparseMatrix(
70 const DofHandler& dof_handler,
71 Type type = Plain,
72 PetscInt block_size = 1,
73 PetscInt aij_block_size = 1) {
74 static_assert(std::is_same_v<typename DofHandler::index_t, PetscInt>);
75 init(dof_handler, type, block_size, aij_block_size);
76 }
77
81 SparseMatrix(const SparseMatrix& other, MatDuplicateOption duplicate_options);
86 SparseMatrix(PetscInt loc_size, PetscInt glob_size, Type type = Plain);
87
88 SparseMatrix& operator=(const SparseMatrix& other) = delete;
89 SparseMatrix(const SparseMatrix&) = delete;
92
102 template <typename DofHandler>
103 void init(
104 const DofHandler& dof_handler,
105 Type type = Plain,
106 PetscInt block_size = 1,
107 PetscInt aij_block_size = 1) {
108 PetscCheckAbort(
109 block_size == 1 || type == Block, PETSC_COMM_WORLD,
110 PETSC_ERR_ARG_INCOMP,
111 "block size != 1 available only with block type matrices");
112 createMatrix(type);
113
114 const PetscInt n_glob = dof_handler.ndofsGlobal();
115 PetscInt dof_begin = 0;
116 PetscInt dof_end = n_glob;
117 if constexpr (DofHandler::parallel) {
118 dof_begin = dof_handler.dofOffset()[mpi::rank()];
119 dof_end = dof_handler.dofOffset()[mpi::rank() + 1];
120 }
121 const PetscInt n_loc = dof_end - dof_begin;
122 // TODO: check not too imbalanced
123 if (type == Block) {
124 PetscCallAbortWorld(MatSetBlockSize(m_petsc_matrix, block_size));
125 }
126 if (aij_block_size != 1) {
127 // n_loc differs between ranks: reduce the check so that all the ranks
128 // abort together instead of hanging in MatSetSizes
129 int bad =
130 aij_block_size < 1 || type == Block || n_loc % aij_block_size != 0;
131 MPI_Allreduce(MPI_IN_PLACE, &bad, 1, MPI_INT, MPI_LOR, PETSC_COMM_WORLD);
132 if (bad) {
133 pcout << "ERROR: aij_block_size must be positive, divide the local "
134 << "number of rows on every rank and is not available with "
135 << "Block type matrices" << std::endl;
136 MPI_Abort(PETSC_COMM_WORLD, -1);
137 }
138 // must be set before the sizes: the block size of a layout cannot be
139 // changed once it is set up
141 MatSetBlockSizes(m_petsc_matrix, aij_block_size, aij_block_size));
142 }
143 setMatrixSizes(n_loc * block_size, n_glob * block_size);
144
145 if (DofHandler::parallel && (!dof_handler.hasRenumbering())) {
146 // if we do not have MPI renumbering, we do not know the sparsity pattern
147 pcout << "WARNING: SparseMatrix without renumberMpiSubdomainWise() is "
148 "not preallocated, assembly will be slow"
149 << std::endl;
150 return;
151 }
152 std::vector<PetscInt> dnn(n_loc, 0), onn(n_loc, 0);
153 computePreallocationData(dof_handler, dof_begin, dof_end, dnn, onn);
154 allocateMatrix(type, dnn, onn, block_size);
155 }
156
158 void compress();
159
161 void zero();
162
164 void print() const;
165
170 void save(
171 const std::string& filename,
172 const std::string& matname = "",
173 PetscViewerFormat format = PETSC_VIEWER_ASCII_MATLAB) const;
174
178 void saveBinary(
179 const std::string& filename, const std::string& matname = "") const;
180
182 std::array<PetscInt, 2> getSize() const;
183
185 PetscInt getBlockSize() const;
186
188 void copy(
189 const la::SparseMatrix& src,
190 MatStructure str = DIFFERENT_NONZERO_PATTERN);
191
193 void insertValue(
194 PetscScalar value, PetscInt i, PetscInt j, InsertMode mode = ADD_VALUES);
195
207 void insertValues(
208 const PetscScalar* loc_mat,
209 const PetscInt* idxs_row,
210 const PetscInt* idxs_col,
211 PetscInt n_loc,
212 DataLayout orientation = ColumnMajor,
213 InsertMode mode = ADD_VALUES);
214
224 void insertValues(
225 const Eigen::Ref<const Eigen::MatrixXd>& loc_mat,
227 idxs_row_col,
228 DataLayout orientation = ColumnMajor,
229 InsertMode mode = ADD_VALUES);
230
241 void insertValues(
242 const Eigen::Ref<const Eigen::MatrixXd>& loc_mat,
245 DataLayout orientation = ColumnMajor,
246 InsertMode mode = ADD_VALUES);
247
261 const PetscScalar* loc_mat,
262 const PetscInt* idxs_row,
263 const PetscInt* idxs_col,
264 PetscInt n_loc,
265 DataLayout orientation = ColumnMajor,
266 InsertMode mode = ADD_VALUES);
267
279 const Eigen::Ref<const Eigen::MatrixXd>& loc_mat,
281 idxs_row_col,
282 DataLayout orientation = ColumnMajor,
283 InsertMode mode = ADD_VALUES);
284
297 const Eigen::Ref<const Eigen::MatrixXd>& loc_mat,
300 DataLayout orientation = ColumnMajor,
301 InsertMode mode = ADD_VALUES);
302
305 Eigen::MatrixXd toEigenDense() const;
307 const auto& getPetscMatrix() const { return m_petsc_matrix; }
309 auto& getPetscMatrix() { return m_petsc_matrix; }
311 std::pair<PetscInt, PetscInt> getMatrixSizes() const;
312
314 PetscReal norm(NormType normType = NORM_FROBENIUS) const;
315 void vmult(const Vector& in, Vector& out) const;
316 void vmultT(const Vector& in, Vector& out) const;
317 void vmultAdd(const Vector& in_mult, const Vector& in_add, Vector& out) const;
318 void vmultTAdd(
319 const Vector& in_mult, const Vector& in_add, Vector& out) const;
320
321 // Matrix products C = A B, C = A B^T, C = A^T B. MAT_INITIAL_MATRIX
322 // replaces the matrix held by C, which may be A or B; MAT_REUSE_MATRIX needs
323 // C from a previous call of the same product
324 void matMult(
325 const SparseMatrix& B,
326 SparseMatrix& C,
327 MatReuse reuse = MAT_INITIAL_MATRIX,
328 PetscReal fill = PETSC_DETERMINE) const;
329 void matMultTranspose(
330 const SparseMatrix& B,
331 SparseMatrix& C,
332 MatReuse reuse = MAT_INITIAL_MATRIX,
333 PetscReal fill = PETSC_DETERMINE) const;
334 void transposeMatMult(
335 const SparseMatrix& B,
336 SparseMatrix& C,
337 MatReuse reuse = MAT_INITIAL_MATRIX,
338 PetscReal fill = PETSC_DETERMINE) const;
339
340 // Add a method to perform MatAXPY
341 void addScaledMatrix(
342 const SparseMatrix& other,
343 PetscScalar scale,
344 MatStructure str = UNKNOWN_NONZERO_PATTERN);
345
347 void scale(PetscScalar value);
348
359 void pinDof(PetscInt dof_idx, PetscScalar value = 1.0);
360
366 void setNearNullSpace(const Vector& v);
367
375 static bool compareSparseMatrices(
376 const SparseMatrix& mat1,
377 const SparseMatrix& mat2,
378 double tolerance = 1e-12);
379
381
382 protected:
383 // Protected constructor for wrapping an existing PETSc matrix
384 explicit SparseMatrix(Mat existing_matrix)
385 : m_petsc_matrix(existing_matrix) {}
386 // Matrix creation and setup methods
387 void createMatrix(Type type);
388
389 void setMatrixSizes(const PetscInt n_loc, const PetscInt n_glob);
390
391 template <typename DofHandler>
393 const DofHandler& dof_handler,
394 const PetscInt dof_begin,
395 const PetscInt dof_end,
396 std::vector<PetscInt>& dnn,
397 std::vector<PetscInt>& onn) {
398 for (auto dof_id = dof_begin; dof_id < dof_end; ++dof_id) {
399 // assert that the key is in the map
400 auto loc_dof_id = dof_id;
401 if (DofHandler::parallel) {
402 loc_dof_id = dof_handler.getCurrToRefNumbering().at(dof_id);
403 }
404 const auto sp_row = dof_handler.getSparsityPattern()[loc_dof_id];
405 for (const auto glob_dof_nz : sp_row) {
406 if (dof_begin <= glob_dof_nz && glob_dof_nz < dof_end) {
407 dnn[dof_id - dof_begin]++;
408 } else {
409 onn[dof_id - dof_begin]++;
410 }
411 }
412 }
413 }
414
415 void allocateMatrix(
416 Type type,
417 const std::vector<PetscInt>& dnn,
418 const std::vector<PetscInt>& onn,
419 PetscInt block_size);
420
422};
423
424} // namespace la
425} // namespace vulpes
426
427#endif // VULPES_LA_SPARSE_MATRIX_HPP_
Definition sparse_matrix.hpp:52
void transposeMatMult(const SparseMatrix &B, SparseMatrix &C, MatReuse reuse=MAT_INITIAL_MATRIX, PetscReal fill=PETSC_DETERMINE) const
Definition sparse_matrix.cpp:435
void scale(PetscScalar value)
Multiply all entries by a scalar, in place.
Definition sparse_matrix.cpp:454
static bool compareSparseMatrices(const SparseMatrix &mat1, const SparseMatrix &mat2, double tolerance=1e-12)
Static function that compares two sparse matrices for equality within a given tolerance.
Definition sparse_matrix.cpp:480
void allocateMatrix(Type type, const std::vector< PetscInt > &dnn, const std::vector< PetscInt > &onn, PetscInt block_size)
Definition sparse_matrix.cpp:80
void insertValuesBlocked(const PetscScalar *loc_mat, const PetscInt *idxs_row, const PetscInt *idxs_col, PetscInt n_loc, DataLayout orientation=ColumnMajor, InsertMode mode=ADD_VALUES)
Insert a blocked sub matrix into the matrix.
Definition sparse_matrix.cpp:294
SparseMatrix & operator=(SparseMatrix &&)=delete
Eigen::MatrixXd toEigenDense() const
Definition sparse_matrix.cpp:335
Mat m_petsc_matrix
Definition sparse_matrix.hpp:421
void setNearNullSpace(const Vector &v)
Attach a near null space to the matrix, used by algebraic multigrid preconditioners (e....
Definition sparse_matrix.cpp:458
PetscReal norm(NormType normType=NORM_FROBENIUS) const
Get the norm of the matrix.
Definition sparse_matrix.cpp:177
void createMatrix(Type type)
Definition sparse_matrix.cpp:49
std::pair< PetscInt, PetscInt > getMatrixSizes() const
Get the local and global sizes of the matrix.
Definition sparse_matrix.cpp:364
SparseMatrix(const SparseMatrix &)=delete
Type
Definition sparse_matrix.hpp:56
@ Plain
Definition sparse_matrix.hpp:56
@ Vectorized
Definition sparse_matrix.hpp:56
@ Block
Definition sparse_matrix.hpp:56
@ IntelMKL
Definition sparse_matrix.hpp:56
@ AcceleratedSIMD
Definition sparse_matrix.hpp:56
PetscInt getBlockSize() const
Get the block size of the matrix.
Definition sparse_matrix.cpp:189
void compress()
Finalize the assembly of the matrix by doing intracommunication.
Definition sparse_matrix.cpp:118
const auto & getPetscMatrix() const
Get the underlying PETSc matrix.
Definition sparse_matrix.hpp:307
SparseMatrix(const DofHandler &dof_handler, Type type=Plain, PetscInt block_size=1, PetscInt aij_block_size=1)
Construct a SparseMatrix based on a DofHandler's sparsity pattern.
Definition sparse_matrix.hpp:69
void matMult(const SparseMatrix &B, SparseMatrix &C, MatReuse reuse=MAT_INITIAL_MATRIX, PetscReal fill=PETSC_DETERMINE) const
Definition sparse_matrix.cpp:415
void copy(const la::SparseMatrix &src, MatStructure str=DIFFERENT_NONZERO_PATTERN)
Copy the contents of another SparseMatrix into this one.
Definition sparse_matrix.cpp:195
void addScaledMatrix(const SparseMatrix &other, PetscScalar scale, MatStructure str=UNKNOWN_NONZERO_PATTERN)
Definition sparse_matrix.cpp:445
void save(const std::string &filename, const std::string &matname="", PetscViewerFormat format=PETSC_VIEWER_ASCII_MATLAB) const
Save the matrix to a file.
Definition sparse_matrix.cpp:132
~SparseMatrix()
Definition sparse_matrix.cpp:516
std::array< PetscInt, 2 > getSize() const
Get the size of the matrix as an array [rows, cols].
Definition sparse_matrix.cpp:183
void insertValues(const PetscScalar *loc_mat, const PetscInt *idxs_row, const PetscInt *idxs_col, PetscInt n_loc, DataLayout orientation=ColumnMajor, InsertMode mode=ADD_VALUES)
Insert a sub matrix into the matrix.
Definition sparse_matrix.cpp:270
void print() const
Print the matrix to standard output.
Definition sparse_matrix.cpp:123
SparseMatrix & operator=(const SparseMatrix &other)=delete
void computePreallocationData(const DofHandler &dof_handler, const PetscInt dof_begin, const PetscInt dof_end, std::vector< PetscInt > &dnn, std::vector< PetscInt > &onn)
Definition sparse_matrix.hpp:392
void saveBinary(const std::string &filename, const std::string &matname="") const
Save the matrix to a file in binary format.
Definition sparse_matrix.cpp:159
void insertValue(PetscScalar value, PetscInt i, PetscInt j, InsertMode mode=ADD_VALUES)
Insert a single value into the matrix.
Definition sparse_matrix.cpp:203
void pinDof(PetscInt dof_idx, PetscScalar value=1.0)
Pin a degree of freedom to enforce a constraint This performs symmetric elimination: sets row and col...
Definition sparse_matrix.cpp:472
void vmultTAdd(const Vector &in_mult, const Vector &in_add, Vector &out) const
Definition sparse_matrix.cpp:385
void vmultAdd(const Vector &in_mult, const Vector &in_add, Vector &out) const
Definition sparse_matrix.cpp:379
void vmult(const Vector &in, Vector &out) const
Definition sparse_matrix.cpp:371
void setMatrixSizes(const PetscInt n_loc, const PetscInt n_glob)
Definition sparse_matrix.cpp:75
SparseMatrix(SparseMatrix &&)=delete
void init(const DofHandler &dof_handler, Type type=Plain, PetscInt block_size=1, PetscInt aij_block_size=1)
Initialize the SparseMatrix based on a DofHandler's sparsity pattern.
Definition sparse_matrix.hpp:103
auto & getPetscMatrix()
Get the underlying PETSc matrix (non-const).
Definition sparse_matrix.hpp:309
void matMultTranspose(const SparseMatrix &B, SparseMatrix &C, MatReuse reuse=MAT_INITIAL_MATRIX, PetscReal fill=PETSC_DETERMINE) const
Definition sparse_matrix.cpp:425
void zero()
Set all entries to zero, keeping the nonzero pattern.
Definition sparse_matrix.cpp:199
SparseMatrix(Mat existing_matrix)
Definition sparse_matrix.hpp:384
void vmultT(const Vector &in, Vector &out) const
Definition sparse_matrix.cpp:375
A wrapper around PETSc Vec for distributed vectors.
Definition vector.hpp:54
Definition boomer_amg.hpp:27
DataLayout
Definition sparse_matrix.hpp:50
@ ColumnMajor
Definition sparse_matrix.hpp:50
@ RowMajor
Definition sparse_matrix.hpp:50
static int rank()
Return the MPI rank in MPI_COMM_WORLD.
Definition mpi_wrappers.hpp:116
Definition cell_manager.hpp:38
vulpes::utils::pcout_t & pcout
Definition pcout.hpp:160
#define PetscCallAbortWorld(...)
Definition petsc_utils.hpp:32