setExprBoundaryFields.C
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration |
5  \\ / A nd | www.openfoam.com
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8  Copyright (C) 2019-2022 OpenCFD Ltd.
9 -------------------------------------------------------------------------------
10 License
11  This file is part of OpenFOAM.
12 
13  OpenFOAM is free software: you can redistribute it and/or modify it
14  under the terms of the GNU General Public License as published by
15  the Free Software Foundation, either version 3 of the License, or
16  (at your option) any later version.
17 
18  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
19  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
21  for more details.
22 
23  You should have received a copy of the GNU General Public License
24  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
25 
26 Application
27  setExprBoundaryFields
28 
29 Group
30  grpPreProcessingUtilities
31 
32 Description
33  Set boundary values using an expression
34 
35 Note
36  Based on funkySetBoundaryFields from
37  Bernhard Gschaider <bgschaid@hfd-research.com>
38 
39 \*---------------------------------------------------------------------------*/
40 
41 #include "argList.H"
42 #include "Time.H"
43 #include "fvMesh.H"
44 #include "pointMesh.H"
45 #include "volFields.H"
46 #include "surfaceFields.H"
47 #include "pointFields.H"
48 #include "patchExprDriver.H"
49 #include "timeSelector.H"
50 #include "readFields.H"
51 
52 using namespace Foam;
53 
54 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
55 // Main program:
56 
57 int main(int argc, char *argv[])
58 {
59  // Normally without functionObjects, with -withFunctionObjects to enable
61 
62  // No -constant, no special treatment for 0/
64 
66  (
67  "ascii",
68  "Write in ASCII format instead of the controlDict setting"
69  );
71  (
72  "dict",
73  "file",
74  "Alternative dictionary for setExprBoundaryFieldsDict"
75  );
77  (
78  "cache-fields",
79  "Cache fields between calls",
80  true // Advanced
81  );
83  (
84  "load-fields",
85  "wordList",
86  "Specify field or fields to preload. Eg, 'T' or '(p T U)'",
87  true // Advanced
88  );
90  (
91  "backup",
92  "Preserve sub-entry as .backup",
93  true // Advanced
94  );
96  (
97  "Evaluate but do not write"
98  );
99 
100  #include "addRegionOption.H"
101  #include "setRootCase.H"
102 
103  const bool dryrun = args.dryRun();
104  const bool backup = args.found("backup");
105  const bool cacheFields = args.found("cache-fields");
106 
107  if (cacheFields)
108  {
109  Warning
110  << "The current cache-fields behaviour (caching disk reads) "
111  << "may lead to unexpected behaviour as previous modifications "
112  << "will not be visible."
113  << endl;
114  }
115 
116  const word dictName("setExprBoundaryFieldsDict");
117 
118  #include "createTime.H"
119 
121 
122  if (times.empty())
123  {
125  << "No times selected." << nl
126  << exit(FatalError);
127  }
128 
129  #include "createNamedMesh.H"
130 
131  #include "setSystemMeshDictionaryIO.H"
132  IOdictionary setExprDict(dictIO);
133 
134  IOstreamOption streamOpt(runTime.writeFormat());
135  if (args.found("ascii"))
136  {
137  streamOpt.format(IOstreamOption::ASCII);
138  }
139 
140  forAll(times, timei)
141  {
142  runTime.setTime(times[timei], timei);
143 
144  Info<< "\nTime = " << runTime.timeName() << endl;
145 
146  mesh.readUpdate();
147 
148  // preload fields specified on command-line
149  if (timei == 0)
150  {
151  wordList preloadFields;
152  args.readListIfPresent("load-fields", preloadFields);
153  readFieldsHandler(mesh).execute(preloadFields);
154  }
155  // preload fields specified in dictionary
156  {
157  wordList preloadFields;
158  setExprDict.readIfPresent("readFields", preloadFields);
159  readFieldsHandler(mesh).execute(preloadFields);
160  }
161 
162  for (const entry& dEntry : setExprDict)
163  {
164  if (!dEntry.isDict())
165  {
166  if (dEntry.keyword() != "readFields")
167  {
168  Info<< "Ignoring non-dictionary entry "
169  << dEntry.keyword() << nl;
170  }
171  continue;
172  }
173 
174  const dictionary& dict = dEntry.dict();
175 
176  const word fieldName(dict.get<word>("field"));
177 
178  List<dictionary> exprDicts;
179  dict.readEntry("expressions", exprDicts);
180 
181  if (exprDicts.empty())
182  {
183  Info<< "No expressions for " << fieldName << nl;
184  continue;
185  }
186 
187 
188  // Read dictionary
189  // Note: disable class type checking so we can load field
190  const word oldTypeName = IOdictionary::typeName;
191  const_cast<word&>(IOdictionary::typeName) = word::null;
192 
193  IOobject fieldHeader
194  (
195  fieldName,
196  mesh.thisDb().time().timeName(),
197  mesh.thisDb(),
200  false
201  );
202 
203  const bool headOk = fieldHeader.typeHeaderOk<IOdictionary>(false);
204 
205  if (!headOk)
206  {
207  // Restore type
208  const_cast<word&>(IOdictionary::typeName) = oldTypeName;
209 
211  << "Requested field to change " << fieldName
212  << " does not exist in " << fieldHeader.path() << endl;
213  continue;
214  }
215 
216  IOdictionary fieldDict(fieldHeader);
217 
218  // Restore type
219  const_cast<word&>(IOdictionary::typeName) = oldTypeName;
220 
221  // Fake type back to what was in field
222  const_cast<word&>(fieldDict.type()) = fieldDict.headerClassName();
223 
224  Info<< "Processing field " << fieldName << nl;
225 
226  dictionary& boundaryFieldDict = fieldDict.subDict("boundaryField");
227 
228  for (const dictionary& currDict : exprDicts)
229  {
230  const word patchName(currDict.get<word>("patch"));
231  const word targetName(currDict.get<word>("target"));
232 
233  dictionary& patchDict = boundaryFieldDict.subDict(patchName);
234 
235  expressions::exprString valueExpr_("expression", currDict);
236 
237  Info<< "Set boundaryField/" << patchName << '/'
238  << targetName << nl
239  << "with expression" << nl
240  << "<<<<" << nl
241  << valueExpr_.c_str() << nl
242  << ">>>>" << nl;
243 
244  expressions::patchExprDriver driver(currDict, mesh);
245 
246  // Search files only
247  driver.setSearchBehaviour
248  (
250  cacheFields
251  );
252 
253  driver.clearVariables();
254  driver.parse(valueExpr_);
255 
256  // Serializing via Field::writeEntry etc
257  OStringStream serialize;
258  driver.result().writeEntry("", serialize);
259 
260  if (backup && !dryrun)
261  {
262  patchDict.changeKeyword
263  (
264  targetName,
265  word(targetName + ".backup"),
266  true // Overwrite
267  );
268  }
269 
270  patchDict.set(targetName, serialize.str().c_str());
271 
272  if (dryrun)
273  {
274  Info<< "Evaluated:" << nl
275  << "<<<<" << nl
276  << serialize.str().c_str() // (already includes nl)
277  << ">>>>" << nl;
278  }
279  }
280 
281  if (!dryrun)
282  {
283  Info<< "Write " << fieldDict.filePath() << nl;
284  fieldDict.regIOobject::writeObject(streamOpt, true);
285  }
286  }
287  }
288 
289  Info<< "\nEnd\n" << endl;
290 
291  return 0;
292 }
293 
294 
295 // ************************************************************************* //
Foam::surfaceFields.
dictionary dict
static void noFunctionObjects(bool addWithOption=false)
Remove &#39;-noFunctionObjects&#39; option and ignore any occurrences.
Definition: argList.C:514
errorManipArg< error, int > exit(error &err, const int errNo=1)
Definition: errorManip.H:125
error FatalError
Error stream (stdout output on all processes), with additional &#39;FOAM FATAL ERROR&#39; header text and sta...
A list of keyword definitions, which are a keyword followed by a number of values (eg...
Definition: dictionary.H:120
Foam::string str() const
Get the string - as Foam::string rather than std::string.
Definition: StringStream.H:96
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
Definition: error.H:578
A simple field-loader, as per the readFields function object.
Definition: readFields.H:44
constexpr char nl
The newline &#39;\n&#39; character (0x0a)
Definition: Ostream.H:49
"ascii" (normal default)
bool empty() const noexcept
True if the UList is empty (ie, size() is zero)
Definition: UListI.H:420
const word dictName("faMeshDefinition")
engineTime & runTime
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition: Ostream.H:487
Required Variables.
static void addBoolOption(const word &optName, const string &usage="", bool advanced=false)
Add a bool option to validOptions with usage information.
Definition: argList.C:365
Ostream & writeEntry(const keyType &key, const T &value)
Write a keyword/value entry.
Definition: Ostream.H:312
A simple container for options an IOstream can normally have.
Driver for patch expressions.
Ignore writing from objectRegistry::writeObject()
T get(const word &keyword, enum keyType::option matchOpt=keyType::REGEX) const
Find and return a T. FatalIOError if not found, or if the number of tokens is incorrect.
const dictionary & subDict(const word &keyword, enum keyType::option matchOpt=keyType::REGEX) const
Find and return a sub-dictionary.
Definition: dictionary.C:453
virtual const objectRegistry & thisDb() const
Return the object registry - resolve conflict polyMesh/lduMesh.
Definition: fvMesh.H:377
IOdictionary is derived from dictionary and IOobject to give the dictionary automatic IO functionalit...
Definition: IOdictionary.H:50
#define forAll(list, i)
Loop across all elements in list.
Definition: stdFoam.H:413
bool readEntry(const word &keyword, T &val, enum keyType::option matchOpt=keyType::REGEX, IOobjectOption::readOption readOpt=IOobjectOption::MUST_READ) const
Find entry and assign to T val. FatalIOError if it is found and the number of tokens is incorrect...
dynamicFvMesh & mesh
virtual readUpdateState readUpdate()
Update the mesh based on the mesh files saved in time.
Definition: fvMesh.C:668
A class for handling words, derived from Foam::string.
Definition: word.H:63
static void addDryRunOption(const string &usage, bool advanced=false)
Enable a &#39;dry-run&#39; bool option, with usage information.
Definition: argList.C:495
const Time & time() const noexcept
Return time registry.
int dryRun() const noexcept
Return the dry-run flag.
Definition: argListI.H:109
Reading required, file watched for runTime modification.
static const word null
An empty word.
Definition: word.H:84
static void addOption(const word &optName, const string &param="", const string &usage="", bool advanced=false)
Add an option to validOptions with usage information.
Definition: argList.C:376
virtual void setTime(const Time &t)
Reset the time and time-index to those of the given time.
Definition: Time.C:977
bool typeHeaderOk(const bool checkType=true, const bool search=true, const bool verbose=true)
Read header (uses typeFilePath to find file) and check its info.
static word timeName(const scalar t, const int precision=precision_)
Return time name of given scalar time formatted with the given precision.
Definition: Time.C:760
bool readListIfPresent(const word &optName, List< T > &list) const
If named option is present, get a List of values treating a single entry like a list of size 1...
Definition: argListI.H:387
static instantList select0(Time &runTime, const argList &args)
Return the set of times selected based on the argList options and also set the runTime to the first i...
Definition: timeSelector.C:234
IOstreamOption::streamFormat writeFormat() const noexcept
The write stream format.
Definition: Time.H:486
messageStream Warning
Warning stream (stdout output on master, null elsewhere), with additional &#39;FOAM Warning&#39; header text...
Search disk (eg, standalone app)
Definition: exprDriver.H:149
#define WarningInFunction
Report a warning using Foam::Warning.
messageStream Info
Information stream (stdout output on master, null elsewhere)
IOobject dictIO
entry * set(entry *entryPtr)
Assign a new entry, overwriting any existing entry.
Definition: dictionary.C:777
bool changeKeyword(const keyType &oldKeyword, const keyType &newKeyword, bool overwrite=false)
Change the keyword for an entry,.
Foam::argList args(argc, argv)
bool execute(const UList< word > &fieldNames)
Definition: readFields.H:181
Defines the attributes of an object for which implicit objectRegistry management is supported...
Definition: IOobject.H:166
Output to string buffer, using a OSstream. Always UNCOMPRESSED.
Definition: StringStream.H:256
streamFormat format() const noexcept
Get the current stream format.
bool found(const word &optName) const
Return true if the named option is found.
Definition: argListI.H:171
static void addOptions(const bool constant=true, const bool withZero=false)
Add timeSelector options to argList::validOptions.
Definition: timeSelector.C:101
Namespace for OpenFOAM.
A keyword and a list of tokens is an &#39;entry&#39;.
Definition: entry.H:63