Loading...
Searching...
No Matches
foamFormatConvert.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) 2011-2017 OpenFOAM Foundation
9 Copyright (C) 2016-2025 OpenCFD Ltd.
10-------------------------------------------------------------------------------
11License
12 This file is part of OpenFOAM.
13
14 OpenFOAM is free software: you can redistribute it and/or modify it
15 under the terms of the GNU General Public License as published by
16 the Free Software Foundation, either version 3 of the License, or
17 (at your option) any later version.
18
19 OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
20 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
26
27Application
28 foamFormatConvert
29
30Group
31 grpMiscUtilities
32
33Description
34 Converts all IOobjects associated with a case into the format specified
35 in the controlDict.
36
37 Mainly used to convert binary mesh/field files to ASCII.
38
39 Problem: any zero-size List written binary gets written as '0'. When
40 reading the file as a dictionary this is interpreted as a label. This
41 is (usually) not a problem when doing patch fields since these get the
42 'uniform', 'nonuniform' prefix. However zone contents are labelLists
43 not labelFields and these go wrong. For now hacked a solution where
44 we detect the keywords in zones and redo the dictionary entries
45 to be labelLists.
46
47Usage
48
49 - foamFormatConvert [OPTION]
50
51 \param -noConstant \n
52 Exclude the constant/ directory from the times list
53
54 \param -enableFunctionEntries \n
55 By default all dictionary preprocessing of fields is disabled
56
57\*---------------------------------------------------------------------------*/
58
59#include "argList.H"
60#include "timeSelector.H"
61#include "Time.H"
62#include "volFields.H"
63#include "surfaceFields.H"
64#include "pointFields.H"
65#include "cellIOList.H"
66#include "IOobjectList.H"
67#include "IOPtrList.H"
68#include "cloud.H"
69#include "labelIOField.H"
70#include "scalarIOField.H"
72#include "symmTensorIOField.H"
73#include "tensorIOField.H"
74#include "labelFieldIOField.H"
75#include "vectorFieldIOField.H"
77#include "fieldDictionary.H"
78
79#include "writeMeshObject.H"
80
81using namespace Foam;
82
83// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
84
85namespace Foam
86{
88}
89
90
91// Hack to do zones which have Lists in them. See above.
92bool writeZones
93(
94 const word& name,
95 const fileName& meshDir,
98)
99{
101 (
102 name,
103 runTime.timeName(),
104 meshDir,
105 runTime,
109 );
110
111 bool writeOk = false;
112
113 if (io.typeHeaderOk<cellZoneMesh>(false))
114 {
115 Info<< " Reading " << io.headerClassName()
116 << " : " << name << endl;
117
118 // Switch off type checking (for reading e.g. faceZones as
119 // generic list of dictionaries).
120 const word oldTypeName = IOPtrList<entry>::typeName;
122
124
125 for (entry& e : meshObject)
126 {
127 if (e.isDict())
128 {
129 dictionary& d = e.dict();
130
131 if (d.found("faceLabels"))
132 {
133 d.set("faceLabels", labelList(d.lookup("faceLabels")));
134 }
135
136 if (d.found("flipMap"))
137 {
138 d.set("flipMap", boolList(d.lookup("flipMap")));
139 }
140
141 if (d.found("cellLabels"))
142 {
143 d.set("cellLabels", labelList(d.lookup("cellLabels")));
144 }
145
146 if (d.found("pointLabels"))
147 {
148 d.set("pointLabels", labelList(d.lookup("pointLabels")));
149 }
150 }
151 }
152
153 const_cast<word&>(IOPtrList<entry>::typeName) = oldTypeName;
154 // Fake type back to what was in field
155 const_cast<word&>(meshObject.type()) = io.headerClassName();
156
157 Info<< " Writing " << name << endl;
158
159 // Force writing as ASCII
160 writeOk = meshObject.regIOobject::writeObject
161 (
163 true
164 );
165 }
166
167 return writeOk;
168}
169
170
171// Reduction for non-empty strings.
172template<class StringType>
173struct uniqueEqOp
174{
175 void operator()(List<StringType>& x, const List<StringType>& y) const
176 {
177 List<StringType> newX(x.size()+y.size());
178 label n = 0;
179 forAll(x, i)
180 {
181 if (!x[i].empty())
182 {
183 newX[n++] = x[i];
184 }
185 }
186 forAll(y, i)
187 {
188 if (!y[i].empty() && !x.found(y[i]))
189 {
190 newX[n++] = y[i];
191 }
192 }
193 newX.setSize(n);
194 x.transfer(newX);
195 }
196};
197
198
199template<class Type>
200bool writeOptionalMeshObject
201(
202 const word& name,
203 const fileName& meshDir,
204 Time& runTime,
205 bool writeOnProc
206)
207{
209 (
210 name,
211 runTime.timeName(),
212 meshDir,
213 runTime,
217 );
218
219 // Check if available and the correct type.
220 // Done as typeHeaderOk<regIOobject> + isHeaderClass to ensure
221 // local-only reading and circumvent is_globalIOobject<Type> check
222 // in typeHeaderOk<Type>
223
224 bool readOnProc =
225 (
226 io.typeHeaderOk<regIOobject>(false)
227 && io.isHeaderClass<Type>()
228 );
229
230 bool writeOk = false;
231
232 if (returnReduceOr(readOnProc))
233 {
234 Info<< " Reading " << Type::typeName << " : " << name << endl;
235 Type meshObject(io, readOnProc && writeOnProc);
236
237 Info<< " Writing " << name << endl;
238 writeOk = meshObject.regIOobject::write(readOnProc && writeOnProc);
239 }
240
241 return writeOk;
242}
243
244
245int main(int argc, char *argv[])
246{
248 (
249 "Converts all IOobjects associated with a case into the format"
250 " specified in the controlDict"
251 );
254 (
255 "noConstant",
256 "Exclude the 'constant/' dir in the times list"
257 );
259 (
260 "enableFunctionEntries",
261 "Enable expansion of dictionary directives - #include, #codeStream etc"
262 );
263
264 #include "addRegionOption.H"
265 #include "setRootCase.H"
266
267 // enable noConstant by switching
268 if (!args.found("noConstant"))
269 {
270 args.setOption("constant");
271 }
272 else
273 {
274 args.unsetOption("constant");
275 Info<< "Excluding the constant directory." << nl << endl;
276 }
277
278
279 #include "createTime.H"
280 // Optional mesh (used to read Clouds)
282
283 const bool enableEntries = args.found("enableFunctionEntries");
284 if (enableEntries)
285 {
286 Info<< "Allowing dictionary preprocessing ('#include', '#codeStream')."
287 << endl;
288 }
289
290 const int oldFlag = entry::disableFunctionEntries;
291 if (!enableEntries)
292 {
293 // By default disable dictionary expansion for fields
295 }
296
297 // Make sure we do not use the master-only reading since we read
298 // fields (different per processor) as dictionaries.
300
301
302 // Specified region or default region
303 #include "getRegionOption.H"
304 if (!polyMesh::regionName(regionName).empty())
305 {
306 Info<< "Using region " << regionName << nl << endl;
307 }
308
309 const fileName meshDir
310 (
312 );
313
314
316
317 forAll(timeDirs, timeI)
318 {
319 runTime.setTime(timeDirs[timeI], timeI);
320 Info<< "Time = " << runTime.timeName() << endl;
321
322 // Convert all the standard mesh files
324 (
325 "cells",
326 meshDir,
327 runTime,
328 false // do not check typeName since varies between binary/ascii
329 );
330 writeMeshObject<labelIOList>("owner", meshDir, runTime);
331 writeMeshObject<labelIOList>("neighbour", meshDir, runTime);
333 (
334 "faces",
335 meshDir,
336 runTime,
337 false // do not check typeName since varies between binary/ascii
338 );
339 writeMeshObject<pointIOField>("points", meshDir, runTime);
340 // Write boundary in ascii. This is only needed for fileHandler to
341 // kick in. Should not give problems since always writing ascii.
342 writeZones("boundary", meshDir, runTime, IOstreamOption::UNCOMPRESSED);
343 writeMeshObject<labelIOList>("pointProcAddressing", meshDir, runTime);
344 writeMeshObject<labelIOList>("faceProcAddressing", meshDir, runTime);
345 writeMeshObject<labelIOList>("cellProcAddressing", meshDir, runTime);
347 (
348 "boundaryProcAddressing",
349 meshDir,
350 runTime
351 );
352
353 // foamyHexMesh vertices
355 (
356 "internalDelaunayVertices",
358 runTime
359 );
360
361 if (runTime.writeFormat() == IOstreamOption::ASCII)
362 {
363 // Only do zones when converting from binary to ascii
364 // The other way gives problems since working on dictionary level.
365 const IOstreamOption::compressionType compress =
366 runTime.writeCompression();
367 writeZones("cellZones", meshDir, runTime, compress);
368 writeZones("faceZones", meshDir, runTime, compress);
369 writeZones("pointZones", meshDir, runTime, compress);
370 }
371
372 // Get list of objects from the database
373 IOobjectList objects
374 (
375 runTime,
376 runTime.timeName(),
378 );
379
380 forAllConstIters(objects, iter)
381 {
382 const IOobject& io = *(iter.val());
383
384 if
385 (
386 Foam::fieldTypes::is_volume(io.headerClassName())
387 || Foam::fieldTypes::is_internal(io.headerClassName())
388 || Foam::fieldTypes::is_surface(io.headerClassName())
389 || Foam::fieldTypes::is_point(io.headerClassName())
390 )
391 {
392 Info<< " Reading " << io.headerClassName()
393 << " : " << io.name() << endl;
394
395 fieldDictionary fDict(io, io.headerClassName());
396
397 Info<< " Writing " << io.name() << endl;
398 fDict.regIOobject::write();
399 }
400 }
401
402
403 // Check for lagrangian
404 fileNameList lagrangianDirs
405 (
406 1,
407 fileHandler().filePath
408 (
409 runTime.timePath()
412 )
413 );
414
415 Pstream::combineReduce(lagrangianDirs, uniqueEqOp<fileName>());
416
417 if (!lagrangianDirs.empty())
418 {
419 if (meshPtr)
420 {
421 meshPtr->readUpdate();
422 }
423 else
424 {
425 Info<< " Create polyMesh for time = "
426 << runTime.timeName() << endl;
427
428 meshPtr.reset
429 (
430 new polyMesh
431 (
433 (
435 runTime.timeName(),
436 runTime,
438 )
439 )
440 );
441 }
442
443 const auto& mesh = meshPtr();
444
445 fileNameList cloudDirs
446 (
448 (
449 lagrangianDirs[0],
451 )
452 );
453
454 Pstream::combineReduce(cloudDirs, uniqueEqOp<fileName>());
455
456 for (const auto& cloudDir : cloudDirs)
457 {
458 fileName dir(cloud::prefix/cloudDir);
459
460 // Read with origProcId,origId fields
461 passiveParticleCloud parcels(mesh, cloudDir, true);
462
463 const bool writeOnProc = parcels.size();
464
465 parcels.writeObject
466 (
468 (
469 runTime.writeFormat(),
470 runTime.writeCompression()
471 ),
472 writeOnProc
473 );
474
475
476 // Do local scan for valid cloud objects
477 wordList cloudFields
478 (
479 IOobjectList(runTime, runTime.timeName(), dir).sortedNames()
480 );
481
482 // Combine with all other cloud objects
483 Pstream::combineReduce(cloudFields, uniqueEqOp<word>());
484
485 for (const word& name : cloudFields)
486 {
487 // These ones already done by cloud itself
488 if
489 (
490 name == "positions"
491 || name == "coordinates"
492 || name == "origProcId"
493 || name == "origId"
494 )
495 {
496 continue;
497 }
498
499 #undef doLocalCode
500 #define doLocalCode(Type) \
501 if \
502 ( \
503 writeOptionalMeshObject<Type> \
504 ( \
505 name, dir, runTime, writeOnProc \
506 ) \
507 ) \
508 { \
509 continue; \
510 }
511
518
521
522 #undef doLocalCode
523
524 Info<< " Failed converting " << name << endl;
525 }
526 }
527 }
528
529 Info<< endl;
530 }
531
533
534 Info<< "End\n" << endl;
535
536 return 0;
537}
538
539
540// ************************************************************************* //
scalar y
label n
Required Classes.
A PtrList of objects of type <T> with automated input and output.
Definition IOPtrList.H:53
List of IOobjects with searching and retrieving facilities. Implemented as a HashTable,...
wordList sortedNames() const
The sorted names of the IOobjects.
@ NO_REGISTER
Do not request registration (bool: false).
@ MUST_READ
Reading required.
@ NO_WRITE
Ignore writing from objectRegistry::writeObject().
Defines the attributes of an object for which implicit objectRegistry management is supported,...
Definition IOobject.H:191
static fileCheckTypes fileModificationChecking
Type of file modification checking.
Definition IOobject.H:358
A simple container for options an IOstream can normally have.
@ ASCII
"ascii" (normal default)
compressionType
Compression treatment (UNCOMPRESSED | COMPRESSED).
@ UNCOMPRESSED
compression = false
static void combineReduce(T &value, CombineOp cop, const int tag=UPstream::msgType(), const int communicator=UPstream::worldComm)
Reduce inplace (cf. MPI Allreduce) applying cop to inplace combine value from different processors.
Class to control time during OpenFOAM simulations that is also the top-level objectRegistry.
Definition Time.H:75
static void addBoolOption(const word &optName, const string &usage="", bool advanced=false)
Add a bool option to validOptions with usage information.
Definition argList.C:389
static void addNote(const string &note)
Add extra notes for the usage information.
Definition argList.C:477
Pointer management similar to std::unique_ptr, with some additional methods and type checking.
Definition autoPtr.H:65
static const word prefix
The prefix to local: lagrangian.
Definition cloud.H:79
A list of keyword definitions, which are a keyword followed by a number of values (eg,...
Definition dictionary.H:133
ITstream & lookup(const word &keyword, enum keyType::option matchOpt=keyType::REGEX) const
Find and return an entry data stream. FatalIOError if not found, or not a stream.
Definition dictionary.C:367
bool found(const word &keyword, enum keyType::option matchOpt=keyType::REGEX) const
Find an entry (const access) with the given keyword.
entry * set(entry *entryPtr)
Assign a new entry, overwriting any existing entry.
Definition dictionary.C:765
A keyword and a list of tokens is an 'entry'.
Definition entry.H:66
static int disableFunctionEntries
Enable or disable use of function entries and variable expansions.
Definition entry.H:139
Read field as dictionary (without mesh).
A class for handling file names.
Definition fileName.H:75
@ DIRECTORY
A directory.
Definition fileName.H:85
The meshObject is a concrete regIOobject to register MeshObject items.
Definition MeshObject.H:93
A Cloud of passive particles.
Mesh consisting of general polyhedral cells.
Definition polyMesh.H:79
static const word & regionName(const word &region)
The mesh region name or word::null if polyMesh::defaultRegion.
Definition polyMesh.C:796
static word defaultRegion
Return the default region name.
Definition polyMesh.H:406
fileName meshDir() const
Return the local mesh directory (dbDir()/meshSubDir).
Definition polyMesh.C:826
regIOobject is an abstract class derived from IOobject to handle automatic object registration with t...
Definition regIOobject.H:71
static void addOptions(const bool constant=true, const bool withZero=false)
Add timeSelector options to argList::validOptions.
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...
A class for handling words, derived from Foam::string.
Definition word.H:66
static const word null
An empty word.
Definition word.H:84
#define defineTemplateTypeNameAndDebug(Type, DebugSwitch)
Define the typeName and debug information for templates, useful.
Definition className.H:158
dynamicFvMesh & mesh
engineTime & runTime
Foam::autoPtr< Foam::dynamicFvMesh > meshPtr
Foam::word regionName(args.getOrDefault< word >("region", Foam::polyMesh::defaultRegion))
const auto & io
#define doLocalCode(FieldType, Variable)
auto & name
Required Classes.
bool is_volume(const word &clsName)
Test if the class name appears to be a volume field.
Definition volFields.C:165
bool is_surface(const word &clsName)
Test if the class name appears to be a surface field.
bool is_point(const word &clsName)
Test if the class name appears to be a point field.
Definition pointFields.C:94
bool is_internal(const word &clsName)
Test if the class name appears to be a volume internal field.
Definition volFields.C:155
Namespace for OpenFOAM.
IOField< symmTensor > symmTensorIOField
IO for a Field of symmTensor.
List< word > wordList
List of word.
Definition fileName.H:60
bool returnReduceOr(const bool value, const int communicator=UPstream::worldComm)
Perform logical (or) MPI Allreduce on a copy. Uses UPstream::reduceOr.
List< label > labelList
A List of labels.
Definition List.H:62
List< fileName > fileNameList
List of fileName.
refPtr< fileOperation > fileHandler(std::nullptr_t)
Delete current file handler - forwards to fileOperation::handler().
messageStream Info
Information stream (stdout output on master, null elsewhere).
List< instant > instantList
List of instants.
Definition instantList.H:41
IOField< vectorField > vectorFieldIOField
IO for a Field of vectorField.
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition Ostream.H:519
ZoneMesh< cellZone, polyMesh > cellZoneMesh
A ZoneMesh with cellZone content on a polyMesh.
IOField< labelField > labelFieldIOField
IO for a Field of labelField.
bool writeMeshObject(const word &name, const fileName &meshDir, Time &runTime, const bool strictTypeChecking=true, const bool disableHeaderChecking=false)
IOField< sphericalTensor > sphericalTensorIOField
IO for a Field of sphericalTensor.
List< bool > boolList
A List of bools.
Definition List.H:60
IOField< label > labelIOField
IO for a Field of label.
IOField< vector > vectorIOField
IO for a Field of vector.
IOField< tensor > tensorIOField
IO for a Field of tensor.
IOField< scalar > scalarIOField
IO for a Field of scalar.
fileNameList readDir(const fileName &directory, const fileName::Type type=fileName::Type::FILE, const bool filtergz=true, const bool followLink=true)
Read a directory and return the entries as a fileName List.
Definition POSIX.C:965
constexpr char nl
The newline '\n' character (0x0a).
Definition Ostream.H:50
Foam::argList args(argc, argv)
volScalarField & e
#define forAll(list, i)
Loop across all elements in list.
Definition stdFoam.H:299
#define forAllConstIters(container, iter)
Iterate across all elements of the container object with const access.
Definition stdFoam.H:235
Foam::surfaceFields.
Write a mesh object in the format specified in controlDict.