FirstOrderEllipticSolutionsTestHelpers.hpp
1 // Distributed under the MIT License.
2 // See LICENSE.txt for details.
3 
4 #pragma once
5 
6 #include <cstddef>
7 #include <limits>
8 
9 #include "DataStructures/DataBox/PrefixHelpers.hpp"
10 #include "DataStructures/DataBox/Tag.hpp"
11 #include "DataStructures/DataBox/TagName.hpp"
12 #include "DataStructures/DataVector.hpp"
18 #include "NumericalAlgorithms/LinearOperators/Divergence.tpp"
22 #include "Utilities/Numeric.hpp"
23 #include "Utilities/Tuple.hpp"
24 
25 namespace FirstOrderEllipticSolutionsTestHelpers {
26 namespace detail {
27 namespace Tags {
28 
29 template <typename Tag>
30 struct OperatorAppliedTo : db::SimpleTag, db::PrefixTag {
31  using type = typename Tag::type;
32  using tag = Tag;
33 };
34 
35 } // namespace Tags
36 
37 template <typename System, typename SolutionType, typename... Maps,
38  typename... FluxesArgs, typename... SourcesArgs,
39  typename... PrimalFields, typename... AuxiliaryFields,
40  typename... PrimalFluxes, typename... AuxiliaryFluxes>
41 void verify_solution_impl(
42  const SolutionType& solution, const Mesh<System::volume_dim>& mesh,
44  coord_map,
45  const double tolerance, const std::tuple<FluxesArgs...>& fluxes_args,
46  const std::tuple<SourcesArgs...>& sources_args,
47  tmpl::list<PrimalFields...> /*meta*/,
48  tmpl::list<AuxiliaryFields...> /*meta*/,
49  tmpl::list<PrimalFluxes...> /*meta*/,
50  tmpl::list<AuxiliaryFluxes...> /*meta*/) {
51  using all_fields = tmpl::list<PrimalFields..., AuxiliaryFields...>;
52  using all_fluxes = tmpl::list<PrimalFluxes..., AuxiliaryFluxes...>;
53  using FluxesComputer = typename System::fluxes_computer;
54  using SourcesComputer = typename System::sources_computer;
55  CAPTURE(mesh);
56 
57  const size_t num_points = mesh.number_of_grid_points();
58  const auto logical_coords = logical_coordinates(mesh);
59  const auto inertial_coords = coord_map(logical_coords);
60  const auto solution_fields = variables_from_tagged_tuple(
61  solution.variables(inertial_coords, all_fields{}));
62 
63  // Apply operator to solution fields: -div(F) + S = f
64  Variables<all_fluxes> fluxes{num_points};
65  std::apply(
66  [&fluxes, &solution_fields](const auto&... expanded_fluxes_args) {
67  FluxesComputer::apply(make_not_null(&get<PrimalFluxes>(fluxes))...,
68  expanded_fluxes_args...,
69  get<AuxiliaryFields>(solution_fields)...);
70  FluxesComputer::apply(make_not_null(&get<AuxiliaryFluxes>(fluxes))...,
71  expanded_fluxes_args...,
72  get<PrimalFields>(solution_fields)...);
73  },
74  fluxes_args);
75  Variables<db::wrap_tags_in<Tags::OperatorAppliedTo, all_fields>>
76  operator_applied_to_fields{num_points};
77  divergence(make_not_null(&operator_applied_to_fields), fluxes, mesh,
78  coord_map.inv_jacobian(logical_coords));
79  operator_applied_to_fields *= -1.;
80  std::apply(
81  [&operator_applied_to_fields, &solution_fields,
82  &fluxes](const auto&... expanded_sources_args) {
83  SourcesComputer::apply(
84  make_not_null(&get<Tags::OperatorAppliedTo<AuxiliaryFields>>(
85  operator_applied_to_fields))...,
86  expanded_sources_args..., get<PrimalFields>(solution_fields)...);
87  SourcesComputer::apply(
88  make_not_null(&get<Tags::OperatorAppliedTo<PrimalFields>>(
89  operator_applied_to_fields))...,
90  expanded_sources_args..., get<PrimalFields>(solution_fields)...,
91  get<PrimalFluxes>(fluxes)...);
92  },
93  sources_args);
94 
95  // Set RHS for auxiliary equations to minus auxiliary fields, and for primal
96  // equations to the solution's fixed sources f(x)
97  Variables<db::wrap_tags_in<::Tags::FixedSource, all_fields>> fixed_sources{
98  num_points, 0.};
100  get<AuxiliaryFields>(solution_fields))...);
101  fixed_sources *= -1.;
102  fixed_sources.assign_subset(solution.variables(
103  inertial_coords, tmpl::list<::Tags::FixedSource<PrimalFields>...>{}));
104 
105  // Check error norms against the given tolerance
106  tmpl::for_each<all_fields>([&operator_applied_to_fields, &fixed_sources,
107  &tolerance](auto field_tag_v) {
108  using field_tag = tmpl::type_from<decltype(field_tag_v)>;
109  const auto& operator_applied_to_field =
110  get<Tags::OperatorAppliedTo<field_tag>>(operator_applied_to_fields);
111  const auto& fixed_source =
112  get<::Tags::FixedSource<field_tag>>(fixed_sources);
113  double l2_error_square = 0.;
114  double linf_error = 0.;
115  for (size_t i = 0; i < operator_applied_to_field.size(); ++i) {
116  const auto error = abs(operator_applied_to_field[i] - fixed_source[i]);
117  l2_error_square += alg::accumulate(square(error), 0.) / error.size();
118  const double component_linf_error = *alg::max_element(error);
119  if (component_linf_error > linf_error) {
120  linf_error = component_linf_error;
121  }
122  }
123  const double l2_error =
124  sqrt(l2_error_square / operator_applied_to_field.size());
125  CAPTURE(db::tag_name<field_tag>());
126  CAPTURE(l2_error);
127  CAPTURE(linf_error);
128  CHECK(l2_error < tolerance);
129  CHECK(linf_error < tolerance);
130  });
131 }
132 
133 } // namespace detail
134 
135 /// \ingroup TestingFrameworkGroup
136 /// Test that the `solution` numerically solves the `System` on the given grid
137 /// for the given tolerance
138 template <typename System, typename SolutionType, typename... Maps,
139  typename... FluxesArgs, typename... SourcesArgs>
141  const SolutionType& solution, const Mesh<System::volume_dim>& mesh,
143  coord_map,
144  const double tolerance,
145  const std::tuple<FluxesArgs...>& fluxes_args = std::tuple<>{},
146  const std::tuple<SourcesArgs...>& sources_args = std::tuple<>{}) {
147  detail::verify_solution_impl<System>(
148  solution, mesh, coord_map, tolerance, fluxes_args, sources_args,
149  typename System::primal_fields{}, typename System::auxiliary_fields{},
150  typename System::primal_fluxes{}, typename System::auxiliary_fluxes{});
151 }
152 
153 /*!
154  * \ingroup TestingFrameworkGroup
155  * Test that the `solution` numerically solves the `System` on the given grid
156  * and that the discretization error decreases as expected for a smooth
157  * function.
158  *
159  * \details We expect exponential convergence for a smooth solution, so the
160  * tolerance is computed as
161  *
162  * \f{equation}
163  * C_1 \exp{\left(-C_2 * N_\mathrm{points}\right)}
164  * \f}
165  *
166  * where \f$C_1\f$ is the `tolerance_offset`, \f$C_2\f$ is the
167  * `tolerance_scaling` and \f$N_\mathrm{points}\f$ is the number of grid points
168  * per dimension.
169  */
170 template <typename System, typename SolutionType,
171  size_t Dim = System::volume_dim, typename... Maps,
172  typename PackageFluxesArgs>
174  const SolutionType& solution,
176  coord_map,
177  const double tolerance_offset, const double tolerance_scaling,
178  PackageFluxesArgs&& package_fluxes_args) {
179  INFO("Verify smooth solution");
180  for (size_t num_points = Spectral::minimum_number_of_points<
181  Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto>;
182  num_points <=
183  Spectral::maximum_number_of_points<Spectral::Basis::Legendre>;
184  num_points++) {
185  CAPTURE(num_points);
186  const double tolerance =
187  tolerance_offset * exp(-tolerance_scaling * num_points);
188  CAPTURE(tolerance);
189  const Mesh<Dim> mesh{num_points, Spectral::Basis::Legendre,
190  Spectral::Quadrature::GaussLobatto};
191  FirstOrderEllipticSolutionsTestHelpers::verify_solution<System>(
192  solution, mesh, coord_map, tolerance, package_fluxes_args(mesh));
193  }
194 }
195 
196 /*!
197  * \ingroup TestingFrameworkGroup
198  * Test that the `solution` numerically solves the `System` on the given grid
199  * and that the discretization error decreases as a power law.
200  *
201  * \details The tolerance is computed as
202  *
203  * \f{equation}
204  * C \left(N_\mathrm{points}\right)^{-p}
205  * \f}
206  *
207  * where \f$C\f$ is the `tolerance_offset`, \f$p\f$ is the `tolerance_pow` and
208  * \f$N_\mathrm{points}\f$ is the number of grid points per dimension.
209  */
210 template <typename System, typename SolutionType,
211  size_t Dim = System::volume_dim, typename... Maps>
213  const SolutionType& solution,
215  coord_map,
216  const double tolerance_offset, const double tolerance_pow) {
217  INFO("Verify solution with power-law convergence");
218  for (size_t num_points = Spectral::minimum_number_of_points<
219  Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto>;
220  num_points <=
221  Spectral::maximum_number_of_points<Spectral::Basis::Legendre>;
222  num_points++) {
223  CAPTURE(num_points);
224  const double tolerance = tolerance_offset * pow(num_points, -tolerance_pow);
225  CAPTURE(tolerance);
226  FirstOrderEllipticSolutionsTestHelpers::verify_solution<System>(
227  solution,
228  Mesh<Dim>{num_points, Spectral::Basis::Legendre,
229  Spectral::Quadrature::GaussLobatto},
230  coord_map, tolerance);
231  }
232 }
233 
234 } // namespace FirstOrderEllipticSolutionsTestHelpers
expand_pack
constexpr void expand_pack(Ts &&...) noexcept
Allows zero-cost unordered expansion of a parameter.
Definition: TMPL.hpp:547
FirstOrderEllipticSolutionsTestHelpers::verify_smooth_solution
void verify_smooth_solution(const SolutionType &solution, const domain::CoordinateMap< Frame::Logical, Frame::Inertial, Maps... > &coord_map, const double tolerance_offset, const double tolerance_scaling, PackageFluxesArgs &&package_fluxes_args)
Definition: FirstOrderEllipticSolutionsTestHelpers.hpp:173
variables_from_tagged_tuple
Variables< tmpl::list< Tags... > > variables_from_tagged_tuple(const tuples::TaggedTuple< Tags... > &tuple) noexcept
Definition: Variables.hpp:819
pow
constexpr decltype(auto) pow(const T &t) noexcept
Compute t^N where N is an integer (positive or negative)
Definition: ConstantExpressions.hpp:160
get
constexpr Tag::type & get(Variables< TagList > &v) noexcept
Return Tag::type pointing into the contiguous array.
Definition: Variables.hpp:660
sqrt
auto sqrt(const TensorExpression< T, typename T::type, tmpl::list<>, tmpl::list<>, tmpl::list<>> &t)
Returns the tensor expression representing the square root of a tensor expression that evaluates to a...
Definition: SquareRoot.hpp:88
db::PrefixTag
Mark a struct as a prefix tag by inheriting from this.
Definition: Tag.hpp:103
square
constexpr decltype(auto) square(const T &x)
Compute the square of x
Definition: ConstantExpressions.hpp:55
MakeWithRandomValues.hpp
std::tuple
db::SimpleTag
Mark a struct as a simple tag by inheriting from this.
Definition: Tag.hpp:36
CoordinateMap.hpp
divergence
Scalar< DataVector > divergence(const tnsr::I< DataVector, Dim, DerivativeFrame > &input, const Mesh< Dim > &mesh, const InverseJacobian< DataVector, Dim, Frame::Logical, DerivativeFrame > &inverse_jacobian) noexcept
Compute the divergence of the vector input
Definition: Divergence.cpp:26
TestHelpers.hpp
domain::CoordinateMap::inv_jacobian
constexpr InverseJacobian< double, dim, SourceFrame, TargetFrame > inv_jacobian(tnsr::I< double, dim, SourceFrame > source_point, const double time=std::numeric_limits< double >::signaling_NaN(), const std::unordered_map< std::string, std::unique_ptr< domain::FunctionsOfTime::FunctionOfTime >> &functions_of_time=std::unordered_map< std::string, std::unique_ptr< domain::FunctionsOfTime::FunctionOfTime >>{}) const noexcept override
Compute the inverse Jacobian of the Maps... at the point(s) source_point
Definition: CoordinateMap.hpp:333
Tags::FixedSource
Prefix indicating a source term that is independent of dynamic variables.
Definition: Prefixes.hpp:75
FirstOrderEllipticSolutionsTestHelpers::verify_solution_with_power_law_convergence
void verify_solution_with_power_law_convergence(const SolutionType &solution, const domain::CoordinateMap< Frame::Logical, Frame::Inertial, Maps... > &coord_map, const double tolerance_offset, const double tolerance_pow)
Definition: FirstOrderEllipticSolutionsTestHelpers.hpp:212
Spectral::minimum_number_of_points
constexpr size_t minimum_number_of_points
Minimum number of possible collocation points for a quadrature type.
Definition: Spectral.hpp:128
cstddef
FirstOrderEllipticSolutionsTestHelpers::verify_solution
void verify_solution(const SolutionType &solution, const Mesh< System::volume_dim > &mesh, const domain::CoordinateMap< Frame::Logical, Frame::Inertial, Maps... > coord_map, const double tolerance, const std::tuple< FluxesArgs... > &fluxes_args=std::tuple<>{}, const std::tuple< SourcesArgs... > &sources_args=std::tuple<>{})
Definition: FirstOrderEllipticSolutionsTestHelpers.hpp:140
MakeWithValue.hpp
LogicalCoordinates.hpp
Mesh::number_of_grid_points
size_t number_of_grid_points() const noexcept
The total number of grid points in all dimensions.
Definition: Mesh.hpp:156
ConstantExpressions.hpp
Tuple.hpp
alg::max_element
decltype(auto) max_element(const Container &c)
Convenience wrapper around std::max_element.
Definition: Algorithm.hpp:327
Mesh
Holds the number of grid points, basis, and quadrature in each direction of the computational grid.
Definition: Mesh.hpp:48
logical_coordinates
void logical_coordinates(gsl::not_null< tnsr::I< DataVector, VolumeDim, Frame::Logical > * > logical_coords, const Mesh< VolumeDim > &mesh) noexcept
Compute the logical coordinates in an Element.
limits
Tensor.hpp
make_not_null
gsl::not_null< T * > make_not_null(T *ptr) noexcept
Construct a not_null from a pointer. Often this will be done as an implicit conversion,...
Definition: Gsl.hpp:880
Mesh.hpp
alg::accumulate
decltype(auto) accumulate(const Container &c, T init)
Convenience wrapper around std::accumulate, returns std::accumulate(begin(c), end(c),...
Definition: Numeric.hpp:54
domain::CoordinateMap
A coordinate map or composition of coordinate maps.
Definition: CoordinateMap.hpp:236