From e50e6edb42948ea29fdf2398db2267ec200c973a Mon Sep 17 00:00:00 2001 From: Jacob Merson Date: Sat, 28 Nov 2026 02:06:53 +0000 Subject: [PATCH 1/7] fix(field): reuse the host copy behind GetDOFHolderDataHost A second GetDOFHolderDataHost on the same field reallocated the host copy and left the first view dangling on device builds. --- include/pcms/field/field.hpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/include/pcms/field/field.hpp b/include/pcms/field/field.hpp index 33ccacfa6..a823d8f82 100644 --- a/include/pcms/field/field.hpp +++ b/include/pcms/field/field.hpp @@ -158,9 +158,12 @@ class Field Kokkos::view_alloc(Kokkos::WithoutInitializing, "owned_values_staged"), values.extent(0), values.extent(1)); detail::CopyDeviceRank2ViewToRank2View(MakeRank2View(staged), values); - host_values_ = Kokkos::View( - Kokkos::view_alloc(Kokkos::WithoutInitializing, "owned_values_host"), - values.extent(0), values.extent(1)); + if (host_values_.extent(0) != values.extent(0) || + host_values_.extent(1) != values.extent(1)) { + host_values_ = Kokkos::View( + Kokkos::view_alloc(Kokkos::WithoutInitializing, "owned_values_host"), + values.extent(0), values.extent(1)); + } DeepCopyMismatchLayouts(host_values_, staged); return MakeConstRank2View(host_values_); } @@ -190,7 +193,7 @@ class Field std::shared_ptr layout_; std::unique_ptr> data_; // Host copy backing GetDOFHolderDataHost when device memory is not host - // memory. + // memory; reused, so earlier host views stay valid. mutable Kokkos::View host_values_; }; From add1707b96039bd186afb025a3018ee7ae1d3e04 Mon Sep 17 00:00:00 2001 From: Jacob Merson Date: Fri, 27 Nov 2026 06:54:36 +0000 Subject: [PATCH 2/7] feat(field): the owned global ids on the device, FieldLayout::GetGids --- include/pcms/field/field_layout.hpp | 5 +++++ .../backends/omega_h/lagrange_evaluator.hpp | 2 +- src/pcms/backends/omega_h/lagrange_layout.cpp | 2 +- src/pcms/backends/omega_h/lagrange_layout.hpp | 3 ++- src/pcms/field/field_layout.cpp | 13 +++++++++++++ test/test_omega_h_lagrange_field.cpp | 17 +++++++++++++++++ 6 files changed, 39 insertions(+), 3 deletions(-) diff --git a/include/pcms/field/field_layout.hpp b/include/pcms/field/field_layout.hpp index 8691f4a41..8fb605dcf 100644 --- a/include/pcms/field/field_layout.hpp +++ b/include/pcms/field/field_layout.hpp @@ -95,6 +95,9 @@ class FieldLayout virtual GlobalIDView GetGidsHost() const = 0; + // Device analogue of GetGidsHost(): the global ids of the owned DOF holders. + [[nodiscard]] virtual GlobalIDView GetGids() const; + // Maps each local DOF holder to its contiguous active index, ordered by GID // within each entity block. Components are not included in the permutation. // For local GIDs [102, 7, 41, 19], the permutation is [3, 0, 2, 1]. Thus @@ -172,6 +175,8 @@ class FieldLayout std::shared_ptr geometry_; std::string name_; Kokkos::View global_to_local_host_; + // GetGids(): the owned global ids copied to the device on first use + mutable Kokkos::View gids_; Kokkos::View global_to_local_; }; diff --git a/src/pcms/backends/omega_h/lagrange_evaluator.hpp b/src/pcms/backends/omega_h/lagrange_evaluator.hpp index 58fee0658..133c5b180 100644 --- a/src/pcms/backends/omega_h/lagrange_evaluator.hpp +++ b/src/pcms/backends/omega_h/lagrange_evaluator.hpp @@ -193,7 +193,7 @@ class OmegaHLagrangePointEvaluator : public PointEvaluator const int stride = stride_; const auto holders = holders_; const auto weights = weights_; - const auto gids = layout_->GetGids(); + const auto gids = layout_->GetGidsWithGhosts(); Kokkos::View offsets("offsets", n + 1); Kokkos::View columns("columns", holders.extent(0)); Kokkos::View entries("entries", holders.extent(0)); diff --git a/src/pcms/backends/omega_h/lagrange_layout.cpp b/src/pcms/backends/omega_h/lagrange_layout.cpp index dc58ba05f..a3102e000 100644 --- a/src/pcms/backends/omega_h/lagrange_layout.cpp +++ b/src/pcms/backends/omega_h/lagrange_layout.cpp @@ -167,7 +167,7 @@ GlobalIDView OmegaHLagrangeLayout::GetGidsHost() const owned_gids_host_.size()); } -GlobalIDView OmegaHLagrangeLayout::GetGids() const +GlobalIDView OmegaHLagrangeLayout::GetGidsWithGhosts() const { return GlobalIDView(gids_.data(), gids_.size()); } diff --git a/src/pcms/backends/omega_h/lagrange_layout.hpp b/src/pcms/backends/omega_h/lagrange_layout.hpp index cc0bf960a..3f2538ab8 100644 --- a/src/pcms/backends/omega_h/lagrange_layout.hpp +++ b/src/pcms/backends/omega_h/lagrange_layout.hpp @@ -38,7 +38,8 @@ class OmegaHLagrangeLayout : public FieldLayout Rank1View GetOwnedHost() const override; GlobalIDView GetGidsHost() const override; - GlobalIDView GetGids() const; + /// @return the global ids of the DOF holders with ghosts, in mesh order + [[nodiscard]] GlobalIDView GetGidsWithGhosts() const; CoordinateView GetDOFHolderCoordinates() const override; EntOffsetsArray GetEntOffsets() const override; Kokkos::View GetOwnedIndicesHost() const override; diff --git a/src/pcms/field/field_layout.cpp b/src/pcms/field/field_layout.cpp index fdd34f7fb..3ecde2439 100644 --- a/src/pcms/field/field_layout.cpp +++ b/src/pcms/field/field_layout.cpp @@ -50,6 +50,19 @@ void FieldLayout::BuildGlobalToLocalPermutation( Kokkos::deep_copy(global_to_local_, global_to_local_host_); } +GlobalIDView FieldLayout::GetGids() const +{ + const auto host = GetGidsHost(); + if (gids_.extent(0) != host.size()) { + Kokkos::View copy("field_layout_gids", host.size()); + for (std::size_t i = 0; i < host.size(); ++i) { + copy(i) = host[i]; + } + gids_ = Kokkos::create_mirror_view_and_copy(DeviceMemorySpace{}, copy); + } + return GlobalIDView(gids_.data(), gids_.size()); +} + Kokkos::View FieldLayout::GetGlobalToLocalPermutationHost() const { diff --git a/test/test_omega_h_lagrange_field.cpp b/test/test_omega_h_lagrange_field.cpp index 4b16ecb6e..1a7f7c934 100644 --- a/test/test_omega_h_lagrange_field.cpp +++ b/test/test_omega_h_lagrange_field.cpp @@ -66,6 +66,23 @@ TEST_CASE("OmegaHLagrangeLayout order-1 properties") REQUIRE(offsets[0] == 0); for (int i = 1; i < pcms::ent_offsets_len; ++i) REQUIRE(offsets[i] == nverts); + + // GetGids is GetGidsHost on the device + const auto host_gids = layout.GetGidsHost(); + const auto device_gids = layout.GetGids(); + REQUIRE(device_gids.size() == host_gids.size()); + Kokkos::View copied("gids", + device_gids.size()); + Kokkos::parallel_for( + "copy_gids", + Kokkos::RangePolicy( + 0, static_cast(copied.extent(0))), + KOKKOS_LAMBDA(const LO i) { copied(i) = device_gids[i]; }); + const auto copied_host = + Kokkos::create_mirror_view_and_copy(pcms::HostMemorySpace{}, copied); + for (std::size_t i = 0; i < host_gids.size(); ++i) { + CHECK(copied_host(i) == host_gids[i]); + } } TEST_CASE("OmegaHLagrangeLayout order-0 properties") From c6001f771ed25c8822466fbd48ead5bcac20b681 Mon Sep 17 00:00:00 2001 From: Jacob Merson Date: Fri, 27 Nov 2026 04:21:09 +0000 Subject: [PATCH 3/7] feat(field): internal accumulating transpose, functional = E^T values + beta functional --- .../pcms/field/detail/evaluate_transpose.hpp | 21 ++++++++ include/pcms/field/point_evaluator.hpp | 48 +++++++++++++++---- src/pcms/backends/omega_h/field_data.hpp | 21 ++++++-- .../backends/omega_h/lagrange_evaluator.hpp | 4 +- src/pcms/field/CMakeLists.txt | 1 + test/test_distributed_evaluation.cpp | 13 +++++ 6 files changed, 95 insertions(+), 13 deletions(-) create mode 100644 include/pcms/field/detail/evaluate_transpose.hpp diff --git a/include/pcms/field/detail/evaluate_transpose.hpp b/include/pcms/field/detail/evaluate_transpose.hpp new file mode 100644 index 000000000..71ae59bc2 --- /dev/null +++ b/include/pcms/field/detail/evaluate_transpose.hpp @@ -0,0 +1,21 @@ +// Part of pcms/field/point_evaluator.hpp, which includes it after declaring +// PointEvaluator and before defining it. +#include "pcms/field/point_evaluator.hpp" +#ifndef PCMS_FIELD_DETAIL_EVALUATE_TRANSPOSE_HPP +#define PCMS_FIELD_DETAIL_EVALUATE_TRANSPOSE_HPP + +namespace pcms::detail +{ + +/// @brief functional = E^T values + beta functional, with the checks of +/// PointEvaluator::EvaluateTranspose; beta == 0 does not read the +/// functional (collective) +template +void EvaluateTranspose( + const PointEvaluator& evaluator, + ValueView values, + Field& functional, T beta); + +} // namespace pcms::detail + +#endif // PCMS_FIELD_DETAIL_EVALUATE_TRANSPOSE_HPP diff --git a/include/pcms/field/point_evaluator.hpp b/include/pcms/field/point_evaluator.hpp index b248358d4..70a3e3b95 100644 --- a/include/pcms/field/point_evaluator.hpp +++ b/include/pcms/field/point_evaluator.hpp @@ -23,6 +23,15 @@ namespace pcms template class Field; +template +class PointEvaluator; +} // namespace pcms + +#include "pcms/field/detail/evaluate_transpose.hpp" + +namespace pcms +{ + /// @brief The evaluation at the points as a CSR matrix whose columns are the /// global ids of the DOF holders. template @@ -92,11 +101,7 @@ class PointEvaluator ValueView values, Field& functional) const { - if (!SupportsTranspose() || op_ != DifferentialOperator::Value) { - throw pcms_error("PointEvaluator::EvaluateTranspose: not supported"); - } - CheckArguments("PointEvaluator::EvaluateTranspose", functional, values); - EvaluateTransposeImpl(values.GetValues(), functional); + TransposeChecked(values, functional, T{}); } /// @return whether GetMatrix and the Value operator are supported @@ -182,11 +187,12 @@ class PointEvaluator const Field& field, ValueView values) const = 0; - /// @brief Adds E^T values to the functional; called only if - /// SupportsTranspose(), with checked arguments. + /// @brief functional = E^T values + beta functional, on the owned DOF + /// holders, synchronized; beta == 0 must not read the functional. + /// Called only if SupportsTranspose(), with checked arguments. virtual void EvaluateTransposeImpl( Rank2View /*values*/, - Field& /*functional*/) const + Field& /*functional*/, T /*beta*/) const { } @@ -194,6 +200,23 @@ class PointEvaluator virtual PointMatrix GetMatrixImpl() const { return {}; } private: + template + friend void detail::EvaluateTranspose( + const PointEvaluator& evaluator, + ValueView values, Field& functional, + U beta); + + void TransposeChecked( + ValueView values, + Field& functional, T beta) const + { + if (!SupportsTranspose() || op_ != DifferentialOperator::Value) { + throw pcms_error("PointEvaluator::EvaluateTranspose: not supported"); + } + CheckArguments("PointEvaluator::EvaluateTranspose", functional, values); + EvaluateTransposeImpl(values.GetValues(), functional, beta); + } + /// @brief Checks that `field` is of the accepted layout and that `values` /// has the basis and shape of the output for it. /// @throws pcms_error if the layout or the basis differs @@ -235,6 +258,15 @@ class PointEvaluator std::shared_ptr accepted_layout_; }; +template +void detail::EvaluateTranspose( + const PointEvaluator& evaluator, + ValueView values, + Field& functional, T beta) +{ + evaluator.TransposeChecked(values, functional, beta); +} + // Variant types using default layout for device memory space using PointEvaluatorVariant = std::variant>, diff --git a/src/pcms/backends/omega_h/field_data.hpp b/src/pcms/backends/omega_h/field_data.hpp index bedf625f5..2ab27831f 100644 --- a/src/pcms/backends/omega_h/field_data.hpp +++ b/src/pcms/backends/omega_h/field_data.hpp @@ -134,11 +134,26 @@ class OmegaHFieldData // Fills the tag's ghost entries with their owners' values. Collective. void Synchronize() override { mesh_->sync_tag(tag_dim_, tag_name_); } - // Sets the values from one entry per entity and component, of which only - // the owners' entries are read, and fills the ghosts. Collective. - void SetFromOwners(Omega_h::Read values) + // Sets the values to `values` + beta times the current ones, from one entry + // per entity and component, of which only the owners' entries are read, and + // fills the ghosts. beta == 0 does not read the current values. Collective. + void SetFromOwners(Omega_h::Read values, T beta = T{}) { const int nc = layout_->GetNumComponents(); + if (beta != T{}) { + const auto current = + mesh_->get_array(tag_dim_, tag_name_); + Omega_h::Write combined(values.size(), "set_from_owners"); + const auto b = static_cast(beta); + Kokkos::parallel_for( + "pcms::OmegaHFieldData::SetFromOwners::Combine", + Kokkos::RangePolicy(0, + values.size()), + KOKKOS_LAMBDA(const LO i) { + combined[i] = values[i] + b * current[i]; + }); + values = Omega_h::Read(combined); + } const auto synced = mesh_->sync_array(tag_dim_, values, nc); mesh_->set_tag(tag_dim_, tag_name_, synced); const auto owned = layout_->GetOwnedIndices(); diff --git a/src/pcms/backends/omega_h/lagrange_evaluator.hpp b/src/pcms/backends/omega_h/lagrange_evaluator.hpp index 133c5b180..d781fd0b8 100644 --- a/src/pcms/backends/omega_h/lagrange_evaluator.hpp +++ b/src/pcms/backends/omega_h/lagrange_evaluator.hpp @@ -154,7 +154,7 @@ class OmegaHLagrangePointEvaluator : public PointEvaluator // Public for the same reason as EvaluateImpl. void EvaluateTransposeImpl( Rank2View values, - Field& functional) const override + Field& functional, T beta) const override { PCMS_FUNCTION_TIMER; using TagValue = utility::OmegaHValue_t; @@ -182,7 +182,7 @@ class OmegaHLagrangePointEvaluator : public PointEvaluator layout_->GetDOFHolderEntityDim(), Omega_h::Read(sums), n_comp, OMEGA_H_SUM); dynamic_cast&>(functional.GetData()) - .SetFromOwners(reduced); + .SetFromOwners(reduced, beta); } [[nodiscard]] bool SupportsMatrix() const noexcept override { return true; } diff --git a/src/pcms/field/CMakeLists.txt b/src/pcms/field/CMakeLists.txt index ae55e25cd..88a48870f 100644 --- a/src/pcms/field/CMakeLists.txt +++ b/src/pcms/field/CMakeLists.txt @@ -11,6 +11,7 @@ set(PCMS_FIELD_HEADERS ../../../include/pcms/field/field_factory.hpp ../../../include/pcms/field/function_space.hpp ../../../include/pcms/field/point_evaluator.hpp + ../../../include/pcms/field/detail/evaluate_transpose.hpp ../../../include/pcms/field/point_evaluator_factory.hpp ../../../include/pcms/field/query_points.hpp ../../../include/pcms/field/differential_operator.hpp diff --git a/test/test_distributed_evaluation.cpp b/test/test_distributed_evaluation.cpp index 18c912aa5..717f96cc7 100644 --- a/test/test_distributed_evaluation.cpp +++ b/test/test_distributed_evaluation.cpp @@ -311,6 +311,19 @@ void CheckTransposeAndMatrix(const pcms::FunctionSpace& space, Check(differ == 0, name + ": a second EvaluateTranspose overwrites"); } + pcms::detail::EvaluateTranspose(*evaluator, y_view, functional, + pcms::Real(1)); + { + const auto twice = functional.GetDOFHolderDataHost().GetValues(); + int differ = 0; + for (LO h = 0; h < n_owned; ++h) { + for (int c = 0; c < nc; ++c) { + differ += std::abs(twice(h, c) - 2 * once(h, c)) > 1e-14; + } + } + Check(differ == 0, name + ": beta = 1 adds E^T y to the functional"); + } + // E x from the CSR rows, with x looked up by global id const auto matrix = evaluator->GetMatrix(); const auto offsets = Kokkos::create_mirror_view_and_copy( From e78f992917a76335b44b70f358dc17b0cf8df901 Mon Sep 17 00:00:00 2001 From: Jacob Merson Date: Fri, 27 Nov 2026 04:35:59 +0000 Subject: [PATCH 4/7] refactor(field): the evaluation rows are internal; no public evaluation matrix --- include/pcms/field/point_evaluator.hpp | 27 ---------- .../backends/omega_h/lagrange_evaluator.hpp | 51 ++++++++++--------- src/pcms/field/CMakeLists.txt | 1 + src/pcms/field/point_rows.hpp | 50 ++++++++++++++++++ test/test_distributed_evaluation.cpp | 47 ++--------------- test/test_galerkin_projection.cpp | 22 ++++---- 6 files changed, 92 insertions(+), 106 deletions(-) create mode 100644 src/pcms/field/point_rows.hpp diff --git a/include/pcms/field/point_evaluator.hpp b/include/pcms/field/point_evaluator.hpp index 70a3e3b95..c391682ec 100644 --- a/include/pcms/field/point_evaluator.hpp +++ b/include/pcms/field/point_evaluator.hpp @@ -32,16 +32,6 @@ class PointEvaluator; namespace pcms { -/// @brief The evaluation at the points as a CSR matrix whose columns are the -/// global ids of the DOF holders. -template -struct PointMatrix -{ - Kokkos::View row_offsets; // [points + 1] - Kokkos::View columns; // [entries] - Kokkos::View values; // [entries] -}; - /// @brief Evaluates fields at the points of a BoundPoints. /// /// Created by PointEvaluatorFactory::CreatePointEvaluator. Evaluate writes @@ -104,20 +94,6 @@ class PointEvaluator TransposeChecked(values, functional, T{}); } - /// @return whether GetMatrix and the Value operator are supported - [[nodiscard]] virtual bool SupportsMatrix() const noexcept { return false; } - - /// @brief The evaluation as a sparse matrix E: component c of the values is - /// E times component c of the DOFs. - /// @throws pcms_error if the matrix is not supported - [[nodiscard]] PointMatrix GetMatrix() const - { - if (!SupportsMatrix() || op_ != DifferentialOperator::Value) { - throw pcms_error("PointEvaluator::GetMatrix: not supported"); - } - return GetMatrixImpl(); - } - /// @return number of query points [[nodiscard]] LO NumPoints() const noexcept { return bound_->NumPoints(); } @@ -196,9 +172,6 @@ class PointEvaluator { } - /// @return the evaluation matrix; called only if SupportsMatrix() - virtual PointMatrix GetMatrixImpl() const { return {}; } - private: template friend void detail::EvaluateTranspose( diff --git a/src/pcms/backends/omega_h/lagrange_evaluator.hpp b/src/pcms/backends/omega_h/lagrange_evaluator.hpp index d781fd0b8..ded982f55 100644 --- a/src/pcms/backends/omega_h/lagrange_evaluator.hpp +++ b/src/pcms/backends/omega_h/lagrange_evaluator.hpp @@ -5,6 +5,7 @@ #include "pcms/backends/omega_h/lagrange_layout.hpp" #include "pcms/field/point_evaluator_factory.hpp" #include "pcms/field/point_evaluator.hpp" +#include "pcms/field/point_rows.hpp" #include "pcms/field/field_data.hpp" #include "pcms/backends/omega_h/field_data.hpp" #include "pcms/utility/assert.hpp" @@ -69,6 +70,19 @@ void FillOmegaHLagrangeRows( }); } +/// @return the offsets of `num_rows` rows of `stride` entries each +inline Kokkos::View StrideOffsets(LO num_rows, + int stride) +{ + Kokkos::View offsets("omega_h_lagrange_offsets", + num_rows + 1); + Kokkos::parallel_for( + "pcms::omega_h::StrideOffsets", + Kokkos::RangePolicy(0, num_rows + 1), + KOKKOS_LAMBDA(const LO p) { offsets(p) = p * stride; }); + return offsets; +} + } // namespace detail // OmegaHLagrangePointEvaluator implements PointEvaluator for simplex @@ -83,7 +97,9 @@ void FillOmegaHLagrangeRows( template > -class OmegaHLagrangePointEvaluator : public PointEvaluator +class OmegaHLagrangePointEvaluator + : public PointEvaluator + , public pcms::detail::RowsSource { public: /// @param layout Omega_h Lagrange layout of the evaluated fields @@ -108,6 +124,9 @@ class OmegaHLagrangePointEvaluator : public PointEvaluator detail::FillOmegaHLagrangeRows<3>(mesh, layout_->GetOrder(), *binding_, holders_, weights_); } + rows_ = pcms::detail::PointRows{ + detail::StrideOffsets(binding_->NumPoints(), stride_), holders_, + weights_}; } // Public because CUDA forbids extended lambdas in non-public member @@ -185,38 +204,24 @@ class OmegaHLagrangePointEvaluator : public PointEvaluator .SetFromOwners(reduced, beta); } - [[nodiscard]] bool SupportsMatrix() const noexcept override { return true; } + [[nodiscard]] const pcms::detail::PointRows& Rows() const override + { + return rows_; + } - PointMatrix GetMatrixImpl() const override + [[nodiscard]] GlobalIDView HolderGids() const override { - const LO n = binding_->NumPoints(); - const int stride = stride_; - const auto holders = holders_; - const auto weights = weights_; - const auto gids = layout_->GetGidsWithGhosts(); - Kokkos::View offsets("offsets", n + 1); - Kokkos::View columns("columns", holders.extent(0)); - Kokkos::View entries("entries", holders.extent(0)); - Kokkos::parallel_for( - "OmegaHLagrangePointEvaluator::GetMatrix", - Kokkos::RangePolicy(0, n + 1), - KOKKOS_LAMBDA(const LO p) { - offsets(p) = p * stride; - for (int v = p * stride; p < n && v < (p + 1) * stride; ++v) { - columns(v) = gids[holders(v)]; - entries(v) = static_cast(weights(v)); - } - }); - return PointMatrix{offsets, columns, entries}; + return layout_->GetGidsWithGhosts(); } private: std::shared_ptr layout_; std::shared_ptr binding_; - // the evaluation matrix: stride_ entries per point + // the evaluation rows: stride_ entries per point int stride_; Kokkos::View holders_; Kokkos::View weights_; + pcms::detail::PointRows rows_; }; // --------------------------------------------------------------------------- diff --git a/src/pcms/field/CMakeLists.txt b/src/pcms/field/CMakeLists.txt index 88a48870f..9bacb9c83 100644 --- a/src/pcms/field/CMakeLists.txt +++ b/src/pcms/field/CMakeLists.txt @@ -4,6 +4,7 @@ set(PCMS_FIELD_HEADERS ../../../include/pcms/field/value_view.hpp element_dispatch.hpp gid_permutation.hpp + point_rows.hpp ../../../include/pcms/field/field_layout.hpp layout/empty.hpp ../../../include/pcms/field/out_of_bounds_policy.hpp diff --git a/src/pcms/field/point_rows.hpp b/src/pcms/field/point_rows.hpp new file mode 100644 index 000000000..600627bf0 --- /dev/null +++ b/src/pcms/field/point_rows.hpp @@ -0,0 +1,50 @@ +#ifndef PCMS_FIELD_POINT_ROWS_HPP +#define PCMS_FIELD_POINT_ROWS_HPP + +// Private: the evaluation of a field at a set of points as sparse rows of DOF +// weights. + +#include "pcms/field/point_evaluator.hpp" +#include "pcms/utility/arrays.hpp" +#include "pcms/utility/memory_spaces.hpp" +#include "pcms/utility/types.hpp" +#include + +namespace pcms::detail +{ + +/// @brief The evaluation at a set of points as CSR rows: row p holds the +/// (DOF holder, weight) entries of point p, the same for every +/// component. A holder indexes the layout's DOF holders, ghosts +/// included, in the order of FieldLayout::GetOwnedHost. +struct PointRows +{ + Kokkos::View offsets; // [rows + 1] + Kokkos::View holders; + Kokkos::View values; +}; + +/// @brief An evaluator whose evaluation is a PointRows. +class RowsSource +{ +public: + [[nodiscard]] virtual const PointRows& Rows() const = 0; + + /// @return the global id of each DOF holder the rows index; a ghost has + /// its owner's id + [[nodiscard]] virtual GlobalIDView HolderGids() const = 0; + +protected: + ~RowsSource() = default; +}; + +/// @return `evaluator` as a RowsSource, or null if its evaluation has no rows +[[nodiscard]] inline const RowsSource* AsRowsSource( + const PointEvaluator& evaluator) +{ + return dynamic_cast(&evaluator); +} + +} // namespace pcms::detail + +#endif // PCMS_FIELD_POINT_ROWS_HPP diff --git a/test/test_distributed_evaluation.cpp b/test/test_distributed_evaluation.cpp index 717f96cc7..3ea84ab23 100644 --- a/test/test_distributed_evaluation.cpp +++ b/test/test_distributed_evaluation.cpp @@ -237,9 +237,9 @@ void CheckEvaluate(const pcms::FunctionSpace& space, } // The adjoint identity summed over the ranks, the overwrite of a second -// EvaluateTranspose, and the matrix against Evaluate. -void CheckTransposeAndMatrix(const pcms::FunctionSpace& space, - const Points& bound, const std::string& name) +// EvaluateTranspose, and the accumulation with beta = 1. +void CheckTranspose(const pcms::FunctionSpace& space, const Points& bound, + const std::string& name) { const auto& layout = *space.GetLayout(); const int nc = layout.GetNumComponents(); @@ -323,45 +323,6 @@ void CheckTransposeAndMatrix(const pcms::FunctionSpace& space, } Check(differ == 0, name + ": beta = 1 adds E^T y to the functional"); } - - // E x from the CSR rows, with x looked up by global id - const auto matrix = evaluator->GetMatrix(); - const auto offsets = Kokkos::create_mirror_view_and_copy( - pcms::HostMemorySpace{}, matrix.row_offsets); - const auto columns = Kokkos::create_mirror_view_and_copy( - pcms::HostMemorySpace{}, matrix.columns); - const auto entries = - Kokkos::create_mirror_view_and_copy(pcms::HostMemorySpace{}, matrix.values); - Check(offsets.extent(0) == static_cast(n_points) + 1, - name + ": one CSR row per point"); - int wrong = 0; - for (LO p = 0; p + 1 < static_cast(offsets.extent(0)); ++p) { - for (int c = 0; c < nc; ++c) { - Real sum = 0; - for (LO k = offsets(p); k < offsets(p + 1); ++k) { - sum += entries(k) * DofOfGid(columns(k), c); - } - if (std::abs(sum - e_x(p, c)) > 1e-13) { - if (wrong < 3) { - std::fprintf(stderr, - "[rank %d] %s: point %d of %d comp %d: rows %.17g, " - "Evaluate %.17g\n", - Rank(), name.c_str(), p, n_points, c, sum, e_x(p, c)); - for (LO k = offsets(p); k < offsets(p + 1); ++k) { - std::fprintf(stderr, " k %d gid %lld weight %.17g value %.17g\n", - k, static_cast(columns(k)), entries(k), - DofOfGid(columns(k), c)); - } - } - ++wrong; - } - } - } - if (wrong > 0) { - std::fprintf(stderr, "[rank %d] %s: %d of %d values differ\n", Rank(), - name.c_str(), wrong, n_points * nc); - } - Check(wrong == 0, name + ": the CSR rows times x equal Evaluate"); } // A quadrature sums to the domain measure over the ranks and, given its @@ -428,7 +389,7 @@ void RunCases(Omega_h::Library& library, int dim, bool ghosted) geometry, order, nc, pcms::LagrangeOptions{.backend = pcms::LagrangeBackend::OmegaH}); CheckEvaluate(*space, points, bound, dim, name); - CheckTransposeAndMatrix(*space, bound, name); + CheckTranspose(*space, bound, name); if (nc == 1) { CheckQuadrature(space->GetQuadrature(), mesh, PointsPerElement(library, dim, std::max(1, 2 * order)), diff --git a/test/test_galerkin_projection.cpp b/test/test_galerkin_projection.cpp index ac4658099..51d1bdfad 100644 --- a/test/test_galerkin_projection.cpp +++ b/test/test_galerkin_projection.cpp @@ -7,6 +7,7 @@ #include #include #include "field_test_utils.hpp" +#include "pcms/field/point_rows.hpp" #include #include #include @@ -114,26 +115,21 @@ void CheckAdjoint(const std::shared_ptr& space, } } - // the matrix form: E x from the CSR rows equals Evaluate - if (evaluator.SupportsMatrix()) { - const auto matrix = evaluator.GetMatrix(); + // the evaluation rows: E x from the CSR rows equals Evaluate + if (const auto* source = pcms::detail::AsRowsSource(evaluator)) { + const auto* rows = &source->Rows(); const auto offsets = Kokkos::create_mirror_view_and_copy( - pcms::HostMemorySpace{}, matrix.row_offsets); - const auto columns = Kokkos::create_mirror_view_and_copy( - pcms::HostMemorySpace{}, matrix.columns); + pcms::HostMemorySpace{}, rows->offsets); + const auto holders = Kokkos::create_mirror_view_and_copy( + pcms::HostMemorySpace{}, rows->holders); const auto values = Kokkos::create_mirror_view_and_copy( - pcms::HostMemorySpace{}, matrix.values); - const auto gids = space->GetLayout()->GetGidsHost(); - std::map holder_of; - for (std::size_t h = 0; h < gids.extent(0); ++h) { - holder_of[gids(h)] = static_cast(h); - } + pcms::HostMemorySpace{}, rows->values); REQUIRE(offsets.extent(0) == static_cast(num_points) + 1); for (int p = 0; p < num_points; ++p) { for (int c = 0; c < num_components; ++c) { double sum = 0; for (int k = offsets(p); k < offsets(p + 1); ++k) { - sum += values(k) * x(holder_of.at(columns(k)), c); + sum += values(k) * x(holders(k), c); } CHECK(sum == Catch::Approx(e_x_host(p, c)).margin(1e-13)); } From 231d9e8122789f6be749a535977f94e2220076cb Mon Sep 17 00:00:00 2001 From: Jacob Merson Date: Thu, 26 Nov 2026 23:38:30 +0000 Subject: [PATCH 5/7] feat(transfer): Bilinear forms E_test^T W G E_trial and the linear solver Linear and bilinear forms on the overwriting EvaluateTranspose, and the matrix-free and PETSc linear solvers. FieldData gains protected coefficient operations named after SUNDIALS N_Vector (LinearSum, Scale, Const, Div, DotProdLocal, SumOverRanks, MaxOverRanks), which the simple, Omega_h, MeshFields and point-cloud kinds implement in place on their storage. Internal functions over Fields check the operands and call them. The geometry gains a protected reduction over its ranks, which the Omega_h geometry implements on its mesh's communicator: BilinearForm Pair and Contract sum over the ranks of the quadrature's geometry. --- include/pcms/field/detail/field_data.hpp | 83 +++++ include/pcms/field/detail/field_data_ops.hpp | 144 ++++++++ include/pcms/field/detail/field_ops.hpp | 128 +++++++ .../pcms/field/detail/simple_field_data.hpp | 37 ++ include/pcms/field/field_data.hpp | 93 +++++ include/pcms/geometry/detail/quadrature.hpp | 9 + include/pcms/geometry/geometry.hpp | 15 + include/pcms/transfer/projection.hpp | 27 ++ src/pcms/backends/omega_h/entity_layout.cpp | 2 +- src/pcms/backends/omega_h/field_data.hpp | 82 ++++- src/pcms/backends/omega_h/geometry.cpp | 15 + src/pcms/backends/omega_h/lagrange_layout.cpp | 2 +- .../backends/omega_h/omega_h_geometry.hpp | 7 + .../omega_h_meshfields/field_data.hpp | 93 ++++- .../backends/omega_h_meshfields/layout.cpp | 2 +- src/pcms/backends/point_cloud/field_data.cpp | 43 +++ src/pcms/backends/point_cloud/field_data.hpp | 13 + src/pcms/field/CMakeLists.txt | 3 + src/pcms/geometry/geometry.cpp | 10 + src/pcms/transfer/CMakeLists.txt | 6 + src/pcms/transfer/forms.cpp | 203 +++++++++++ src/pcms/transfer/forms.hpp | 142 ++++++++ src/pcms/transfer/linear_solver.cpp | 190 ++++++++++ src/pcms/transfer/linear_solver.hpp | 79 ++++ src/pcms/transfer/petsc_solver.cpp | 339 ++++++++++++++++++ src/pcms/transfer/petsc_solver.hpp | 21 ++ src/pcms/transfer/petsc_utils.cpp | 6 +- src/pcms/transfer/petsc_utils.hpp | 6 +- 28 files changed, 1777 insertions(+), 23 deletions(-) create mode 100644 include/pcms/field/detail/field_data.hpp create mode 100644 include/pcms/field/detail/field_data_ops.hpp create mode 100644 include/pcms/field/detail/field_ops.hpp create mode 100644 src/pcms/transfer/forms.cpp create mode 100644 src/pcms/transfer/forms.hpp create mode 100644 src/pcms/transfer/linear_solver.cpp create mode 100644 src/pcms/transfer/linear_solver.hpp create mode 100644 src/pcms/transfer/petsc_solver.cpp create mode 100644 src/pcms/transfer/petsc_solver.hpp diff --git a/include/pcms/field/detail/field_data.hpp b/include/pcms/field/detail/field_data.hpp new file mode 100644 index 000000000..cf4a6c56a --- /dev/null +++ b/include/pcms/field/detail/field_data.hpp @@ -0,0 +1,83 @@ +// Part of pcms/field/field_data.hpp, which includes it after declaring +// FieldData and before defining it. +#include "pcms/field/field_data.hpp" +#ifndef PCMS_FIELD_DETAIL_FIELD_DATA_HPP +#define PCMS_FIELD_DETAIL_FIELD_DATA_HPP + +#include + +namespace pcms::detail +{ + +// The FieldData coefficient operations, for the coefficient algebra of +// pcms/field/detail/field_ops.hpp, which checks the operands. + +/// @brief z = a x + b y +template +void LinearSum(T a, const FieldData& x, T b, const FieldData& y, + FieldData& z) +{ + z.LinearSum(a, x, b, y); +} + +/// @brief z = c x +template +void Scale(T c, const FieldData& x, FieldData& z) +{ + z.Scale(c, x); +} + +/// @brief z = c +template +void Const(T c, FieldData& z) +{ + z.Const(c); +} + +/// @brief z = x / y, entry by entry +template +void Div(const FieldData& x, const FieldData& y, FieldData& z) +{ + z.Div(x, y); +} + +/// @return the sum of x_i y_i over the coefficients this rank owns +template +[[nodiscard]] T DotProdLocal(const FieldData& x, const FieldData& y) +{ + return x.DotProdLocal(y); +} + +/// @return the smallest coefficient this rank owns +template +[[nodiscard]] T MinLocal(const FieldData& x) +{ + return x.MinLocal(); +} + +/// @return the largest coefficient magnitude this rank owns +template +[[nodiscard]] T MaxNormLocal(const FieldData& x) +{ + return x.MaxNormLocal(); +} + +/// @brief Replaces each value by its sum over the ranks `data` is +/// partitioned over. Collective. +template +void SumOverRanks(const FieldData& data, std::span values) +{ + data.SumOverRanks(values); +} + +/// @brief Replaces each value by its maximum over the ranks `data` is +/// partitioned over. Collective. +template +void MaxOverRanks(const FieldData& data, std::span values) +{ + data.MaxOverRanks(values); +} + +} // namespace pcms::detail + +#endif // PCMS_FIELD_DETAIL_FIELD_DATA_HPP diff --git a/include/pcms/field/detail/field_data_ops.hpp b/include/pcms/field/detail/field_data_ops.hpp new file mode 100644 index 000000000..eda7fd722 --- /dev/null +++ b/include/pcms/field/detail/field_data_ops.hpp @@ -0,0 +1,144 @@ +#ifndef PCMS_FIELD_DETAIL_FIELD_DATA_OPS_HPP +#define PCMS_FIELD_DETAIL_FIELD_DATA_OPS_HPP + +#include "pcms/field/field_data.hpp" +#include "pcms/utility/assert.hpp" +#include "pcms/utility/memory_spaces.hpp" +#include +#include + +namespace pcms::detail +{ + +// The kernels of the FieldData coefficient operations, in place on a kind's +// [dof_holder][component] storage. + +template +using CoefficientView = Kokkos::View; + +/// @return `x` as the kind `Kind` +/// @throws pcms_error if `x` is field data of another kind +template +const Kind& OperandOfKind(const FieldData& x) +{ + const auto* kind = dynamic_cast(&x); + if (kind == nullptr) { + throw pcms_error("FieldData: the operand is field data of another kind"); + } + return *kind; +} + +template +void CheckSameShape(const CoefficientView& a, const CoefficientView& b) +{ + if (a.extent(0) != b.extent(0) || a.extent(1) != b.extent(1)) { + throw pcms_error("FieldData: the operands have different numbers of " + "coefficients"); + } +} + +template +auto CoefficientPolicy(const CoefficientView& out) +{ + return Kokkos::MDRangePolicy>( + {0, 0}, + {static_cast(out.extent(0)), static_cast(out.extent(1))}); +} + +/// @brief out = a x + b y +template +void LinearSumValues(const CoefficientView& out, T a, + const CoefficientView& x, T b, + const CoefficientView& y) +{ + CheckSameShape(out, x); + CheckSameShape(out, y); + Kokkos::parallel_for( + "pcms::FieldData::LinearSum", CoefficientPolicy(out), + KOKKOS_LAMBDA(const int64_t i, const int64_t c) { + out(i, c) = a * x(i, c) + b * y(i, c); + }); +} + +/// @brief out = c x +template +void ScaleValues(const CoefficientView& out, T c, + const CoefficientView& x) +{ + CheckSameShape(out, x); + Kokkos::parallel_for( + "pcms::FieldData::Scale", CoefficientPolicy(out), + KOKKOS_LAMBDA(const int64_t i, const int64_t k) { + out(i, k) = c * x(i, k); + }); +} + +/// @brief out = c +template +void ConstValues(const CoefficientView& out, T c) +{ + Kokkos::deep_copy(out, c); +} + +/// @brief out = x / y, entry by entry +template +void DivValues(const CoefficientView& out, const CoefficientView& x, + const CoefficientView& y) +{ + CheckSameShape(out, x); + CheckSameShape(out, y); + Kokkos::parallel_for( + "pcms::FieldData::Div", CoefficientPolicy(out), + KOKKOS_LAMBDA(const int64_t i, const int64_t c) { + out(i, c) = x(i, c) / y(i, c); + }); +} + +/// @return the sum of x_i y_i +template +T DotProdValues(const CoefficientView& x, const CoefficientView& y) +{ + CheckSameShape(x, y); + T sum = T{}; + Kokkos::parallel_reduce( + "pcms::FieldData::DotProdLocal", CoefficientPolicy(x), + KOKKOS_LAMBDA(const int64_t i, const int64_t c, T& partial) { + partial += x(i, c) * y(i, c); + }, + sum); + return sum; +} + +/// @return the smallest x_i; the largest T for no coefficients +template +T MinValues(const CoefficientView& x) +{ + T min{}; + Kokkos::parallel_reduce( + "pcms::FieldData::MinLocal", CoefficientPolicy(x), + KOKKOS_LAMBDA(const int64_t i, const int64_t c, T& partial) { + partial = x(i, c) < partial ? x(i, c) : partial; + }, + Kokkos::Min(min)); + return min; +} + +/// @return the largest |x_i|; 0 for no coefficients +template +T MaxNormValues(const CoefficientView& x) +{ + T max{}; + Kokkos::parallel_reduce( + "pcms::FieldData::MaxNormLocal", CoefficientPolicy(x), + KOKKOS_LAMBDA(const int64_t i, const int64_t c, T& partial) { + const T a = Kokkos::abs(x(i, c)); + partial = a > partial ? a : partial; + }, + Kokkos::Max(max)); + return max; +} + +} // namespace pcms::detail + +#endif // PCMS_FIELD_DETAIL_FIELD_DATA_OPS_HPP diff --git a/include/pcms/field/detail/field_ops.hpp b/include/pcms/field/detail/field_ops.hpp new file mode 100644 index 000000000..8958b4454 --- /dev/null +++ b/include/pcms/field/detail/field_ops.hpp @@ -0,0 +1,128 @@ +#ifndef PCMS_FIELD_DETAIL_FIELD_OPS_HPP +#define PCMS_FIELD_DETAIL_FIELD_OPS_HPP + +#include "pcms/field/field.hpp" +#include "pcms/utility/assert.hpp" +#include +#include +#include +#include + +namespace pcms::detail +{ + +// The coefficient algebra of the solvers and projections over Fields: each +// function checks its operands, then calls the FieldData coefficient +// operation of the same name. They act on the owned coefficients; those that +// write synchronize the field, and the reductions are collective over the +// ranks the data is partitioned over. + +template +void CheckSameLayout(const Field& a, const Field& b, const char* what) +{ + if (&a.GetLayout() != &b.GetLayout()) { + throw pcms_error(std::string(what) + + ": the fields must have the same layout"); + } +} + +/// @throws pcms_error unless `a` and `b` have the same layout, value basis and +/// kind of field data +template +void CheckOperands(const Field& a, const Field& b, const char* what) +{ + CheckSameLayout(a, b, what); + if (!SameValueBasis(a.GetData().GetValueBasis(), + b.GetData().GetValueBasis())) { + throw pcms_error(std::string(what) + ": the fields' value bases differ"); + } + if (typeid(a.GetData()) != typeid(b.GetData())) { + throw pcms_error(std::string(what) + + ": the fields' data are of different kinds"); + } +} + +/// @brief z = a x + b y +template +void LinearSum(T a, const Field& x, T b, const Field& y, Field& z) +{ + CheckOperands(x, z, "LinearSum"); + CheckOperands(y, z, "LinearSum"); + LinearSum(a, x.GetData(), b, y.GetData(), z.GetData()); + z.Synchronize(); +} + +/// @brief z = c x +template +void Scale(T c, const Field& x, Field& z) +{ + CheckOperands(x, z, "Scale"); + Scale(c, x.GetData(), z.GetData()); + z.Synchronize(); +} + +/// @brief z = c +template +void Const(T c, Field& z) +{ + Const(c, z.GetData()); + z.Synchronize(); +} + +/// @brief z = x / y, entry by entry +template +void Div(const Field& x, const Field& y, Field& z) +{ + CheckOperands(x, z, "Div"); + CheckOperands(y, z, "Div"); + Div(x.GetData(), y.GetData(), z.GetData()); + z.Synchronize(); +} + +/// @return the sum over the owned coefficients of every rank of x_i y_i +template +[[nodiscard]] T DotProd(const Field& x, const Field& y) +{ + CheckOperands(x, y, "DotProd"); + T sum = DotProdLocal(x.GetData(), y.GetData()); + SumOverRanks(x.GetData(), std::span(&sum, 1)); + return sum; +} + +/// @return the smallest owned coefficient over every rank +template +[[nodiscard]] T Min(const Field& x) +{ + T negated = -MinLocal(x.GetData()); + MaxOverRanks(x.GetData(), std::span(&negated, 1)); + return -negated; +} + +/// @return the largest owned coefficient magnitude over every rank +template +[[nodiscard]] T MaxNorm(const Field& x) +{ + T max = MaxNormLocal(x.GetData()); + MaxOverRanks(x.GetData(), std::span(&max, 1)); + return max; +} + +/// @return the Euclidean norm of the coefficients +template +[[nodiscard]] T Norm2(const Field& x) +{ + return std::sqrt(DotProd(x, x)); +} + +/// @brief The pairing of a functional (e.g. the moments E^T W f of a function +/// f) with a function: l(u) = sum_i b_i u_i. Basis-independent: the +/// functional is dual to the coefficients. +template +[[nodiscard]] T Apply(const Field& functional, const Function& u) +{ + return DotProd(functional, static_cast&>(u)); +} + +} // namespace pcms::detail + +#endif // PCMS_FIELD_DETAIL_FIELD_OPS_HPP diff --git a/include/pcms/field/detail/simple_field_data.hpp b/include/pcms/field/detail/simple_field_data.hpp index 76e3b533c..3f9e3f141 100644 --- a/include/pcms/field/detail/simple_field_data.hpp +++ b/include/pcms/field/detail/simple_field_data.hpp @@ -1,6 +1,7 @@ #ifndef PCMS_FIELD_DETAIL_SIMPLE_FIELD_DATA_HPP #define PCMS_FIELD_DETAIL_SIMPLE_FIELD_DATA_HPP +#include "pcms/field/detail/field_data_ops.hpp" #include "pcms/field/field_data.hpp" #include "pcms/field/field_layout.hpp" #include "pcms/utility/arrays.hpp" @@ -52,7 +53,43 @@ class SimpleFieldData detail::CopyDeviceRank2ViewToDeviceView(device_data_, values); } +protected: + void LinearSum(T a, const FieldData& x, T b, + const FieldData& y) override + { + LinearSumValues(device_data_, a, Data(x), b, Data(y)); + } + + void Scale(T c, const FieldData& x) override + { + ScaleValues(device_data_, c, Data(x)); + } + + void Const(T c) override { ConstValues(device_data_, c); } + + void Div(const FieldData& x, const FieldData& y) override + { + DivValues(device_data_, Data(x), Data(y)); + } + + [[nodiscard]] T DotProdLocal(const FieldData& x) const override + { + return DotProdValues(device_data_, Data(x)); + } + + [[nodiscard]] T MinLocal() const override { return MinValues(device_data_); } + + [[nodiscard]] T MaxNormLocal() const override + { + return MaxNormValues(device_data_); + } + private: + static const Kokkos::View& Data(const FieldData& x) + { + return OperandOfKind(x).device_data_; + } + std::shared_ptr layout_; ValueBasis basis_; Kokkos::View device_data_; diff --git a/include/pcms/field/field_data.hpp b/include/pcms/field/field_data.hpp index 9e640ec9e..476902ddc 100644 --- a/include/pcms/field/field_data.hpp +++ b/include/pcms/field/field_data.hpp @@ -3,10 +3,20 @@ #include "pcms/field/value_view.hpp" #include "pcms/utility/arrays.hpp" +#include "pcms/utility/assert.hpp" #include "pcms/utility/memory_spaces.hpp" #include +#include #include +namespace pcms +{ +template +class FieldData; +} // namespace pcms + +#include "pcms/field/detail/field_data.hpp" + namespace pcms { @@ -50,6 +60,89 @@ class FieldData virtual void Synchronize() {} virtual ~FieldData() noexcept = default; + +protected: + // Coefficient operations: the extension API through which PCMS computes + // with the coefficients of fields (the linear solvers and projections), + // reached through the pcms::detail functions of the same names. The set + // follows the SUNDIALS N_Vector naming and grows by adding virtuals whose + // default throws. They act in place on the coefficients this rank owns, on + // the kind's own storage, and leave the ghost copies stale: PCMS + // synchronizes the field (Synchronize) before anything reads them. The + // operands are field data of this kind, layout and value basis (PCMS checks + // them); all but the rank reductions throw unless the kind overrides them. + + /// @brief this = a x + b y + virtual void LinearSum(T /*a*/, const FieldData& /*x*/, T /*b*/, + const FieldData& /*y*/) + { + NoCoefficientOperations(); + } + + /// @brief this = c x + virtual void Scale(T /*c*/, const FieldData& /*x*/) + { + NoCoefficientOperations(); + } + + /// @brief this = c + virtual void Const(T /*c*/) { NoCoefficientOperations(); } + + /// @brief this = x / y, entry by entry + virtual void Div(const FieldData& /*x*/, const FieldData& /*y*/) + { + NoCoefficientOperations(); + } + + /// @return the sum of this_i x_i over the coefficients this rank owns + [[nodiscard]] virtual T DotProdLocal(const FieldData& /*x*/) const + { + NoCoefficientOperations(); + } + + /// @return the smallest coefficient this rank owns + [[nodiscard]] virtual T MinLocal() const { NoCoefficientOperations(); } + + /// @return the largest coefficient magnitude this rank owns + [[nodiscard]] virtual T MaxNormLocal() const { NoCoefficientOperations(); } + + /// @brief Replaces each value by its sum over the ranks the data is + /// partitioned over. Collective; a single rank by default. + virtual void SumOverRanks(std::span /*values*/) const {} + + /// @brief Replaces each value by its maximum over the ranks the data is + /// partitioned over. Collective; a single rank by default. + virtual void MaxOverRanks(std::span /*values*/) const {} + +private: + template + friend void detail::LinearSum(U a, const FieldData& x, U b, + const FieldData& y, FieldData& z); + template + friend void detail::Scale(U c, const FieldData& x, FieldData& z); + template + friend void detail::Const(U c, FieldData& z); + template + friend void detail::Div(const FieldData& x, const FieldData& y, + FieldData& z); + template + friend U detail::DotProdLocal(const FieldData& x, const FieldData& y); + template + friend U detail::MinLocal(const FieldData& x); + template + friend U detail::MaxNormLocal(const FieldData& x); + template + friend void detail::SumOverRanks(const FieldData& data, + std::span values); + template + friend void detail::MaxOverRanks(const FieldData& data, + std::span values); + + [[noreturn]] static void NoCoefficientOperations() + { + throw pcms_error("FieldData: this field data provides no coefficient " + "operations"); + } }; using FieldDataVariant = std::variant< diff --git a/include/pcms/geometry/detail/quadrature.hpp b/include/pcms/geometry/detail/quadrature.hpp index dbe73cb8f..d275b932a 100644 --- a/include/pcms/geometry/detail/quadrature.hpp +++ b/include/pcms/geometry/detail/quadrature.hpp @@ -5,6 +5,7 @@ #define PCMS_GEOMETRY_DETAIL_QUADRATURE_HPP #include +#include #include namespace pcms::detail @@ -29,6 +30,14 @@ using QuadratureRule = std::variant; [[nodiscard]] Quadrature CreateQuadrature(const Geometry& geometry, const QuadratureRule& rule); +/// @brief Replaces each value by its sum over the ranks the entities of +/// `geometry` are partitioned over, e.g. a quadrature sum. Collective. +void SumOverRanks(const Geometry& geometry, std::span values); + +/// @brief Replaces each value by its maximum over the ranks the entities of +/// `geometry` are partitioned over. Collective. +void MaxOverRanks(const Geometry& geometry, std::span values); + } // namespace pcms::detail #endif // PCMS_GEOMETRY_DETAIL_QUADRATURE_HPP diff --git a/include/pcms/geometry/geometry.hpp b/include/pcms/geometry/geometry.hpp index b14174d83..4bc6b1396 100644 --- a/include/pcms/geometry/geometry.hpp +++ b/include/pcms/geometry/geometry.hpp @@ -12,6 +12,7 @@ #include "pcms/utility/uniform_grid.hpp" #include #include +#include #include namespace pcms @@ -191,9 +192,23 @@ class Geometry : public std::enable_shared_from_this [[nodiscard]] virtual Quadrature CreateQuadrature( const detail::QuadratureRule& rule) const; + /// @brief Replaces each value by its sum over the ranks the entities are + /// partitioned over. Collective; a single rank unless the kind + /// overrides it. + virtual void SumOverRanks(std::span /*values*/) const {} + + /// @brief Replaces each value by its maximum over the ranks the entities are + /// partitioned over. Collective; a single rank unless the kind + /// overrides it. + virtual void MaxOverRanks(std::span /*values*/) const {} + private: friend Quadrature detail::CreateQuadrature( const Geometry& geometry, const detail::QuadratureRule& rule); + friend void detail::SumOverRanks(const Geometry& geometry, + std::span values); + friend void detail::MaxOverRanks(const Geometry& geometry, + std::span values); // creates the passkey of BoundPoints::Rebind struct RebindKey : BoundPoints::RebindKey diff --git a/include/pcms/transfer/projection.hpp b/include/pcms/transfer/projection.hpp index 5b553e888..7dcfcd467 100644 --- a/include/pcms/transfer/projection.hpp +++ b/include/pcms/transfer/projection.hpp @@ -14,10 +14,37 @@ #include #include +#include namespace pcms { +/// @brief Options of the mass-system solve of a projection +struct LinearSolveOptions +{ + /// @brief Solution method + enum class Method + { + /// Assembled when PCMS has PETSc, the layout is on one rank and the + /// evaluator has evaluation rows; MatrixFree otherwise + Automatic, + /// Conjugate gradients preconditioned by the lumped mass, matrix free + MatrixFree, + /// PETSc KSP on the assembled matrix (conjugate gradients preconditioned + /// by its diagonal, unless the PETSc options say otherwise); needs + /// PCMS_ENABLE_PETSC + Assembled + }; + /// Solution method + Method method = Method::Automatic; + /// Relative residual tolerance + Real relative_tolerance = 1e-12; + /// Iteration limit; 0 means the number of unknowns + int max_iterations = 0; + /// Assembled: PETSc options prefix of the KSP + std::string petsc_options_prefix; +}; + struct ConservativeProjectionOptions { MassMatrixType mass_matrix_type = MassMatrixType::Consistent; diff --git a/src/pcms/backends/omega_h/entity_layout.cpp b/src/pcms/backends/omega_h/entity_layout.cpp index 4454ba7f2..8eeb14c1d 100644 --- a/src/pcms/backends/omega_h/entity_layout.cpp +++ b/src/pcms/backends/omega_h/entity_layout.cpp @@ -178,7 +178,7 @@ void OmegaHEntityLayout::BuildOwnedViews() bool OmegaHEntityLayout::IsDistributed() const { - return true; + return mesh_.comm()->size() > 1; } EntOffsetsArray OmegaHEntityLayout::GetEntOffsets() const diff --git a/src/pcms/backends/omega_h/field_data.hpp b/src/pcms/backends/omega_h/field_data.hpp index 2ab27831f..bba25bae3 100644 --- a/src/pcms/backends/omega_h/field_data.hpp +++ b/src/pcms/backends/omega_h/field_data.hpp @@ -1,6 +1,7 @@ #ifndef PCMS_BACKENDS_OMEGA_H_FIELD_DATA_HPP #define PCMS_BACKENDS_OMEGA_H_FIELD_DATA_HPP +#include "pcms/field/detail/field_data_ops.hpp" #include "pcms/field/field_data.hpp" #include "pcms/field/field_layout.hpp" #include "pcms/backends/omega_h/omega_h_geometry.hpp" @@ -8,10 +9,12 @@ #include "pcms/utility/memory_spaces.hpp" #include "pcms/utility/omega_h_array_utils.hpp" #include +#include #include #include #include #include +#include #include namespace pcms::omega_h @@ -125,12 +128,69 @@ class OmegaHFieldData void SetValues(Rank2View values) override { pcms::detail::CopyDeviceRank2ViewToDeviceView(device_data_, values); - mesh_->set_tag(tag_dim_, tag_name_, - detail::OwnedValuesAsTag( - GetValues(), layout_->GetOwnedIndices(), - mesh_->nents(tag_dim_), layout_->GetNumComponents())); + SetTagFromOwned(); + } + +protected: + void LinearSum(T a, const FieldData& x, T b, + const FieldData& y) override + { + pcms::detail::LinearSumValues(device_data_, a, Data(x), b, Data(y)); + SetTagFromOwned(); + } + + void Scale(T c, const FieldData& x) override + { + pcms::detail::ScaleValues(device_data_, c, Data(x)); + SetTagFromOwned(); + } + + void Const(T c) override + { + pcms::detail::ConstValues(device_data_, c); + SetTagFromOwned(); + } + + void Div(const FieldData& x, const FieldData& y) override + { + pcms::detail::DivValues(device_data_, Data(x), Data(y)); + SetTagFromOwned(); + } + + [[nodiscard]] T DotProdLocal(const FieldData& x) const override + { + return pcms::detail::DotProdValues(device_data_, Data(x)); + } + + [[nodiscard]] T MinLocal() const override + { + return pcms::detail::MinValues(device_data_); } + [[nodiscard]] T MaxNormLocal() const override + { + return pcms::detail::MaxNormValues(device_data_); + } + + // Sums over the mesh's ranks. Collective. + void SumOverRanks(std::span values) const override + { + for (auto& value : values) { + value = static_cast(mesh_->comm()->allreduce( + static_cast(value), OMEGA_H_SUM)); + } + } + + // Maximizes over the mesh's ranks. Collective. + void MaxOverRanks(std::span values) const override + { + for (auto& value : values) { + value = static_cast(mesh_->comm()->allreduce( + static_cast(value), OMEGA_H_MAX)); + } + } + +public: // Fills the tag's ghost entries with their owners' values. Collective. void Synchronize() override { mesh_->sync_tag(tag_dim_, tag_name_); } @@ -180,6 +240,20 @@ class OmegaHFieldData } private: + static const Kokkos::View& Data(const FieldData& x) + { + return pcms::detail::OperandOfKind(x).device_data_; + } + + // Replaces the tag with the owned values (ghosts zero, local to this rank). + void SetTagFromOwned() + { + mesh_->set_tag(tag_dim_, tag_name_, + detail::OwnedValuesAsTag( + GetValues(), layout_->GetOwnedIndices(), + mesh_->nents(tag_dim_), layout_->GetNumComponents())); + } + std::shared_ptr layout_; ValueBasis basis_; Kokkos::View device_data_; diff --git a/src/pcms/backends/omega_h/geometry.cpp b/src/pcms/backends/omega_h/geometry.cpp index ca178610f..715e03ad1 100644 --- a/src/pcms/backends/omega_h/geometry.cpp +++ b/src/pcms/backends/omega_h/geometry.cpp @@ -4,6 +4,7 @@ #include "pcms/utility/assert.hpp" #include "pcms/utility/omega_h_array_utils.hpp" #include "pcms/utility/detail/profile.hpp" +#include #include "pcms/utility/types.hpp" #include "pcms/utility/uniform_grid.hpp" #include @@ -251,4 +252,18 @@ SupportResults OmegaHGeometry::Neighbourhood( 3 * options.min_supports, options.adapt_radius); } +void OmegaHGeometry::SumOverRanks(std::span values) const +{ + for (auto& value : values) { + value = mesh_.comm()->allreduce(value, OMEGA_H_SUM); + } +} + +void OmegaHGeometry::MaxOverRanks(std::span values) const +{ + for (auto& value : values) { + value = mesh_.comm()->allreduce(value, OMEGA_H_MAX); + } +} + } // namespace pcms::omega_h diff --git a/src/pcms/backends/omega_h/lagrange_layout.cpp b/src/pcms/backends/omega_h/lagrange_layout.cpp index a3102e000..3286d6f23 100644 --- a/src/pcms/backends/omega_h/lagrange_layout.cpp +++ b/src/pcms/backends/omega_h/lagrange_layout.cpp @@ -210,7 +210,7 @@ void OmegaHLagrangeLayout::BuildOwnedViews() bool OmegaHLagrangeLayout::IsDistributed() const { - return true; + return mesh_.comm()->size() > 1; } EntOffsetsArray OmegaHLagrangeLayout::GetEntOffsets() const diff --git a/src/pcms/backends/omega_h/omega_h_geometry.hpp b/src/pcms/backends/omega_h/omega_h_geometry.hpp index 1c413bc7e..2d8e1d9c2 100644 --- a/src/pcms/backends/omega_h/omega_h_geometry.hpp +++ b/src/pcms/backends/omega_h/omega_h_geometry.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -366,6 +367,12 @@ class OmegaHGeometry final : public Geometry [[nodiscard]] Quadrature CreateQuadrature( const pcms::detail::QuadratureRule& rule) const override; + /// @brief The sum over the mesh's ranks. Collective. + void SumOverRanks(std::span values) const override; + + /// @brief The maximum over the mesh's ranks. Collective. + void MaxOverRanks(std::span values) const override; + private: /// The containing-element search, built on first use. const GridPointSearchVariant& Search() const; diff --git a/src/pcms/backends/omega_h_meshfields/field_data.hpp b/src/pcms/backends/omega_h_meshfields/field_data.hpp index cb9f2fd3a..b9414767d 100644 --- a/src/pcms/backends/omega_h_meshfields/field_data.hpp +++ b/src/pcms/backends/omega_h_meshfields/field_data.hpp @@ -3,6 +3,7 @@ #include "pcms/backends/omega_h_meshfields/layout.hpp" #include "pcms/backends/omega_h_meshfields/evaluator_backend.hpp" +#include "pcms/field/detail/field_data_ops.hpp" #include "pcms/field/field_data.hpp" #include "pcms/field/value_view.hpp" #include "pcms/utility/assert.hpp" @@ -10,7 +11,9 @@ #include "pcms/utility/omega_h_array_utils.hpp" #include +#include #include +#include namespace pcms::omega_h_meshfields { @@ -108,19 +111,69 @@ class MeshFieldsFieldData void SetValues(Rank2View values) override { pcms::detail::CopyDeviceRank2ViewToDeviceView(owned_data_, values); - if (!layout_->HasGhosts()) { - SyncBackend(MakeConstRank2View(owned_data_)); - return; + SetBackendFromOwned(); + } + +protected: + void LinearSum(T a, const FieldData& x, T b, + const FieldData& y) override + { + pcms::detail::LinearSumValues(owned_data_, a, Data(x), b, Data(y)); + SetBackendFromOwned(); + } + + void Scale(T c, const FieldData& x) override + { + pcms::detail::ScaleValues(owned_data_, c, Data(x)); + SetBackendFromOwned(); + } + + void Const(T c) override + { + pcms::detail::ConstValues(owned_data_, c); + SetBackendFromOwned(); + } + + void Div(const FieldData& x, const FieldData& y) override + { + pcms::detail::DivValues(owned_data_, Data(x), Data(y)); + SetBackendFromOwned(); + } + + [[nodiscard]] T DotProdLocal(const FieldData& x) const override + { + return pcms::detail::DotProdValues(owned_data_, Data(x)); + } + + [[nodiscard]] T MinLocal() const override + { + return pcms::detail::MinValues(owned_data_); + } + + [[nodiscard]] T MaxNormLocal() const override + { + return pcms::detail::MaxNormValues(owned_data_); + } + + // Sums over the mesh's ranks. Collective. + void SumOverRanks(std::span values) const override + { + for (auto& value : values) { + value = static_cast(layout_->GetMesh().comm()->allreduce( + static_cast>(value), OMEGA_H_SUM)); } - // Write the owned rows into the backend's values with ghosts, keeping its - // ghost values. - auto local = ReadBackend(); - pcms::detail::ScatterRows(MakeConstRank2View(owned_data_), - layout_->GetOwnedIndices(), - pcms::MakeRank2View(local)); - SyncBackend(MakeConstRank2View(local)); } + // Maximizes over the mesh's ranks. Collective. + void MaxOverRanks(std::span values) const override + { + for (auto& value : values) { + value = static_cast(layout_->GetMesh().comm()->allreduce( + static_cast>(value), OMEGA_H_MAX)); + } + } + +public: void Synchronize() override { const int nc = layout_->GetNumComponents(); @@ -151,6 +204,26 @@ class MeshFieldsFieldData } private: + static const Kokkos::View& Data(const FieldData& x) + { + return pcms::detail::OperandOfKind(x).owned_data_; + } + + // Writes the owned values into the backend's values with ghosts, keeping + // its ghost values. + void SetBackendFromOwned() + { + if (!layout_->HasGhosts()) { + SyncBackend(MakeConstRank2View(owned_data_)); + return; + } + auto local = ReadBackend(); + pcms::detail::ScatterRows(MakeConstRank2View(owned_data_), + layout_->GetOwnedIndices(), + pcms::MakeRank2View(local)); + SyncBackend(MakeConstRank2View(local)); + } + // The backend's values of every DOF holder with ghosts, in mesh order. Kokkos::View ReadBackend() const { diff --git a/src/pcms/backends/omega_h_meshfields/layout.cpp b/src/pcms/backends/omega_h_meshfields/layout.cpp index 7b6cb41e1..8c3f30b52 100644 --- a/src/pcms/backends/omega_h_meshfields/layout.cpp +++ b/src/pcms/backends/omega_h_meshfields/layout.cpp @@ -355,7 +355,7 @@ void MeshFieldsAdapterLayout::BuildOwnedViews() bool MeshFieldsAdapterLayout::IsDistributed() const { - return true; + return mesh_.comm()->size() > 1; } Omega_h::Read MeshFieldsAdapterLayout::GetClassIDs() const diff --git a/src/pcms/backends/point_cloud/field_data.cpp b/src/pcms/backends/point_cloud/field_data.cpp index 0642c5147..7bd422fd6 100644 --- a/src/pcms/backends/point_cloud/field_data.cpp +++ b/src/pcms/backends/point_cloud/field_data.cpp @@ -1,5 +1,6 @@ #include "pcms/backends/point_cloud/field_data.hpp" #include "pcms/backends/point_cloud/layout.hpp" +#include "pcms/field/detail/field_data_ops.hpp" #include "pcms/utility/detail/profile.hpp" #include "pcms/utility/assert.hpp" #include "pcms/utility/arrays.hpp" @@ -37,4 +38,46 @@ void PointCloud::SetValues(Rank2View data) pcms::detail::CopyDeviceRank2ViewToDeviceView(device_data_, data); } +const Kokkos::View& PointCloud::Data( + const FieldData& x) +{ + return pcms::detail::OperandOfKind(x).device_data_; +} + +void PointCloud::LinearSum(Real a, const FieldData& x, Real b, + const FieldData& y) +{ + pcms::detail::LinearSumValues(device_data_, a, Data(x), b, Data(y)); +} + +void PointCloud::Scale(Real c, const FieldData& x) +{ + pcms::detail::ScaleValues(device_data_, c, Data(x)); +} + +void PointCloud::Const(Real c) +{ + pcms::detail::ConstValues(device_data_, c); +} + +void PointCloud::Div(const FieldData& x, const FieldData& y) +{ + pcms::detail::DivValues(device_data_, Data(x), Data(y)); +} + +Real PointCloud::DotProdLocal(const FieldData& x) const +{ + return pcms::detail::DotProdValues(device_data_, Data(x)); +} + +Real PointCloud::MinLocal() const +{ + return pcms::detail::MinValues(device_data_); +} + +Real PointCloud::MaxNormLocal() const +{ + return pcms::detail::MaxNormValues(device_data_); +} + } // namespace pcms::point_cloud diff --git a/src/pcms/backends/point_cloud/field_data.hpp b/src/pcms/backends/point_cloud/field_data.hpp index a476e12f4..97e30ab46 100644 --- a/src/pcms/backends/point_cloud/field_data.hpp +++ b/src/pcms/backends/point_cloud/field_data.hpp @@ -25,7 +25,20 @@ class PointCloud Rank2View GetValues() const override; void SetValues(Rank2View data) override; +protected: + void LinearSum(Real a, const FieldData& x, Real b, + const FieldData& y) override; + void Scale(Real c, const FieldData& x) override; + void Const(Real c) override; + void Div(const FieldData& x, const FieldData& y) override; + [[nodiscard]] Real DotProdLocal(const FieldData& x) const override; + [[nodiscard]] Real MinLocal() const override; + [[nodiscard]] Real MaxNormLocal() const override; + private: + static const Kokkos::View& Data( + const FieldData& x); + std::shared_ptr layout_; ValueBasis basis_; Kokkos::View device_data_; diff --git a/src/pcms/field/CMakeLists.txt b/src/pcms/field/CMakeLists.txt index 9bacb9c83..086a98046 100644 --- a/src/pcms/field/CMakeLists.txt +++ b/src/pcms/field/CMakeLists.txt @@ -9,6 +9,9 @@ set(PCMS_FIELD_HEADERS layout/empty.hpp ../../../include/pcms/field/out_of_bounds_policy.hpp ../../../include/pcms/field/field_data.hpp + ../../../include/pcms/field/detail/field_data.hpp + ../../../include/pcms/field/detail/field_data_ops.hpp + ../../../include/pcms/field/detail/field_ops.hpp ../../../include/pcms/field/field_factory.hpp ../../../include/pcms/field/function_space.hpp ../../../include/pcms/field/point_evaluator.hpp diff --git a/src/pcms/geometry/geometry.cpp b/src/pcms/geometry/geometry.cpp index 3b41cebb0..9b7b011e2 100644 --- a/src/pcms/geometry/geometry.cpp +++ b/src/pcms/geometry/geometry.cpp @@ -120,6 +120,16 @@ Quadrature Geometry::CreateQuadrature(const detail::QuadratureRule&) const "that rule"); } +void detail::SumOverRanks(const Geometry& geometry, std::span values) +{ + geometry.SumOverRanks(values); +} + +void detail::MaxOverRanks(const Geometry& geometry, std::span values) +{ + geometry.MaxOverRanks(values); +} + Quadrature detail::CreateQuadrature(const Geometry& geometry, const QuadratureRule& rule) { diff --git a/src/pcms/transfer/CMakeLists.txt b/src/pcms/transfer/CMakeLists.txt index 6b72beac4..38528e6f1 100644 --- a/src/pcms/transfer/CMakeLists.txt +++ b/src/pcms/transfer/CMakeLists.txt @@ -40,6 +40,9 @@ if(PCMS_ENABLE_CONSERVATIVE_PROJECTION) omega_h_control_variate_projection.hpp petsc_utils.hpp omega_h_intersection_quadrature.hpp + forms.hpp + linear_solver.hpp + petsc_solver.hpp omega_h_form_integrator_utils.hpp) list(APPEND PCMS_FIELD_TRANSFER_SOURCES conservative_projection_solver.cpp @@ -49,6 +52,9 @@ if(PCMS_ENABLE_CONSERVATIVE_PROJECTION) omega_h_mc_rhs_integrator.cpp omega_h_control_variate_projection.cpp omega_h_intersection_quadrature.cpp + forms.cpp + linear_solver.cpp + petsc_solver.cpp petsc_utils.cpp) endif() diff --git a/src/pcms/transfer/forms.cpp b/src/pcms/transfer/forms.cpp new file mode 100644 index 000000000..2403c85f8 --- /dev/null +++ b/src/pcms/transfer/forms.cpp @@ -0,0 +1,203 @@ +#include "pcms/transfer/forms.hpp" +#include "pcms/utility/arrays.hpp" +#include "pcms/utility/assert.hpp" +#include +#include +#include +#include +#include + +namespace pcms::transfer::detail +{ + +namespace +{ + +void ApplyWeights(const Kokkos::View& weights, + const Rank2View& values, + const Kokkos::View& out) +{ + Kokkos::parallel_for( + "pcms::transfer::ApplyWeights", + Kokkos::MDRangePolicy>( + {0, 0}, {static_cast(out.extent(0)), + static_cast(out.extent(1))}), + KOKKOS_LAMBDA(const int64_t p, const int64_t c) { + out(p, c) = weights(p) * values(p, c); + }); +} + +// sum over the points of w(p) a(p) . b(p) +Real WeightedDot(const Kokkos::View& weights, + const Rank2View& a, + const Rank2View& b) +{ + Real sum = 0; + Kokkos::parallel_reduce( + "pcms::transfer::WeightedDot", + Kokkos::MDRangePolicy>( + {0, 0}, + {static_cast(a.extent(0)), static_cast(a.extent(1))}), + KOKKOS_LAMBDA(const int64_t i, const int64_t c, Real& partial) { + partial += weights(i) * a(i, c) * b(i, c); + }, + sum); + return sum; +} + +// the points of `quadrature` bound on `geometry`: its own points, else a bind +// of them that starts from the cells the quadrature names +std::shared_ptr PointsOn( + const Quadrature& quadrature, const Geometry& geometry, + const std::shared_ptr& map) +{ + if (map == nullptr && quadrature.points->GetGeometry().get() == &geometry) { + return quadrature.points; + } + return geometry.Bind(quadrature.points->LocatedPoints(), quadrature.other, + OutOfBoundsPolicy{}, map); +} + +// a view shaped [rows][columns], reallocated only when its shape changes +Kokkos::View& Shaped( + Kokkos::View& view, std::size_t rows, + std::size_t columns) +{ + if (view.extent(0) != rows || view.extent(1) != columns) { + view = Kokkos::View( + Kokkos::view_alloc(Kokkos::WithoutInitializing, "bilinear_form_values"), + rows, columns); + } + return view; +} + +} // namespace + +BilinearForm::BilinearForm(std::shared_ptr test, + std::shared_ptr trial, + FormOptions options) + : test_(std::move(test)), + trial_(std::move(trial)), + options_(std::move(options)) +{ + if (trial_ == nullptr || trial_->GetGeometry() == nullptr) { + throw pcms_error("BilinearForm: the trial must have a geometry"); + } + if (trial_ != test_->space || options_.to_trial != nullptr) { + trial_evaluator_ = trial_->CreatePointEvaluator( + PointsOn(test_->quadrature, *trial_->GetGeometry(), options_.to_trial)); + } +} + +BilinearForm::BilinearForm(std::shared_ptr test, + std::shared_ptr trial, + FormOptions options) + : BilinearForm( + [&] { + auto side = std::make_shared(); + side->quadrature = + options.quadrature ? *options.quadrature : test->GetQuadrature(); + const auto& q = side->quadrature; + if (q.points == nullptr || + q.points->GetGeometry() != test->GetGeometry() || + q.weights.extent(0) != static_cast(q.points->NumPoints())) { + throw pcms_error("BilinearForm: the quadrature must be bound on the " + "test space's geometry and have one weight per " + "point"); + } + side->evaluator = test->CreatePointEvaluator(q.points); + side->space = std::move(test); + return std::shared_ptr(std::move(side)); + }(), + std::move(trial), options) +{ +} + +BilinearForm::BilinearForm(std::shared_ptr space, + FormOptions options) + : BilinearForm(space, space, std::move(options)) +{ +} + +ValueView BilinearForm::Weight( + ValueView samples) const +{ + if (samples.extent(0) != test_->quadrature.weights.extent(0)) { + throw std::invalid_argument( + "BilinearForm: samples must have one row per point"); + } + auto& weighted = Shaped(weighted_, samples.extent(0), samples.extent(1)); + ApplyWeights(test_->quadrature.weights, samples.GetValues(), weighted); + return ValueView(samples.GetBasis(), + MakeConstRank2View(weighted)); +} + +void BilinearForm::Assemble(ValueView samples, + Field& functional) const +{ + test_->evaluator->EvaluateTranspose(Weight(samples), functional); +} + +BilinearForm BilinearForm::WithTrial( + std::shared_ptr trial) const +{ + FormOptions options = options_; + options.to_trial = nullptr; + return BilinearForm(test_, std::move(trial), std::move(options)); +} + +ValueView BilinearForm::EvaluateTest( + const Field& v) const +{ + const auto& evaluator = *test_->evaluator; + const ValueBasis basis = evaluator.OutputBasis(v.GetData().GetValueBasis()); + auto& values = Shaped(test_values_, evaluator.NumPoints(), + v.GetLayout().GetNumComponents()); + evaluator.Evaluate( + v, ValueView(basis, MakeRank2View(values))); + return {basis, MakeConstRank2View(values)}; +} + +ValueView BilinearForm::EvaluateTrial( + const Field& u) const +{ + const auto& evaluator = TrialEvaluator(); + const ValueBasis basis = evaluator.OutputBasis(u.GetData().GetValueBasis()); + auto& values = Shaped(trial_values_, evaluator.NumPoints(), + u.GetLayout().GetNumComponents()); + evaluator.Evaluate( + u, ValueView(basis, MakeRank2View(values))); + return {basis, MakeConstRank2View(values)}; +} + +Real BilinearForm::Contract(ValueView a, + ValueView b) const +{ + Real sum = WeightedDot(GetQuadrature().weights, a.GetValues(), b.GetValues()); + pcms::detail::SumOverRanks(*GetQuadrature().points->GetGeometry(), + std::span(&sum, 1)); + return sum; +} + +Real BilinearForm::Pair(const Field& v, const Field& u) const +{ + return Contract(EvaluateTest(v), EvaluateTrial(u)); +} + +void BilinearForm::Apply(const Field& u, Field& functional) const +{ + Assemble(EvaluateTrial(u), functional); +} + +void BilinearForm::ApplyTranspose(const Field& v, Field& functional, + Real beta) const +{ + const ValueBasis written = TrialBasis(functional.GetData().GetValueBasis()); + const auto samples = EvaluateTest(v); + pcms::detail::CheckWrittenValueBasis("BilinearForm::ApplyTranspose", + samples.GetBasis(), written); + pcms::detail::EvaluateTranspose(TrialEvaluator(), Weight(samples), functional, + beta); +} + +} // namespace pcms::transfer::detail diff --git a/src/pcms/transfer/forms.hpp b/src/pcms/transfer/forms.hpp new file mode 100644 index 000000000..5388a90d5 --- /dev/null +++ b/src/pcms/transfer/forms.hpp @@ -0,0 +1,142 @@ +#ifndef PCMS_TRANSFER_FORMS_HPP +#define PCMS_TRANSFER_FORMS_HPP + +#include "pcms/field/coordinate_map.hpp" +#include "pcms/field/field.hpp" +#include "pcms/field/function_space.hpp" +#include "pcms/field/point_evaluator.hpp" +#include "pcms/field/point_evaluator_factory.hpp" +#include "pcms/geometry/quadrature.hpp" +#include "pcms/utility/types.hpp" +#include +#include +#include + +namespace pcms::transfer::detail +{ + +/// @brief The quadrature of a BilinearForm and the map to its trial. +struct FormOptions +{ + /// the quadrature, on the test space's geometry; unset: the test space's + /// GetQuadrature() + std::optional quadrature; + /// map from the test space's geometry to the trial's, or null + std::shared_ptr to_trial; +}; + +/// @brief B = E_test^T W E_trial: the trial evaluated at the points of a +/// quadrature on the test space, weighted, then the transpose of the +/// test evaluation. The evaluations return views of scratch the form +/// owns, valid until the next evaluation of the same side. +class BilinearForm +{ +public: + /// @param trial a space, or any evaluator source with a geometry + /// @throws pcms_error if the quadrature is not on the test space's + /// geometry, the trial has no geometry or an evaluator cannot be + /// created + BilinearForm(std::shared_ptr test, + std::shared_ptr trial, + FormOptions options = {}); + + /// @brief The square form of `space`. + explicit BilinearForm(std::shared_ptr space, + FormOptions options = {}); + + /// @return the form of `trial` on the same test points; the map to the + /// trial is not kept + [[nodiscard]] BilinearForm WithTrial( + std::shared_ptr trial) const; + + /// @brief functional = B u, a field of the test space's layout + void Apply(const Field& u, Field& functional) const; + + /// @brief functional = B^T v + beta functional, a functional of the + /// trial's layout; beta == 0 does not read the functional + void ApplyTranspose(const Field& v, Field& functional, + Real beta = 0) const; + + /// @brief functional = E_test^T W samples + void Assemble(ValueView samples, + Field& functional) const; + + /// @return v^T B u, over the ranks of the quadrature's geometry + /// (collective) + [[nodiscard]] Real Pair(const Field& v, const Field& u) const; + + /// @return E_test v + [[nodiscard]] ValueView EvaluateTest( + const Field& v) const; + + /// @return E_trial u + [[nodiscard]] ValueView EvaluateTrial( + const Field& u) const; + + /// @return the sum over the points of w a . b, over the ranks of the + /// quadrature's geometry (collective) + [[nodiscard]] Real Contract(ValueView a, + ValueView b) const; + + /// @return the basis of the trial's values for a field stored in `stored` + [[nodiscard]] ValueBasis TrialBasis(const ValueBasis& stored) const + { + return TrialEvaluator().OutputBasis(stored); + } + + /// @return whether the trial is the test space, without a map + [[nodiscard]] bool IsSquare() const noexcept + { + return trial_evaluator_ == nullptr; + } + + [[nodiscard]] const std::shared_ptr& TestSpace() + const noexcept + { + return test_->space; + } + [[nodiscard]] const Quadrature& GetQuadrature() const noexcept + { + return test_->quadrature; + } + /// @return E_test: the test space at the quadrature's points + [[nodiscard]] const PointEvaluator& TestEvaluator() const noexcept + { + return *test_->evaluator; + } + /// @return E_trial: the trial at the quadrature's points + [[nodiscard]] const PointEvaluator& TrialEvaluator() const noexcept + { + return trial_evaluator_ != nullptr ? *trial_evaluator_ : *test_->evaluator; + } + +private: + /// The test side, shared by the forms WithTrial makes. + struct Test + { + std::shared_ptr space; + Quadrature quadrature; + std::unique_ptr> evaluator; + }; + + BilinearForm(std::shared_ptr test, + std::shared_ptr trial, + FormOptions options); + + /// @return W samples, in scratch the form owns + [[nodiscard]] ValueView Weight( + ValueView samples) const; + + std::shared_ptr test_; + std::shared_ptr trial_; + FormOptions options_; + // null when the trial is the test space without a map + std::unique_ptr> trial_evaluator_; + mutable Kokkos::View test_values_; + mutable Kokkos::View trial_values_; + mutable Kokkos::View weighted_; +}; + +} // namespace pcms::transfer::detail + +#endif // PCMS_TRANSFER_FORMS_HPP diff --git a/src/pcms/transfer/linear_solver.cpp b/src/pcms/transfer/linear_solver.cpp new file mode 100644 index 000000000..070748d61 --- /dev/null +++ b/src/pcms/transfer/linear_solver.cpp @@ -0,0 +1,190 @@ +#include "pcms/transfer/linear_solver.hpp" +#include "pcms/field/detail/field_ops.hpp" +#include "pcms/field/point_rows.hpp" +#include "pcms/transfer/petsc_solver.hpp" +#include "pcms/utility/assert.hpp" +#include + +namespace pcms::transfer::detail +{ + +namespace +{ + +constexpr Real RowSumTolerance = 1e-12; + +// whether every owned coefficient, on every rank, exceeds a round-off +// fraction of the largest magnitude (collective) +bool AllPositive(const Field& values) +{ + return pcms::detail::Min(values) > + RowSumTolerance * pcms::detail::MaxNorm(values); +} + +Function CreateInBasis(const FunctionSpace& space, + const ValueBasis& basis) +{ + return space.CreateFunction("", basis.variance, basis.system, + basis.scaling); +} + +// lumped = B 1 in `basis`; whether it is positive +bool Lump(const BilinearForm& form, const ValueBasis& basis, + Function& lumped) +{ + auto ones = CreateInBasis(*form.TestSpace(), basis); + pcms::detail::Const(Real(1), ones); + form.Apply(ones, lumped); + return AllPositive(lumped); +} + +// x = b / (B 1) +class LumpedSolver final : public LinearSolver +{ +public: + explicit LumpedSolver(const BilinearForm& form) : form_(form) + { + InBasis( + form_.TestSpace()->CreateFunction().GetData().GetValueBasis()); + } + + void Solve(const Field& functional, + Field& solution) const override + { + pcms::detail::Div(functional, InBasis(functional.GetData().GetValueBasis()), + solution); + } + +private: + const Function& InBasis(const ValueBasis& basis) const + { + if (!lumped_ || lumped_->GetData().GetValueBasis() != basis) { + lumped_.emplace(CreateInBasis(*form_.TestSpace(), basis)); + if (!Lump(form_, basis, *lumped_)) { + lumped_.reset(); + throw pcms_error("LinearSolver: a row sum of the lumped form is not " + "positive; lumping needs a non-negative basis"); + } + } + return *lumped_; + } + + const BilinearForm& form_; + mutable std::optional> lumped_; +}; + +// whether the assembled solve applies to `form` +bool CanAssemble(const BilinearForm& form) +{ + return !form.TestSpace()->GetLayout()->IsDistributed() && + pcms::detail::AsRowsSource(form.TestEvaluator()) != nullptr; +} + +} // namespace + +void RequireCoefficientOperations( + const std::shared_ptr& space, const std::string& caller) +{ + auto probe = space->CreateFunction(); + try { + pcms::detail::Const(Real(0), probe); + } catch (const pcms_error&) { + throw pcms_error(caller + ": the field data of the target space provides " + "no coefficient operations"); + } +} + +CgSolver::CgSolver(const BilinearForm& form, Real relative_tolerance, + int max_iterations) + : form_(form), + relative_tolerance_(relative_tolerance), + max_iterations_(max_iterations) +{ +} + +CgSolver::Scratch& CgSolver::InBasis(const ValueBasis& basis) const +{ + if (scratch_ == nullptr || + scratch_->residual.GetData().GetValueBasis() != basis) { + const auto& space = *form_.TestSpace(); + scratch_ = std::make_unique(Scratch{ + CreateInBasis(space, basis), CreateInBasis(space, basis), + CreateInBasis(space, basis), CreateInBasis(space, basis), std::nullopt}); + auto& lumped = scratch_->lumped.emplace(CreateInBasis(space, basis)); + if (!Lump(form_, basis, lumped)) { + scratch_->lumped.reset(); + } + } + return *scratch_; +} + +void CgSolver::Solve(const Field& functional, Field& solution) const +{ + auto& scratch = InBasis(solution.GetData().GetValueBasis()); + auto& r = scratch.residual; + auto& p = scratch.direction; + auto& ap = scratch.image; + auto& z = scratch.preconditioned; + const auto precondition = [&]() { + if (scratch.lumped) { + pcms::detail::Div(r, *scratch.lumped, z); + } else { + pcms::detail::Scale(Real(1), r, z); + } + }; + iterations_ = 0; + pcms::detail::Const(Real(0), solution); + pcms::detail::Scale(Real(1), functional, r); + const Real target = relative_tolerance_ * pcms::detail::Norm2(functional); + if (pcms::detail::Norm2(r) <= target) { + return; + } + precondition(); + pcms::detail::Scale(Real(1), z, p); + Real rz = pcms::detail::Apply(r, z); + const int max_iterations = + max_iterations_ > 0 + ? max_iterations_ + : static_cast(form_.TestSpace()->GetLayout()->GlobalSize()); + for (int iteration = 1; iteration <= max_iterations; ++iteration) { + form_.Apply(p, ap); + const Real curvature = pcms::detail::Apply(ap, p); + if (!(curvature > 0)) { + break; + } + const Real alpha = rz / curvature; + pcms::detail::LinearSum(alpha, p, Real(1), solution, solution); + pcms::detail::LinearSum(-alpha, ap, Real(1), r, r); + if (pcms::detail::Norm2(r) <= target) { + iterations_ = iteration; + return; + } + precondition(); + const Real rz_next = pcms::detail::Apply(r, z); + pcms::detail::LinearSum(Real(1), z, rz_next / rz, p, p); + rz = rz_next; + } + throw pcms_error("CgSolver: the conjugate gradients did not converge"); +} + +std::unique_ptr CreateLinearSolver( + const BilinearForm& form, MassMatrixType type, + const LinearSolveOptions& options) +{ + if (!form.IsSquare()) { + throw pcms_error("CreateLinearSolver: the form is not square"); + } + RequireCoefficientOperations(form.TestSpace(), "CreateLinearSolver"); + if (type == MassMatrixType::Lumped) { + return std::make_unique(form); + } + if (options.method == LinearSolveOptions::Method::Assembled || + (options.method == LinearSolveOptions::Method::Automatic && + CanAssemble(form))) { + return CreatePetscSolver(form, options); + } + return std::make_unique(form, options.relative_tolerance, + options.max_iterations); +} + +} // namespace pcms::transfer::detail diff --git a/src/pcms/transfer/linear_solver.hpp b/src/pcms/transfer/linear_solver.hpp new file mode 100644 index 000000000..ad026d5d0 --- /dev/null +++ b/src/pcms/transfer/linear_solver.hpp @@ -0,0 +1,79 @@ +#ifndef PCMS_TRANSFER_LINEAR_SOLVER_HPP +#define PCMS_TRANSFER_LINEAR_SOLVER_HPP + +#include "pcms/field/field.hpp" +#include "pcms/transfer/forms.hpp" +#include "pcms/transfer/mass_matrix_type.hpp" +#include "pcms/transfer/projection.hpp" +#include +#include +#include + +namespace pcms::transfer::detail +{ + +/// @throws pcms_error naming `caller` unless the field data of the functions +/// of `space` provides the FieldData coefficient operations +void RequireCoefficientOperations( + const std::shared_ptr& space, const std::string& caller); + +/// @brief Solves B x = b for a square BilinearForm B: b a functional, x +/// coefficients, both fields of the form's test layout. +class LinearSolver +{ +public: + virtual ~LinearSolver() noexcept = default; + + /// @brief solution = B^-1 functional + virtual void Solve(const Field& functional, + Field& solution) const = 0; +}; + +/// @brief Conjugate gradients on all components jointly, on the form's Apply +/// and the coefficient operations; B must be symmetric positive +/// definite. The preconditioner is the lumped form B 1, or the +/// identity where that is not positive. +class CgSolver final : public LinearSolver +{ +public: + /// Holds a reference to `form`, which must outlive the solver. + CgSolver(const BilinearForm& form, Real relative_tolerance, + int max_iterations); + + /// @throws pcms_error if the iterations do not converge + void Solve(const Field& functional, + Field& solution) const override; + + /// @return the iterations of the last Solve + [[nodiscard]] int Iterations() const noexcept { return iterations_; } + +private: + /// The vectors in one value basis and the lumped form. + struct Scratch + { + Function residual, direction, image, preconditioned; + std::optional> lumped; + }; + + /// @return the scratch in `basis`, made anew when the basis changes + Scratch& InBasis(const ValueBasis& basis) const; + + const BilinearForm& form_; + Real relative_tolerance_; + int max_iterations_; + mutable std::unique_ptr scratch_; + mutable int iterations_ = 0; +}; + +/// @return the solver of `form`: x = b / (B 1) for a Lumped `type`, else the +/// method of `options`. Holds a reference to `form`, which must +/// outlive the solver. +/// @throws pcms_error if the form is not square, a lumped form is not +/// positive, or the method is not available +std::unique_ptr CreateLinearSolver( + const BilinearForm& form, MassMatrixType type, + const LinearSolveOptions& options); + +} // namespace pcms::transfer::detail + +#endif // PCMS_TRANSFER_LINEAR_SOLVER_HPP diff --git a/src/pcms/transfer/petsc_solver.cpp b/src/pcms/transfer/petsc_solver.cpp new file mode 100644 index 000000000..7b3aab598 --- /dev/null +++ b/src/pcms/transfer/petsc_solver.cpp @@ -0,0 +1,339 @@ +#include "pcms/transfer/petsc_solver.hpp" +#include "pcms/field/point_rows.hpp" +#include "pcms/transfer/petsc_utils.hpp" +#include "pcms/utility/assert.hpp" +#include +#include +#include +#include +#include + +namespace pcms::transfer::detail +{ + +namespace +{ + +void Check(PetscErrorCode ierr) +{ + if (ierr != PETSC_SUCCESS) { + throw pcms_error("PetscSolver: PETSc error " + std::to_string(ierr)); + } +} + +// Destroys a PETSc object. +template +struct PetscDestroy +{ + template + void operator()(Handle handle) const + { + Destroy(&handle); + } +}; + +template +using PetscPtr = + std::unique_ptr, PetscDestroy>; + +template +using DeviceView = Kokkos::View; +using UnmanagedScalars = Kokkos::View>; + +constexpr bool DeviceIsHost = + Kokkos::SpaceAccessibility::accessible; + +// the array of `vector` in DeviceMemorySpace +void RequireDeviceArray(PetscMemType memtype) +{ + if (DeviceIsHost != static_cast(PetscMemTypeHost(memtype))) { + throw pcms_error("PetscSolver: the PETSc vector is not in the memory " + "space of the PCMS device"); + } +} + +// The owned global ids in ascending order: row r of the matrix is the r-th. +DeviceView SortedGids(GlobalIDView gids) +{ + DeviceView sorted( + Kokkos::view_alloc(Kokkos::WithoutInitializing, "petsc_sorted_gids"), + gids.size()); + Kokkos::parallel_for( + "pcms::PetscSolver::CopyGids", + Kokkos::RangePolicy( + 0, static_cast(sorted.extent(0))), + KOKKOS_LAMBDA(const LO i) { sorted(i) = gids[i]; }); + Kokkos::sort(sorted); + return sorted; +} + +// the row of `gid`, or -1 if no owned holder has it (PETSc ignores the entry) +KOKKOS_INLINE_FUNCTION PetscInt RowOf(const DeviceView& sorted, GO gid) +{ + LO lo = 0; + LO hi = static_cast(sorted.extent(0)); + while (lo < hi) { + const LO mid = lo + (hi - lo) / 2; + if (sorted(mid) < gid) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo < static_cast(sorted.extent(0)) && sorted(lo) == gid + ? static_cast(lo) + : PetscInt{-1}; +} + +// the row of each owned holder +DeviceView OwnedRows(GlobalIDView gids, + const DeviceView& sorted) +{ + DeviceView rows( + Kokkos::view_alloc(Kokkos::WithoutInitializing, "petsc_owned_rows"), + gids.size()); + Kokkos::parallel_for( + "pcms::PetscSolver::OwnedRows", + Kokkos::RangePolicy(0, + static_cast(rows.extent(0))), + KOKKOS_LAMBDA(const LO o) { rows(o) = RowOf(sorted, gids[o]); }); + return rows; +} + +// The COO entries of E^T W E: one n x n block per run of consecutive points +// with the same support (an element's points); rows and columns are the ranks +// of the holders' global ids among the owned ones. +struct Coo +{ + DeviceView rows; + DeviceView columns; + DeviceView values; +}; + +// whether point p's support differs from point p - 1's +KOKKOS_INLINE_FUNCTION bool StartsBlock( + const Kokkos::View& offsets, + const Kokkos::View& holders, LO p) +{ + if (p == 0) { + return true; + } + const LO n = offsets(p + 1) - offsets(p); + if (n != offsets(p) - offsets(p - 1)) { + return true; + } + for (LO i = 0; i < n; ++i) { + if (holders(offsets(p) + i) != holders(offsets(p - 1) + i)) { + return true; + } + } + return false; +} + +Coo AssembleCoo(const pcms::detail::PointRows& rows, + GlobalIDView gids, + const DeviceView& sorted, + const Kokkos::View& weights) +{ + const auto num_points = static_cast(rows.offsets.extent(0)) - 1; + const auto offsets = rows.offsets; + const auto holders = rows.holders; + const auto entries = rows.values; + DeviceView holder_rows( + Kokkos::view_alloc(Kokkos::WithoutInitializing, "coo_holder_rows"), + gids.size()); + Kokkos::parallel_for( + "pcms::PetscSolver::HolderRows", + Kokkos::RangePolicy( + 0, static_cast(holder_rows.extent(0))), + KOKKOS_LAMBDA(const LO h) { holder_rows(h) = RowOf(sorted, gids[h]); }); + + // the first point of each block, and num_points after the last + DeviceView first( + Kokkos::view_alloc(Kokkos::WithoutInitializing, "coo_block_first"), + num_points + 1); + LO num_blocks = 0; + Kokkos::parallel_scan( + "pcms::PetscSolver::CooBlocks", + Kokkos::RangePolicy(0, num_points + 1), + KOKKOS_LAMBDA(const LO p, LO& partial, const bool final) { + const bool starts = p == num_points || StartsBlock(offsets, holders, p); + if (final && starts) { + first(partial) = p; + } + if (p < num_points && starts) { + ++partial; + } + }, + num_blocks); + + DeviceView start("coo_start", num_blocks + 1); + Kokkos::parallel_scan( + "pcms::PetscSolver::CooOffsets", + Kokkos::RangePolicy(0, num_blocks + 1), + KOKKOS_LAMBDA(const LO b, LO& partial, const bool final) { + if (final) { + start(b) = partial; + } + if (b < num_blocks) { + const LO n = offsets(first(b) + 1) - offsets(first(b)); + partial += n * n; + } + }); + LO nnz = 0; + Kokkos::deep_copy(nnz, Kokkos::subview(start, num_blocks)); + Coo coo{DeviceView("coo_rows", nnz), + DeviceView("coo_columns", nnz), + DeviceView("coo_values", nnz)}; + const auto out_rows = coo.rows; + const auto out_columns = coo.columns; + const auto out_values = coo.values; + Kokkos::parallel_for( + "pcms::PetscSolver::Coo", + Kokkos::RangePolicy(0, num_blocks), + KOKKOS_LAMBDA(const LO b) { + const LO head = offsets(first(b)); + const LO n = offsets(first(b) + 1) - head; + for (LO i = 0; i < n; ++i) { + for (LO j = 0; j < n; ++j) { + Real value = 0; + for (LO p = first(b); p < first(b + 1); ++p) { + value += + weights(p) * entries(offsets(p) + i) * entries(offsets(p) + j); + } + const LO k = start(b) + i * n + j; + out_rows(k) = holder_rows(holders(head + i)); + out_columns(k) = holder_rows(holders(head + j)); + out_values(k) = value; + } + } + }); + return coo; +} + +// x = B^-1 b by a KSP on the assembled B, one solve per component +class PetscSolver final : public LinearSolver +{ +public: + PetscSolver(const BilinearForm& form, const LinearSolveOptions& options) + { + const auto& layout = *form.TestSpace()->GetLayout(); + if (layout.IsDistributed()) { + throw pcms_error("PetscSolver: the assembled solve is serial; the " + "layout is distributed"); + } + const auto* source = pcms::detail::AsRowsSource(form.TestEvaluator()); + if (source == nullptr) { + throw pcms_error("PetscSolver: the assembled solve needs an evaluator " + "with evaluation rows"); + } + const auto gids = layout.GetGids(); + const auto sorted = SortedGids(gids); + size_ = static_cast(sorted.extent(0)); + owned_rows_ = OwnedRows(gids, sorted); + + const auto coo = AssembleCoo(source->Rows(), source->HolderGids(), sorted, + form.GetQuadrature().weights); + const auto nnz = static_cast(coo.rows.extent(0)); + // the symbolic phase of PETSc runs on the host + auto coo_rows = + Kokkos::create_mirror_view_and_copy(HostMemorySpace{}, coo.rows); + auto coo_columns = + Kokkos::create_mirror_view_and_copy(HostMemorySpace{}, coo.columns); + Mat matrix = nullptr; + Check(createSeqAIJMat(PETSC_COMM_SELF, size_, size_, 0, nullptr, &matrix)); + matrix_.reset(matrix); + Check(MatSetPreallocationCOO(matrix_.get(), nnz, coo_rows.data(), + coo_columns.data())); + Check(MatSetValuesCOO(matrix_.get(), coo.values.data(), INSERT_VALUES)); + Vec vector = nullptr; + Check(createSeqVec(PETSC_COMM_SELF, size_, &vector)); + rhs_.reset(vector); + Check(createSeqVec(PETSC_COMM_SELF, size_, &vector)); + solution_.reset(vector); + + KSP ksp = nullptr; + Check(KSPCreate(PETSC_COMM_SELF, &ksp)); + ksp_.reset(ksp); + Check(KSPSetOperators(ksp_.get(), matrix_.get(), matrix_.get())); + Check(KSPSetType(ksp_.get(), KSPCG)); + PC pc = nullptr; + Check(KSPGetPC(ksp_.get(), &pc)); + Check(PCSetType(pc, PCJACOBI)); + Check(KSPSetNormType(ksp_.get(), KSP_NORM_UNPRECONDITIONED)); + Check(KSPSetTolerances( + ksp_.get(), options.relative_tolerance, PETSC_DEFAULT, PETSC_DEFAULT, + options.max_iterations > 0 ? options.max_iterations : size_)); + if (!options.petsc_options_prefix.empty()) { + Check( + KSPSetOptionsPrefix(ksp_.get(), options.petsc_options_prefix.c_str())); + } + Check(KSPSetFromOptions(ksp_.get())); + Check(KSPSetUp(ksp_.get())); + } + + void Solve(const Field& functional, + Field& solution) const override + { + const auto b = functional.GetDOFHolderData().GetValues(); + const auto rows = owned_rows_; + Kokkos::View x( + Kokkos::view_alloc(Kokkos::WithoutInitializing, "petsc_solution"), + b.extent(0), b.extent(1)); + for (std::size_t c = 0; c < b.extent(1); ++c) { + PetscScalar* rhs_array = nullptr; + PetscMemType memtype{}; + Check(VecGetArrayWriteAndMemType(rhs_.get(), &rhs_array, &memtype)); + RequireDeviceArray(memtype); + const UnmanagedScalars rhs(rhs_array, static_cast(size_)); + Kokkos::deep_copy(rhs, PetscScalar(0)); + Kokkos::parallel_for( + "pcms::PetscSolver::Pack", + Kokkos::RangePolicy(0, rows.extent(0)), + KOKKOS_LAMBDA(const LO o) { rhs(rows(o)) = b(o, c); }); + Kokkos::fence(); + Check(VecRestoreArrayWriteAndMemType(rhs_.get(), &rhs_array)); + Check(KSPSolve(ksp_.get(), rhs_.get(), solution_.get())); + KSPConvergedReason reason{}; + Check(KSPGetConvergedReason(ksp_.get(), &reason)); + if (reason < 0) { + throw pcms_error("PetscSolver: the KSP did not converge"); + } + const PetscScalar* result_array = nullptr; + Check( + VecGetArrayReadAndMemType(solution_.get(), &result_array, &memtype)); + RequireDeviceArray(memtype); + const Kokkos::View> + result(result_array, static_cast(size_)); + Kokkos::parallel_for( + "pcms::PetscSolver::Unpack", + Kokkos::RangePolicy(0, rows.extent(0)), + KOKKOS_LAMBDA(const LO o) { x(o, c) = result(rows(o)); }); + Kokkos::fence(); + Check(VecRestoreArrayReadAndMemType(solution_.get(), &result_array)); + } + solution.SetDOFHolderDataUnchecked(MakeConstRank2View(x)); + solution.Synchronize(); + } + +private: + PetscInt size_ = 0; + DeviceView owned_rows_; + // destroyed in reverse order: the KSP before the matrix it uses + PetscPtr matrix_; + PetscPtr rhs_; + PetscPtr solution_; + PetscPtr ksp_; +}; + +} // namespace + +std::unique_ptr CreatePetscSolver( + const BilinearForm& form, const LinearSolveOptions& options) +{ + return std::make_unique(form, options); +} + +} // namespace pcms::transfer::detail diff --git a/src/pcms/transfer/petsc_solver.hpp b/src/pcms/transfer/petsc_solver.hpp new file mode 100644 index 000000000..adcae85b1 --- /dev/null +++ b/src/pcms/transfer/petsc_solver.hpp @@ -0,0 +1,21 @@ +#ifndef PCMS_TRANSFER_PETSC_SOLVER_HPP +#define PCMS_TRANSFER_PETSC_SOLVER_HPP + +#include "pcms/transfer/linear_solver.hpp" +#include + +namespace pcms::transfer::detail +{ + +/// @return a PETSc KSP on the assembled matrix of a square `form` (serial): +/// conjugate gradients preconditioned by its diagonal, to the +/// tolerance and iteration limit of `options`, unless the options of +/// its PETSc prefix say otherwise. Holds a reference to `form`. +/// @throws pcms_error if the layout is distributed or the test evaluator has +/// no evaluation rows +std::unique_ptr CreatePetscSolver( + const BilinearForm& form, const LinearSolveOptions& options); + +} // namespace pcms::transfer::detail + +#endif // PCMS_TRANSFER_PETSC_SOLVER_HPP diff --git a/src/pcms/transfer/petsc_utils.cpp b/src/pcms/transfer/petsc_utils.cpp index f76fa3657..deb0aae92 100644 --- a/src/pcms/transfer/petsc_utils.cpp +++ b/src/pcms/transfer/petsc_utils.cpp @@ -12,7 +12,8 @@ PetscErrorCode createSeqAIJMat(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat* mat) { PetscFunctionBeginUser; -#if defined(PETSC_HAVE_KOKKOS) +#if defined(PETSC_HAVE_KOKKOS) && \ + (defined(KOKKOS_ENABLE_CUDA) || defined(KOKKOS_ENABLE_HIP)) PetscCall(MatCreateSeqAIJKokkos(comm, m, n, nz, nnz, mat)); #else PetscCall(MatCreateSeqAIJ(comm, m, n, nz, nnz, mat)); @@ -23,7 +24,8 @@ PetscErrorCode createSeqAIJMat(MPI_Comm comm, PetscInt m, PetscInt n, PetscErrorCode createSeqVec(MPI_Comm comm, PetscInt n, Vec* vec) { PetscFunctionBeginUser; -#if defined(PETSC_HAVE_KOKKOS) +#if defined(PETSC_HAVE_KOKKOS) && \ + (defined(KOKKOS_ENABLE_CUDA) || defined(KOKKOS_ENABLE_HIP)) PetscCall(VecCreateSeqKokkos(comm, n, vec)); #else PetscCall(VecCreateSeq(comm, n, vec)); diff --git a/src/pcms/transfer/petsc_utils.hpp b/src/pcms/transfer/petsc_utils.hpp index 3aecf9942..938e306e5 100644 --- a/src/pcms/transfer/petsc_utils.hpp +++ b/src/pcms/transfer/petsc_utils.hpp @@ -16,14 +16,12 @@ namespace pcms::transfer { -// Creates a sequential AIJ matrix using the Kokkos backend when available, -// falling back to standard sequential AIJ on CPU-only builds. +// Creates a sequential AIJ matrix: Kokkos AIJ on GPU builds, AIJ otherwise. // Pass nz=0 and nnz=nullptr when using COO preallocation afterwards. PetscErrorCode createSeqAIJMat(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat* mat); -// Creates a sequential vector using the Kokkos backend when available, -// falling back to standard sequential vector on CPU-only builds. +// Creates a sequential vector: a Kokkos vector on GPU builds, Seq otherwise. PetscErrorCode createSeqVec(MPI_Comm comm, PetscInt n, Vec* vec); } // namespace pcms::transfer From 86b5b454a879d00f20bbaa0ae8a9170ca71b6958 Mon Sep 17 00:00:00 2001 From: Jacob Merson Date: Thu, 26 Nov 2026 23:38:30 +0000 Subject: [PATCH 6/7] test(transfer): Bilinear forms E_test^T W G E_trial and the linear solver --- test/CMakeLists.txt | 14 ++ test/forms_test_utils.hpp | 54 ++++ test/test_bilinear_form.cpp | 357 +++++++++++++++++++++++++++ test/test_distributed_evaluation.cpp | 17 ++ test/test_distributed_forms.cpp | 316 ++++++++++++++++++++++++ test/test_galerkin_projection.cpp | 58 +++++ test/test_omega_h_lagrange_field.cpp | 2 +- 7 files changed, 817 insertions(+), 1 deletion(-) create mode 100644 test/forms_test_utils.hpp create mode 100644 test/test_bilinear_form.cpp create mode 100644 test/test_distributed_forms.cpp diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index b7bdffb69..dc9d3d218 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -72,6 +72,19 @@ if(PCMS_ENABLE_OMEGA_H AND TARGET pcms::coupler) mpi_test(test_distributed_evaluation_4p 4 $) endif() + if(PCMS_ENABLE_CONSERVATIVE_PROJECTION) + add_exe(test_distributed_forms) + target_link_libraries(test_distributed_forms meshfields::meshfields + pcms::transfer) + if(HOST_NPROC GREATER_EQUAL 2) + mpi_test(test_distributed_forms_2p 2 + $) + endif() + if(HOST_NPROC GREATER_EQUAL 4) + mpi_test(test_distributed_forms_4p 4 + $) + endif() + endif() endif() add_exe(test_ohClassPtn_appRibPtn) set(cyclone2p ${PCMS_TEST_DATA_DIR}/cyclone/23elements/2p.osh/) @@ -514,6 +527,7 @@ if(Catch2_FOUND) list(APPEND PCMS_UNIT_TEST_SOURCES test_quadrature.cpp test_galerkin_projection.cpp + test_bilinear_form.cpp test_omega_h_intersection_rhs_integrator.cpp test_omega_h_mass_integrator.cpp test_omega_h_mc_rhs_integrator.cpp diff --git a/test/forms_test_utils.hpp b/test/forms_test_utils.hpp new file mode 100644 index 000000000..c6de243f9 --- /dev/null +++ b/test/forms_test_utils.hpp @@ -0,0 +1,54 @@ +#ifndef PCMS_TEST_FORMS_TEST_UTILS_HPP +#define PCMS_TEST_FORMS_TEST_UTILS_HPP + +#include +#include +#include +#include +#include +#include + +namespace pcms::test +{ + +using Matrix = std::map, Real>; + +/// @return E^T W E of the form's quadrature from the test evaluator's rows, +/// keyed by the global ids of the DOF holders +inline Matrix AssembleMass(const transfer::detail::BilinearForm& form) +{ + const auto* source = detail::AsRowsSource(form.TestEvaluator()); + REQUIRE(source != nullptr); + const auto& rows = source->Rows(); + const auto offsets = + Kokkos::create_mirror_view_and_copy(HostMemorySpace{}, rows.offsets); + const auto holders = + Kokkos::create_mirror_view_and_copy(HostMemorySpace{}, rows.holders); + const auto values = + Kokkos::create_mirror_view_and_copy(HostMemorySpace{}, rows.values); + const auto device_gids = source->HolderGids(); + Kokkos::View gids_view("gids", device_gids.size()); + Kokkos::parallel_for( + "gids", + Kokkos::RangePolicy( + 0, static_cast(gids_view.extent(0))), + KOKKOS_LAMBDA(const LO i) { gids_view(i) = device_gids[i]; }); + const auto gids = + Kokkos::create_mirror_view_and_copy(HostMemorySpace{}, gids_view); + const auto weights = Kokkos::create_mirror_view_and_copy( + HostMemorySpace{}, form.GetQuadrature().weights); + Matrix matrix; + for (std::size_t p = 0; p + 1 < offsets.extent(0); ++p) { + for (LO i = offsets(p); i < offsets(p + 1); ++i) { + for (LO j = offsets(p); j < offsets(p + 1); ++j) { + matrix[{gids(holders(i)), gids(holders(j))}] += + weights(p) * values(i) * values(j); + } + } + } + return matrix; +} + +} // namespace pcms::test + +#endif // PCMS_TEST_FORMS_TEST_UTILS_HPP diff --git a/test/test_bilinear_form.cpp b/test/test_bilinear_form.cpp new file mode 100644 index 000000000..2e65740a0 --- /dev/null +++ b/test/test_bilinear_form.cpp @@ -0,0 +1,357 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "field_test_utils.hpp" +#include "forms_test_utils.hpp" +#include +#include +#include +#include +#include "pcms/utility/coordinate_systems/cartesian.hpp" +#include "pcms/utility/coordinate_systems/cylindrical.hpp" + +namespace pcms +{ +using omega_h::CreateGeometry; +using omega_h::OmegaHLagrangeLayout; +} // namespace pcms + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +namespace +{ + +using pcms::test::AssembleMass; +using pcms::test::Matrix; + +// lumped = B 1 +void Lump(const pcms::transfer::detail::BilinearForm& form, + pcms::Field& lumped) +{ + auto ones = form.TestSpace()->CreateFunction(); + pcms::detail::Const(pcms::Real(1), ones); + form.Apply(ones, lumped); +} + +pcms::transfer::detail::BilinearForm MassForm( + const std::shared_ptr& space) +{ + return pcms::transfer::detail::BilinearForm(space); +} + +// The reference P1 mass matrix of a triangle mesh, summed over the elements: +// the element block is area / 12 * (1 + delta_ij) +Matrix BuildReferenceMassMap(Omega_h::Mesh& mesh, + const pcms::FunctionSpace& space) +{ + const auto layout = + std::dynamic_pointer_cast( + space.GetLayout()); + REQUIRE(layout != nullptr); + const auto areas = + Omega_h::HostRead(Omega_h::measure_elements_real(&mesh)); + const auto faces2nodes = + Omega_h::HostRead(mesh.ask_down(Omega_h::FACE, Omega_h::VERT).ab2b); + const auto& gids = layout->GetGidsHost(); + Matrix ref; + for (int e = 0; e < mesh.nelems(); ++e) { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + ref[{static_cast(gids[faces2nodes[e * 3 + i]]), + static_cast(gids[faces2nodes[e * 3 + j]])}] += + areas[e] / 12.0 * (i == j ? 2.0 : 1.0); + } + } + } + return ref; +} + +} // namespace + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +TEST_CASE("BilinearForm: assembled matrix matches buildElementMassMatrix", + "[bilinear_form]") +{ + Omega_h::Library lib; + auto mesh = pcms::test::BuildUnitSquare(lib, 0); + auto space = pcms::test::MakeP1Space(mesh); + const auto ref = BuildReferenceMassMap(mesh, *space); + const auto form = MassForm(space); + const auto matrix = AssembleMass(form); + for (const auto& [key, ref_val] : ref) { + CAPTURE(key.first, key.second, ref_val); + REQUIRE(matrix.count(key) == 1); + CHECK(matrix.at(key) == Catch::Approx(ref_val).epsilon(1e-12)); + } +} + +TEST_CASE("BilinearForm: row sums are positive and total the domain area", + "[bilinear_form]") +{ + Omega_h::Library lib; + auto mesh = pcms::test::BuildUnitSquare(lib, 0); + auto space = pcms::test::MakeP1Space(mesh); + const auto matrix = AssembleMass(MassForm(space)); + std::map row_sums; + for (const auto& [key, value] : matrix) { + row_sums[key.first] += value; + } + pcms::Real grand_total = 0.0; + for (const auto& [row, sum] : row_sums) { + CAPTURE(row, sum); + CHECK(sum > 0.0); + grand_total += sum; + } + CHECK(grand_total == Catch::Approx(1.0).epsilon(1e-10)); +} + +TEST_CASE("BilinearForm: lumped mass equals the consistent row sums", + "[bilinear_form]") +{ + // Row-sum lumping: M_L(i,i) = sum_j M_C(i,j) = integral(N_i dx). The trace + // equals the domain area. + Omega_h::Library lib; + auto mesh = pcms::test::BuildUnitSquare(lib, 0); + auto space = pcms::test::MakeP1Space(mesh); + const auto form = MassForm(space); + const auto matrix = AssembleMass(form); + auto lumped = space->CreateFunction(); + Lump(form, lumped); + const auto layout = + std::dynamic_pointer_cast( + space->GetLayout()); + const auto& gids = layout->GetGidsHost(); + const auto values = lumped.GetDOFHolderDataHost().GetValues(); + pcms::Real trace = 0.0; + for (int v = 0; v < mesh.nverts(); ++v) { + pcms::Real row_sum = 0.0; + for (const auto& [key, value] : matrix) { + if (key.first == static_cast(gids[v])) { + row_sum += value; + } + } + CAPTURE(v, row_sum); + CHECK(values(v, 0) == Catch::Approx(row_sum).epsilon(1e-12)); + trace += values(v, 0); + } + CHECK(trace == Catch::Approx(1.0).epsilon(1e-10)); +} + +TEST_CASE("BilinearForm: P0 mass is diagonal with the element areas, lumped " + "or not", + "[bilinear_form]") +{ + Omega_h::Library lib; + auto mesh = pcms::test::BuildUnitSquare(lib, 0); + auto geometry = pcms::CreateGeometry(mesh, pcms::detail::DeferredCartesian()); + auto space = pcms::CreateLagrangeSpace( + geometry, 0, 1, + pcms::LagrangeOptions{.backend = pcms::LagrangeBackend::OmegaH}); + const auto form = MassForm(space); + const auto matrix = AssembleMass(form); + auto lumped = space->CreateFunction(); + Lump(form, lumped); + const auto lumped_values = lumped.GetDOFHolderDataHost().GetValues(); + + const auto elem_areas = Omega_h::measure_elements_real(&mesh); + const auto elem_areas_h = Omega_h::HostRead(elem_areas); + const auto layout = + std::dynamic_pointer_cast( + space->GetLayout()); + const auto& gids = layout->GetGidsHost(); + for (const auto& [key, value] : matrix) { + if (key.first != key.second) { + CHECK(value == Catch::Approx(0.0).margin(1e-14)); + } + } + for (int e = 0; e < mesh.nelems(); ++e) { + const pcms::GO gid = gids[e]; + CAPTURE(e, elem_areas_h[e]); + CHECK(matrix.at({gid, gid}) == + Catch::Approx(elem_areas_h[e]).epsilon(1e-12)); + CHECK(lumped_values(e, 0) == Catch::Approx(elem_areas_h[e]).epsilon(1e-12)); + } +} + +TEST_CASE("BilinearForm: a multi-component space has the same mass matrix, " + "and the form needs a space with a natural quadrature", + "[bilinear_form]") +{ + Omega_h::Library lib; + auto mesh = pcms::test::BuildUnitSquare(lib, 0); + auto space = pcms::CreateLagrangeSpace( + pcms::CreateGeometry(mesh, pcms::detail::DeferredCartesian()), 1, 2, + pcms::LagrangeOptions{.backend = pcms::LagrangeBackend::OmegaH}); + const auto matrix = AssembleMass(MassForm(space)); + const auto scalar = AssembleMass(MassForm(pcms::test::MakeP1Space(mesh))); + REQUIRE(matrix.size() == scalar.size()); + for (const auto& [key, value] : scalar) { + CHECK(matrix.at(key) == Catch::Approx(value).epsilon(1e-12)); + } +} + +TEST_CASE("BilinearForm: a trial on another mesh, applied, transposed and " + "paired", + "[bilinear_form]") +{ + Omega_h::Library lib; + auto coarse = pcms::test::BuildSquareMesh(lib, 2); + auto fine = pcms::test::BuildSquareMesh(lib, 4); + const auto test_space = pcms::test::MakeP1Space(coarse); + const auto trial_space = pcms::test::MakeP1Space(fine); + const auto linear = [](pcms::Real x, pcms::Real y, pcms::Real* out) { + out[0] = 1 + x - 2 * y; + }; + auto u = trial_space->CreateFunction(); + auto v = test_space->CreateFunction(); + auto w = test_space->CreateFunction(); + pcms::test::SetFieldComponents(u, linear); + pcms::test::SetFieldComponents(w, linear); + pcms::test::SetFieldComponents( + v, [](pcms::Real x, pcms::Real y, pcms::Real* out) { out[0] = x + y; }); + // int (x + y) (1 + x - 2 y) over the unit square + const pcms::Real exact = 5.0 / 12.0; + const pcms::transfer::detail::BilinearForm form(test_space, trial_space); + CHECK(form.Pair(v, u) == Catch::Approx(exact).epsilon(1e-12)); + auto functional = test_space->CreateFunction(); + form.Apply(u, functional); + CHECK(pcms::detail::DotProd(v, functional) == + Catch::Approx(exact).epsilon(1e-12)); + auto transposed = trial_space->CreateFunction(); + form.ApplyTranspose(v, transposed); + CHECK(pcms::detail::DotProd(transposed, u) == + Catch::Approx(exact).epsilon(1e-12)); + // the same points with the test space as the trial + const auto square = form.WithTrial(test_space); + CHECK(square.Pair(v, w) == Catch::Approx(exact).epsilon(1e-12)); + CHECK(square.IsSquare()); + CHECK_FALSE(form.IsSquare()); +} + +namespace +{ + +// Field data without the coefficient operations. +class NoOperationsData final : public pcms::FieldData +{ +public: + explicit NoOperationsData(pcms::ValueBasis basis) : basis_(std::move(basis)) + { + } + pcms::FieldValueType GetValueType() const override + { + return pcms::detail::ValueTypeOfRank(basis_.Rank()); + } + const pcms::ValueBasis& GetValueBasis() const override { return basis_; } + +private: + pcms::ValueBasis basis_; +}; + +// A space on the layout and evaluator of another, whose fields' data has no +// coefficient operations. +class NoOperationsSpace final : public pcms::FunctionSpace +{ +public: + explicit NoOperationsSpace(std::shared_ptr space) + : FunctionSpace(space->GetLayout(), space, space->GetGeometry()), + space_(std::move(space)) + { + } + +protected: + pcms::Quadrature CreateQuadrature() const override + { + return space_->GetQuadrature(); + } + pcms::FieldDataVariant CreateFieldData(pcms::Type /*storage_type*/, + pcms::ValueBasis basis) const override + { + return std::unique_ptr>( + std::make_unique(std::move(basis))); + } + +private: + std::shared_ptr space_; +}; + +} // namespace + +TEST_CASE("CreateLinearSolver: a target without coefficient operations throws", + "[bilinear_form]") +{ + Omega_h::Library lib; + auto mesh = pcms::test::BuildSquareMesh(lib, 2); + const auto space = + std::make_shared(pcms::test::MakeP1Space(mesh)); + const pcms::transfer::detail::BilinearForm form(space); + CHECK_THROWS_WITH( + pcms::transfer::detail::CreateLinearSolver( + form, pcms::MassMatrixType::Consistent, pcms::LinearSolveOptions{}), + Catch::Matchers::ContainsSubstring("no coefficient operations")); +} + +TEST_CASE("CreateLinearSolver: the assembled and matrix-free solves recover " + "u, the lumped solve divides by B 1", + "[bilinear_form]") +{ + Omega_h::Library lib; + auto mesh = pcms::test::BuildSquareMesh(lib, 4); + const auto space = pcms::test::MakeP1Space(mesh); + const auto form = MassForm(space); + auto u = space->CreateFunction(); + pcms::test::SetFieldComponents( + u, [](pcms::Real x, pcms::Real y, pcms::Real* out) { + out[0] = std::sin(3 * x) + y * y; + }); + auto bu = space->CreateFunction(); + form.Apply(u, bu); + const auto u_host = u.GetDOFHolderDataHost().GetValues(); + // the default picks the assembled solve for a serial form with rows + CHECK(dynamic_cast( + pcms::transfer::detail::CreateLinearSolver( + form, pcms::MassMatrixType::Consistent, {}) + .get()) == nullptr); + for (const auto method : {pcms::LinearSolveOptions::Method::MatrixFree, + pcms::LinearSolveOptions::Method::Assembled, + pcms::LinearSolveOptions::Method::Automatic}) { + auto x = space->CreateFunction(); + pcms::transfer::detail::CreateLinearSolver( + form, pcms::MassMatrixType::Consistent, + pcms::LinearSolveOptions{.method = method}) + ->Solve(bu, x); + const auto x_host = x.GetDOFHolderDataHost().GetValues(); + for (std::size_t h = 0; h < x_host.extent(0); ++h) { + CHECK(x_host(h, 0) == Catch::Approx(u_host(h, 0)).margin(1e-8)); + } + } + auto lumped = space->CreateFunction(); + Lump(form, lumped); + auto x = space->CreateFunction(); + pcms::transfer::detail::CreateLinearSolver(form, pcms::MassMatrixType::Lumped, + pcms::LinearSolveOptions{}) + ->Solve(bu, x); + const auto x_host = x.GetDOFHolderDataHost().GetValues(); + const auto b_host = bu.GetDOFHolderDataHost().GetValues(); + const auto l_host = lumped.GetDOFHolderDataHost().GetValues(); + for (std::size_t h = 0; h < x_host.extent(0); ++h) { + CHECK(x_host(h, 0) == + Catch::Approx(b_host(h, 0) / l_host(h, 0)).epsilon(1e-12)); + } +} diff --git a/test/test_distributed_evaluation.cpp b/test/test_distributed_evaluation.cpp index 3ea84ab23..d5eab5473 100644 --- a/test/test_distributed_evaluation.cpp +++ b/test/test_distributed_evaluation.cpp @@ -14,9 +14,11 @@ #include "pcms/transfer/omega_h_intersection_quadrature.hpp" #endif +#include #include #include #include +#include #include #include @@ -354,6 +356,20 @@ void CheckQuadrature(const pcms::Quadrature& quadrature, Omega_h::Mesh& mesh, } // The points per element of the Gauss rule of `order` on a serial mesh. +// The geometry's reductions are over the mesh's ranks. +void CheckReductions(const pcms::Geometry& geometry, const std::string& name) +{ + const Real size = SumOverRanks(Real(1)); + const auto rank = static_cast(Rank()); + std::array sums{1.0, rank}; + pcms::detail::SumOverRanks(geometry, std::span(sums)); + Check(sums[0] == size && sums[1] == size * (size - 1) / 2, + name + ": SumOverRanks"); + std::array max{rank}; + pcms::detail::MaxOverRanks(geometry, std::span(max)); + Check(max[0] == size - 1, name + ": MaxOverRanks"); +} + int PointsPerElement(Omega_h::Library& library, int dim, int order) { auto mesh = @@ -380,6 +396,7 @@ void RunCases(Omega_h::Library& library, int dim, bool ghosted) } auto geometry = pcms::omega_h::CreateGeometry(mesh, pcms::detail::DeferredCartesian()); + CheckReductions(*geometry, Case(ghosted, dim, 1, 1)); for (int order : {0, 1}) { const auto points = LocalPoints(mesh, order); const auto bound = Bind(*geometry, points, dim); diff --git a/test/test_distributed_forms.cpp b/test/test_distributed_forms.cpp new file mode 100644 index 000000000..dd79d6053 --- /dev/null +++ b/test/test_distributed_forms.cpp @@ -0,0 +1,316 @@ +#include + +#include +#include +#include +#include + +#include "distributed_test_utils.hpp" +#include "pcms/backends/omega_h/omega_h.hpp" +#include "pcms/field/detail/field_ops.hpp" +#include "pcms/field/function_spaces.hpp" +#include "pcms/transfer/forms.hpp" +#include "pcms/transfer/linear_solver.hpp" +#include "pcms/utility/arrays.hpp" + +#include +#include +#include +#include +#include + +using pcms::GO; +using pcms::LO; +using pcms::Real; +using pcms::transfer::detail::BilinearForm; +using pcms::transfer::detail::FormOptions; +using Space = std::shared_ptr; + +namespace +{ + +using Host2D = Kokkos::View; +using Device2D = Kokkos::View; + +int failures = 0; + +int Rank() +{ + int rank = -1; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + return rank; +} + +Real SumOverRanks(Real local) +{ + Real global = 0; + MPI_Allreduce(&local, &global, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + return global; +} + +// Checks a value that is the same on every rank; rank 0 reports it. +void CheckClose(Real value, Real expected, Real tolerance, + const std::string& what) +{ + if (!(std::abs(value - expected) <= tolerance)) { + ++failures; + if (Rank() == 0) { + std::fprintf(stderr, "check failed: %s: %.17g != %.17g\n", what.c_str(), + value, expected); + } + } +} + +// Every rank's DOFs depend only on the holders' global ids. +Real DofOfGid(GO gid, int c, Real phase) +{ + return std::sin(1.3 * static_cast(gid) + 0.7 * c + phase); +} + +pcms::Function FieldOfGids(const Space& space, Real phase) +{ + const auto& layout = *space->GetLayout(); + const auto gids = layout.GetGidsHost(); + Host2D x("x", layout.GetNumDofHolder(), layout.GetNumComponents()); + for (size_t h = 0; h < x.extent(0); ++h) { + for (size_t c = 0; c < x.extent(1); ++c) { + x(h, c) = phase < 0 ? 1.0 : DofOfGid(gids(h), c, phase); + } + } + auto field = space->CreateFunction(); + field.SetDOFHolderDataHost(pcms::ValueView( + field.GetData().GetValueBasis(), pcms::MakeConstRank2View(x))); + field.Synchronize(); + return field; +} + +pcms::Function Ones(const Space& space) +{ + return FieldOfGids(space, -1); +} + +// sum over the ranks of the owned entries of component c (or of all, c < 0) +Real Total(const pcms::Field& field, int c = -1) +{ + const auto values = field.GetDOFHolderDataHost().GetValues(); + Real sum = 0; + for (size_t h = 0; h < values.extent(0); ++h) { + for (size_t k = 0; k < values.extent(1); ++k) { + if (c < 0 || static_cast(k) == c) { + sum += values(h, k); + } + } + } + return SumOverRanks(sum); +} + +// sum over the ranks of the owned x_i y_i +Real GlobalDot(const pcms::Field& x, const pcms::Field& y) +{ + const auto a = x.GetDOFHolderDataHost().GetValues(); + const auto b = y.GetDOFHolderDataHost().GetValues(); + Real sum = 0; + for (size_t h = 0; h < a.extent(0); ++h) { + for (size_t k = 0; k < a.extent(1); ++k) { + sum += a(h, k) * b(h, k); + } + } + return SumOverRanks(sum); +} + +Real MaxDifference(const pcms::Field& x, const pcms::Field& y) +{ + const auto a = x.GetDOFHolderDataHost().GetValues(); + const auto b = y.GetDOFHolderDataHost().GetValues(); + Real local = 0; + for (size_t h = 0; h < a.extent(0); ++h) { + for (size_t k = 0; k < a.extent(1); ++k) { + local = std::max(local, std::abs(a(h, k) - b(h, k))); + } + } + Real global = 0; + MPI_Allreduce(&local, &global, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); + return global; +} + +// DotProd, Apply and Norm2 of the coefficients reduce over the ranks. +void CheckVectorOps(const pcms::Function& v, + const pcms::Function& w, const std::string& name) +{ + const Real vw = GlobalDot(v, w); + const Real tolerance = 1e-12 * std::max(1.0, std::abs(vw)); + CheckClose(pcms::detail::DotProd(v, w), vw, tolerance, + name + ": DotProd over the ranks"); + CheckClose(pcms::detail::Apply(w, v), vw, tolerance, + name + ": Apply over the ranks"); + const Real vv = GlobalDot(v, v); + CheckClose(pcms::detail::Norm2(v), std::sqrt(vv), 1e-12 * std::max(1.0, vv), + name + ": Norm2 over the ranks"); +} + +Space Lagrange(const std::shared_ptr& geometry, int order, + int nc) +{ + return pcms::CreateLagrangeSpace( + geometry, order, nc, + pcms::LagrangeOptions{.backend = pcms::LagrangeBackend::OmegaH}); +} + +std::string Name(bool ghosted, int dim, const std::string& what) +{ + return std::string(ghosted ? "ghosted" : "element-based") + " dim " + + std::to_string(dim) + ": " + what; +} + +// Assemble of f = 1 over the space's quadrature: the owned entries total the +// measure, per component. +void CheckAssemble(const Space& space, const std::string& name) +{ + const BilinearForm form(space); + const int nc = space->GetLayout()->GetNumComponents(); + Device2D ones("ones", form.GetQuadrature().weights.extent(0), nc); + Kokkos::deep_copy(ones, 1.0); + auto functional = space->CreateFunction(); + const pcms::ValueView samples( + functional.GetData().GetValueBasis(), pcms::MakeConstRank2View(ones)); + form.Assemble(samples, functional); + for (int c = 0; c < nc; ++c) { + CheckClose(Total(functional, c), 1.0, 1e-12, + name + ": Assemble of 1 totals the measure"); + } + // overwrites: a second call gives the same result + form.Assemble(samples, functional); + CheckClose(Total(functional), nc, 1e-12, name + ": Assemble overwrites"); +} + +// B u and B^T v of random u and v: the global adjoint identity, Pair summed +// over the ranks, B 1 and B^T 1 totalling the measure, and the overwrite. +void CheckBilinearForm(const BilinearForm& form, const Space& test, + const Space& trial, const std::string& name) +{ + const int nc = test->GetLayout()->GetNumComponents(); + const auto u = FieldOfGids(trial, 0.3); + const auto v = FieldOfGids(test, 1.9); + auto bu = test->CreateFunction(); + auto btv = trial->CreateFunction(); + form.Apply(u, bu); + form.ApplyTranspose(v, btv); + const Real vbu = GlobalDot(v, bu); + const Real ubtv = GlobalDot(u, btv); + CheckClose(ubtv, vbu, 1e-12 * std::max(1.0, std::abs(vbu)), + name + ": == over the ranks"); + CheckClose(form.Pair(v, u), vbu, 1e-12 * std::max(1.0, std::abs(vbu)), + name + ": Pair is over the ranks"); + CheckVectorOps(v, bu, name); + + form.Apply(Ones(trial), bu); + CheckClose(Total(bu), nc, 1e-12, name + ": B 1 totals the measure"); + form.Apply(Ones(trial), bu); + CheckClose(Total(bu), nc, 1e-12, name + ": Apply overwrites"); + form.ApplyTranspose(Ones(test), btv); + CheckClose(Total(btv), nc, 1e-12, name + ": B^T 1 totals the measure"); + form.ApplyTranspose(Ones(test), btv); + CheckClose(Total(btv), nc, 1e-12, name + ": ApplyTranspose overwrites"); +} + +// The square mass form: the lumped mass totals the measure, and the lumped +// and matrix-free solves recover u. +void CheckMassForm(const Space& space, const std::string& name) +{ + const BilinearForm form(space); + CheckBilinearForm(form, space, space, name); + const int nc = space->GetLayout()->GetNumComponents(); + auto lumped = space->CreateFunction(); + form.Apply(Ones(space), lumped); + CheckClose(Total(lumped), nc, 1e-12, + name + ": the lumped mass totals the measure"); + + const auto u = FieldOfGids(space, 0.3); + auto bu = space->CreateFunction(); + form.Apply(u, bu); + auto x = space->CreateFunction(); + const auto solver = pcms::transfer::detail::CreateLinearSolver( + form, pcms::MassMatrixType::Consistent, {}); + const bool matrix_free = + dynamic_cast(solver.get()) != + nullptr; + CheckClose(matrix_free ? 1 : 0, 1, 0, + name + ": the default solve of a distributed form is matrix free"); + solver->Solve(bu, x); + CheckClose(MaxDifference(x, u), 0, 1e-8, + name + ": the matrix-free solve of B x = B u recovers u"); +} + +void RunCases(Omega_h::Library& library, int dim, bool ghosted) +{ + auto world = library.world(); + const int n = (dim == 2 ? 4 : 2) * world->size(); + const auto build = [&]() { + auto mesh = + Omega_h::build_box(world, OMEGA_H_SIMPLEX, 1.0, 1.0, dim == 3 ? 1.0 : 0.0, + n, n, dim == 3 ? n : 0, false); + if (ghosted) { + mesh.set_parting(OMEGA_H_GHOSTED, 1, false); + } else { + mesh.set_parting(OMEGA_H_ELEM_BASED, 0, false); + } + return mesh; + }; + auto mesh = build(); + auto other_mesh = build(); + const auto geometry = + pcms::omega_h::CreateGeometry(mesh, pcms::detail::DeferredCartesian()); + const auto other_geometry = pcms::omega_h::CreateGeometry( + other_mesh, pcms::detail::DeferredCartesian()); + for (int nc : {1, 2}) { + for (int order : {0, 1}) { + const auto space = Lagrange(geometry, order, nc); + const auto what = + "P" + std::to_string(order) + " components " + std::to_string(nc); + CheckAssemble(space, Name(ghosted, dim, what)); + CheckMassForm(space, Name(ghosted, dim, what + " mass")); + } + // P1 test and P0 trial on one mesh + const auto p1 = Lagrange(geometry, 1, nc); + const auto p0 = Lagrange(geometry, 0, nc); + CheckBilinearForm( + BilinearForm(p1, p0), p1, p0, + Name(ghosted, dim, "P1 x P0 components " + std::to_string(nc))); + // P1 on two meshes with the same partition + const auto other_p1 = Lagrange(other_geometry, 1, nc); + CheckBilinearForm( + BilinearForm(p1, other_p1), p1, other_p1, + Name(ghosted, dim, + "P1 x P1 of another mesh components " + std::to_string(nc))); + } +} + +} // namespace + +int main(int argc, char** argv) +{ + try { + MPI_Init(&argc, &argv); + { + Omega_h::Library library(&argc, &argv); + distributed_test::require(library.world()->size() >= 2, + "test requires at least 2 MPI ranks"); + for (int dim : {2, 3}) { + for (bool ghosted : {false, true}) { + RunCases(library, dim, ghosted); + } + } + } + int total = 0; + MPI_Allreduce(&failures, &total, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); + if (Rank() == 0) { + std::printf("distributed forms test: %d failed checks\n", total); + } + MPI_Finalize(); + return total == 0 ? 0 : 1; + } catch (const std::exception& e) { + distributed_test::AbortAllRanks(e.what()); + } catch (...) { + distributed_test::AbortAllRanks("unknown exception"); + } +} diff --git a/test/test_galerkin_projection.cpp b/test/test_galerkin_projection.cpp index 51d1bdfad..1be59f002 100644 --- a/test/test_galerkin_projection.cpp +++ b/test/test_galerkin_projection.cpp @@ -4,6 +4,9 @@ #include #include #include +#include +#include +#include #include #include #include "field_test_utils.hpp" @@ -104,6 +107,9 @@ void CheckAdjoint(const std::shared_ptr& space, } CAPTURE(lhs, rhs); CHECK(std::abs(lhs - rhs) <= 1e-12 * std::max(1.0, scale)); + // the pairing of the functional with the function is the same number + CHECK(std::abs(pcms::detail::Apply(functional, field) - lhs) <= + 1e-12 * std::max(1.0, scale)); // overwrites: a second call gives the same result evaluator.EvaluateTranspose(y_view, functional); @@ -198,6 +204,58 @@ TEST_CASE("EvaluateTranspose checks its arguments", "[adjoint]") pcms::pcms_error); } +TEST_CASE("coefficient operations: LinearSum, Scale, Const, Div, DotProd, " + "Norm2 and the pairing", + "[field_ops]") +{ + using pcms::detail::Apply; + using pcms::detail::DotProd; + Omega_h::Library lib; + auto mesh = pcms::test::BuildSquareMesh(lib, 3); + const auto space = pcms::test::MakeP1Space(mesh); + std::mt19937 rng(7); + const auto a = RandomDofs(*space->GetLayout(), rng); + const auto b = RandomDofs(*space->GetLayout(), rng); + auto x = space->CreateFunction(); + auto y = space->CreateFunction(); + SetDofs(x, a); + SetDofs(y, b); + double dot = 0, xx = 0; + for (std::size_t i = 0; i < a.extent(0); ++i) { + for (std::size_t c = 0; c < a.extent(1); ++c) { + dot += a(i, c) * b(i, c); + xx += a(i, c) * a(i, c); + } + } + CHECK(DotProd(x, y) == Catch::Approx(dot).epsilon(1e-14)); + CHECK(Apply(x, y) == Catch::Approx(dot).epsilon(1e-14)); + CHECK(pcms::detail::Norm2(x) == Catch::Approx(std::sqrt(xx)).epsilon(1e-14)); + auto z = space->CreateFunction(); + pcms::detail::LinearSum(3.0, x, 1.0, y, z); // z = 3 a + b + pcms::detail::Scale(0.5, z, z); // z = (3 a + b) / 2 + auto twos = space->CreateFunction(); + pcms::detail::Const(2.0, twos); + pcms::detail::Div(z, twos, z); // z = (3 a + b) / 4 + const auto values = z.GetDOFHolderDataHost().GetValues(); + for (std::size_t i = 0; i < a.extent(0); ++i) { + for (std::size_t c = 0; c < a.extent(1); ++c) { + CHECK(values(i, c) == + Catch::Approx(0.25 * (3 * a(i, c) + b(i, c))).epsilon(1e-14)); + } + } + // fields of another layout are refused + auto other = pcms::test::MakeP1Space(mesh)->CreateFunction(); + CHECK_THROWS_AS(DotProd(x, other), pcms::pcms_error); + // so are operands of another kind of field data + const pcms::detail::SimpleFieldData other_kind( + space->GetLayout(), x.GetData().GetValueBasis()); + CHECK_THROWS_WITH(pcms::detail::DotProdLocal(x.GetData(), other_kind), + Catch::Matchers::ContainsSubstring("another kind")); + CHECK_THROWS_WITH( + pcms::detail::LinearSum(1.0, x.GetData(), 1.0, other_kind, z.GetData()), + Catch::Matchers::ContainsSubstring("another kind")); +} + TEST_CASE("FunctionSpace::GetQuadrature is exact for products of two " "functions of the space", "[quadrature]") diff --git a/test/test_omega_h_lagrange_field.cpp b/test/test_omega_h_lagrange_field.cpp index 1a7f7c934..9eab6a007 100644 --- a/test/test_omega_h_lagrange_field.cpp +++ b/test/test_omega_h_lagrange_field.cpp @@ -45,7 +45,7 @@ TEST_CASE("OmegaHLagrangeLayout order-1 properties") REQUIRE(layout.GetNumComponents() == 2); REQUIRE(layout.GetNumDofHolder() == mesh.nents(0)); REQUIRE(layout.GetNumGlobalDofHolder() == mesh.nglobal_ents(0)); - REQUIRE(layout.IsDistributed()); // always true for Omega_h mesh layouts + REQUIRE(layout.IsDistributed() == (mesh.comm()->size() > 1)); // DOF holder coordinates should match vertex coordinates auto coords_device = layout.GetDOFHolderCoordinates().GetValues(); From 115cf0c85df0d07ae4ef09a9fc357aa5eb35cde0 Mon Sep 17 00:00:00 2001 From: Jacob Merson Date: Sat, 28 Nov 2026 02:35:27 +0000 Subject: [PATCH 7/7] perf(omega_h): reuse the scatter buffer of EvaluateTranspose --- src/pcms/backends/omega_h/lagrange_evaluator.hpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/pcms/backends/omega_h/lagrange_evaluator.hpp b/src/pcms/backends/omega_h/lagrange_evaluator.hpp index ded982f55..edf93a723 100644 --- a/src/pcms/backends/omega_h/lagrange_evaluator.hpp +++ b/src/pcms/backends/omega_h/lagrange_evaluator.hpp @@ -182,8 +182,12 @@ class OmegaHLagrangePointEvaluator const int stride = stride_; const auto holders = holders_; const auto weights = weights_; - Omega_h::Write sums(layout_->GetNumDofHolderWithGhosts() * n_comp, - 0, "transpose_sums"); + const int size = layout_->GetNumDofHolderWithGhosts() * n_comp; + if (transpose_sums_.size() != size) { + transpose_sums_ = Omega_h::Write(size, "transpose_sums"); + } + Omega_h::fill(transpose_sums_, TagValue(0)); + const auto sums = transpose_sums_; pcms::detail::ForEach( "OmegaHLagrangePointEvaluator::EvaluateTranspose", static_cast(found.extent(0)), KOKKOS_LAMBDA(const LO k) { @@ -222,6 +226,8 @@ class OmegaHLagrangePointEvaluator Kokkos::View holders_; Kokkos::View weights_; pcms::detail::PointRows rows_; + // the scatter target of EvaluateTranspose, reused across calls + mutable Omega_h::Write> transpose_sums_; }; // ---------------------------------------------------------------------------