DOLFINx 0.12.0.0
DOLFINx C++
Loading...
Searching...
No Matches
MatrixCSR.h
1// Copyright (C) 2021-2022 Garth N. Wells and Chris N. Richardson
2//
3// This file is part of DOLFINx (https://www.fenicsproject.org)
4//
5// SPDX-License-Identifier: LGPL-3.0-or-later
6
7#pragma once
8
9#include "SparsityPattern.h"
10#include "Vector.h"
11#include "matrix_csr_impl.h"
12#include <algorithm>
13#include <dolfinx/common/IndexMap.h>
14#include <dolfinx/common/MPI.h>
15#include <dolfinx/graph/AdjacencyList.h>
16#include <mpi.h>
17#include <numeric>
18#include <span>
19#include <utility>
20#include <vector>
21
22// Define requirements on sparsity pattern required for MatrixCSR constructor
23// allowing alternative implementations that can provide these essentials.
24template <typename T>
25concept SparsityImplementation = requires(T sp, int i) {
26 { sp.graph() };
27 requires std::forward_iterator<typename decltype(sp.graph().first)::iterator>;
28 requires std::convertible_to<std::int32_t,
29 typename decltype(sp.graph().first)::value_type>;
30 requires std::forward_iterator<
31 typename decltype(sp.graph().second)::iterator>;
32 requires std::convertible_to<
33 std::int64_t, typename decltype(sp.graph().second)::value_type>;
34
35 { sp.block_size(i) } -> std::same_as<int>;
36 {
37 sp.index_map(i)
38 } -> std::same_as<std::shared_ptr<const dolfinx::common::IndexMap>>;
39};
40
41namespace dolfinx::la
42{
44enum class BlockMode : int
45{
46 compact = 0,
51};
52
67template <typename Scalar, typename Container = std::vector<Scalar>,
68 typename ColContainer = std::vector<std::int32_t>,
69 typename RowPtrContainer = std::vector<std::int64_t>>
70class MatrixCSR
71{
72 static_assert(std::is_same_v<typename Container::value_type, Scalar>);
73 static_assert(std::is_integral_v<typename ColContainer::value_type>);
74 static_assert(std::is_integral_v<typename RowPtrContainer::value_type>);
75
76 template <typename, typename, typename, typename>
77 friend class MatrixCSR;
78
79public:
81 using value_type = Scalar;
82
84 using container_type = Container;
85
87 using column_container_type = ColContainer;
88
90 using rowptr_container_type = RowPtrContainer;
91
115 template <int BS0 = 1, int BS1 = 1>
117 {
118 if ((BS0 != _bs[0] and BS0 > 1 and _bs[0] > 1)
119 or (BS1 != _bs[1] and BS1 > 1 and _bs[1] > 1))
120 {
121 throw std::runtime_error(
122 "Cannot insert blocks of different size than matrix block size");
123 }
124
125 return [this](std::span<const std::int32_t> rows,
126 std::span<const std::int32_t> cols,
127 std::span<const value_type> data) -> int
128 {
129 this->set<BS0, BS1>(data, rows, cols);
130 return 0;
131 };
132 }
133
157 template <int BS0 = 1, int BS1 = 1>
159 {
160 if ((BS0 != _bs[0] and BS0 > 1 and _bs[0] > 1)
161 or (BS1 != _bs[1] and BS1 > 1 and _bs[1] > 1))
162 {
163 throw std::runtime_error(
164 "Cannot insert blocks of different size than matrix block size");
165 }
166
167 return [this](std::span<const std::int32_t> rows,
168 std::span<const std::int32_t> cols,
169 std::span<const value_type> data) -> int
170 {
171 this->add<BS0, BS1>(data, rows, cols);
172 return 0;
173 };
174 }
175
199 template <SparsityImplementation T>
200 MatrixCSR(const T& p, BlockMode mode = BlockMode::compact);
201
202 // Copy constructor (deleted). Copying deep-copies the matrix data and
203 // duplicates the communicator, which is collective. Both matrices
204 // would also share ::_request, so a copy taken while a scatter is in
205 // flight would wait on data delivered into the original's buffer.
206 MatrixCSR(const MatrixCSR& A) = delete;
207
212 MatrixCSR(MatrixCSR&& A) = default;
213
215 ~MatrixCSR() = default;
216
217 // Copy assignment (deleted). Same reasons as the copy constructor.
218 MatrixCSR& operator=(const MatrixCSR& A) = delete;
219
224 MatrixCSR& operator=(MatrixCSR&& A) = default;
225
239 template <typename Scalar0, typename Container0, typename ColContainer0,
240 typename RowPtrContainer0>
241 explicit MatrixCSR(
242 const MatrixCSR<Scalar0, Container0, ColContainer0, RowPtrContainer0>& A)
243 : _index_maps(A._index_maps), _block_mode(A.block_mode()),
244 _bs(A.block_size()), _data(A._data.begin(), A._data.end()),
245 _cols(A.cols().begin(), A.cols().end()),
246 _row_ptr(A.row_ptr().begin(), A.row_ptr().end()),
247 _off_diagonal_offset(A.off_diag_offset().begin(),
248 A.off_diag_offset().end()),
249 _comm(A.comm()), _request(MPI_REQUEST_NULL), _unpack_pos(A._unpack_pos),
250 _val_send_disp(A._val_send_disp), _val_recv_disp(A._val_recv_disp),
251 _ghost_row_to_rank(A._ghost_row_to_rank), _finalized(A._finalized)
252 {
253 }
254
259 [[deprecated("Use std::ranges::fill(A.values(), v) instead.")]]
261 {
262 check_not_finalized();
263 std::ranges::fill(_data, x);
264 }
265
282 template <int BS0, int BS1>
283 void set(std::span<const value_type> x, std::span<const std::int32_t> rows,
284 std::span<const std::int32_t> cols)
285 {
286 check_not_finalized();
287 auto set_fn = [](value_type& y, const value_type& x) { y = x; };
288
289 std::int32_t num_rows
290 = _index_maps[0]->size_local() + _index_maps[0]->num_ghosts();
291 assert(x.size() == rows.size() * cols.size() * BS0 * BS1);
292 if (_bs[0] == BS0 and _bs[1] == BS1)
293 {
294 impl::insert_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols, set_fn,
295 num_rows);
296 }
297 else if (_bs[0] == 1 and _bs[1] == 1)
298 {
299 // Set blocked data in a regular CSR matrix (_bs[0]=1, _bs[1]=1)
300 // with correct sparsity
301 impl::insert_blocked_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols,
302 set_fn, num_rows);
303 }
304 else
305 {
306 assert(BS0 == 1 and BS1 == 1);
307 // Set non-blocked data in a blocked CSR matrix (BS0=1, BS1=1)
308 impl::insert_nonblocked_csr(_data, _cols, _row_ptr, x, rows, cols, set_fn,
309 num_rows, _bs[0], _bs[1]);
310 }
311 }
312
328 template <int BS0 = 1, int BS1 = 1>
329 void add(std::span<const value_type> x, std::span<const std::int32_t> rows,
330 std::span<const std::int32_t> cols)
331 {
332 check_not_finalized();
333 auto add_fn = [](value_type& y, const value_type& x) { y += x; };
334
335 assert(x.size() == rows.size() * cols.size() * BS0 * BS1);
336 if (_bs[0] == BS0 and _bs[1] == BS1)
337 {
338 impl::insert_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols, add_fn,
339 _row_ptr.size());
340 }
341 else if (_bs[0] == 1 and _bs[1] == 1)
342 {
343 // Add blocked data to a regular CSR matrix (_bs[0]=1, _bs[1]=1)
344 impl::insert_blocked_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols,
345 add_fn, _row_ptr.size());
346 }
347 else
348 {
349 assert(BS0 == 1 and BS1 == 1);
350 // Add non-blocked data to a blocked CSR matrix (BS0=1, BS1=1)
351 impl::insert_nonblocked_csr(_data, _cols, _row_ptr, x, rows, cols, add_fn,
352 _row_ptr.size(), _bs[0], _bs[1]);
353 }
354 }
355
357 std::int32_t num_owned_rows() const { return _index_maps[0]->size_local(); }
358
360 std::int32_t num_all_rows() const { return _row_ptr.size() - 1; }
361
371 std::vector<value_type> to_dense() const
372 {
373 const std::size_t nrows = num_all_rows();
374 const std::size_t ncols = _index_maps[1]->size_global();
375 std::vector<value_type> A(nrows * ncols * _bs[0] * _bs[1], value_type(0));
376 for (std::size_t r = 0; r < nrows; ++r)
377 {
378 for (std::int32_t j = _row_ptr[r]; j < _row_ptr[r + 1]; ++j)
379 {
380 for (int i0 = 0; i0 < _bs[0]; ++i0)
381 {
382 for (int i1 = 0; i1 < _bs[1]; ++i1)
383 {
384 std::array<std::int32_t, 1> local_col{_cols[j]};
385 std::array<std::int64_t, 1> global_col{0};
386 _index_maps[1]->local_to_global(local_col, global_col);
387 A[(r * _bs[0] + i0) * ncols * _bs[1] + global_col[0] * _bs[1] + i1]
388 = _data[j * _bs[0] * _bs[1] + i0 * _bs[1] + i1];
389 }
390 }
391 }
392 }
393
394 return A;
395 }
396
404 {
407 }
408
419 {
420 check_not_finalized();
421 const std::int32_t local_size0 = _index_maps[0]->size_local();
422 const std::int32_t num_ghosts0 = _index_maps[0]->num_ghosts();
423 const int bs2 = _bs[0] * _bs[1];
424
425 // For each ghost row, pack and send values to send to neighborhood
426 std::vector<int> insert_pos = _val_send_disp;
427 _ghost_value_data.resize(_val_send_disp.back());
428 for (int i = 0; i < num_ghosts0; ++i)
429 {
430 int rank = _ghost_row_to_rank[i];
431
432 // Get position in send buffer to place data to send to this
433 // neighbour
434 std::int32_t val_pos = insert_pos[rank];
435 std::copy(std::next(_data.data(), _row_ptr[local_size0 + i] * bs2),
436 std::next(_data.data(), _row_ptr[local_size0 + i + 1] * bs2),
437 std::next(_ghost_value_data.begin(), val_pos));
438 insert_pos[rank]
439 += bs2 * (_row_ptr[local_size0 + i + 1] - _row_ptr[local_size0 + i]);
440 }
441
442 _ghost_value_data_in.resize(_val_recv_disp.back());
443
444 // Compute data sizes for send and receive from displacements
445 std::vector<int> val_send_count(_val_send_disp.size() - 1);
446 std::adjacent_difference(std::next(_val_send_disp.begin()),
447 _val_send_disp.end(), val_send_count.begin());
448
449 std::vector<int> val_recv_count(_val_recv_disp.size() - 1);
450 std::adjacent_difference(std::next(_val_recv_disp.begin()),
451 _val_recv_disp.end(), val_recv_count.begin());
452
453 int status = MPI_Ineighbor_alltoallv(
454 _ghost_value_data.data(), val_send_count.data(), _val_send_disp.data(),
455 dolfinx::MPI::mpi_t<value_type>, _ghost_value_data_in.data(),
456 val_recv_count.data(), _val_recv_disp.data(),
457 dolfinx::MPI::mpi_t<value_type>, _comm.comm(), &_request);
458 dolfinx::MPI::check_error(_comm.comm(), status);
459 }
460
467 {
468 check_not_finalized();
469 int status = MPI_Wait(&_request, MPI_STATUS_IGNORE);
470 dolfinx::MPI::check_error(_comm.comm(), status);
471
472 _ghost_value_data.clear();
473 _ghost_value_data.shrink_to_fit();
474
475 // Add to local rows
476 int bs2 = _bs[0] * _bs[1];
477 assert(_ghost_value_data_in.size() == _unpack_pos.size() * bs2);
478 for (std::size_t i = 0; i < _unpack_pos.size(); ++i)
479 for (int j = 0; j < bs2; ++j)
480 _data[_unpack_pos[i] * bs2 + j] += _ghost_value_data_in[i * bs2 + j];
481
482 _ghost_value_data_in.clear();
483 _ghost_value_data_in.shrink_to_fit();
484
485 // Set ghost row data to zero
486 std::int32_t local_size0 = _index_maps[0]->size_local();
487 std::fill(std::next(_data.begin(), _row_ptr[local_size0] * bs2),
488 _data.end(), 0);
489 }
490
494 double squared_norm() const
495 {
496 const std::size_t num_owned_rows = _index_maps[0]->size_local();
497 const int bs2 = _bs[0] * _bs[1];
498 assert(num_owned_rows < _row_ptr.size());
499 double norm_sq_local = std::accumulate(
500 _data.cbegin(),
501 std::next(_data.cbegin(), _row_ptr[num_owned_rows] * bs2), double(0),
502 [](auto norm, value_type y) { return norm + std::norm(y); });
503 double norm_sq;
504 MPI_Allreduce(&norm_sq_local, &norm_sq, 1, MPI_DOUBLE, MPI_SUM,
505 _comm.comm());
506 return norm_sq;
507 }
508
519 void mult(Vector<value_type>& x, Vector<value_type>& y) const;
520
552
554 MPI_Comm comm() const { return _comm.comm(); }
555
563 std::shared_ptr<const common::IndexMap> index_map(int dim) const
564 {
565 return _index_maps.at(dim);
566 }
567
570 container_type& values() { return _data; }
571
574 const container_type& values() const { return _data; }
575
578 const rowptr_container_type& row_ptr() const { return _row_ptr; }
579
582 const column_container_type& cols() const { return _cols; }
583
594 {
595 return _off_diagonal_offset;
596 }
597
600 std::array<int, 2> block_size() const { return _bs; }
601
603 BlockMode block_mode() const { return _block_mode; }
604
624 {
625 // Remove any zero entries (blocks, where all entries in the block
626 // are within tolerance of zero) in data, and update the column
627 // indices and row pointers accordingly.
628 const std::size_t bs2 = _bs[0] * _bs[1];
629
630 // True if every entry of the block starting at block index j is
631 // within tolerance of zero, i.e. the whole block can be dropped.
632 auto is_zero_block = [this, bs2, tol](std::int64_t j)
633 {
634 return std::all_of(std::next(_data.begin(), j * bs2),
635 std::next(_data.begin(), (j + 1) * bs2),
636 [tol](value_type x)
637 { return std::abs(x) <= std::abs(tol); });
638 };
639
640 std::int64_t ptr_out = 0;
641 std::vector<std::int64_t> new_row_ptr = {0};
642 std::vector<std::int64_t> new_off_diagonal_offset;
643 new_row_ptr.reserve(_row_ptr.size());
644 new_off_diagonal_offset.reserve(_off_diagonal_offset.size());
645 for (std::size_t i = 0; i < _row_ptr.size() - 1; ++i)
646 {
647 for (std::int64_t j = _row_ptr[i]; j < _off_diagonal_offset[i]; ++j)
648 {
649 if (!is_zero_block(j))
650 {
651 _cols[ptr_out] = _cols[j];
652 std::copy_n(std::next(_data.begin(), j * bs2), bs2,
653 std::next(_data.begin(), ptr_out * bs2));
654 ++ptr_out;
655 }
656 }
657 new_off_diagonal_offset.push_back(ptr_out);
658 for (std::int64_t j = _off_diagonal_offset[i]; j < _row_ptr[i + 1]; ++j)
659 {
660 if (!is_zero_block(j))
661 {
662 _cols[ptr_out] = _cols[j];
663 std::copy_n(std::next(_data.begin(), j * bs2), bs2,
664 std::next(_data.begin(), ptr_out * bs2));
665 ++ptr_out;
666 }
667 }
668 new_row_ptr.push_back(ptr_out);
669 }
670 _data.resize(ptr_out * bs2);
671 _cols.resize(ptr_out);
672 _row_ptr = new_row_ptr;
673 _off_diagonal_offset = new_off_diagonal_offset;
674 _finalized = true;
675 }
676
677private:
678 // Parallel distribution of the rows and columns
679 std::array<std::shared_ptr<const common::IndexMap>, 2> _index_maps;
680
681 // Block mode (compact or expanded)
682 BlockMode _block_mode;
683
684 // Block sizes
685 std::array<int, 2> _bs;
686
687 // Matrix data
688 container_type _data;
690 rowptr_container_type _row_ptr;
691
692 // Start of off-diagonal (unowned columns) on each row
693 rowptr_container_type _off_diagonal_offset;
694
695 // Communicator with neighborhood (ghost->owner communicator for rows)
696 dolfinx::MPI::Comm _comm;
697
698 // -- Precomputed data for scatter_rev/update
699
700 // Request in non-blocking communication
701 MPI_Request _request;
702
703 // Position in _data to add received data
704 std::vector<std::size_t> _unpack_pos;
705
706 // Displacements for alltoall for each neighbor when sending and
707 // receiving
708 std::vector<int> _val_send_disp, _val_recv_disp;
709
710 // Ownership of each row, by neighbor (for the neighbourhood defined
711 // on _comm)
712 std::vector<int> _ghost_row_to_rank;
713
714 // Temporary stores for data during non-blocking communication
715 container_type _ghost_value_data;
716 container_type _ghost_value_data_in;
717
718 // Set by eliminate_zeros(). Once true, the sparsity may have been
719 // reduced and the precomputed scatter_rev communication pattern
720 // (_unpack_pos, _val_send_disp, _val_recv_disp) is no longer valid,
721 // so further modification of the matrix is disallowed.
722 bool _finalized = false;
723
724 // Throw if the matrix has been finalized by eliminate_zeros().
725 void check_not_finalized() const
726 {
727 if (_finalized)
728 {
729 throw std::runtime_error(
730 "MatrixCSR has been finalized by eliminate_zeros() and can no "
731 "longer be modified or scattered.");
732 }
733 }
734};
735//-----------------------------------------------------------------------------
736
738template <typename U, typename V, typename W, typename X>
739template <SparsityImplementation SparsityType>
740MatrixCSR<U, V, W, X>::MatrixCSR(const SparsityType& p, BlockMode mode)
741 : _index_maps({p.index_map(0), p.index_map(1)}), _block_mode(mode),
742 _bs({p.block_size(0), p.block_size(1)}),
743 _data(p.graph().first.size() * _bs[0] * _bs[1], 0),
744 _cols(p.graph().first.begin(), p.graph().first.end()),
745 _row_ptr(p.graph().second.begin(), p.graph().second.end()),
746 _comm(MPI_COMM_NULL)
747{
748 if (_block_mode == BlockMode::expanded)
749 {
750 // Rebuild IndexMaps
751 for (int i = 0; i < 2; ++i)
752 {
753 auto im = _index_maps[i];
754 std::int32_t size_local = im->size_local() * _bs[i];
755 std::span ghost_i = im->ghosts();
756 std::vector<std::int64_t> ghosts;
757 const std::vector<int> ghost_owner_i(im->owners().begin(),
758 im->owners().end());
759 std::vector<int> src_rank;
760 for (std::size_t j = 0; j < ghost_i.size(); ++j)
761 {
762 for (int k = 0; k < _bs[i]; ++k)
763 {
764 ghosts.push_back(ghost_i[j] * _bs[i] + k);
765 src_rank.push_back(ghost_owner_i[j]);
766 }
767 }
768
769 std::array<std::vector<int>, 2> src_dest0
770 = {std::vector(_index_maps[i]->src().begin(),
771 _index_maps[i]->src().end()),
772 std::vector(_index_maps[i]->dest().begin(),
773 _index_maps[i]->dest().end())};
774 _index_maps[i] = std::make_shared<common::IndexMap>(
775 _index_maps[i]->comm(), size_local, src_dest0, ghosts, src_rank);
776 }
777
778 // Convert sparsity pattern and set _bs to 1
779
780 column_container_type new_cols;
781 new_cols.reserve(_data.size());
782 rowptr_container_type new_row_ptr{0};
783 new_row_ptr.reserve(_row_ptr.size() * _bs[0]);
784 std::span<const std::int32_t> num_diag_nnz = p.off_diagonal_offsets();
785 for (std::size_t i = 0; i < _row_ptr.size() - 1; ++i)
786 {
787 // Repeat row _bs[0] times
788 for (int q0 = 0; q0 < _bs[0]; ++q0)
789 {
790 _off_diagonal_offset.push_back(new_row_ptr.back()
791 + num_diag_nnz[i] * _bs[1]);
792 for (auto j = _row_ptr[i]; j < _row_ptr[i + 1]; ++j)
793 {
794 for (int q1 = 0; q1 < _bs[1]; ++q1)
795 new_cols.push_back(_cols[j] * _bs[1] + q1);
796 }
797 new_row_ptr.push_back(new_cols.size());
798 }
799 }
800 _cols = new_cols;
801 _row_ptr = new_row_ptr;
802 _bs[0] = 1;
803 _bs[1] = 1;
804 }
805 else
806 {
807 // Compute off-diagonal offset for each row (compact)
808 std::span<const std::int32_t> num_diag_nnz = p.off_diagonal_offsets();
809 _off_diagonal_offset.reserve(num_diag_nnz.size());
810 std::ranges::transform(num_diag_nnz, _row_ptr,
811 std::back_inserter(_off_diagonal_offset),
812 std::plus{});
813 }
814
815 // Some short-hand
816 std::array local_size
817 = {_index_maps[0]->size_local(), _index_maps[1]->size_local()};
818 std::array local_range
819 = {_index_maps[0]->local_range(), _index_maps[1]->local_range()};
820 std::span ghosts1 = _index_maps[1]->ghosts();
821
822 std::span ghosts0 = _index_maps[0]->ghosts();
823 std::span src_ranks = _index_maps[0]->src();
824 std::span dest_ranks = _index_maps[0]->dest();
825
826 // Create neighbourhood communicator (owner <- ghost)
827 MPI_Comm comm;
828 MPI_Dist_graph_create_adjacent(_index_maps[0]->comm(), dest_ranks.size(),
829 dest_ranks.data(), MPI_UNWEIGHTED,
830 src_ranks.size(), src_ranks.data(),
831 MPI_UNWEIGHTED, MPI_INFO_NULL, false, &comm);
832 _comm = dolfinx::MPI::Comm(comm, false);
833
834 // Build map from ghost row index position to owning (neighborhood)
835 // rank
836 _ghost_row_to_rank.reserve(_index_maps[0]->owners().size());
837 for (int r : _index_maps[0]->owners())
838 {
839 auto it = std::ranges::lower_bound(src_ranks, r);
840 assert(it != src_ranks.end() and *it == r);
841 std::size_t pos = std::ranges::distance(src_ranks.begin(), it);
842 _ghost_row_to_rank.push_back(pos);
843 }
844
845 // Compute size of data to send to each neighbor
846 std::vector<std::int32_t> data_per_proc(src_ranks.size(), 0);
847 for (std::size_t i = 0; i < _ghost_row_to_rank.size(); ++i)
848 {
849 assert(_ghost_row_to_rank[i] < (int)data_per_proc.size());
850 std::size_t pos = local_size[0] + i;
851 data_per_proc[_ghost_row_to_rank[i]] += _row_ptr[pos + 1] - _row_ptr[pos];
852 }
853
854 // Compute send displacements
855 _val_send_disp.resize(src_ranks.size() + 1, 0);
856 std::partial_sum(data_per_proc.begin(), data_per_proc.end(),
857 std::next(_val_send_disp.begin()));
858
859 // For each ghost row, pack and send indices to neighborhood
860 std::vector<std::int64_t> ghost_index_data(2 * _val_send_disp.back());
861 {
862 std::vector<int> insert_pos = _val_send_disp;
863 for (std::size_t i = 0; i < _ghost_row_to_rank.size(); ++i)
864 {
865 int rank = _ghost_row_to_rank[i];
866 std::int32_t row_id = local_size[0] + i;
867 for (int j = _row_ptr[row_id]; j < _row_ptr[row_id + 1]; ++j)
868 {
869 // Get position in send buffer
870 std::int32_t idx_pos = 2 * insert_pos[rank];
871
872 // Pack send data (row, col) as global indices
873 ghost_index_data[idx_pos] = ghosts0[i];
874 if (std::int32_t col_local = _cols[j]; col_local < local_size[1])
875 ghost_index_data[idx_pos + 1] = col_local + local_range[1][0];
876 else
877 ghost_index_data[idx_pos + 1] = ghosts1[col_local - local_size[1]];
878
879 insert_pos[rank] += 1;
880 }
881 }
882 }
883
884 // Communicate data with neighborhood
885 std::vector<std::int64_t> ghost_index_array;
886 std::vector<int> recv_disp;
887 {
888 std::vector<int> send_sizes;
889 std::ranges::transform(data_per_proc, std::back_inserter(send_sizes),
890 [](auto x) { return 2 * x; });
891
892 std::vector<int> recv_sizes(dest_ranks.size());
893 send_sizes.reserve(1);
894 recv_sizes.reserve(1);
895 MPI_Neighbor_alltoall(send_sizes.data(), 1, MPI_INT, recv_sizes.data(), 1,
896 MPI_INT, _comm.comm());
897
898 // Build send/recv displacement
899 std::vector<int> send_disp{0};
900 std::partial_sum(send_sizes.begin(), send_sizes.end(),
901 std::back_inserter(send_disp));
902 recv_disp = {0};
903 std::partial_sum(recv_sizes.begin(), recv_sizes.end(),
904 std::back_inserter(recv_disp));
905
906 ghost_index_array.resize(recv_disp.back());
907 MPI_Neighbor_alltoallv(ghost_index_data.data(), send_sizes.data(),
908 send_disp.data(), MPI_INT64_T,
909 ghost_index_array.data(), recv_sizes.data(),
910 recv_disp.data(), MPI_INT64_T, _comm.comm());
911 }
912
913 // Store receive displacements for future use, when transferring
914 // data values
915 _val_recv_disp.resize(recv_disp.size());
916 int bs2 = _bs[0] * _bs[1];
917 std::ranges::transform(recv_disp, _val_recv_disp.begin(),
918 [&bs2](auto d) { return bs2 * d / 2; });
919 std::ranges::transform(_val_send_disp, _val_send_disp.begin(),
920 [&bs2](auto d) { return d * bs2; });
921
922 // Global-to-local map for ghost columns
923 std::vector<std::pair<std::int64_t, std::int32_t>> global_to_local;
924 global_to_local.reserve(ghosts1.size());
925 for (std::int64_t idx : ghosts1)
926 global_to_local.push_back({idx, global_to_local.size() + local_size[1]});
927 std::ranges::sort(global_to_local);
928
929 // Compute location in which data for each index should be stored
930 // when received
931 for (std::size_t i = 0; i < ghost_index_array.size(); i += 2)
932 {
933 // Row must be on this process
934 std::int32_t local_row = ghost_index_array[i] - local_range[0][0];
935 assert(local_row >= 0 and local_row < local_size[0]);
936
937 // Column may be owned or unowned
938 std::int32_t local_col = ghost_index_array[i + 1] - local_range[1][0];
939 if (local_col < 0 or local_col >= local_size[1])
940 {
941 auto it = std::ranges::lower_bound(
942 global_to_local, std::pair(ghost_index_array[i + 1], -1),
943 [](auto a, auto b) { return a.first < b.first; });
944 assert(it != global_to_local.end()
945 and it->first == ghost_index_array[i + 1]);
946 local_col = it->second;
947 }
948 auto cit0 = std::next(_cols.begin(), _row_ptr[local_row]);
949 auto cit1 = std::next(_cols.begin(), _row_ptr[local_row + 1]);
950
951 // Find position of column index and insert data
952 auto cit = std::lower_bound(cit0, cit1, local_col);
953 assert(cit != cit1);
954 assert(*cit == local_col);
955 std::size_t d = std::ranges::distance(_cols.begin(), cit);
956 _unpack_pos.push_back(d);
957 }
958
959 _unpack_pos.shrink_to_fit();
960}
961//-----------------------------------------------------------------------------
962
963// The matrix A is distributed across P processes by blocks of rows:
964// A = | A_0 |
965// | A_1 |
966// | ... |
967// | A_P-1 |
968//
969// Each submatrix A_i is owned by a single process "i" and can be further
970// decomposed into diagonal (Ai[0]) and off diagonal (Ai[1]) blocks:
971// Ai = |Ai[0] Ai[1]|
972//
973// If A is square, the diagonal block Ai[0] is also square and contains
974// only owned columns and rows. The block Ai[1] contains ghost columns
975// (unowned dofs).
976
977// Likewise, a local vector x can be decomposed into owned and ghost blocks:
978// xi = | x[0] |
979// | x[1] |
980//
981// So the product y = Ax can be computed into two separate steps:
982// y[0] = |Ai[0] Ai[1]| | x[0] | = Ai[0] x[0] + Ai[1] x[1]
983// | x[1] |
984//
987template <typename Scalar, typename V, typename W, typename X>
989 la::Vector<Scalar>& y) const
990{
991 // start communication (update ghosts)
993
994 std::int32_t nrowslocal = num_owned_rows();
995 std::span<const std::int64_t> Arow_ptr(row_ptr().data(), nrowslocal + 1);
996 std::span<const std::int32_t> Acols(cols().data(), Arow_ptr[nrowslocal]);
997 std::span<const std::int64_t> Aoff_diag_offset(off_diag_offset().data(),
998 nrowslocal);
999 std::span<const Scalar> Avalues(values().data(),
1000 Arow_ptr[nrowslocal] * _bs[0] * _bs[1]);
1001
1002 std::span<const Scalar> _x = x.array();
1003 std::span<Scalar> _y = y.array();
1004
1005 std::span<const std::int64_t> Arow_begin(Arow_ptr.data(), nrowslocal);
1006 std::span<const std::int64_t> Arow_end(Arow_ptr.data() + 1, nrowslocal);
1007
1008 // First stage: spmv - diagonal
1009 // yi[0] += Ai[0] * xi[0]
1010 if (_bs[1] == 1)
1011 {
1012 impl::spmv<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1013 _bs[0], std::integral_constant<int, 1>{});
1014 }
1015 else if (_bs[1] == 2)
1016 {
1017 impl::spmv<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1018 _bs[0], std::integral_constant<int, 2>{});
1019 }
1020 else if (_bs[1] == 3)
1021 {
1022 impl::spmv<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1023 _bs[0], std::integral_constant<int, 3>{});
1024 }
1025 else
1026 {
1027 impl::spmv<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1028 _bs[0], _bs[1]);
1029 }
1030
1031 // finalize ghost update
1032 x.scatter_fwd_end();
1033
1034 // Second stage: spmv - off-diagonal
1035 // yi[0] += Ai[1] * xi[1]
1036 if (_bs[1] == 1)
1037 {
1038 impl::spmv<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1039 _bs[0], std::integral_constant<int, 1>{});
1040 }
1041 else if (_bs[1] == 2)
1042 {
1043 impl::spmv<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1044 _bs[0], std::integral_constant<int, 2>{});
1045 }
1046 else if (_bs[1] == 3)
1047 {
1048 impl::spmv<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1049 _bs[0], std::integral_constant<int, 3>{});
1050 }
1051 else
1052 {
1053 impl::spmv<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1054 _bs[0], _bs[1]);
1055 }
1056}
1057
1060template <typename Scalar, typename V, typename W, typename X>
1062 la::Vector<Scalar>& y) const
1063{
1064 std::int32_t nrowslocal = num_owned_rows();
1065 std::span<const std::int64_t> Arow_ptr(row_ptr().data(), nrowslocal + 1);
1066 std::span<const std::int32_t> Acols(cols().data(), Arow_ptr[nrowslocal]);
1067 std::span<const std::int64_t> Aoff_diag_offset(off_diag_offset().data(),
1068 nrowslocal);
1069 std::span<const Scalar> Avalues(values().data(),
1070 Arow_ptr[nrowslocal] * _bs[0] * _bs[1]);
1071
1072 std::span<const Scalar> _x = x.array();
1073 std::span<Scalar> _y = y.array();
1074
1075 std::span<const std::int64_t> Arow_begin(Arow_ptr.data(), nrowslocal);
1076 std::span<const std::int64_t> Arow_end(Arow_ptr.data() + 1, nrowslocal);
1077
1078 // Compute ghost region contribution and scatter back. Zero only the
1079 // ghost portion of y so the caller's owned values are preserved (multT
1080 // accumulates).
1081 std::int32_t ncolslocal = index_map(1)->size_local();
1082 std::fill(std::next(_y.begin(), ncolslocal * _bs[1]), _y.end(), Scalar(0));
1083 if (_bs[1] == 1)
1084 {
1085 impl::spmvT<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1086 _bs[0], std::integral_constant<int, 1>{});
1087 }
1088 else if (_bs[1] == 2)
1089 {
1090 impl::spmvT<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1091 _bs[0], std::integral_constant<int, 2>{});
1092 }
1093 else if (_bs[1] == 3)
1094 {
1095 impl::spmvT<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1096 _bs[0], std::integral_constant<int, 3>{});
1097 }
1098 else
1099 {
1100 impl::spmvT<Scalar>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
1101 _bs[0], _bs[1]);
1102 }
1103
1104 y.scatter_rev(std::plus<Scalar>{});
1105
1106 if (_bs[1] == 1)
1107 {
1108 impl::spmvT<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1109 _bs[0], std::integral_constant<int, 1>{});
1110 }
1111 else if (_bs[1] == 2)
1112 {
1113 impl::spmvT<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1114 _bs[0], std::integral_constant<int, 2>{});
1115 }
1116 else if (_bs[1] == 3)
1117 {
1118 impl::spmvT<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1119 _bs[0], std::integral_constant<int, 3>{});
1120 }
1121 else
1122 {
1123 impl::spmvT<Scalar>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
1124 _bs[0], _bs[1]);
1125 }
1126}
1127} // namespace dolfinx::la
A duplicate MPI communicator and manage lifetime of the communicator.
Definition MPI.h:47
MPI_Comm comm() const noexcept
Return the underlying MPI_Comm object.
Definition MPI.cpp:71
const container_type & values() const
Get local values (const version).
Definition MatrixCSR.h:574
std::shared_ptr< const common::IndexMap > index_map(int dim) const
Index map for the row or column space.
Definition MatrixCSR.h:563
const rowptr_container_type & off_diag_offset() const
Get the start of off-diagonal (unowned columns) on each row, allowing the matrix to be split (virtual...
Definition MatrixCSR.h:593
void set(std::span< const value_type > x, std::span< const std::int32_t > rows, std::span< const std::int32_t > cols)
Set values in the matrix.
Definition MatrixCSR.h:283
MatrixCSR(const MatrixCSR< Scalar0, Container0, ColContainer0, RowPtrContainer0 > &A)
Copy-convert matrix, possibly using to different container types.
Definition MatrixCSR.h:241
RowPtrContainer rowptr_container_type
Row pointer container type.
Definition MatrixCSR.h:90
void scatter_rev_end()
End transfer of ghost row data to owning ranks.
Definition MatrixCSR.h:466
container_type & values()
Get local data values.
Definition MatrixCSR.h:570
auto mat_add_values()
Insertion functor for adding values to a matrix. It is typically used in finite element assembly func...
Definition MatrixCSR.h:158
BlockMode block_mode() const
Get 'block mode'.
Definition MatrixCSR.h:603
void add(std::span< const value_type > x, std::span< const std::int32_t > rows, std::span< const std::int32_t > cols)
Accumulate values in the matrix.
Definition MatrixCSR.h:329
std::int32_t num_owned_rows() const
Number of local rows excluding ghost rows.
Definition MatrixCSR.h:357
ColContainer column_container_type
Column index container type.
Definition MatrixCSR.h:87
void mult(Vector< value_type > &x, Vector< value_type > &y) const
Compute the product y += Ax.
Definition MatrixCSR.h:988
MatrixCSR(MatrixCSR &&A)=default
MatrixCSR & operator=(MatrixCSR &&A)=default
MatrixCSR(const T &p, BlockMode mode=BlockMode::compact)
Create a distributed matrix.
double squared_norm() const
Compute the Frobenius norm squared across all processes.
Definition MatrixCSR.h:494
void scatter_rev()
Transfer ghost row data to the owning ranks accumulating received values on the owned rows,...
Definition MatrixCSR.h:403
void multT(Vector< value_type > &x, Vector< value_type > &y) const
Compute the product y += A^T x.
Definition MatrixCSR.h:1061
void eliminate_zeros(value_type tol=0)
Remove any zero entries in the matrix data.
Definition MatrixCSR.h:623
Container container_type
Matrix entries container type.
Definition MatrixCSR.h:84
Scalar value_type
Scalar type.
Definition MatrixCSR.h:81
void scatter_rev_begin()
Begin transfer of ghost row data to owning ranks, where it will be accumulated into existing owned ro...
Definition MatrixCSR.h:418
const column_container_type & cols() const
Definition MatrixCSR.h:582
void set(value_type x)
Set all non-zero local entries to a value, including entries in ghost rows.
Definition MatrixCSR.h:260
~MatrixCSR()=default
Destructor.
std::array< int, 2 > block_size() const
Get block sizes.
Definition MatrixCSR.h:600
std::int32_t num_all_rows() const
Number of local rows including ghost rows.
Definition MatrixCSR.h:360
const rowptr_container_type & row_ptr() const
Get local row pointers.
Definition MatrixCSR.h:578
std::vector< value_type > to_dense() const
Copy to a dense matrix.
Definition MatrixCSR.h:371
MPI_Comm comm() const
Get MPI communicator that matrix is defined on.
Definition MatrixCSR.h:554
auto mat_set_values()
Insertion functor for setting values in a matrix. It is typically used in finite element assembly fun...
Definition MatrixCSR.h:116
A vector that can be distributed across processes.
Definition Vector.h:51
void scatter_rev(BinaryOperation op)
Scatter (send) of ghost data values to the owning process and assign/accumulate into the owned data e...
Definition Vector.h:446
void scatter_fwd_end(U unpack)
End scatter (send) of local data values that are ghosted on other processes.
Definition Vector.h:320
container_type & array() noexcept
Get the process-local part of the vector.
Definition Vector.h:472
void scatter_fwd_begin(U pack, GetPtr get_ptr)
Begin scatter (send) of local data that is ghosted on other processes.
Definition Vector.h:278
Definition MatrixCSR.h:25
MPI_Datatype mpi_t
Retrieves the MPI data type associated to the provided type.
Definition MPI.h:326
void check_error(MPI_Comm comm, int code) noexcept
Check MPI error code. If the error code is not equal to MPI_SUCCESS, then std::abort is called.
Definition MPI.cpp:89
int size(MPI_Comm comm)
Definition MPI.cpp:81
int rank(MPI_Comm comm)
Return process rank for the communicator.
Definition MPI.cpp:73
constexpr std::array< std::int64_t, 2 > local_range(int index, std::int64_t N, int size)
Partition a global range [0, N - 1] across callers into non-overlapping sub-partitions of almost equa...
Definition local_range.h:26
Linear algebra interface.
Definition dolfinx_la.h:7
BlockMode
Modes for representing block structured matrices.
Definition MatrixCSR.h:45
@ expanded
Definition MatrixCSR.h:48
auto norm(const V &x, Norm type=Norm::l2)
Compute the norm of the vector.
Definition Vector.h:563