Nektar++
Loading...
Searching...
No Matches
ExpressionBlockOp.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: ExpressionBlockOp.hpp
4//
5// For more information, please see: http://www.nektar.info
6//
7// The MIT License
8//
9// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
10// Department of Aeronautics, Imperial College London (UK), and Scientific
11// Computing and Imaging Institute, University of Utah (USA).
12//
13// Permission is hereby granted, free of charge, to any person obtaining a
14// copy of this software and associated documentation files (the "Software"),
15// to deal in the Software without restriction, including without limitation
16// the rights to use, copy, modify, merge, publish, distribute, sublicense,
17// and/or sell copies of the Software, and to permit persons to whom the
18// Software is furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30//
31// Description:
32//
33///////////////////////////////////////////////////////////////////////////////
34
35/**
36 * @file ExpressionBlockOp.hpp
37 * @brief Per-block interface of the Expression operator, holding the
38 * evaluation settings shared by all back-ends.
39 *
40 * See ExpressionOp.hpp for the family overview; the concrete
41 * evaluators are in ExpressionBlockOpSerialAVXGeneric.hpp and
42 * ExpressionBlockOpDeviceGeneric.hpp.
43 */
44
45#pragma once
46
48
49#include <cctype>
50#include <set>
51#include <string>
52#include <vector>
53
56
58{
59
60/**
61 * @brief Block-level interface of the Expression operator: evaluates
62 * the configured expressions at every quadrature point of one element
63 * block.
64 *
65 * @details
66 * Besides setting the BlockAccessor states accepted by Apply() to
67 * physical space on both sides, this class holds the evaluation
68 * settings -- expressions, per-expression variable counts, component
69 * mask, time, scale and append flag. One instance per block is created
70 * by ElmtOp::Create via ExpressionOp::Create, and the settings are
71 * written through the whole-field ExpressionOp setters, which forward
72 * to every block.
73 *
74 * All setters are plain stores except SetExpressions(), which goes
75 * through the virtual v_SetExpressions() so a back-end can prepare for
76 * evaluation.
77 *
78 * @tparam TData Floating-point type of the field data.
79 *
80 * @see detail::ExpressionBlockOpImpl (ExpressionBlockOpSerialAVXGeneric.hpp /
81 * ExpressionBlockOpDeviceGeneric.hpp) for the v_Apply() implementations.
82 */
83template <typename TData>
85 : public ElmtBlockOp<FieldState::Phys, FieldState::Phys, TData>
86{
87public:
88 /**
89 * @brief Create one block operator through the block-operator
90 * factory.
91 *
92 * The factory key is #name + @p execStr + @p implStr; since the
93 * family registers only "Generic" implementations, any other
94 * @p implStr falls back to the Generic key of the same execution
95 * space (see ElmtBlockOp::Create).
96 *
97 * @param block_idx Index of the block within the expansion
98 * list's Collections.
99 * @param exp Representative expansion of the block.
100 * @param dataWarehouse Data warehouse shared with the other
101 * operators on the expansion list.
102 * @param execStr Execution-space part of the factory
103 * key.
104 * @param implStr Implementation part of the factory key.
105 */
106 static std::shared_ptr<ExpressionBlockOp<TData>> Create(
107 const unsigned int block_idx,
110 const std::string &execStr, const std::string &implStr)
111 {
113 template Create<ExpressionBlockOp>(block_idx, exp, dataWarehouse,
114 execStr, implStr);
115 }
116
117 /// Block-operator base name; Create() appends the execution space
118 /// and implementation to it to form the factory key.
119 static inline const std::string name = "BlockExpression";
120
121 /**
122 * @brief Split an expression's variable list into the individual
123 * variable names.
124 *
125 * Entries 0-3 are the built-in x, y, z and t; entries from 4
126 * onwards name the extra field variables (EVARS).
127 *
128 * @param expression Expression whose variable list is split.
129 *
130 * @return The comma/space-separated names, in list order.
131 */
132 static std::vector<std::string> GetEvarsNames(
133 const LibUtilities::EquationSharedPtr &expression)
134 {
135 std::vector<std::string> vnames;
136 StringUtils::Split(vnames, expression->GetVlist(),
138 return vnames;
139 }
140
141 /**
142 * @brief The variables an expression uses: every name in @p expr that
143 * is not called as a function, so also its parameters and constants.
144 *
145 * @param expr Expression to scan.
146 *
147 * @return The distinct variable names in @p expr.
148 */
149 static std::set<std::string> GetExpressionVariables(const std::string &expr)
150 {
152 }
153
154 /**
155 * @brief The functions an expression calls: every name in @p expr
156 * followed by an opening parenthesis.
157 *
158 * @param expr Expression to scan.
159 *
160 * @return The distinct function names in @p expr.
161 */
162 static std::set<std::string> GetExpressionFunctions(const std::string &expr)
163 {
165 }
166
167 /**
168 * @brief Set the expressions to evaluate (one per component) via
169 * the back-end hook v_SetExpressions().
170 */
172 const std::vector<LibUtilities::EquationSharedPtr> &exprs)
173 {
174 v_SetExpressions(exprs);
175 }
176
177 /**
178 * @brief Whether this back-end can evaluate @p exprs under the current
179 * component mask.
180 */
182 const std::vector<LibUtilities::EquationSharedPtr> &exprs) const
183 {
184 return v_IsAvailable(exprs);
185 }
186
187 /// @brief Set the value substituted for the built-in variable `t`.
188 void SetTime(const TData &time)
189 {
190 this->m_time = time;
191 }
192
193 /// @brief Set the factor every evaluated value is multiplied by.
194 void SetScale(const TData &scale)
195 {
196 this->m_scale = scale;
197 }
198
199 /**
200 * @brief Choose between accumulating onto the output and
201 * overwriting it.
202 */
203 void SetAppend(const bool &append)
204 {
205 this->m_append = append;
206 }
207
208 /**
209 * @brief Set the variable count of each expression, as computed by
210 * ExpressionOp::GetNumberEvars().
211 */
212 void SetNumEvars(const std::vector<unsigned int> &numEvars)
213 {
214 this->m_numEvars = numEvars;
215 }
216
217 /**
218 * @brief Set the per-component enable flags (see the mask notes in
219 * ExpressionOp::SetComponentMask, including the requirement that
220 * the mask be final before SetExpressions()).
221 */
222 void SetComponentMask(const std::vector<bool> &cmask)
223 {
224 this->m_cmask = cmask;
225 }
226
227protected:
228 /// Parsed expressions, one per field component.
229 std::vector<LibUtilities::EquationSharedPtr> m_expressions;
230 /// Variable-list length of each expression: the built-in x, y, z
231 /// and t plus any field-valued EVARS. The implementations read
232 /// entry 0 only, assuming all expressions share one variable list.
233 std::vector<unsigned int> m_numEvars;
234 /// Per-component enable flags.
235 std::vector<bool> m_cmask;
236
237 /// Value of the built-in time variable `t`.
238 TData m_time = 0.0;
239 /// Factor applied to every evaluated expression value.
240 TData m_scale = 1.0;
241 /// Accumulate onto the output (true) or overwrite it (false).
242 bool m_append = false;
243
244 /**
245 * @brief Construct the interface part of a concrete block
246 * operator; called by the factory-registered creator functions.
247 *
248 * @param block_idx Index of the block within the expansion
249 * list's Collections.
250 * @param exp Representative expansion of the block.
251 * @param dataWarehouse Data warehouse shared with the other
252 * operators on the expansion list.
253 */
254 ExpressionBlockOp(const unsigned int block_idx,
257 : ElmtBlockOp<FieldState::Phys, FieldState::Phys, TData>(block_idx, exp,
258 dataWarehouse)
259 {
260 }
261
262 ~ExpressionBlockOp() override = default;
263
264 /**
265 * @brief Implementation hook for SetExpressions().
266 *
267 * Overrides must arrange that #m_expressions, and whatever the
268 * back-end derives from them, are in place before the work queued
269 * by the next Apply() runs; that work need not have finished by
270 * the time this call returns.
271 *
272 * @param exprs Parsed expressions, one per component.
273 */
274 virtual void v_SetExpressions(
275 const std::vector<LibUtilities::EquationSharedPtr> &exprs) = 0;
276
277 /**
278 * @brief Implementation hook for IsAvailable().
279 *
280 * @param exprs Parsed expressions, one per component.
281 */
282 virtual bool v_IsAvailable(
283 const std::vector<LibUtilities::EquationSharedPtr> &exprs) const = 0;
284
285private:
286 /// Kind of name GetExpressionNames() collects.
287 enum class NameKind
288 {
289 Variable, ///< A name not called as a function.
290 Function ///< A name followed by an opening parenthesis.
291 };
292
293 /**
294 * @brief The names of kind @p kind in @p expr.
295 *
296 * Numbers are skipped, so that an exponent is not read as a name.
297 */
298 static std::set<std::string> GetExpressionNames(const std::string &expr,
299 const NameKind kind)
300 {
301 const auto isName = [](const char c) {
302 return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
303 };
304
305 std::set<std::string> names;
306 for (size_t i = 0; i < expr.size();)
307 {
308 const char c = expr[i];
309 if (std::isdigit(static_cast<unsigned char>(c)) || c == '.')
310 {
311 for (++i; i < expr.size(); ++i)
312 {
313 const bool sign =
314 (expr[i] == '+' || expr[i] == '-') &&
315 (expr[i - 1] == 'e' || expr[i - 1] == 'E');
316 if (!isName(expr[i]) && expr[i] != '.' && !sign)
317 {
318 break;
319 }
320 }
321 }
322 else if (std::isalpha(static_cast<unsigned char>(c)) || c == '_')
323 {
324 size_t j = i + 1;
325 while (j < expr.size() && isName(expr[j]))
326 {
327 ++j;
328 }
329 size_t k = j;
330 while (k < expr.size() &&
331 std::isspace(static_cast<unsigned char>(expr[k])))
332 {
333 ++k;
334 }
335 const NameKind found = k < expr.size() && expr[k] == '('
338 if (found == kind)
339 {
340 names.insert(expr.substr(i, j - i));
341 }
342 i = j;
343 }
344 else
345 {
346 ++i;
347 }
348 }
349 return names;
350 }
351};
352
353} // namespace Nektar::MultiRegions
Block-level base class, implementation-strategy tags and device launch helpers shared by every elemen...
#define sign(a, b)
return the sign(b)*a
Definition Polylib.cpp:47
Base class of the per-family block operators: applies one element operation to every element of one b...
Block-level interface of the Expression operator: evaluates the configured expressions at every quadr...
ExpressionBlockOp(const unsigned int block_idx, const LocalRegions::ExpansionSharedPtr &exp, LibUtilities::NekDataWarehouseSharedPtr dataWarehouse)
Construct the interface part of a concrete block operator; called by the factory-registered creator f...
static std::vector< std::string > GetEvarsNames(const LibUtilities::EquationSharedPtr &expression)
Split an expression's variable list into the individual variable names.
static std::set< std::string > GetExpressionFunctions(const std::string &expr)
The functions an expression calls: every name in expr followed by an opening parenthesis.
static std::set< std::string > GetExpressionVariables(const std::string &expr)
The variables an expression uses: every name in expr that is not called as a function,...
void SetComponentMask(const std::vector< bool > &cmask)
Set the per-component enable flags (see the mask notes in ExpressionOp::SetComponentMask,...
void SetExpressions(const std::vector< LibUtilities::EquationSharedPtr > &exprs)
Set the expressions to evaluate (one per component) via the back-end hook v_SetExpressions().
NameKind
Kind of name GetExpressionNames() collects.
@ Variable
A name not called as a function.
@ Function
A name followed by an opening parenthesis.
std::vector< LibUtilities::EquationSharedPtr > m_expressions
Parsed expressions, one per field component.
bool m_append
Accumulate onto the output (true) or overwrite it (false).
bool IsAvailable(const std::vector< LibUtilities::EquationSharedPtr > &exprs) const
Whether this back-end can evaluate exprs under the current component mask.
static const std::string name
Block-operator base name; Create() appends the execution space and implementation to it to form the f...
TData m_time
Value of the built-in time variable t.
std::vector< unsigned int > m_numEvars
Variable-list length of each expression: the built-in x, y, z and t plus any field-valued EVARS....
void SetNumEvars(const std::vector< unsigned int > &numEvars)
Set the variable count of each expression, as computed by ExpressionOp::GetNumberEvars().
void SetAppend(const bool &append)
Choose between accumulating onto the output and overwriting it.
virtual void v_SetExpressions(const std::vector< LibUtilities::EquationSharedPtr > &exprs)=0
Implementation hook for SetExpressions().
virtual bool v_IsAvailable(const std::vector< LibUtilities::EquationSharedPtr > &exprs) const =0
Implementation hook for IsAvailable().
TData m_scale
Factor applied to every evaluated expression value.
void SetTime(const TData &time)
Set the value substituted for the built-in variable t.
std::vector< bool > m_cmask
Per-component enable flags.
static std::set< std::string > GetExpressionNames(const std::string &expr, const NameKind kind)
The names of kind kind in expr.
static std::shared_ptr< ExpressionBlockOp< TData > > Create(const unsigned int block_idx, const LocalRegions::ExpansionSharedPtr &exp, LibUtilities::NekDataWarehouseSharedPtr dataWarehouse, const std::string &execStr, const std::string &implStr)
Create one block operator through the block-operator factory.
void SetScale(const TData &scale)
Set the factor every evaluated value is multiplied by.
Predicate matching any of a set of characters.
std::shared_ptr< NekDataWarehouse > NekDataWarehouseSharedPtr
std::shared_ptr< Equation > EquationSharedPtr
Definition Equation.h:135
std::shared_ptr< Expansion > ExpansionSharedPtr
Definition Expansion.h:66
Container & Split(Container &result, std::string_view input, Pred pred, TokenCompressMode mode=eTokenCompressOff)
Splits input at characters matching pred into result, which is cleared first. An empty input gives a ...
FieldState
Possible states for Field data.