Nektar++
FilterIntegral.cpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File FilterIntegral.cpp
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: Outputs integrals of fields during time-stepping.
32//
33///////////////////////////////////////////////////////////////////////////////
34
40
41#include <boost/algorithm/string.hpp>
42
43namespace Nektar::SolverUtils
44{
45std::string FilterIntegral::className =
48
49/**
50 * @brief Initialise the filter and parse the session file parameters.
51 */
54 const std::shared_ptr<EquationSystem> &pEquation, const ParamMap &pParams)
55 : Filter(pSession, pEquation)
56{
57 std::string outName;
58 std::string ext = ".int";
59 outName = Filter::SetupOutput(ext, pParams);
60
61 // Composites (to calculate integrals on)
62 auto it = pParams.find("Composites");
63 ASSERTL0(it != pParams.end(), "Missing parameter 'Composites'.");
64 ASSERTL0(it->second.length() > 0, "Empty parameter 'Composites'.");
65
66 std::vector<std::string> splitComposite;
67 boost::split(m_splitCompString, it->second, boost::is_any_of(","),
68 boost::token_compress_on);
69
70 for (auto &comp : m_splitCompString)
71 {
72 boost::trim(comp);
73 size_t first = comp.find_first_of('[') + 1;
74 size_t last = comp.find_last_of(']') - 1;
75 auto tmpString = comp.substr(first, last - first + 1);
76
77 std::vector<unsigned int> tmpVec;
78 bool parseGood = ParseUtils::GenerateSeqVector(tmpString, tmpVec);
79
80 ASSERTL0(parseGood && !tmpVec.empty(),
81 "Unable to read composite regions index range for "
82 "FilterIntegral: " +
83 comp);
84
85 m_compVector.emplace_back(tmpVec);
86 }
87
88 // OutputPrecision
89 size_t precision;
90 it = pParams.find("OutputPrecision");
91 if (it == pParams.end())
92 {
93 precision = 7;
94 }
95 else
96 {
97 ASSERTL0(it->second.length() > 0, "Empty parameter 'OutputPrecision'.");
98 precision = std::stoi(it->second);
99 }
100
101 // Lock equation system pointer
102 auto equationSys = m_equ.lock();
103 ASSERTL0(equationSys, "Weak pointer expired");
104
105 m_numVariables = equationSys->GetNvariables();
106
107 m_comm = pSession->GetComm();
108 if (m_comm->GetRank() == 0)
109 {
110 m_outFile.open(outName);
111 ASSERTL0(m_outFile.good(), "Unable to open: '" + outName + "'");
112 m_outFile.setf(std::ios::scientific, std::ios::floatfield);
113 m_outFile.precision(precision);
114 m_outFile << "#Time";
115
116 for (auto &compName : m_splitCompString)
117 {
118 for (size_t j = 0; j < m_numVariables; ++j)
119 {
120 std::string varName = equationSys->GetVariable(j);
121 m_outFile << " " + compName + "_" + varName + "_integral";
122 }
123 }
124 m_outFile << std::endl;
125 }
126
127 // OutputFrequency
128 it = pParams.find("OutputFrequency");
129 if (it == pParams.end())
130 {
132 }
133 else
134 {
135 ASSERTL0(it->second.length() > 0, "Empty parameter 'OutputFrequency'.");
136 LibUtilities::Equation equ(m_session->GetInterpreter(), it->second);
137 m_outputFrequency = round(equ.Evaluate());
138 }
139}
140
141/**
142 * @brief Parse composite list and geometric entities to integrate over.
143 */
146 [[maybe_unused]] const NekDouble &time)
147{
148
149 // Create map from element ID -> expansion list ID
150 auto expList = pFields[0]->GetExp();
151 auto meshGraph = pFields[0]->GetGraph();
152
153 for (size_t i = 0; i < expList->size(); ++i)
154 {
155 auto exp = (*expList)[i];
156 m_geomElmtIdToExpId[exp->GetGeom()->GetGlobalID()] = i;
157 }
158
159 // Create a map from geom ID -> trace expansion list ID
160 std::map<size_t, size_t> geomIdToTraceId;
161 auto trace = pFields[0]->GetTrace()->GetExp();
162 for (size_t i = 0; i < trace->size(); ++i)
163 {
164 auto exp = (*trace)[i];
165 geomIdToTraceId[exp->GetGeom()->GetGlobalID()] = i;
166 }
167
168 // Get comp list dimension from first composite & element
169 auto composites = pFields[0]->GetGraph()->GetComposites();
170 size_t meshDim = pFields[0]->GetGraph()->GetMeshDimension();
171
172 for (int i = 0; i < m_compVector.size(); ++i)
173 {
174 // Check composite is present in the rank
175 if (composites.find(m_compVector[i][0]) == composites.end())
176 {
177 continue;
178 }
179
180 std::vector<std::shared_ptr<SpatialDomains::Geometry>> geomVec =
181 composites[m_compVector[i][0]]->m_geomVec;
182 size_t dim =
183 composites[m_compVector[i][0]]->m_geomVec[0]->GetShapeDim();
184
185 // Vector of all geometry IDs contained within the composite list
186 std::vector<size_t> compGeomIds;
187 for (auto compNum : m_compVector[i])
188 {
189 ASSERTL0(composites.find(compNum) != composites.end(),
190 "In FilterIntegral defined composite C[" +
191 std::to_string(compNum) +
192 "] does not exist in the mesh.")
193
194 auto compGeom = composites[compNum]->m_geomVec;
195
196 for (auto &geom : compGeom)
197 {
198 compGeomIds.emplace_back(geom->GetGlobalID());
199 }
200
201 // Only check first element in each comp for dimension
202 ASSERTL0(
203 dim == compGeom[0]->GetShapeDim(),
204 "Differing geometry dimensions specified in FilterIntegral '" +
205 m_splitCompString[i] + "'.");
206 }
207
208 std::vector<std::pair<LocalRegions::ExpansionSharedPtr, int>>
209 tmpCompExp(compGeomIds.size());
210
211 // If dimension of composite == dimension of mesh then we only need the
212 // expansion of the element
213 if (dim == pFields[0]->GetShapeDimension())
214 {
215 for (size_t j = 0; j < compGeomIds.size(); ++j)
216 {
217 tmpCompExp[j] = std::make_pair(
218 (*expList)[m_geomElmtIdToExpId[compGeomIds[j]]], -1);
219 }
220 }
221 // however if the dimension is less we need the expansion of the element
222 // containing the global composite geometry and the face/edge local ID
223 // within that. 3D mesh -> 2D, 2D -> 1D.
224 // @TODO: Restructure with the new dimension independent functions
225 // and check all is correct with this filter.
226 else if (meshDim == 3 && dim == 2)
227 {
228 for (size_t j = 0; j < compGeomIds.size(); ++j)
229 {
231 (*trace)[geomIdToTraceId[compGeomIds[j]]];
233 std::dynamic_pointer_cast<LocalRegions::Expansion2D>(exp);
234
235 LocalRegions::ExpansionSharedPtr leftAdjElmtExp =
236 std::dynamic_pointer_cast<LocalRegions::Expansion>(
237 exp2D->GetLeftAdjacentElementExp());
238 int leftAdjElmtFace = exp2D->GetLeftAdjacentElementTrace();
239
240 tmpCompExp[j] = std::make_pair(leftAdjElmtExp, leftAdjElmtFace);
241 }
242 }
243 else if (meshDim == 2 && dim == 1)
244 {
245 for (size_t j = 0; j < compGeomIds.size(); ++j)
246 {
248 (*trace)[geomIdToTraceId[compGeomIds[j]]];
250 std::dynamic_pointer_cast<LocalRegions::Expansion1D>(exp);
251
252 LocalRegions::ExpansionSharedPtr leftAdjElmtExp =
253 std::dynamic_pointer_cast<LocalRegions::Expansion>(
254 exp1D->GetLeftAdjacentElementExp());
255 int leftAdjElmtEdge = exp1D->GetLeftAdjacentElementTrace();
256
257 tmpCompExp[j] = std::make_pair(leftAdjElmtExp, leftAdjElmtEdge);
258 }
259 }
260 else
261 {
262 ASSERTL0(false,
263 "FilterIntegral: Only composite dimensions equal to or "
264 "one lower than the mesh dimension are supported.")
265 }
266
267 m_compExpMap[i] = tmpCompExp;
268 }
270 {
271 v_Update(pFields, time);
272 }
273}
274
275/**
276 * @brief Calculate integral over requested composites.
277 */
280 const NekDouble &time)
281{
282 if (m_index++ % m_outputFrequency > 0)
283 {
284 return;
285 }
286
287 if (m_comm->GetRank() == 0)
288 {
289 m_outFile << time;
290 }
291
292 for (size_t j = 0; j < m_compVector.size(); ++j)
293 {
294 for (size_t i = 0; i < m_numVariables; ++i)
295 {
297 phys = pFields[i]->GetPhys();
298
299 NekDouble sum = 0.0;
300 NekDouble c = 0.0;
301
302 // Check if composite is on the rank
303 if (m_compExpMap.find(j) != m_compExpMap.end())
304 {
305 auto compExp = m_compExpMap[j];
306 size_t dim = compExp[0].first->GetGeom()->GetShapeDim();
307 size_t meshDim = pFields[i]->GetGraph()->GetMeshDimension();
308
309 // Evaluate integral using improved Kahan–Babuška summation
310 // algorithm to reduce numerical error from adding floating
311 // points
312 for (auto &expPair : compExp)
313 {
314 NekDouble input = 0;
315 auto exp = expPair.first;
316
317 if (meshDim == dim)
318 {
319 size_t offset = pFields[i]->GetPhys_Offset(
320 m_geomElmtIdToExpId[exp->GetGeom()->GetGlobalID()]);
321 input = exp->Integral(phys + offset);
322 }
323 else if (meshDim == 3 && dim == 2)
324 {
325 Array<OneD, NekDouble> facePhys;
326 exp->GetTracePhysVals(expPair.second, exp, phys,
327 facePhys);
328 input =
329 pFields[i]
330 ->GetTrace()
331 ->GetExp(exp->GetGeom()->GetTid(expPair.second))
332 ->Integral(facePhys);
333 }
334 else if (meshDim == 2 && dim == 1)
335 {
336 Array<OneD, NekDouble> edgePhys;
337 exp->GetTracePhysVals(expPair.second, exp, phys,
338 edgePhys);
339 input =
340 pFields[i]
341 ->GetTrace()
342 ->GetExp(exp->GetGeom()->GetTid(expPair.second))
343 ->Integral(edgePhys);
344 }
345 else
346 {
347 ASSERTL0(false,
348 "FilterIntegral: Only composite dimensions "
349 "equal to or one lower than the mesh "
350 "dimension are supported.")
351 }
352
353 NekDouble t = sum + input;
354 c += fabs(sum) >= fabs(input) ? (sum - t) + input
355 : (input - t) + sum;
356 sum = t;
357 }
358 }
359
360 // Sum integral values from all ranks
361 Array<OneD, NekDouble> sumArray(1, sum + c);
362 m_comm->AllReduce(sumArray, LibUtilities::ReduceSum);
363 if (m_comm->GetRank() == 0)
364 {
365 m_outFile << " " << sumArray[0];
366 }
367 }
368 }
369
370 if (m_comm->GetRank() == 0)
371 {
372 m_outFile << std::endl;
373 }
374}
375
376/**
377 * @brief This is a time-dependent filter.
378 */
381 &pFields,
382 [[maybe_unused]] const NekDouble &time)
383{
384 if (m_comm->GetRank() == 0)
385 {
386 m_outFile.close();
387 }
388}
389
391{
392 return true;
393}
394
395} // namespace Nektar::SolverUtils
#define ASSERTL0(condition, msg)
Definition: ErrorUtil.hpp:208
tKey RegisterCreatorFunction(tKey idKey, CreatorFunction classCreator, std::string pDesc="")
Register a class with the factory.
static bool GenerateSeqVector(const std::string &str, std::vector< unsigned int > &out)
Takes a comma-separated compressed string and converts it to entries in a vector.
Definition: ParseUtils.cpp:104
SOLVER_UTILS_EXPORT std::string SetupOutput(const std::string ext, const ParamMap &pParams)
Definition: Filter.h:139
LibUtilities::SessionReaderSharedPtr m_session
Definition: Filter.h:93
const std::weak_ptr< EquationSystem > m_equ
Definition: Filter.h:94
std::map< std::string, std::string > ParamMap
Definition: Filter.h:66
std::map< int, std::vector< std::pair< LocalRegions::ExpansionSharedPtr, int > > > m_compExpMap
Map of composite ID to vector of expansions an face/edge local ID.
void v_Update(const Array< OneD, const MultiRegions::ExpListSharedPtr > &pFields, const NekDouble &time) final
Calculate integral over requested composites.
std::map< size_t, size_t > m_geomElmtIdToExpId
Mapping from geometry ID to expansion ID.
static FilterSharedPtr create(const LibUtilities::SessionReaderSharedPtr &pSession, const std::shared_ptr< EquationSystem > &pEquation, const std::map< std::string, std::string > &pParams)
Creates an instance of this class.
size_t m_outputFrequency
Frequency to write to output data file in timesteps.
size_t m_numVariables
Number of fields to perform integral on.
std::ofstream m_outFile
Out file.
bool v_IsTimeDependent() final
Returns true as filter depends on time.
LibUtilities::CommSharedPtr m_comm
Global communicator.
static std::string className
Name of the class.
void v_Finalise(const Array< OneD, const MultiRegions::ExpListSharedPtr > &pFields, const NekDouble &time) final
This is a time-dependent filter.
std::vector< std::vector< unsigned int > > m_compVector
Vector of vector of composites IDs as integers.
SOLVER_UTILS_EXPORT FilterIntegral(const LibUtilities::SessionReaderSharedPtr &pSession, const std::shared_ptr< EquationSystem > &pEquation, const ParamMap &pParams)
Constructs the integral filter and parses filter options, opens file.
std::vector< std::string > m_splitCompString
Vector of composite IDs as a single string.
void v_Initialise(const Array< OneD, const MultiRegions::ExpListSharedPtr > &pFields, const NekDouble &time) final
Parse composite list and geometric entities to integrate over.
std::shared_ptr< SessionReader > SessionReaderSharedPtr
std::shared_ptr< Expansion > ExpansionSharedPtr
Definition: Expansion.h:66
std::shared_ptr< Expansion2D > Expansion2DSharedPtr
Definition: Expansion1D.h:46
std::shared_ptr< Expansion1D > Expansion1DSharedPtr
Definition: Expansion1D.h:50
FilterFactory & GetFilterFactory()
double NekDouble