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
66template <typename Scalar, typename Container = std::vector<Scalar>,
67 typename ColContainer = std::vector<std::int32_t>,
68 typename RowPtrContainer = std::vector<std::int64_t>>
69class MatrixCSR
70{
71 static_assert(std::is_same_v<typename Container::value_type, Scalar>);
72 static_assert(std::is_integral_v<typename ColContainer::value_type>);
73 static_assert(std::is_integral_v<typename RowPtrContainer::value_type>);
74
75 template <typename, typename, typename, typename>
76 friend class MatrixCSR;
77
78public:
80 using value_type = Scalar;
81
83 using container_type = Container;
84
86 using column_container_type = ColContainer;
87
89 using rowptr_container_type = RowPtrContainer;
90
114 template <int BS0 = 1, int BS1 = 1>
116 {
117 if ((BS0 != _bs[0] and BS0 > 1 and _bs[0] > 1)
118 or (BS1 != _bs[1] and BS1 > 1 and _bs[1] > 1))
119 {
120 throw std::runtime_error(
121 "Cannot insert blocks of different size than matrix block size");
122 }
123
124 return [&](std::span<const std::int32_t> rows,
125 std::span<const std::int32_t> cols,
126 std::span<const value_type> data) -> int
127 {
128 this->set<BS0, BS1>(data, rows, cols);
129 return 0;
130 };
131 }
132
156 template <int BS0 = 1, int BS1 = 1>
158 {
159 if ((BS0 != _bs[0] and BS0 > 1 and _bs[0] > 1)
160 or (BS1 != _bs[1] and BS1 > 1 and _bs[1] > 1))
161 {
162 throw std::runtime_error(
163 "Cannot insert blocks of different size than matrix block size");
164 }
165
166 return [&](std::span<const std::int32_t> rows,
167 std::span<const std::int32_t> cols,
168 std::span<const value_type> data) -> int
169 {
170 this->add<BS0, BS1>(data, rows, cols);
171 return 0;
172 };
173 }
174
198 template <SparsityImplementation T>
199 MatrixCSR(const T& p, BlockMode mode = BlockMode::compact);
200
203 MatrixCSR(MatrixCSR&& A) = default;
204
207 MatrixCSR(const MatrixCSR& A) = default;
208
222 template <typename Scalar0, typename Container0, typename ColContainer0,
223 typename RowPtrContainer0>
224 explicit MatrixCSR(
225 const MatrixCSR<Scalar0, Container0, ColContainer0, RowPtrContainer0>& A)
226 : _index_maps(A._index_maps), _block_mode(A.block_mode()),
227 _bs(A.block_size()), _data(A._data.begin(), A._data.end()),
228 _cols(A.cols().begin(), A.cols().end()),
229 _row_ptr(A.row_ptr().begin(), A.row_ptr().end()),
230 _off_diagonal_offset(A.off_diag_offset().begin(),
231 A.off_diag_offset().end()),
232 _comm(A.comm()), _request(MPI_REQUEST_NULL), _unpack_pos(A._unpack_pos),
233 _val_send_disp(A._val_send_disp), _val_recv_disp(A._val_recv_disp),
234 _ghost_row_to_rank(A._ghost_row_to_rank)
235 {
236 }
237
242 [[deprecated("Use std::ranges::fill(A.values(), v) instead.")]]
244 {
245 std::ranges::fill(_data, x);
246 }
247
264 template <int BS0, int BS1>
265 void set(std::span<const value_type> x, std::span<const std::int32_t> rows,
266 std::span<const std::int32_t> cols)
267 {
268 auto set_fn = [](value_type& y, const value_type& x) { y = x; };
269
270 std::int32_t num_rows
271 = _index_maps[0]->size_local() + _index_maps[0]->num_ghosts();
272 assert(x.size() == rows.size() * cols.size() * BS0 * BS1);
273 if (_bs[0] == BS0 and _bs[1] == BS1)
274 {
275 impl::insert_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols, set_fn,
276 num_rows);
277 }
278 else if (_bs[0] == 1 and _bs[1] == 1)
279 {
280 // Set blocked data in a regular CSR matrix (_bs[0]=1, _bs[1]=1)
281 // with correct sparsity
282 impl::insert_blocked_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols,
283 set_fn, num_rows);
284 }
285 else
286 {
287 assert(BS0 == 1 and BS1 == 1);
288 // Set non-blocked data in a blocked CSR matrix (BS0=1, BS1=1)
289 impl::insert_nonblocked_csr(_data, _cols, _row_ptr, x, rows, cols, set_fn,
290 num_rows, _bs[0], _bs[1]);
291 }
292 }
293
309 template <int BS0 = 1, int BS1 = 1>
310 void add(std::span<const value_type> x, std::span<const std::int32_t> rows,
311 std::span<const std::int32_t> cols)
312 {
313 auto add_fn = [](value_type& y, const value_type& x) { y += x; };
314
315 assert(x.size() == rows.size() * cols.size() * BS0 * BS1);
316 if (_bs[0] == BS0 and _bs[1] == BS1)
317 {
318 impl::insert_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols, add_fn,
319 _row_ptr.size());
320 }
321 else if (_bs[0] == 1 and _bs[1] == 1)
322 {
323 // Add blocked data to a regular CSR matrix (_bs[0]=1, _bs[1]=1)
324 impl::insert_blocked_csr<BS0, BS1>(_data, _cols, _row_ptr, x, rows, cols,
325 add_fn, _row_ptr.size());
326 }
327 else
328 {
329 assert(BS0 == 1 and BS1 == 1);
330 // Add non-blocked data to a blocked CSR matrix (BS0=1, BS1=1)
331 impl::insert_nonblocked_csr(_data, _cols, _row_ptr, x, rows, cols, add_fn,
332 _row_ptr.size(), _bs[0], _bs[1]);
333 }
334 }
335
337 std::int32_t num_owned_rows() const { return _index_maps[0]->size_local(); }
338
340 std::int32_t num_all_rows() const { return _row_ptr.size() - 1; }
341
351 std::vector<value_type> to_dense() const
352 {
353 const std::size_t nrows = num_all_rows();
354 const std::size_t ncols = _index_maps[1]->size_global();
355 std::vector<value_type> A(nrows * ncols * _bs[0] * _bs[1], value_type(0));
356 for (std::size_t r = 0; r < nrows; ++r)
357 {
358 for (std::int32_t j = _row_ptr[r]; j < _row_ptr[r + 1]; ++j)
359 {
360 for (int i0 = 0; i0 < _bs[0]; ++i0)
361 {
362 for (int i1 = 0; i1 < _bs[1]; ++i1)
363 {
364 std::array<std::int32_t, 1> local_col{_cols[j]};
365 std::array<std::int64_t, 1> global_col{0};
366 _index_maps[1]->local_to_global(local_col, global_col);
367 A[(r * _bs[0] + i0) * ncols * _bs[1] + global_col[0] * _bs[1] + i1]
368 = _data[j * _bs[0] * _bs[1] + i0 * _bs[1] + i1];
369 }
370 }
371 }
372 }
373
374 return A;
375 }
376
384 {
387 }
388
399 {
400 const std::int32_t local_size0 = _index_maps[0]->size_local();
401 const std::int32_t num_ghosts0 = _index_maps[0]->num_ghosts();
402 const int bs2 = _bs[0] * _bs[1];
403
404 // For each ghost row, pack and send values to send to neighborhood
405 std::vector<int> insert_pos = _val_send_disp;
406 _ghost_value_data.resize(_val_send_disp.back());
407 for (int i = 0; i < num_ghosts0; ++i)
408 {
409 int rank = _ghost_row_to_rank[i];
410
411 // Get position in send buffer to place data to send to this
412 // neighbour
413 std::int32_t val_pos = insert_pos[rank];
414 std::copy(std::next(_data.data(), _row_ptr[local_size0 + i] * bs2),
415 std::next(_data.data(), _row_ptr[local_size0 + i + 1] * bs2),
416 std::next(_ghost_value_data.begin(), val_pos));
417 insert_pos[rank]
418 += bs2 * (_row_ptr[local_size0 + i + 1] - _row_ptr[local_size0 + i]);
419 }
420
421 _ghost_value_data_in.resize(_val_recv_disp.back());
422
423 // Compute data sizes for send and receive from displacements
424 std::vector<int> val_send_count(_val_send_disp.size() - 1);
425 std::adjacent_difference(std::next(_val_send_disp.begin()),
426 _val_send_disp.end(), val_send_count.begin());
427
428 std::vector<int> val_recv_count(_val_recv_disp.size() - 1);
429 std::adjacent_difference(std::next(_val_recv_disp.begin()),
430 _val_recv_disp.end(), val_recv_count.begin());
431
432 int status = MPI_Ineighbor_alltoallv(
433 _ghost_value_data.data(), val_send_count.data(), _val_send_disp.data(),
434 dolfinx::MPI::mpi_t<value_type>, _ghost_value_data_in.data(),
435 val_recv_count.data(), _val_recv_disp.data(),
436 dolfinx::MPI::mpi_t<value_type>, _comm.comm(), &_request);
437 dolfinx::MPI::check_error(_comm.comm(), status);
438 }
439
446 {
447 int status = MPI_Wait(&_request, MPI_STATUS_IGNORE);
448 dolfinx::MPI::check_error(_comm.comm(), status);
449
450 _ghost_value_data.clear();
451 _ghost_value_data.shrink_to_fit();
452
453 // Add to local rows
454 int bs2 = _bs[0] * _bs[1];
455 assert(_ghost_value_data_in.size() == _unpack_pos.size() * bs2);
456 for (std::size_t i = 0; i < _unpack_pos.size(); ++i)
457 for (int j = 0; j < bs2; ++j)
458 _data[_unpack_pos[i] * bs2 + j] += _ghost_value_data_in[i * bs2 + j];
459
460 _ghost_value_data_in.clear();
461 _ghost_value_data_in.shrink_to_fit();
462
463 // Set ghost row data to zero
464 std::int32_t local_size0 = _index_maps[0]->size_local();
465 std::fill(std::next(_data.begin(), _row_ptr[local_size0] * bs2),
466 _data.end(), 0);
467 }
468
472 double squared_norm() const
473 {
474 const std::size_t num_owned_rows = _index_maps[0]->size_local();
475 const int bs2 = _bs[0] * _bs[1];
476 assert(num_owned_rows < _row_ptr.size());
477 double norm_sq_local = std::accumulate(
478 _data.cbegin(),
479 std::next(_data.cbegin(), _row_ptr[num_owned_rows] * bs2), double(0),
480 [](auto norm, value_type y) { return norm + std::norm(y); });
481 double norm_sq;
482 MPI_Allreduce(&norm_sq_local, &norm_sq, 1, MPI_DOUBLE, MPI_SUM,
483 _comm.comm());
484 return norm_sq;
485 }
486
497 void mult(Vector<value_type>& x, Vector<value_type>& y) const;
498
530
532 MPI_Comm comm() const { return _comm.comm(); }
533
541 std::shared_ptr<const common::IndexMap> index_map(int dim) const
542 {
543 return _index_maps.at(dim);
544 }
545
548 container_type& values() { return _data; }
549
552 const container_type& values() const { return _data; }
553
556 const rowptr_container_type& row_ptr() const { return _row_ptr; }
557
560 const column_container_type& cols() const { return _cols; }
561
572 {
573 return _off_diagonal_offset;
574 }
575
578 std::array<int, 2> block_size() const { return _bs; }
579
581 BlockMode block_mode() const { return _block_mode; }
582
583private:
584 // Parallel distribution of the rows and columns
585 std::array<std::shared_ptr<const common::IndexMap>, 2> _index_maps;
586
587 // Block mode (compact or expanded)
588 BlockMode _block_mode;
589
590 // Block sizes
591 std::array<int, 2> _bs;
592
593 // Matrix data
594 container_type _data;
596 rowptr_container_type _row_ptr;
597
598 // Start of off-diagonal (unowned columns) on each row
599 rowptr_container_type _off_diagonal_offset;
600
601 // Communicator with neighborhood (ghost->owner communicator for rows)
602 dolfinx::MPI::Comm _comm;
603
604 // -- Precomputed data for scatter_rev/update
605
606 // Request in non-blocking communication
607 MPI_Request _request;
608
609 // Position in _data to add received data
610 std::vector<std::size_t> _unpack_pos;
611
612 // Displacements for alltoall for each neighbor when sending and
613 // receiving
614 std::vector<int> _val_send_disp, _val_recv_disp;
615
616 // Ownership of each row, by neighbor (for the neighbourhood defined
617 // on _comm)
618 std::vector<int> _ghost_row_to_rank;
619
620 // Temporary stores for data during non-blocking communication
621 container_type _ghost_value_data;
622 container_type _ghost_value_data_in;
623};
624//-----------------------------------------------------------------------------
625
627template <typename U, typename V, typename W, typename X>
628template <SparsityImplementation SparsityType>
629MatrixCSR<U, V, W, X>::MatrixCSR(const SparsityType& p, BlockMode mode)
630 : _index_maps({p.index_map(0), p.index_map(1)}), _block_mode(mode),
631 _bs({p.block_size(0), p.block_size(1)}),
632 _data(p.graph().first.size() * _bs[0] * _bs[1], 0),
633 _cols(p.graph().first.begin(), p.graph().first.end()),
634 _row_ptr(p.graph().second.begin(), p.graph().second.end()),
635 _comm(MPI_COMM_NULL)
636{
637 if (_block_mode == BlockMode::expanded)
638 {
639 // Rebuild IndexMaps
640 for (int i = 0; i < 2; ++i)
641 {
642 auto im = _index_maps[i];
643 std::int32_t size_local = im->size_local() * _bs[i];
644 std::span ghost_i = im->ghosts();
645 std::vector<std::int64_t> ghosts;
646 const std::vector<int> ghost_owner_i(im->owners().begin(),
647 im->owners().end());
648 std::vector<int> src_rank;
649 for (std::size_t j = 0; j < ghost_i.size(); ++j)
650 {
651 for (int k = 0; k < _bs[i]; ++k)
652 {
653 ghosts.push_back(ghost_i[j] * _bs[i] + k);
654 src_rank.push_back(ghost_owner_i[j]);
655 }
656 }
657
658 std::array<std::vector<int>, 2> src_dest0
659 = {std::vector(_index_maps[i]->src().begin(),
660 _index_maps[i]->src().end()),
661 std::vector(_index_maps[i]->dest().begin(),
662 _index_maps[i]->dest().end())};
663 _index_maps[i] = std::make_shared<common::IndexMap>(
664 _index_maps[i]->comm(), size_local, src_dest0, ghosts, src_rank);
665 }
666
667 // Convert sparsity pattern and set _bs to 1
668
669 column_container_type new_cols;
670 new_cols.reserve(_data.size());
671 rowptr_container_type new_row_ptr{0};
672 new_row_ptr.reserve(_row_ptr.size() * _bs[0]);
673 std::span<const std::int32_t> num_diag_nnz = p.off_diagonal_offsets();
674 for (std::size_t i = 0; i < _row_ptr.size() - 1; ++i)
675 {
676 // Repeat row _bs[0] times
677 for (int q0 = 0; q0 < _bs[0]; ++q0)
678 {
679 _off_diagonal_offset.push_back(new_row_ptr.back()
680 + num_diag_nnz[i] * _bs[1]);
681 for (auto j = _row_ptr[i]; j < _row_ptr[i + 1]; ++j)
682 {
683 for (int q1 = 0; q1 < _bs[1]; ++q1)
684 new_cols.push_back(_cols[j] * _bs[1] + q1);
685 }
686 new_row_ptr.push_back(new_cols.size());
687 }
688 }
689 _cols = new_cols;
690 _row_ptr = new_row_ptr;
691 _bs[0] = 1;
692 _bs[1] = 1;
693 }
694 else
695 {
696 // Compute off-diagonal offset for each row (compact)
697 std::span<const std::int32_t> num_diag_nnz = p.off_diagonal_offsets();
698 _off_diagonal_offset.reserve(num_diag_nnz.size());
699 std::ranges::transform(num_diag_nnz, _row_ptr,
700 std::back_inserter(_off_diagonal_offset),
701 std::plus{});
702 }
703
704 // Some short-hand
705 std::array local_size
706 = {_index_maps[0]->size_local(), _index_maps[1]->size_local()};
707 std::array local_range
708 = {_index_maps[0]->local_range(), _index_maps[1]->local_range()};
709 std::span ghosts1 = _index_maps[1]->ghosts();
710
711 std::span ghosts0 = _index_maps[0]->ghosts();
712 std::span src_ranks = _index_maps[0]->src();
713 std::span dest_ranks = _index_maps[0]->dest();
714
715 // Create neighbourhood communicator (owner <- ghost)
716 MPI_Comm comm;
717 MPI_Dist_graph_create_adjacent(_index_maps[0]->comm(), dest_ranks.size(),
718 dest_ranks.data(), MPI_UNWEIGHTED,
719 src_ranks.size(), src_ranks.data(),
720 MPI_UNWEIGHTED, MPI_INFO_NULL, false, &comm);
721 _comm = dolfinx::MPI::Comm(comm, false);
722
723 // Build map from ghost row index position to owning (neighborhood)
724 // rank
725 _ghost_row_to_rank.reserve(_index_maps[0]->owners().size());
726 for (int r : _index_maps[0]->owners())
727 {
728 auto it = std::ranges::lower_bound(src_ranks, r);
729 assert(it != src_ranks.end() and *it == r);
730 std::size_t pos = std::distance(src_ranks.begin(), it);
731 _ghost_row_to_rank.push_back(pos);
732 }
733
734 // Compute size of data to send to each neighbor
735 std::vector<std::int32_t> data_per_proc(src_ranks.size(), 0);
736 for (std::size_t i = 0; i < _ghost_row_to_rank.size(); ++i)
737 {
738 assert(_ghost_row_to_rank[i] < (int)data_per_proc.size());
739 std::size_t pos = local_size[0] + i;
740 data_per_proc[_ghost_row_to_rank[i]] += _row_ptr[pos + 1] - _row_ptr[pos];
741 }
742
743 // Compute send displacements
744 _val_send_disp.resize(src_ranks.size() + 1, 0);
745 std::partial_sum(data_per_proc.begin(), data_per_proc.end(),
746 std::next(_val_send_disp.begin()));
747
748 // For each ghost row, pack and send indices to neighborhood
749 std::vector<std::int64_t> ghost_index_data(2 * _val_send_disp.back());
750 {
751 std::vector<int> insert_pos = _val_send_disp;
752 for (std::size_t i = 0; i < _ghost_row_to_rank.size(); ++i)
753 {
754 int rank = _ghost_row_to_rank[i];
755 std::int32_t row_id = local_size[0] + i;
756 for (int j = _row_ptr[row_id]; j < _row_ptr[row_id + 1]; ++j)
757 {
758 // Get position in send buffer
759 std::int32_t idx_pos = 2 * insert_pos[rank];
760
761 // Pack send data (row, col) as global indices
762 ghost_index_data[idx_pos] = ghosts0[i];
763 if (std::int32_t col_local = _cols[j]; col_local < local_size[1])
764 ghost_index_data[idx_pos + 1] = col_local + local_range[1][0];
765 else
766 ghost_index_data[idx_pos + 1] = ghosts1[col_local - local_size[1]];
767
768 insert_pos[rank] += 1;
769 }
770 }
771 }
772
773 // Communicate data with neighborhood
774 std::vector<std::int64_t> ghost_index_array;
775 std::vector<int> recv_disp;
776 {
777 std::vector<int> send_sizes;
778 std::ranges::transform(data_per_proc, std::back_inserter(send_sizes),
779 [](auto x) { return 2 * x; });
780
781 std::vector<int> recv_sizes(dest_ranks.size());
782 send_sizes.reserve(1);
783 recv_sizes.reserve(1);
784 MPI_Neighbor_alltoall(send_sizes.data(), 1, MPI_INT, recv_sizes.data(), 1,
785 MPI_INT, _comm.comm());
786
787 // Build send/recv displacement
788 std::vector<int> send_disp{0};
789 std::partial_sum(send_sizes.begin(), send_sizes.end(),
790 std::back_inserter(send_disp));
791 recv_disp = {0};
792 std::partial_sum(recv_sizes.begin(), recv_sizes.end(),
793 std::back_inserter(recv_disp));
794
795 ghost_index_array.resize(recv_disp.back());
796 MPI_Neighbor_alltoallv(ghost_index_data.data(), send_sizes.data(),
797 send_disp.data(), MPI_INT64_T,
798 ghost_index_array.data(), recv_sizes.data(),
799 recv_disp.data(), MPI_INT64_T, _comm.comm());
800 }
801
802 // Store receive displacements for future use, when transferring
803 // data values
804 _val_recv_disp.resize(recv_disp.size());
805 int bs2 = _bs[0] * _bs[1];
806 std::ranges::transform(recv_disp, _val_recv_disp.begin(),
807 [&bs2](auto d) { return bs2 * d / 2; });
808 std::ranges::transform(_val_send_disp, _val_send_disp.begin(),
809 [&bs2](auto d) { return d * bs2; });
810
811 // Global-to-local map for ghost columns
812 std::vector<std::pair<std::int64_t, std::int32_t>> global_to_local;
813 global_to_local.reserve(ghosts1.size());
814 for (std::int64_t idx : ghosts1)
815 global_to_local.push_back({idx, global_to_local.size() + local_size[1]});
816 std::ranges::sort(global_to_local);
817
818 // Compute location in which data for each index should be stored
819 // when received
820 for (std::size_t i = 0; i < ghost_index_array.size(); i += 2)
821 {
822 // Row must be on this process
823 std::int32_t local_row = ghost_index_array[i] - local_range[0][0];
824 assert(local_row >= 0 and local_row < local_size[0]);
825
826 // Column may be owned or unowned
827 std::int32_t local_col = ghost_index_array[i + 1] - local_range[1][0];
828 if (local_col < 0 or local_col >= local_size[1])
829 {
830 auto it = std::ranges::lower_bound(
831 global_to_local, std::pair(ghost_index_array[i + 1], -1),
832 [](auto a, auto b) { return a.first < b.first; });
833 assert(it != global_to_local.end()
834 and it->first == ghost_index_array[i + 1]);
835 local_col = it->second;
836 }
837 auto cit0 = std::next(_cols.begin(), _row_ptr[local_row]);
838 auto cit1 = std::next(_cols.begin(), _row_ptr[local_row + 1]);
839
840 // Find position of column index and insert data
841 auto cit = std::lower_bound(cit0, cit1, local_col);
842 assert(cit != cit1);
843 assert(*cit == local_col);
844 std::size_t d = std::distance(_cols.begin(), cit);
845 _unpack_pos.push_back(d);
846 }
847
848 _unpack_pos.shrink_to_fit();
849}
850//-----------------------------------------------------------------------------
851
852// The matrix A is distributed across P processes by blocks of rows:
853// A = | A_0 |
854// | A_1 |
855// | ... |
856// | A_P-1 |
857//
858// Each submatrix A_i is owned by a single process "i" and can be further
859// decomposed into diagonal (Ai[0]) and off diagonal (Ai[1]) blocks:
860// Ai = |Ai[0] Ai[1]|
861//
862// If A is square, the diagonal block Ai[0] is also square and contains
863// only owned columns and rows. The block Ai[1] contains ghost columns
864// (unowned dofs).
865
866// Likewise, a local vector x can be decomposed into owned and ghost blocks:
867// xi = | x[0] |
868// | x[1] |
869//
870// So the product y = Ax can be computed into two separate steps:
871// y[0] = |Ai[0] Ai[1]| | x[0] | = Ai[0] x[0] + Ai[1] x[1]
872// | x[1] |
873//
876template <typename Scalar, typename V, typename W, typename X>
878 la::Vector<Scalar>& y) const
879{
880 // start communication (update ghosts)
882
883 std::int32_t nrowslocal = num_owned_rows();
884 std::span<const std::int64_t> Arow_ptr(row_ptr().data(), nrowslocal + 1);
885 std::span<const std::int32_t> Acols(cols().data(), Arow_ptr[nrowslocal]);
886 std::span<const std::int64_t> Aoff_diag_offset(off_diag_offset().data(),
887 nrowslocal);
888 std::span<const Scalar> Avalues(values().data(),
889 Arow_ptr[nrowslocal] * _bs[0] * _bs[1]);
890
891 std::span<const Scalar> _x = x.array();
892 std::span<Scalar> _y = y.array();
893
894 std::span<const std::int64_t> Arow_begin(Arow_ptr.data(), nrowslocal);
895 std::span<const std::int64_t> Arow_end(Arow_ptr.data() + 1, nrowslocal);
896
897 // First stage: spmv - diagonal
898 // yi[0] += Ai[0] * xi[0]
899 if (_bs[1] == 1)
900 {
901 impl::spmv<Scalar, 1>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
902 _bs[0], 1);
903 }
904 else
905 {
906 impl::spmv<Scalar, -1>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
907 _bs[0], _bs[1]);
908 }
909
910 // finalize ghost update
911 x.scatter_fwd_end();
912
913 // Second stage: spmv - off-diagonal
914 // yi[0] += Ai[1] * xi[1]
915 if (_bs[1] == 1)
916 {
917 impl::spmv<Scalar, 1>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
918 _bs[0], 1);
919 }
920 else
921 {
922 impl::spmv<Scalar, -1>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
923 _bs[0], _bs[1]);
924 }
925}
926
929template <typename Scalar, typename V, typename W, typename X>
931 la::Vector<Scalar>& y) const
932{
933 std::int32_t nrowslocal = num_owned_rows();
934 std::span<const std::int64_t> Arow_ptr(row_ptr().data(), nrowslocal + 1);
935 std::span<const std::int32_t> Acols(cols().data(), Arow_ptr[nrowslocal]);
936 std::span<const std::int64_t> Aoff_diag_offset(off_diag_offset().data(),
937 nrowslocal);
938 std::span<const Scalar> Avalues(values().data(),
939 Arow_ptr[nrowslocal] * _bs[0] * _bs[1]);
940
941 std::span<const Scalar> _x = x.array();
942 std::span<Scalar> _y = y.array();
943
944 std::span<const std::int64_t> Arow_begin(Arow_ptr.data(), nrowslocal);
945 std::span<const std::int64_t> Arow_end(Arow_ptr.data() + 1, nrowslocal);
946
947 // Compute ghost region contribution and scatter back. Zero only the
948 // ghost portion of y so the caller's owned values are preserved (multT
949 // accumulates).
950 int ncolslocal = index_map(1)->size_local();
951 std::fill(std::next(_y.begin(), ncolslocal * _bs[1]), _y.end(), Scalar(0));
952 if (_bs[1] == 1)
953 impl::spmvT<Scalar, 1>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
954 _bs[0], 1);
955 else
956 impl::spmvT<Scalar, -1>(Avalues, Aoff_diag_offset, Arow_end, Acols, _x, _y,
957 _bs[0], _bs[1]);
958
959 y.scatter_rev(std::plus<Scalar>{});
960
961 if (_bs[1] == 1)
962 impl::spmvT<Scalar, 1>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x, _y,
963 _bs[0], 1);
964 else
965 impl::spmvT<Scalar, -1>(Avalues, Arow_begin, Aoff_diag_offset, Acols, _x,
966 _y, _bs[0], _bs[1]);
967}
968
969} // namespace dolfinx::la
A duplicate MPI communicator and manage lifetime of the communicator.
Definition MPI.h:43
const container_type & values() const
Get local values (const version).
Definition MatrixCSR.h:552
std::shared_ptr< const common::IndexMap > index_map(int dim) const
Index map for the row or column space.
Definition MatrixCSR.h:541
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:571
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:265
MatrixCSR(const MatrixCSR< Scalar0, Container0, ColContainer0, RowPtrContainer0 > &A)
Copy-convert matrix, possibly using to different container types.
Definition MatrixCSR.h:224
RowPtrContainer rowptr_container_type
Row pointer container type.
Definition MatrixCSR.h:89
void scatter_rev_end()
End transfer of ghost row data to owning ranks.
Definition MatrixCSR.h:445
container_type & values()
Get local data values.
Definition MatrixCSR.h:548
auto mat_add_values()
Insertion functor for adding values to a matrix. It is typically used in finite element assembly func...
Definition MatrixCSR.h:157
BlockMode block_mode() const
Get 'block mode'.
Definition MatrixCSR.h:581
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:310
std::int32_t num_owned_rows() const
Number of local rows excluding ghost rows.
Definition MatrixCSR.h:337
ColContainer column_container_type
Column index container type.
Definition MatrixCSR.h:86
void mult(Vector< value_type > &x, Vector< value_type > &y) const
Compute the product y += Ax.
Definition MatrixCSR.h:877
MatrixCSR(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:472
void scatter_rev()
Transfer ghost row data to the owning ranks accumulating received values on the owned rows,...
Definition MatrixCSR.h:383
void multT(Vector< value_type > &x, Vector< value_type > &y) const
Compute the product y += A^T x.
Definition MatrixCSR.h:930
Container container_type
Matrix entries container type.
Definition MatrixCSR.h:83
Scalar value_type
Scalar type.
Definition MatrixCSR.h:80
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:398
const column_container_type & cols() const
Definition MatrixCSR.h:560
void set(value_type x)
Set all non-zero local entries to a value, including entries in ghost rows.
Definition MatrixCSR.h:243
std::array< int, 2 > block_size() const
Get block sizes.
Definition MatrixCSR.h:578
std::int32_t num_all_rows() const
Number of local rows including ghost rows.
Definition MatrixCSR.h:340
const rowptr_container_type & row_ptr() const
Get local row pointers.
Definition MatrixCSR.h:556
std::vector< value_type > to_dense() const
Copy to a dense matrix.
Definition MatrixCSR.h:351
MPI_Comm comm() const
Get MPI communicator that matrix is defined on.
Definition MatrixCSR.h:532
MatrixCSR(const MatrixCSR &A)=default
auto mat_set_values()
Insertion functor for setting values in a matrix. It is typically used in finite element assembly fun...
Definition MatrixCSR.h:115
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
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:375
void scatter_fwd_end(U unpack)
End scatter (send) of local data values that are ghosted on other processes.
Definition Vector.h:259
void scatter_fwd_begin(U pack, GetPtr get_ptr)
Begin scatter (send) of local data that is ghosted on other processes.
Definition Vector.h:222
Definition MatrixCSR.h:25
MPI_Datatype mpi_t
Retrieves the MPI data type associated to the provided type.
Definition MPI.h:257
void check_error(MPI_Comm comm, int code)
Check MPI error code. If the error code is not equal to MPI_SUCCESS, then std::abort is called.
Definition MPI.cpp:80
int size(MPI_Comm comm)
Definition MPI.cpp:72
int rank(MPI_Comm comm)
Return process rank for the communicator.
Definition MPI.cpp:64
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:480