externalCoupled.H
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) 2015-2020 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 i
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 Class
27  Foam::functionObjects::externalCoupled
28 
29 Group
30  grpFieldFunctionObjects
31 
32 Description
33  Provides a simple file-based communication interface for explicit coupling
34  with an external application, so that data is transferred to- and from
35  OpenFOAM. The data exchange employs specialised boundary conditions to
36  provide either one-way or two-way coupling models.
37 
38  The coupling is through plain text files where OpenFOAM boundary data
39  is read/written as one line per face (data from all processors collated):
40  \verbatim
41  # Patch: <patch name>
42  <fld1> <fld2> .. <fldn> //face0
43  <fld1> <fld2> .. <fldn> //face1
44  ..
45  <fld1> <fld2> .. <fldn> //faceN
46  \endverbatim
47 
48  where the actual entries depend on the boundary condition type:
49  - mixed: value, snGrad, refValue, refGrad, valueFraction
50  - externalCoupledMixed: output of writeDataMaster
51  - other: value, snGrad
52 
53  These text files are located in a user specified communications directory
54  which gets read/written on the master processor only.
55 
56  In the communications directory the structure will be:
57  \verbatim
58  <regionsName>/<patchGroup>/<fieldName>.[in|out]
59  \endverbatim
60 
61  (where \c regionsName is either the name of a single region or a composite
62  of multiple region names)
63 
64  At start-up, the boundary creates a lock file, i.e.:
65  \verbatim
66  OpenFOAM.lock
67  \endverbatim
68 
69  ... to signal the external source to wait. During the function object
70  execution the boundary values are written to files (one per region,
71  per patch(group), per field), e.g.
72  \verbatim
73  <regionsName>/<patchGroup>/<fieldName>.out
74  \endverbatim
75 
76  The lock file is then removed, instructing the external source to take
77  control of the program execution. When ready, the external program
78  should create the return values, e.g. to files
79  \verbatim
80  <regionsName>/<patchGroup>/<fieldName>.in
81  \endverbatim
82 
83  ... and then reinstate the lock file. The function object will then
84  read these values, apply them to the boundary conditions and pass
85  program execution back to OpenFOAM.
86 
87 Usage
88  Minimal example by using \c system/controlDict.functions:
89  \verbatim
90  externalCoupled1
91  {
92  // Mandatory entries (unmodifiable)
93  type externalCoupled;
94  libs (fieldFunctionObjects);
95  commsDir "<case>/comms";
96  regions
97  {
98  "(region1|region0)" // Name of region(s)
99  {
100  TPatchGroup // Name of patch(group)
101  {
102  readFields (p); // List of fields to read
103  writeFields (T); // List of fields to write
104  }
105  }
106  }
107  initByExternal true;
108 
109  // Optional entries (runtime modifiable)
110  waitInterval 1;
111  timeOut 100;
112  statusDone done; // Any arbitrary status=... value
113  calcFrequency 1;
114 
115  // Optional (inherited) entries
116  ...
117  }
118  \endverbatim
119 
120  This reads/writes (on the master processor) the directory:
121  \verbatim
122  comms/region0_region1/TPatchGroup/
123  \endverbatim
124 
125  with contents:
126  \verbatim
127  patchPoints (collected points)
128  patchFaces (collected faces)
129  p.in (input file of p, written by external application)
130  T.out (output file of T, written by OpenFOAM)
131  \endverbatim
132 
133  The patchPoints/patchFaces files denote the (collated) geometry
134  which will be written if it does not exist yet or can be written as
135  a preprocessing step using the createExternalCoupledPatchGeometry
136  application.
137 
138  The entries comprise:
139  \table
140  Property | Description | Type | Req'd | Dflt
141  type | Type name: externalCoupled | word | yes | -
142  libs | Library name: fieldFunctionObjects | word | yes | -
143  commsDir | Communication directory | word | yes | -
144  regions | The regions to couple | word | yes | -
145  initByExternal | Initialization values supplied by external app <!--
146  --> | bool | yes | -
147  waitInterval | Wait interval in [s] | label | no | 1
148  timeOut | Timeout in [s] | label | no | 100*waitInterval
149  statusDone | Lockfile status=... on termination | word | no | done
150  calcFrequency | Calculation frequency | label | no | 1
151  \endtable
152 
153  The inherited entries are elaborated in:
154  - \link timeFunctionObject.H \endlink
155 
156  Usage by the \c postProcess utility is not available.
157 
158 See also
159  - Foam::functionObject
160  - Foam::functionObjects::timeFunctionObject
161  - Foam::externalFileCouple
162  - ExtendedCodeGuide::functionObjects::field::externalCoupled
163 
164 SourceFiles
165  externalCoupled.C
166  externalCoupledTemplates.C
167 
168 \*---------------------------------------------------------------------------*/
169 
170 #ifndef functionObjects_externalCoupled_H
171 #define functionObjects_externalCoupled_H
172 
173 #include "timeFunctionObject.H"
174 #include "externalFileCoupler.H"
175 #include "DynamicList.H"
176 #include "wordRes.H"
177 #include "scalarField.H"
178 #include "UPtrList.H"
179 
180 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
181 
182 namespace Foam
183 {
184 
185 // Forward Declarations
186 class fvMesh;
187 class IFstream;
188 
189 namespace functionObjects
190 {
191 
192 /*---------------------------------------------------------------------------*\
193  Class externalCoupled Declaration
194 \*---------------------------------------------------------------------------*/
195 
196 class externalCoupled
197 :
198  public functionObjects::timeFunctionObject,
199  public externalFileCoupler
200 {
201 
202  // Private Member Data
203 
204  //- Calculation frequency
205  label calcFrequency_;
206 
207  //- The last timeIndex when coupling was triggered
208  label lastTrigger_;
209 
210  //- Names of (composite) regions
211  DynamicList<word> regionGroupNames_;
212 
213  // Per (composite) region the names of the regions
214  DynamicList<wordList> regionGroupRegions_;
215 
216  // Per (composite) region the indices of the group information
217  HashTable<labelList> regionToGroups_;
218 
219  // Per group the names of the patches/patchGroups
220  DynamicList<wordRe> groupNames_;
221 
222  // Per group the names of the fields to read
223  DynamicList<wordList> groupReadFields_;
224 
225  // Per group the names of the fields to write
226  DynamicList<wordList> groupWriteFields_;
227 
228  //- Initialised coupling
229  bool initialisedCoupling_;
230 
231 
232  // Private Member Functions
233 
234  //- Return the file path to the communications directory for the region
235  static fileName groupDir
236  (
237  const fileName& commsDir,
238  const word& regionsName,
239  const wordRe& groupName
240  );
241 
242  //- Read data for a single region, single field
243  template<class Type>
244  bool readData
245  (
246  const UPtrList<const fvMesh>& meshes,
247  const wordRe& groupName,
248  const word& fieldName
249  );
250 
251  //- Write data for a single region, single field
252  template<class Type>
253  bool writeData
254  (
255  const UPtrList<const fvMesh>& meshes,
256  const wordRe& groupName,
257  const word& fieldName
258  ) const;
259 
260  void initCoupling();
261 
262  //- Read (and distribute) scalar columns from stream. Every processor
263  // gets nRows (= patch size) of these. Note: could make its argument
264  // ISstream& but then would need additional logic to construct valid
265  // stream on all processors.
266  void readColumns
267  (
268  const label nRows,
269  const label nColumns,
270  autoPtr<IFstream>& masterFilePtr,
272  ) const;
273 
274  //- Read (and distribute) lines from stream. Every processor
275  // gets nRows (= patch size) of these. Data kept as stream (instead
276  // of strings) for ease of interfacing to readData routines that take
277  // an Istream.
278  void readLines
279  (
280  const label nRows,
281  autoPtr<IFstream>& masterFilePtr,
283  ) const;
284 
285  //- Helper: append data from all processors onto master
286  template<class Type>
287  static tmp<Field<Type>> gatherAndCombine(const Field<Type>& fld);
288 
289  static void checkOrder(const wordList& regionNames);
290 
291  //- Perform the coupling with necessary initialization etc.
292  void performCoupling();
293 
294 
295 public:
296 
297  //- Runtime type information
298  TypeName("externalCoupled");
299 
300  //- Name of patch key, e.g. '// Patch:' when looking for start of patch data
301  static string patchKey;
302 
303  //- Inherited variable for logging
304  using functionObject::log;
305 
306 
307  // Constructors
308 
309  //- Construct given time and dictionary
311  (
312  const word& name,
313  const Time& runTime,
314  const dictionary& dict
315  );
316 
317  //- No copy construct
318  externalCoupled(const externalCoupled&) = delete;
319 
320  //- No copy assignment
321  void operator=(const externalCoupled&) = delete;
322 
323 
324  //- Destructor
325  virtual ~externalCoupled() = default;
326 
327 
328  // Member Functions
329 
330  // Function object control
331 
332  //- Called at each ++ or += of the time-loop
333  virtual bool execute();
334 
335  //- Manual execute (sub-loop or when converged)
336  virtual bool execute(const label subIndex);
337 
338  //- Called when Time::run() determines that the time-loop exits
339  virtual bool end();
340 
341  //- Read and set the function object if its data have changed
342  virtual bool read(const dictionary& dict);
343 
344  //- Write, currently a no-op
345  virtual bool write();
346 
347 
348  // File creation, removal
349 
350  //- Write data files (all regions, all fields) from master (OpenFOAM)
351  virtual void writeDataMaster() const;
352 
353  //- Read data files (all regions, all fields) on master (OpenFOAM)
354  virtual void readDataMaster();
355 
356  //- Remove data files written by master (OpenFOAM)
357  virtual void removeDataMaster() const;
358 
359  //- Remove data files written by slave (external code)
360  virtual void removeDataSlave() const;
361 
362 
363  // Other
364 
365  //- Create single name by appending words (in sorted order),
366  //- separated by '_'
367  static word compositeName(const wordList&);
368 
369  //- Write geometry for the group as region/patch
370  static void writeGeometry
371  (
373  const fileName& commsDir,
374  const wordRe& groupName
375  );
376 };
377 
378 
379 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
380 
381 } // End namespace functionObjects
382 } // End namespace Foam
383 
384 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
385 
386 #ifdef NoRepository
387  #include "externalCoupledTemplates.C"
388 #endif
389 
390 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
391 
392 #endif
393 
394 // ************************************************************************* //
Foam::functionObjects::externalCoupled::operator=
void operator=(const externalCoupled &)=delete
No copy assignment.
Foam::functionObjects::externalCoupled::readDataMaster
virtual void readDataMaster()
Read data files (all regions, all fields) on master (OpenFOAM)
Definition: externalCoupled.C:681
runTime
engineTime & runTime
Definition: createEngineTime.H:13
wordRes.H
UPtrList.H
Foam::functionObjects::externalCoupled::read
virtual bool read(const dictionary &dict)
Read and set the function object if its data have changed.
Definition: externalCoupled.C:560
Foam::Time
Class to control time during OpenFOAM simulations that is also the top-level objectRegistry.
Definition: Time.H:73
Foam::word
A class for handling words, derived from Foam::string.
Definition: word.H:65
Foam::fileName
A class for handling file names.
Definition: fileName.H:73
Foam::tmp
A class for managing temporary objects.
Definition: PtrList.H:61
scalarField.H
Foam::DynamicList< word >
Foam::functionObjects::timeFunctionObject
Virtual base class for function objects with a reference to Time.
Definition: timeFunctionObject.H:56
Foam::functionObjects::externalCoupled
Provides a simple file-based communication interface for explicit coupling with an external applicati...
Definition: externalCoupled.H:257
Foam::functionObjects::externalCoupled::~externalCoupled
virtual ~externalCoupled()=default
Destructor.
Foam::wordRe
A wordRe is a Foam::word, but can contain a regular expression for matching words or strings.
Definition: wordRe.H:80
regionNames
wordList regionNames
Definition: getAllRegionOptions.H:37
timeFunctionObject.H
Foam::Field
Generic templated field type.
Definition: Field.H:63
externalFileCoupler.H
meshes
Foam::PtrList< Foam::fvMesh > meshes(regionNames.size())
Foam::UPtrList
A list of pointers to objects of type <T>, without allocation/deallocation management of the pointers...
Definition: UPtrList.H:62
fld
gmvFile<< "tracers "<< particles.size()<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().x()<< ' ';}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().y()<< ' ';}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().z()<< ' ';}gmvFile<< nl;for(const word &name :lagrangianScalarNames){ IOField< scalar > fld(IOobject(name, runTime.timeName(), cloud::prefix, mesh, IOobject::MUST_READ, IOobject::NO_WRITE))
Definition: gmvOutputLagrangian.H:23
Foam::functionObjects::externalCoupled::end
virtual bool end()
Called when Time::run() determines that the time-loop exits.
Definition: externalCoupled.C:547
dict
dictionary dict
Definition: searchingEngine.H:14
Foam::dictionary
A list of keyword definitions, which are a keyword followed by a number of values (eg,...
Definition: dictionary.H:123
Foam::functionObjects::externalCoupled::removeDataMaster
virtual void removeDataMaster() const
Remove data files written by master (OpenFOAM)
Definition: externalCoupled.C:769
Foam
Namespace for OpenFOAM.
Definition: atmBoundaryLayer.C:33
Foam::functionObjects::externalCoupled::writeDataMaster
virtual void writeDataMaster() const
Write data files (all regions, all fields) from master (OpenFOAM)
Definition: externalCoupled.C:725
Foam::functionObjects::externalCoupled::patchKey
static string patchKey
Name of patch key, e.g. '// Patch:' when looking for start of patch data.
Definition: externalCoupled.H:362
Foam::HashTable
A HashTable similar to std::unordered_map.
Definition: HashTable.H:105
Foam::functionObjects::externalCoupled::removeDataSlave
virtual void removeDataSlave() const
Remove data files written by slave (external code)
Definition: externalCoupled.C:799
Foam::functionObjects::externalCoupled::write
virtual bool write()
Write, currently a no-op.
Definition: externalCoupled.C:829
Foam::autoPtr
Pointer management similar to std::unique_ptr, with some additional methods and type checking.
Definition: HashPtrTable.H:53
Foam::externalFileCoupler
Encapsulates the logic for coordinating between OpenFOAM and an external application.
Definition: externalFileCoupler.H:107
Foam::functionObjects::externalCoupled::execute
virtual bool execute()
Called at each ++ or += of the time-loop.
Definition: externalCoupled.C:523
Foam::functionObject::name
const word & name() const noexcept
Return the name of this functionObject.
Definition: functionObject.C:143
Foam::List< scalarField >
Foam::functionObjects::externalCoupled::TypeName
TypeName("externalCoupled")
Runtime type information.
Foam::OStringStream
Output to string buffer, using a OSstream. Always UNCOMPRESSED.
Definition: StringStream.H:227
Foam::functionObjects::externalCoupled::externalCoupled
externalCoupled(const word &name, const Time &runTime, const dictionary &dict)
Construct given time and dictionary.
Definition: externalCoupled.C:500
externalCoupledTemplates.C
DynamicList.H
Foam::functionObjects::externalCoupled::writeGeometry
static void writeGeometry(const UPtrList< const fvMesh > &meshes, const fileName &commsDir, const wordRe &groupName)
Write geometry for the group as region/patch.
Definition: externalCoupled.C:237
Foam::functionObjects::externalCoupled::compositeName
static word compositeName(const wordList &)
Definition: externalCoupled.C:345
Foam::functionObject::log
bool log
Flag to write log into Info.
Definition: functionObject.H:355
Foam::data
Database for solution data, solver performance and other reduced data.
Definition: data.H:55