TimeIO.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 | Copyright (C) 2011-2017 OpenFOAM Foundation
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8 License
9  This file is part of OpenFOAM.
10 
11  OpenFOAM is free software: you can redistribute it and/or modify it
12  under the terms of the GNU General Public License as published by
13  the Free Software Foundation, either version 3 of the License, or
14  (at your option) any later version.
15 
16  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
17  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19  for more details.
20 
21  You should have received a copy of the GNU General Public License
22  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
23 
24 \*---------------------------------------------------------------------------*/
25 
26 #include "Time.H"
27 #include "Pstream.H"
28 #include "simpleObjectRegistry.H"
29 #include "dimensionedConstants.H"
30 #include "IOdictionary.H"
31 #include "fileOperation.H"
32 
33 // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
34 
36 {
37  word application;
38  if (controlDict_.readIfPresent("application", application))
39  {
40  // Do not override if already set so external application can override
41  setEnv("FOAM_APPLICATION", application, false);
42  }
43 
44 
45  // Check for local switches and settings
46  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47 
48  // Debug switches
49  if (controlDict_.found("DebugSwitches"))
50  {
51  Info<< "Overriding DebugSwitches according to " << controlDict_.name()
52  << endl;
53 
55  const dictionary& localSettings = controlDict_.subDict("DebugSwitches");
56  forAllConstIter(dictionary, localSettings, iter)
57  {
58  const word& name = iter().keyword();
59 
60  simpleObjectRegistryEntry* objPtr = objects.lookupPtr(name);
61 
62  if (objPtr)
63  {
64  Info<< " " << iter() << endl;
65 
66  const List<simpleRegIOobject*>& objects = *objPtr;
67 
68  if (iter().isDict())
69  {
70  forAll(objects, i)
71  {
73  os << iter().dict();
74  IStringStream is(os.str());
75  objects[i]->readData(is);
76  }
77  }
78  else
79  {
80  forAll(objects, i)
81  {
82  objects[i]->readData(iter().stream());
83  }
84  }
85  }
86  }
87  }
88 
89  // Optimisation Switches
90  if (controlDict_.found("OptimisationSwitches"))
91  {
92  Info<< "Overriding OptimisationSwitches according to "
93  << controlDict_.name() << endl;
94 
96  const dictionary& localSettings = controlDict_.subDict
97  (
98  "OptimisationSwitches"
99  );
100  forAllConstIter(dictionary, localSettings, iter)
101  {
102  const word& name = iter().keyword();
103 
104  simpleObjectRegistryEntry* objPtr = objects.lookupPtr(name);
105 
106  if (objPtr)
107  {
108  Info<< " " << iter() << endl;
109 
110  const List<simpleRegIOobject*>& objects = *objPtr;
111 
112  if (iter().isDict())
113  {
114  forAll(objects, i)
115  {
117  os << iter().dict();
118  IStringStream is(os.str());
119  objects[i]->readData(is);
120  }
121  }
122  else
123  {
124  forAll(objects, i)
125  {
126  objects[i]->readData(iter().stream());
127  }
128  }
129  }
130  }
131 
132 
133  // Handle fileHandler override explicitly since interacts with
134  // local dictionary monitoring.
135  word fileHandlerName;
136  if
137  (
138  localSettings.readIfPresent("fileHandler", fileHandlerName)
139  && fileHandler().type() != fileHandlerName
140  )
141  {
142  // Remove the old watches since destroying the file
143  fileNameList oldWatchedFiles(controlDict_.watchIndices());
144  forAllReverse(controlDict_.watchIndices(), i)
145  {
146  label watchi = controlDict_.watchIndices()[i];
147  oldWatchedFiles[i] = fileHandler().getFile(watchi);
148  fileHandler().removeWatch(watchi);
149  }
150  controlDict_.watchIndices().clear();
151 
152  // Installing the new handler
153  Info<< "Overriding fileHandler to " << fileHandlerName << endl;
154 
155  autoPtr<fileOperation> handler
156  (
158  (
159  fileHandlerName,
160  true
161  )
162  );
163  Foam::fileHandler(handler);
164 
165  // Reinstall old watches
166  fileHandler().addWatches(controlDict_, oldWatchedFiles);
167  }
168  }
169 
170 
171  // DimensionedConstants. Handled as a special case since both e.g.
172  // the 'unitSet' might be changed and the individual values
173  if (controlDict_.found("DimensionedConstants"))
174  {
175  Info<< "Overriding DimensionedConstants according to "
176  << controlDict_.name() << endl;
177 
178  // Change in-memory
180  (
181  controlDict_.subDict("DimensionedConstants")
182  );
183 
184 
186 
187  IStringStream dummyIs("");
188 
189  forAllConstIter(simpleObjectRegistry, objects, iter)
190  {
191  const List<simpleRegIOobject*>& objects = *iter;
192 
193  forAll(objects, i)
194  {
195  objects[i]->readData(dummyIs);
196 
197  Info<< " ";
198  objects[i]->writeData(Info);
199  Info<< endl;
200  }
201  }
202  }
203 
204 
205  // Dimension sets
206  if (controlDict_.found("DimensionSets"))
207  {
208  Info<< "Overriding DimensionSets according to "
209  << controlDict_.name() << endl;
210 
212  dict.merge(controlDict_.subDict("DimensionSets"));
213 
215 
216  simpleObjectRegistryEntry* objPtr = objects.lookupPtr("DimensionSets");
217 
218  if (objPtr)
219  {
220  Info<< controlDict_.subDict("DimensionSets") << endl;
221 
222  const List<simpleRegIOobject*>& objects = *objPtr;
223 
224  forAll(objects, i)
225  {
227  os << dict;
228  IStringStream is(os.str());
229  objects[i]->readData(is);
230  }
231  }
232  }
233 
234 
235  if (!deltaTchanged_)
236  {
237  deltaT_ = readScalar(controlDict_.lookup("deltaT"));
238  }
239 
240  if (controlDict_.found("writeControl"))
241  {
243  (
244  controlDict_.lookup("writeControl")
245  );
246  }
247 
248  scalar oldWriteInterval = writeInterval_;
249 
250  if (controlDict_.readIfPresent("writeInterval", writeInterval_))
251  {
253  {
254  FatalIOErrorInFunction(controlDict_)
255  << "writeInterval < 1 for writeControl timeStep"
256  << exit(FatalIOError);
257  }
258  }
259  else
260  {
261  controlDict_.lookup("writeFrequency") >> writeInterval_;
262  }
263 
264 
265  if (oldWriteInterval != writeInterval_)
266  {
267  switch (writeControl_)
268  {
269  case wcRunTime:
270  case wcAdjustableRunTime:
271  // Recalculate writeTimeIndex_ to be in units of current
272  // writeInterval.
274  (
276  * oldWriteInterval
278  );
279  break;
280 
281  default:
282  break;
283  }
284  }
285 
286  if (controlDict_.readIfPresent("purgeWrite", purgeWrite_))
287  {
288  if (purgeWrite_ < 0)
289  {
291  << "invalid value for purgeWrite " << purgeWrite_
292  << ", should be >= 0, setting to 0"
293  << endl;
294 
295  purgeWrite_ = 0;
296  }
297  }
298 
299  if (controlDict_.found("timeFormat"))
300  {
301  const word formatName(controlDict_.lookup("timeFormat"));
302 
303  if (formatName == "general")
304  {
305  format_ = general;
306  }
307  else if (formatName == "fixed")
308  {
309  format_ = fixed;
310  }
311  else if (formatName == "scientific")
312  {
314  }
315  else
316  {
318  << "unsupported time format " << formatName
319  << endl;
320  }
321  }
322 
323  controlDict_.readIfPresent("timePrecision", precision_);
324 
325  // stopAt at 'endTime' or a specified value
326  // if nothing is specified, the endTime is zero
327  if (controlDict_.found("stopAt"))
328  {
329  stopAt_ = stopAtControlNames_.read(controlDict_.lookup("stopAt"));
330 
331  if (stopAt_ == saEndTime)
332  {
333  controlDict_.lookup("endTime") >> endTime_;
334  }
335  else
336  {
337  endTime_ = GREAT;
338  }
339  }
340  else if (!controlDict_.readIfPresent("endTime", endTime_))
341  {
342  endTime_ = 0;
343  }
344 
346 
347  if (controlDict_.found("writeVersion"))
348  {
349  writeVersion_ = IOstream::versionNumber
350  (
351  controlDict_.lookup("writeVersion")
352  );
353  }
354 
355  if (controlDict_.found("writeFormat"))
356  {
357  writeFormat_ = IOstream::formatEnum
358  (
359  controlDict_.lookup("writeFormat")
360  );
361  }
362 
363  if (controlDict_.found("writePrecision"))
364  {
366  (
367  readUint(controlDict_.lookup("writePrecision"))
368  );
369 
372 
375 
376  FatalError().precision(IOstream::defaultPrecision());
377  FatalIOError.error::operator()().precision
378  (
380  );
381  }
382 
383  if (controlDict_.found("writeCompression"))
384  {
385  writeCompression_ = IOstream::compressionEnum
386  (
387  controlDict_.lookup("writeCompression")
388  );
389 
390  if
391  (
392  writeFormat_ == IOstream::BINARY
393  && writeCompression_ == IOstream::COMPRESSED
394  )
395  {
396  IOWarningInFunction(controlDict_)
397  << "Selecting compressed binary is inefficient and ineffective"
398  ", resetting to uncompressed binary"
399  << endl;
400 
401  writeCompression_ = IOstream::UNCOMPRESSED;
402  }
403  }
404 
405  controlDict_.readIfPresent("graphFormat", graphFormat_);
406  controlDict_.readIfPresent("runTimeModifiable", runTimeModifiable_);
407 
408 
409 
410 
411  if (!runTimeModifiable_ && controlDict_.watchIndices().size())
412  {
413  forAllReverse(controlDict_.watchIndices(), i)
414  {
415  fileHandler().removeWatch(controlDict_.watchIndices()[i]);
416  }
417  controlDict_.watchIndices().clear();
418  }
419 }
420 
421 
423 {
424  if (controlDict_.regIOobject::read())
425  {
426  readDict();
427 
428  if (runTimeModifiable_)
429  {
430  // For IOdictionary the call to regIOobject::read() would have
431  // already updated all the watchIndices via the addWatch but
432  // controlDict_ is an unwatchedIOdictionary so will only have
433  // stored the dependencies as files.
434  fileHandler().addWatches(controlDict_, controlDict_.files());
435  }
436  controlDict_.files().clear();
437 
438  return true;
439  }
440  else
441  {
442  return false;
443  }
444 }
445 
446 
448 {
449  if (runTimeModifiable_)
450  {
451  // Get state of all monitored objects (=registered objects with a
452  // valid filePath).
453  // Note: requires same ordering in objectRegistries on different
454  // processors!
456  (
457  (
460  ),
462  );
463 
464  // Time handling is special since controlDict_ is the one dictionary
465  // that is not registered to any database.
466 
467  if (controlDict_.readIfModified())
468  {
469  readDict();
470  functionObjects_.read();
471 
472  if (runTimeModifiable_)
473  {
474  // For IOdictionary the call to regIOobject::read() would have
475  // already updated all the watchIndices via the addWatch but
476  // controlDict_ is an unwatchedIOdictionary so will only have
477  // stored the dependencies as files.
478 
479  fileHandler().addWatches(controlDict_, controlDict_.files());
480  }
481  controlDict_.files().clear();
482  }
483 
484  bool registryModified = objectRegistry::modified();
485 
486  if (registryModified)
487  {
489  }
490  }
491 }
492 
493 
495 {
496  const word tmName(timeName());
497 
498  IOdictionary timeDict
499  (
500  IOobject
501  (
502  "time",
503  tmName,
504  "uniform",
505  *this,
508  false
509  )
510  );
511 
512  timeDict.add("value", timeName(timeToUserTime(value()), maxPrecision_));
513  timeDict.add("name", string(tmName));
514  timeDict.add("index", timeIndex_);
515  timeDict.add("deltaT", timeToUserTime(deltaT_));
516  timeDict.add("deltaT0", timeToUserTime(deltaT0_));
517 
518  return timeDict.regIOobject::writeObject
519  (
523  true
524  );
525 }
526 
527 
529 (
533  const bool valid
534 ) const
535 {
536  if (writeTime())
537  {
538  bool writeOK = writeTimeDict();
539 
540  if (writeOK)
541  {
542  writeOK = objectRegistry::writeObject(fmt, ver, cmp, valid);
543  }
544 
545  if (writeOK)
546  {
547  // Does the writeTime trigger purging?
548  if (writeTime_ && purgeWrite_)
549  {
551 
552  while (previousWriteTimes_.size() > purgeWrite_)
553  {
555  }
556  }
557  }
558 
559  return writeOK;
560  }
561  else
562  {
563  return false;
564  }
565 }
566 
567 
569 {
570  writeTime_ = true;
571  return write();
572 }
573 
574 
576 {
578  endTime_ = value();
579 
580  return writeNow();
581 }
582 
583 
585 {
586  writeOnce_ = true;
587 }
588 
589 
590 // ************************************************************************* //
bool read()
Read and set the function objects if their data have changed.
dictionary dict
bool found(const word &, bool recursive=false, bool patternMatch=true) const
Search dictionary for given keyword.
Definition: dictionary.C:431
#define forAll(list, i)
Loop across all elements in list.
Definition: UList.H:428
static streamFormat formatEnum(const word &)
Return stream format of given format name.
Definition: IOstream.C:39
intWM_LABEL_SIZE_t label
A label is an int32_t or int64_t as specified by the pre-processor macro WM_LABEL_SIZE.
Definition: label.H:59
scalar deltaT_
Definition: TimeState.H:56
static compressionType compressionEnum(const word &)
Return compression of given compression name.
Definition: IOstream.C:61
virtual bool writeObject(IOstream::streamFormat fmt, IOstream::versionNumber ver, IOstream::compressionType cmp, const bool valid) const
Write the objects.
bool writeAndEnd()
Write the objects now (not at end of iteration) and end the run.
Definition: TimeIO.C:575
stopAtControls stopAt_
Definition: Time.H:124
errorManipArg< error, int > exit(error &err, const int errNo=1)
Definition: errorManip.H:124
void readModifiedObjects()
Read the objects that have been modified.
virtual int precision() const
Get precision of output field.
Definition: OSstream.C:285
Dictionary reading and supplying the dimensioned constants used within OpenFOAM, particularly for the...
error FatalError
A list of keyword definitions, which are a keyword followed by any number of values (e...
Definition: dictionary.H:137
set endTime to stop immediately w/ writing
Definition: Time.H:102
scalar writeInterval_
Definition: Time.H:129
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bound...
Definition: HashTable.H:60
static unsigned int defaultPrecision()
Return the default precision.
Definition: IOstream.H:461
void size(const label)
Override size to be inconsistent with allocated storage.
Definition: ListI.H:163
virtual bool modified() const
Return true if any of the object&#39;s files have been modified.
static fmtflags format_
Time directory name format.
Definition: Time.H:154
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition: Ostream.H:253
#define forAllReverse(list, i)
Reverse loop across all elements in list.
Definition: UList.H:440
const labelList & watchIndices() const
Return file-monitoring handles.
Definition: regIOobjectI.H:91
const T * lookupPtr(const word &) const
Find and return an entry if present, otherwise return nullptr.
simpleObjectRegistry & debugObjects()
Get access to registered debug switch objects.
Definition: debug.C:328
writeControls writeControl_
Definition: Time.H:127
virtual word timeName() const
Return current time name.
Definition: Time.C:654
label writeTimeIndex_
Definition: TimeState.H:60
dictionary & dimensionedConstants()
simpleObjectRegistry & optimisationObjects()
Get access to registered optimisation switch objects.
Definition: debug.C:350
bool add(entry *, bool mergeEntry=false)
Add a new entry.
Definition: dictionary.C:814
virtual fileName::Type type(const fileName &, const bool followLink=true) const =0
Return the file type: DIRECTORY, FILE or LINK.
static const int maxPrecision_
Maximum time directory name precision.
Definition: Time.H:160
fileName path() const
Return complete path.
Definition: IOobject.C:385
IOdictionary is derived from dictionary and IOobject to give the dictionary automatic IO functionalit...
Definition: IOdictionary.H:52
static autoPtr< fileOperation > New(const word &type, const bool verbose)
Select type.
const dictionary & subDict(const word &) const
Find and return a sub-dictionary.
Definition: dictionary.C:692
virtual scalar timeToUserTime(const scalar t) const
Convert the real-time (s) into user-time (e.g. CA deg)
Definition: TimeState.C:58
virtual bool writeTimeDict() const
Write time dictionary to the <time>/uniform directory.
Definition: TimeIO.C:494
bool writeTime() const
Return true if this is a write time.
Definition: TimeStateI.H:65
scalar deltaT0_
Definition: TimeState.H:58
virtual void updateStates(const bool masterOnly, const bool syncPar) const
Update state of all files.
label purgeWrite_
Definition: Time.H:131
static const NamedEnum< stopAtControls, 4 > stopAtControlNames_
Definition: Time.H:123
const fileNameList & files() const
static int precision_
Time directory name precision.
Definition: Time.H:157
void clear()
Clear the list, i.e. set size to zero.
Definition: ListI.H:124
A class for handling words, derived from string.
Definition: word.H:59
virtual bool readIfModified()
Read object if modified (as set by call to modified)
virtual fileName getFile(const label) const
Get name of file being watched (using handle)
const scalar & value() const
Return const reference to value.
bool readIfPresent(const word &, T &, bool recursive=false, bool patternMatch=true) const
Find an entry if present, and assign to T.
streamFormat
Enumeration for the format of data in the stream.
Definition: IOstream.H:86
virtual void addWatches(regIOobject &, const fileNameList &) const
Helper: add watches for list of regIOobjects.
scalar endTime_
Definition: Time.H:121
const fileOperation & fileHandler()
Get current file handler.
bool readScalar(const char *buf, doubleScalar &s)
Read whole of buf as a scalar. Return true if succesful.
Definition: doubleScalar.H:63
const word & name() const
Name function is needed to disambiguate those inherited.
OSstream Sout(cout, "Sout")
Definition: IOstreams.H:51
forAllConstIter(PtrDictionary< phaseModel >, mixture.phases(), phase)
Definition: pEqn.H:29
compressionType
Enumeration for the format of data in the stream.
Definition: IOstream.H:193
bool rmDir(const fileName &)
Remove a dirctory and its contents.
Definition: POSIX.C:1008
FIFOStack< word > previousWriteTimes_
Definition: Time.H:132
virtual void readDict()
Read the control dictionary and set the write controls etc.
Definition: TimeIO.C:35
static fileCheckTypes fileModificationChecking
Type of file modification checking.
Definition: IOobject.H:208
prefixOSstream Perr(cerr, "Perr")
Definition: IOstreams.H:54
const word & name() const
Return const reference to name.
static const NamedEnum< writeControls, 5 > writeControlNames_
Definition: Time.H:126
void readModifiedObjects()
Read the objects that have been modified.
Definition: TimeIO.C:447
simpleObjectRegistry & dimensionSetObjects()
Get access to registered dimensionSets switch objects.
Definition: debug.C:361
bool deltaTchanged_
Definition: TimeState.H:59
void writeOnce()
Write the objects once (one shot) and continue the run.
Definition: TimeIO.C:584
unsigned int readUint(Istream &)
Definition: uintIO.C:31
dictionary & dimensionSystems()
Top level dictionary.
Definition: dimensionSets.C:79
static bool & parRun()
Is this a parallel run?
Definition: UPstream.H:394
virtual bool read()
Read control dictionary, update controls and time.
Definition: TimeIO.C:422
#define WarningInFunction
Report a warning using Foam::Warning.
static const versionNumber currentVersion
Current version number.
Definition: IOstream.H:206
#define FatalIOErrorInFunction(ios)
Report an error message using Foam::FatalIOError.
Definition: error.H:331
Object registry for simpleRegIOobject. Maintains ordering.
stop when Time reaches the prescribed endTime
Definition: Time.H:100
bool writeOnce_
Definition: Time.H:135
Input from memory buffer stream.
Definition: IStringStream.H:49
prefixOSstream Pout(cout, "Pout")
Definition: IOstreams.H:53
simpleObjectRegistry & dimensionedConstantObjects()
Get access to registered dimensionedConstant switch objects.
Definition: debug.C:372
string str() const
Return the string.
Version number type.
Definition: IOstream.H:96
OSstream Serr(cerr, "Serr")
Definition: IOstreams.H:52
messageStream Info
bool merge(const dictionary &)
Merge entries from the given dictionary.
Definition: dictionary.C:1090
Enum read(Istream &) const
Read a word from Istream and return the corresponding.
Definition: NamedEnum.C:61
virtual bool writeObject(IOstream::streamFormat, IOstream::versionNumber, IOstream::compressionType, const bool valid) const
Write using given format, version and compression.
Definition: TimeIO.C:529
#define IOWarningInFunction(ios)
Report an IO warning using Foam::Warning.
An auto-pointer similar to the STL auto_ptr but with automatic casting to a reference to the type and...
Definition: PtrList.H:52
virtual bool write(const bool valid=true) const
Write using setting from DB.
IOobject defines the attributes of an object for which implicit objectRegistry management is supporte...
Definition: IOobject.H:92
Output to memory buffer stream.
Definition: OStringStream.H:49
bool setEnv(const word &name, const std::string &value, const bool overwrite)
Set an environment variable.
Definition: POSIX.C:122
bool writeNow()
Write the objects now (not at end of iteration) and continue.
Definition: TimeIO.C:568
virtual bool removeWatch(const label) const
Remove watch on a file (using handle)
ITstream & lookup(const word &, bool recursive=false, bool patternMatch=true) const
Find and return an entry data stream.
Definition: dictionary.C:576
label timeIndex_
Definition: TimeState.H:55
IOerror FatalIOError