Nektar++
Loading...
Searching...
No Matches
ExpressionOp.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: ExpressionOp.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 ExpressionOp.hpp
37 * @brief Public interface of the Expression operator, which evaluates
38 * analytical expressions at the quadrature points of a physical-space
39 * field.
40 *
41 * @details
42 * The operator writes to every output component `nc` the value
43 * `scale * f_nc(x, y, z, t, ...)`, where `f_nc` is a parsed
44 * session-file expression (LibUtilities::Equation), `(x, y, z)` are
45 * the quadrature-point coordinates, `t` is the time set through
46 * SetTime(), and any expression variables beyond those built-in four
47 * ("EVARS") take their values from the components of the input field.
48 * Optionally the result is accumulated onto the output instead of
49 * overwriting it (SetAppend()). SolverCore uses the operator to
50 * evaluate a session's initial-condition and body-forcing functions,
51 * and the boundary-condition operators in MultiRegions/BndCondOps use it
52 * to evaluate Dirichlet and Neumann data on boundary expansions.
53 *
54 * The operation is purely pointwise -- there is no basis, matrix or
55 * tensor-product structure to exploit -- so this family provides a
56 * single "Generic" block implementation per execution space instead of
57 * the StdMat/SumFac/SumFacTOP split of the transform-type families
58 * (ExpressionBlockOpSerialAVXGeneric.hpp, ExpressionBlockOpDeviceGeneric.hpp).
59 * The whole-field interface classes are registered through the CMake-generated
60 * factory declarations shared by all element operators; the family has no
61 * factory template of its own.
62 *
63 * @see ExpressionBlockOp.hpp for the per-block interface holding the
64 * evaluation settings.
65 */
66
67#pragma once
68
70
72
74
76{
77
78/**
79 * @brief Whole-field interface of the Expression operator: evaluates
80 * one analytical expression per field component at every quadrature
81 * point.
82 *
83 * @details
84 * As with the other element-operator interfaces, deriving from
85 * ElmtOp<FieldState::Phys, FieldState::Phys, TData> sets the Apply()
86 * parameter types at compile time: both fields must be in physical
87 * space. Unusually for an element operator, the input field is not
88 * transformed -- it supplies the values of any extra expression
89 * variables (EVARS) beyond the built-in x, y, z and t, and merely
90 * sets the storage layout when there are none. The operator holds one
91 * ExpressionBlockOp per element block (m_blockOp) and its v_Apply()
92 * delegates each block of the input/output fields to the matching
93 * block operator.
94 *
95 * The evaluation settings live in the block operators; every setter
96 * here simply forwards its value to all of them. The intended workflow
97 * is Create(), then optionally SetComponentMask(), then
98 * SetExpressions() -- mandatory, Apply() asserts otherwise -- then
99 * optionally SetTime(), SetScale() and SetAppend(), then Apply().
100 * Expressions may be swapped at any time between applications.
101 *
102 * SetTime(), SetScale() and SetAppend() are order-free and may be
103 * changed between applications. SetComponentMask() is not: the mask
104 * must be final before SetExpressions() is called, and changing it
105 * afterwards requires calling SetExpressions() again (the in-tree
106 * callers in MultiRegions/BndCondOps set the mask first).
107 *
108 * @tparam TData Floating-point type of the field data.
109 *
110 * @see ExpressionBlockOp for the per-block settings and the
111 * v_SetExpressions() hook the back-ends implement.
112 */
113template <typename TData>
114class ExpressionOp : public ElmtOp<FieldState::Phys, FieldState::Phys, TData>
115{
116 friend class ElmtOp<FieldState::Phys, FieldState::Phys, TData>;
117
118public:
119 /**
120 * @brief Create an Expression operator through the two-stage
121 * element-operator factory and initialise its default settings.
122 *
123 * After the interface object and its per-block operators are built
124 * by ElmtOp::Create, every block operator is given the defaults:
125 * all components enabled in the mask, time 0 and scale 1 (the
126 * append flag defaults to false in ExpressionBlockOp). No
127 * expressions are set -- SetExpressions() must be called before
128 * the first Apply().
129 *
130 * @param expansionList Expansion list the operator acts on;
131 * its Collections define the blocks.
132 * @param components Names of the field components; their
133 * count sizes the default component mask.
134 * @param execStr Execution space ("Serial", "AVX" or
135 * "Device"); if empty, taken from the
136 * session's "opExecSpace" command-line
137 * argument or, failing that, the build's
138 * default (see ElmtOp::Create).
139 * @param implStr Block implementation part of the
140 * factory key. This family registers only
141 * "Generic", so any other request falls
142 * back to it (see ElmtBlockOp::Create).
143 *
144 * @return The newly created operator, ready for SetExpressions().
145 */
146 static std::shared_ptr<ExpressionOp<TData>> Create(
147 const MultiRegions::ExpListSharedPtr &expansionList,
148 const std::vector<std::string> &components,
149 const std::string &execStr = "", const std::string &implStr = "")
150 {
151 auto op =
153 ExpressionOp, ExpressionBlockOp>(expansionList, components,
154 execStr, implStr);
155
156 // Default component mask, true for all components, time 0 and scale
157 // 1.
158 op->m_blockHostOp.resize(op->m_blockOp.size(), nullptr);
159 op->m_useHostOp.resize(op->m_blockOp.size(), false);
160 op->SetComponentMask(std::vector<bool>(components.size(), true));
161 op->SetTime(0.0);
162 op->SetScale(1.0);
163 return op;
164 }
165
166 /// Operator base name; Create() appends the execution space to it
167 /// to form the factory key.
168 static inline const std::string name = "Expression";
169
170 /**
171 * @brief Set the expressions to evaluate, one per field component
172 * in component order.
173 *
174 * The variable count of each expression is extracted with
175 * GetNumberEvars() and stored on the block operators with
176 * SetNumEvars(); the expressions go through their
177 * v_SetExpressions() hook. Also marks the operator ready for Apply().
178 *
179 * @param exprs Parsed expressions; their number must equal the
180 * number of components of the fields later passed
181 * to Apply().
182 */
184 const std::vector<LibUtilities::EquationSharedPtr> &exprs)
185 {
186 // Check number of EVARS for new expressions
187 std::vector<unsigned int> numEvars;
188 for (unsigned int ne = 0; ne < exprs.size(); ++ne)
189 {
190 numEvars.push_back(this->GetNumberEvars(exprs[ne]));
191 }
192
193 // A block whose back-end cannot evaluate the expressions, a device
194 // without some function of the host interpreter, evaluates them on
195 // the host instead. Its host block operator is created the first
196 // time, and kept for when the expressions are set again.
197 m_warnOnceHostOp = false;
198 for (unsigned int blk = 0; blk < m_blockOp.size(); ++blk)
199 {
200 m_useHostOp[blk] = !m_blockOp[blk]->IsAvailable(exprs);
201 if (m_useHostOp[blk])
202 {
203 if (!m_blockHostOp[blk])
204 {
206 blk,
208 .GetExpVector()[0],
209 this->m_expansionList->GetDataWarehouseSharedPtr(),
210 "Serial", "Generic");
211 m_blockHostOp[blk]->SetComponentMask(m_cmask);
212 m_blockHostOp[blk]->SetTime(m_time);
213 m_blockHostOp[blk]->SetScale(m_scale);
214 m_blockHostOp[blk]->SetAppend(m_append);
215 }
216 m_blockHostOp[blk]->SetExpressions(exprs);
217 m_blockHostOp[blk]->SetNumEvars(numEvars);
218 }
219 else
220 {
221 this->m_blockOp[blk]->SetExpressions(exprs);
222 this->m_blockOp[blk]->SetNumEvars(numEvars);
223 }
224 }
225
227 }
228
229 /**
230 * @brief Set the value substituted for the built-in time variable
231 * `t` in every expression (default 0).
232 */
233 void SetTime(const TData &time)
234 {
235 m_time = time;
236
237 // Loop over the blocks.
238 for (unsigned int blk = 0; blk < m_blockOp.size(); ++blk)
239 {
240 this->m_blockOp[blk]->SetTime(time);
241 if (m_blockHostOp[blk])
242 {
243 m_blockHostOp[blk]->SetTime(time);
244 }
245 }
246 }
247
248 /**
249 * @brief Set the factor every evaluated expression value is
250 * multiplied by before it is written or appended (default 1).
251 */
252 void SetScale(const TData &scale)
253 {
254 m_scale = scale;
255
256 // Loop over the blocks.
257 for (unsigned int blk = 0; blk < m_blockOp.size(); ++blk)
258 {
259 this->m_blockOp[blk]->SetScale(scale);
260 if (m_blockHostOp[blk])
261 {
262 m_blockHostOp[blk]->SetScale(scale);
263 }
264 }
265 }
266
267 /**
268 * @brief Choose between accumulating onto the output
269 * (`out += scale * f`) and overwriting it (`out = scale * f`, the
270 * default).
271 */
272 void SetAppend(const bool &append)
273 {
274 m_append = append;
275
276 // Loop over the blocks.
277 for (unsigned int blk = 0; blk < m_blockOp.size(); ++blk)
278 {
279 this->m_blockOp[blk]->SetAppend(append);
280 if (m_blockHostOp[blk])
281 {
282 m_blockHostOp[blk]->SetAppend(append);
283 }
284 }
285 }
286
287 /**
288 * @brief Select which output components the expressions are
289 * evaluated for (default: all enabled).
290 *
291 * @param cmask One flag per component, in component order;
292 * Apply() asserts its size matches the number of
293 * expressions.
294 *
295 * @note Call this before SetExpressions() (see the class notes on
296 * the setter ordering).
297 *
298 * @note Masked-out output components are not guaranteed to be left
299 * untouched.
300 */
301 void SetComponentMask(const std::vector<bool> &cmask)
302 {
303 m_cmask = cmask;
304
305 // Loop over the blocks.
306 for (unsigned int blk = 0; blk < m_blockOp.size(); ++blk)
307 {
308 this->m_blockOp[blk]->SetComponentMask(cmask);
309 if (m_blockHostOp[blk])
310 {
311 m_blockHostOp[blk]->SetComponentMask(cmask);
312 }
313 }
314 }
315
316 /**
317 * @brief Count the variables of an expression, i.e. the length of
318 * its variable list.
319 *
320 * The list contains the built-in `x y z t` (the
321 * LibUtilities::Equation default) plus any extra field variables
322 * (EVARS) declared in the session; the count is therefore at
323 * least four; the back-ends assume those four are present, and
324 * use the count to decide how many input-field components to
325 * gather per point.
326 *
327 * @param expression Expression whose variable list is counted.
328 *
329 * @return Number of comma/space-separated names in the list.
330 */
331 static unsigned int GetNumberEvars(
332 const LibUtilities::EquationSharedPtr &expression)
333 {
334 // Extract the number of expression variables (EVARS).
335 // Note that we use four by default: x, y, z, t
336 std::vector<std::string> vars;
337 auto variableList = expression->GetVlist();
338 StringUtils::Split(vars, variableList, StringUtils::IsAnyOf(", "));
339 return vars.size();
340 }
341
342protected:
343 /// Whether SetExpressions() has been called; Apply() asserts this.
345 /// One block operator per element block, filled by ElmtOp::Create.
346 std::vector<std::shared_ptr<ExpressionBlockOp<TData>>> m_blockOp;
347 /// Host block operator of each block whose own could not evaluate some
348 /// expressions set, otherwise null. Created by SetExpressions().
349 std::vector<std::shared_ptr<ExpressionBlockOp<TData>>> m_blockHostOp;
350 /// Whether each block evaluates the current expressions with its host
351 /// block operator.
352 std::vector<bool> m_useHostOp;
353 /// Set once the use of a host block operator has been warned about, for
354 /// the current expressions.
355 bool m_warnOnceHostOp = false;
356
357 /// Settings forwarded to the block operators, kept for those of
358 /// #m_blockHostOp, created after them.
359 std::vector<bool> m_cmask;
360 TData m_time = 0.0;
361 TData m_scale = 1.0;
362 bool m_append = false;
363
364 /**
365 * @brief Construct the interface part of a concrete implementation;
366 * called by the factory-registered creator functions.
367 *
368 * @param expansionList Expansion list the operator acts on.
369 * @param components Component names the operator is set up
370 * for.
371 */
373 const std::vector<std::string> &components)
374 : ElmtOp<FieldState::Phys, FieldState::Phys, TData>(expansionList,
375 components)
376 {
377 }
378
379 ~ExpressionOp() override = default;
380
381 /**
382 * @brief Evaluate the expressions block by block: checks that the
383 * fields conform and that expressions have been set, then hands
384 * each input/output block pair to its block operator.
385 *
386 * @param in Physical-space field supplying the EVAR
387 * values; not modified unless it is the same
388 * object as @p out.
389 * @param out Physical-space field receiving the evaluated
390 * expressions; in append mode its existing values
391 * are accumulated onto.
392 */
395 {
396 ASSERTL1(in.GetNumComponents() == out.GetNumComponents(),
397 "Number of input and output components differ");
398
399 ASSERTL1(in.GetNumHomoModes() == out.GetNumHomoModes(),
400 "Number of input and output homogeneous modes differ");
401
402 ASSERTL1(this->m_isExpressionsDefined,
403 "No expressions defined for this Operator. Define with "
404 "SetExpressions().")
405
406 // Loop over the blocks.
407 for (unsigned int blk = 0; blk < this->m_blockOp.size(); ++blk)
408 {
409 // Block dependent.
410 auto &inblock = in.GetBlocks()[blk];
411 auto &outblock = out.GetBlocks()[blk];
412
413 if (m_useHostOp[blk])
414 {
416 "Expression evaluated on the host: the execution "
417 "space cannot evaluate it.");
418 m_warnOnceHostOp = true;
419 this->m_blockHostOp[blk]->Apply(inblock, outblock);
420 }
421 else
422 {
423 this->m_blockOp[blk]->Apply(inblock, outblock);
424 }
425 }
426 }
427};
428
429} // namespace Nektar::MultiRegions
Whole-field base class and factory machinery shared by every element-operator family in the MultiRegi...
#define WARNINGL0(condition, msg)
#define ASSERTL1(condition, msg)
Assert Level 1 – Debugging which is used whether in FULLDEBUG or DEBUG compilation mode....
Per-block interface of the Expression operator, holding the evaluation settings shared by all back-en...
A Field represents expansion data to be operated on.
Common base class of the element-operator interfaces: an operator applied independently to every elem...
Definition ElmtOp.hpp:111
static std::shared_ptr< TOperator< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Build a complete element operator: the whole-field interface object plus one block operator per eleme...
Definition ElmtOp.hpp:166
Block-level interface of the Expression operator: evaluates the configured expressions at every quadr...
void SetComponentMask(const std::vector< bool > &cmask)
Set the per-component enable flags (see the mask notes in ExpressionOp::SetComponentMask,...
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.
Whole-field interface of the Expression operator: evaluates one analytical expression per field compo...
bool m_isExpressionsDefined
Whether SetExpressions() has been called; Apply() asserts this.
static const std::string name
Operator base name; Create() appends the execution space to it to form the factory key.
std::vector< std::shared_ptr< ExpressionBlockOp< TData > > > m_blockOp
One block operator per element block, filled by ElmtOp::Create.
std::vector< bool > m_useHostOp
Whether each block evaluates the current expressions with its host block operator.
static std::shared_ptr< ExpressionOp< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components, const std::string &execStr="", const std::string &implStr="")
Create an Expression operator through the two-stage element-operator factory and initialise its defau...
bool m_warnOnceHostOp
Set once the use of a host block operator has been warned about, for the current expressions.
void v_Apply(LibUtilities::Field< TData, FieldState::Phys > &in, LibUtilities::Field< TData, FieldState::Phys > &out) override
Evaluate the expressions block by block: checks that the fields conform and that expressions have bee...
static unsigned int GetNumberEvars(const LibUtilities::EquationSharedPtr &expression)
Count the variables of an expression, i.e. the length of its variable list.
void SetComponentMask(const std::vector< bool > &cmask)
Select which output components the expressions are evaluated for (default: all enabled).
std::vector< std::shared_ptr< ExpressionBlockOp< TData > > > m_blockHostOp
Host block operator of each block whose own could not evaluate some expressions set,...
void SetScale(const TData &scale)
Set the factor every evaluated expression value is multiplied by before it is written or appended (de...
void SetTime(const TData &time)
Set the value substituted for the built-in time variable t in every expression (default 0).
void SetExpressions(const std::vector< LibUtilities::EquationSharedPtr > &exprs)
Set the expressions to evaluate, one per field component in component order.
std::vector< bool > m_cmask
Settings forwarded to the block operators, kept for those of m_blockHostOp, created after them.
void SetAppend(const bool &append)
Choose between accumulating onto the output (out += scale * f) and overwriting it (out = scale * f,...
ExpressionOp(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > &components)
Construct the interface part of a concrete implementation; called by the factory-registered creator f...
MultiRegions::ExpListSharedPtr m_expansionList
Expansion list the operator acts on.
Definition Operator.hpp:349
Predicate matching any of a set of characters.
std::shared_ptr< Equation > EquationSharedPtr
Definition Equation.h:135
std::shared_ptr< ExpList > ExpListSharedPtr
Shared pointer to an ExpList object.
Collections::Collection GetCollection(MultiRegions::ExpListSharedPtr expansionList, unsigned int block_idx)
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.