Nektar++
Loading...
Searching...
No Matches
Operator.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: Operator.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 Operator.hpp
37 * @brief Whole-field operator base class and factory machinery shared by
38 * every operator family in the MultiRegions library.
39 *
40 * @details
41 * Operator fixes no input or output field type; it only provides what
42 * every family's interface class needs regardless of what kind of
43 * operator it is: the expansion list, component names and data
44 * warehouse an instance was built with, the factory lookup performed
45 * by Create(), and the execution-space default returned by
46 * GetOpExecSpace(). Families that act element by element derive their
47 * public interface from ElmtOp (ElmtOp.hpp) instead, which adds the
48 * per-block factory stage on top of this class.
49 */
50
51#pragma once
52
53#include <string>
54#include <vector>
55
63
65
70
72{
73
74// Forward-declare the Operator base class so we can define the factory
75template <typename TData> class Operator;
76
77/// @brief Factory of Operator<TData> interface objects, keyed by
78/// `TOperator::name + execStr`.
79template <typename TData>
83 const std::vector<std::string> &>;
84
85/// @brief Return the process-wide singleton OperatorFactory<TData>.
86template <typename TData> OperatorFactory<TData> &GetOperatorFactory();
87
88/**
89 * @brief Common base class of the operator family interfaces: holds the
90 * expansion list, component names and data warehouse an operator was
91 * built with, and provides the family-agnostic Create() and
92 * GetOpExecSpace().
93 *
94 * @tparam TData Floating-point type of the field data.
95 *
96 * @see ElmtOp for the element-by-element specialisation that adds the
97 * per-block factory stage.
98 */
99template <typename TData> class Operator
100{
101public:
102 virtual ~Operator() = default;
103
104 /**
105 * @brief Construct the interface part of a concrete operator;
106 * called by the factory-registered creator functions.
107 *
108 * @param expansionList Expansion list the operator acts on.
109 * @param components Names of the field components the
110 * operator is set up for.
111 */
113 const std::vector<std::string> components)
114 : m_expansionList(expansionList), m_components(components),
115 m_dataWarehouse(expansionList->GetDataWarehouseSharedPtr())
116 {
117 }
118
119 /**
120 * @brief Create a concrete operator instance through the operator
121 * factory.
122 *
123 * The factory key is `TOperator::name + execStr`, where an empty
124 * @p execStr is resolved by GetOpExecSpace(). The product is
125 * handed back through a static_pointer_cast to @p TOperator, so
126 * the creator registered under the key must construct that class
127 * or one derived from it.
128 *
129 * @tparam TOperator Family interface class supplying the static
130 * `name` string.
131 *
132 * @param expansionList Expansion list the operator acts on.
133 * @param components Names of the field components the
134 * operator is set up for.
135 * @param execStr Execution space ("Serial", "AVX" or
136 * "Device"); if empty, GetOpExecSpace()
137 * supplies it from the session's
138 * "opExecSpace" command-line argument or,
139 * failing that, the build's default, with
140 * a warning.
141 *
142 * @return The newly created operator. Creation raises a fatal
143 * error (throws ErrorUtil::NekError) if no implementation is
144 * registered under the requested key.
145 */
146 template <template <typename> typename TOperator>
147 static std::shared_ptr<TOperator<TData>> Create(
148 const MultiRegions::ExpListSharedPtr &expansionList,
149 const std::vector<std::string> components, const std::string &execStr)
150 {
151 auto session = expansionList->GetSession();
152
153 std::string execStr0 = (execStr == "")
155 : execStr;
156
157 std::string requestedKey = TOperator<TData>::name + execStr0;
158
159 OperatorFactory<TData> &factory = GetOperatorFactory<TData>();
160
161 // No suitable operator was found.
162 if (!factory.ModuleExists(requestedKey))
163 {
164 std::stringstream msg;
165 msg << "No such operator: " << requestedKey << std::endl;
166 factory.PrintAvailableClasses(msg);
167 NEKERROR(ErrorUtil::efatal, msg.str());
168 }
169
170 return std::static_pointer_cast<TOperator<TData>>(
171 factory.CreateInstance(requestedKey, expansionList, components));
172 }
173
174 /**
175 * @brief Return the execution space name ("opExecSpace") for an
176 * operator.
177 *
178 * The space comes from the command-line argument "opExecSpace". Without
179 * it the operator takes the space the build provides, "Device" when a
180 * device is present and otherwise "AVX" or "Serial", and, if @p warn,
181 * warns that it has done so.
182 *
183 * @param session Session reader to recover the relevant command-line
184 * argument.
185 * @param warn Whether to warn when the space is defaulted.
186 *
187 * @return std::string containing the implementation name (e.g. "Serial",
188 * "Device").
189 */
190 static std::string GetOpExecSpace(
191 std::shared_ptr<LibUtilities::SessionReader> session,
192 const bool warn = true)
193 {
194 std::string OpExec = (nekGetNumDevice()) ? "Device" :
195#if defined(NEKTAR_ENABLE_SIMD)
196 "AVX";
197#else
198 "Serial";
199#endif
200
201 if (session->DefinesCmdLineArgument("opExecSpace"))
202 {
203 OpExec = session->GetCmdLineArgument<std::string>("opExecSpace");
204 }
205 else if (warn)
206 {
208 "No execution space specified for operator. Defaulting "
209 "to " +
210 OpExec);
211 }
212 return OpExec;
213 }
214
215 /**
216 * @brief Return the row of the default implementation table
217 * (DefaultOpImplTable.hpp) that a block of elements takes, or null if
218 * none does.
219 *
220 * @param exp The block's representative element, whose shape and
221 * highest order over its directions are used, or null.
222 * @param execSpace Execution space ("Serial", "AVX" or "Device").
223 */
226 const std::string &execSpace)
227 {
228 const DefaultOpImplRule *rule = nullptr;
229 if (exp)
230 {
232 execSpace, execSpace == "Device" ? GetDeviceArchitecture() : "",
233 exp->DetShapeType(), exp->EvalBasisNumModesMax() - 1);
234 }
235 return rule;
236 }
237
238 /**
239 * @brief Return the implementation a block of elements takes when
240 * neither the command line nor the session names one for its operator.
241 *
242 * This is the implementation of the block's row of the default
243 * implementation table (DefaultOpImplTable.hpp), by execution space,
244 * device architecture, element shape and expansion order, and SumFac
245 * where no row applies or without an expansion. On Device the table
246 * currently gives SumFacTOP from order three in 3D and order six in 1D
247 * and 2D. The default is taken per block, so the blocks of a mesh of
248 * mixed order or shape can take different implementations.
249 *
250 * @param exp The block's representative element, or null.
251 * @param execSpace Execution space ("Serial", "AVX" or "Device").
252 *
253 * @return std::string containing the implementation name.
254 */
255 static std::string GetDefaultOpImpl(
257 const std::string &execSpace)
258 {
259 const DefaultOpImplRule *rule = GetDefaultOpImplRule(exp, execSpace);
260 return rule ? std::string(rule->opImpl) : "SumFac";
261 }
262
263 /**
264 * @brief Return the default interleave widths, one per block of
265 * @p expansionList, that persistent Fields (e.g. solution storage,
266 * time-integration and linear-solver workspace) built on it should be
267 * constructed with.
268 *
269 * A block takes the vector width of the session's execution space when
270 * its implementation is SumFac or the execution space is AVX, so that
271 * Fields are created at that width rather than reshaped on every
272 * Apply; 1 otherwise. The implementation is the command line's
273 * "opImpl" or, without it, the block's default of GetDefaultOpImpl(),
274 * so that each block matches the operators' default for it; a session
275 * that names implementations per operator (a backend section) leaves
276 * that default out, since one width cannot follow a mix. A DG
277 * projection takes the same interleave widths as a continuous one: the
278 * trace operators read a field at whatever width each of its blocks
279 * carries.
280 *
281 * @param expansionList Expansion list the fields are built on; its
282 * session supplies the command-line arguments
283 * and the backend sections.
284 *
285 * @return std::vector<unsigned int> of interleave widths, one per
286 * block, for GetBlockAttributes().
287 */
288 static std::vector<unsigned int> GetDefaultInterleaveWidths(
289 const MultiRegions::ExpListSharedPtr &expansionList)
290 {
291 const auto session = expansionList->GetSession();
292 std::vector<unsigned int> interleave_widths;
293 if (!session)
294 {
295 // Without a session there is no execution space to follow.
296 interleave_widths.assign(GetCollections(expansionList).size(), 1u);
297 }
298 else
299 {
300 const std::string execName = GetOpExecSpace(session, false);
301
302 const LibUtilities::BackendMap &backend =
303 session->GetBackendMap(execName);
304 const bool cmdLineImpl = session->DefinesCmdLineArgument("opImpl");
305 const std::string cmdLineImplName =
306 cmdLineImpl ? session->GetCmdLineArgument<std::string>("opImpl")
307 : "";
308
309 for (auto &coll : GetCollections(expansionList))
310 {
311 const std::string implName =
312 cmdLineImpl ? cmdLineImplName
313 : backend.empty()
314 ? GetDefaultOpImpl(coll.GetExpVector()[0], execName)
315 : ""; // "" for now as different block operators might
316 // use different implementations
317 interleave_widths.push_back(
318 (implName == "SumFac" || execName == "AVX")
319 ? NektarSpaces::GetVectorWidth<TData>(execName)
320 : 1u);
321 }
322 }
323 return interleave_widths;
324 }
325
326 /**
327 * @brief Return true if the session uses a Discontinuous (DG) projection.
328 *
329 * @param session Session reader to recover the relevant SolverInfo.
330 *
331 * @return bool true if the "Projection" SolverInfo is "DG" or
332 * "Discontinuous".
333 */
335 std::shared_ptr<LibUtilities::SessionReader> session)
336 {
337 if (!session->DefinesSolverInfo("Projection"))
338 {
339 return false;
340 }
341
342 std::string projection =
343 StringUtils::ToUpperCopy(session->GetSolverInfo("Projection"));
344 return projection == "DG" || projection == "DISCONTINUOUS";
345 }
346
347protected:
348 /// Expansion list the operator acts on.
350 /// Names of the field components the operator was built for.
351 std::vector<std::string> m_components;
352 /// Data warehouse shared with the other operators on the expansion
353 /// list, used to build and cache shared tables (basis matrices,
354 /// mode indices, geometric factors) once.
356};
357
358} // namespace Nektar::MultiRegions
The table of default operator implementations, by execution space, device architecture,...
#define NEKERROR(type, msg)
Assert Level 0 – Fundamental assert which is used whether in FULLDEBUG, DEBUG or OPT compilation mode...
LibUtilities::SessionReaderSharedPtr session
bool ModuleExists(tKey idKey)
Checks if a particular module is available.
tBasePtr CreateInstance(tKey idKey, tParam... args)
Create an instance of the class referred to by idKey.
void PrintAvailableClasses(std::ostream &pOut=std::cout)
Prints the available classes to stdout.
Common base class of the operator family interfaces: holds the expansion list, component names and da...
Definition Operator.hpp:100
Operator(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > components)
Construct the interface part of a concrete operator; called by the factory-registered creator functio...
Definition Operator.hpp:112
std::vector< std::string > m_components
Names of the field components the operator was built for.
Definition Operator.hpp:351
MultiRegions::ExpListSharedPtr m_expansionList
Expansion list the operator acts on.
Definition Operator.hpp:349
static std::vector< unsigned int > GetDefaultInterleaveWidths(const MultiRegions::ExpListSharedPtr &expansionList)
Return the default interleave widths, one per block of expansionList, that persistent Fields (e....
Definition Operator.hpp:288
static std::shared_ptr< TOperator< TData > > Create(const MultiRegions::ExpListSharedPtr &expansionList, const std::vector< std::string > components, const std::string &execStr)
Create a concrete operator instance through the operator factory.
Definition Operator.hpp:147
static std::string GetDefaultOpImpl(const StdRegions::StdExpansionSharedPtr &exp, const std::string &execSpace)
Return the implementation a block of elements takes when neither the command line nor the session nam...
Definition Operator.hpp:255
LibUtilities::NekDataWarehouseSharedPtr m_dataWarehouse
Data warehouse shared with the other operators on the expansion list, used to build and cache shared ...
Definition Operator.hpp:355
static bool IsDiscontinuousProjection(std::shared_ptr< LibUtilities::SessionReader > session)
Return true if the session uses a Discontinuous (DG) projection.
Definition Operator.hpp:334
static std::string GetOpExecSpace(std::shared_ptr< LibUtilities::SessionReader > session, const bool warn=true)
Return the execution space name ("opExecSpace") for an operator.
Definition Operator.hpp:190
static const DefaultOpImplRule * GetDefaultOpImplRule(const StdRegions::StdExpansionSharedPtr &exp, const std::string &execSpace)
Return the row of the default implementation table (DefaultOpImplTable.hpp) that a block of elements ...
Definition Operator.hpp:224
std::shared_ptr< NekDataWarehouse > NekDataWarehouseSharedPtr
std::map< std::string, std::string > BackendMap
Collections::CollectionVector GetCollections(MultiRegions::ExpListSharedPtr expansionList)
const DefaultOpImplRule * FindDefaultOpImplRule(const std::string_view execSpace, const std::string_view arch, const LibUtilities::ShapeType shape, const int order, const DefaultOpImplRule *first=std::begin(defaultOpImplTable), const DefaultOpImplRule *last=std::end(defaultOpImplTable))
Return the row of a default implementation table that a block takes, or null if none does (the block ...
std::shared_ptr< ExpList > ExpListSharedPtr
Shared pointer to an ExpList object.
OperatorFactory< TData > & GetOperatorFactory()
Return the process-wide singleton OperatorFactory<TData>, constructing it on first use.
std::shared_ptr< StdExpansion > StdExpansionSharedPtr
std::string ToUpperCopy(std::string str)
static unsigned int nekGetNumDevice()
Definition Backends.hpp:397
static std::string GetDeviceArchitecture()
Return the architecture id of the device the calling rank uses, as the default implementation table (...
One row of the default implementation table.
std::string_view opImpl
Implementation the row selects.