Time.C 32 KB
Newer Older
Henry's avatar
Henry committed
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
5
    \\  /    A nd           | Copyright (C) 2011-2016 OpenFOAM Foundation
6
     \\/     M anipulation  | Copyright (C) 2015-2017 OpenCFD Ltd.
Henry's avatar
Henry committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "Time.H"
#include "PstreamReduceOps.H"
#include "argList.H"
29
#include "HashSet.H"
mark's avatar
mark committed
30
#include "profiling.H"
Henry's avatar
Henry committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

#include <sstream>

// * * * * * * * * * * * * * Static Member Data  * * * * * * * * * * * * * * //

namespace Foam
{
    defineTypeNameAndDebug(Time, 0);

    template<>
    const char* Foam::NamedEnum
    <
        Foam::Time::stopAtControls,
        4
    >::names[] =
    {
        "endTime",
        "noWriteNow",
        "writeNow",
        "nextWrite"
    };

    template<>
    const char* Foam::NamedEnum
    <
        Foam::Time::writeControls,
        5
    >::names[] =
    {
        "timeStep",
        "runTime",
        "adjustableRunTime",
        "clockTime",
        "cpuTime"
    };
}

const Foam::NamedEnum<Foam::Time::stopAtControls, 4>
    Foam::Time::stopAtControlNames_;

const Foam::NamedEnum<Foam::Time::writeControls, 5>
    Foam::Time::writeControlNames_;

Foam::Time::fmtflags Foam::Time::format_(Foam::Time::general);
75

Henry's avatar
Henry committed
76
77
int Foam::Time::precision_(6);

78
79
const int Foam::Time::maxPrecision_(3 - log10(SMALL));

Henry's avatar
Henry committed
80
81
82
Foam::word Foam::Time::controlDictName("controlDict");


Henry Weller's avatar
Henry Weller committed
83
// * * * * * * * * * * * * Protected Member Functions  * * * * * * * * * * * //
Henry's avatar
Henry committed
84
85
86
87
88
89
90
91
92
93
94
95

void Foam::Time::adjustDeltaT()
{
    bool adjustTime = false;
    scalar timeToNextWrite = VGREAT;

    if (writeControl_ == wcAdjustableRunTime)
    {
        adjustTime = true;
        timeToNextWrite = max
        (
            0.0,
96
            (writeTimeIndex_ + 1)*writeInterval_ - (value() - startTime_)
Henry's avatar
Henry committed
97
98
99
100
101
        );
    }

    if (adjustTime)
    {
102
        scalar nSteps = timeToNextWrite/deltaT_;
Henry's avatar
Henry committed
103
104
105
106

        // For tiny deltaT the label can overflow!
        if (nSteps < labelMax)
        {
107
108
            // nSteps can be < 1 so make sure at least 1
            label nStepsToNextWrite = max(1, round(nSteps));
Henry's avatar
Henry committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

            scalar newDeltaT = timeToNextWrite/nStepsToNextWrite;

            // Control the increase of the time step to within a factor of 2
            // and the decrease within a factor of 5.
            if (newDeltaT >= deltaT_)
            {
                deltaT_ = min(newDeltaT, 2.0*deltaT_);
            }
            else
            {
                deltaT_ = max(newDeltaT, 0.2*deltaT_);
            }
        }
    }

    functionObjects_.adjustTimeStep();
}


void Foam::Time::setControls()
{
    // default is to resume calculation from "latestTime"
    const word startFrom = controlDict_.lookupOrDefault<word>
    (
        "startFrom",
        "latestTime"
    );

    if (startFrom == "startTime")
    {
        controlDict_.lookup("startTime") >> startTime_;
    }
    else
    {
        // Search directory for valid time directories
        instantList timeDirs = findTimes(path(), constant());

        if (startFrom == "firstTime")
        {
            if (timeDirs.size())
            {
                if (timeDirs[0].name() == constant() && timeDirs.size() >= 2)
                {
                    startTime_ = timeDirs[1].value();
                }
                else
                {
                    startTime_ = timeDirs[0].value();
                }
            }
        }
        else if (startFrom == "latestTime")
        {
            if (timeDirs.size())
            {
                startTime_ = timeDirs.last().value();
            }
        }
        else
        {
170
            FatalIOErrorInFunction(controlDict_)
Henry's avatar
Henry committed
171
172
173
174
175
176
177
178
179
180
181
182
                << "expected startTime, firstTime or latestTime"
                << " found '" << startFrom << "'"
                << exit(FatalIOError);
        }
    }

    setTime(startTime_, 0);

    readDict();
    deltaTSave_ = deltaT_;
    deltaT0_ = deltaT_;

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
    // Check if time directory exists
    // If not increase time precision to see if it is formatted differently.
    if (!exists(timePath(), false))
    {
        int oldPrecision = precision_;
        int requiredPrecision = -1;
        bool found = false;
        for
        (
            precision_ = maxPrecision_;
            precision_ > oldPrecision;
            precision_--
        )
        {
            // Update the time formatting
            setTime(startTime_, 0);

            // Check the existence of the time directory with the new format
            found = exists(timePath(), false);

            if (found)
            {
                requiredPrecision = precision_;
            }
        }

        if (requiredPrecision > 0)
        {
            // Update the time precision
            precision_ = requiredPrecision;

            // Update the time formatting
            setTime(startTime_, 0);

217
            WarningInFunction
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
                << "Increasing the timePrecision from " << oldPrecision
                << " to " << precision_
                << " to support the formatting of the current time directory "
                << timeName() << nl << endl;
        }
        else
        {
            // Could not find time directory so assume it is not present
            precision_ = oldPrecision;

            // Revert the time formatting
            setTime(startTime_, 0);
        }
    }

Henry's avatar
Henry committed
233
234
235
236
237
238
239
240
241
242
    if (Pstream::parRun())
    {
        scalar sumStartTime = startTime_;
        reduce(sumStartTime, sumOp<scalar>());
        if
        (
            mag(Pstream::nProcs()*startTime_ - sumStartTime)
          > Pstream::nProcs()*deltaT_/10.0
        )
        {
243
            FatalIOErrorInFunction(controlDict_)
Henry's avatar
Henry committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
                << "Start time is not the same for all processors" << nl
                << "processor " << Pstream::myProcNo() << " has startTime "
                << startTime_ << exit(FatalIOError);
        }
    }

    IOdictionary timeDict
    (
        IOobject
        (
            "time",
            timeName(),
            "uniform",
            *this,
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE,
            false
        )
    );

    // Read and set the deltaT only if time-step adjustment is active
    // otherwise use the deltaT from the controlDict
    if (controlDict_.lookupOrDefault<Switch>("adjustTimeStep", false))
    {
        if (timeDict.readIfPresent("deltaT", deltaT_))
        {
            deltaTSave_ = deltaT_;
            deltaT0_ = deltaT_;
        }
    }

    timeDict.readIfPresent("deltaT0", deltaT0_);

    if (timeDict.readIfPresent("index", startTimeIndex_))
    {
        timeIndex_ = startTimeIndex_;
    }


    // Check if values stored in time dictionary are consistent

    // 1. Based on time name
    bool checkValue = true;

    string storedTimeName;
    if (timeDict.readIfPresent("name", storedTimeName))
    {
        if (storedTimeName == timeName())
        {
            // Same time. No need to check stored value
            checkValue = false;
        }
    }

    // 2. Based on time value
    //    (consistent up to the current time writing precision so it won't
    //     trigger if we just change the write precision)
    if (checkValue)
    {
        scalar storedTimeValue;
        if (timeDict.readIfPresent("value", storedTimeValue))
        {
            word storedTimeName(timeName(storedTimeValue));

            if (storedTimeName != timeName())
            {
310
                IOWarningInFunction(timeDict)
Henry's avatar
Henry committed
311
312
313
314
315
316
317
318
319
320
321
322
323
                    << "Time read from time dictionary " << storedTimeName
                    << " differs from actual time " << timeName() << '.' << nl
                    << "    This may cause unexpected database behaviour."
                    << " If you are not interested" << nl
                    << "    in preserving time state delete"
                    << " the time dictionary."
                    << endl;
            }
        }
    }
}


324
void Foam::Time::setMonitoring(const bool forceProfiling)
325
{
326
    const dictionary* profilingDict = controlDict_.subDictPtr("profiling");
327
328
329
330
331
    if (!profilingDict)
    {
        // ... or from etc/controlDict
        profilingDict = debug::controlDict().subDictPtr("profiling");
    }
332

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
    // initialize profiling on request
    // otherwise rely on profiling entry within controlDict
    // and skip if 'active' keyword is explicitly set to false
    if (forceProfiling)
    {
        profiling::initialize
        (
            IOobject
            (
                "profiling",
                timeName(),
                "uniform",
                *this,
                IOobject::NO_READ,
                IOobject::AUTO_WRITE
            ),
            *this
        );
    }
    else if
353
354
355
356
    (
        profilingDict
     && profilingDict->lookupOrDefault<Switch>("active", true)
    )
357
    {
mark's avatar
mark committed
358
        profiling::initialize
359
        (
360
            *profilingDict,
361
362
363
364
365
366
367
368
369
370
371
372
373
            IOobject
            (
                "profiling",
                timeName(),
                "uniform",
                *this,
                IOobject::NO_READ,
                IOobject::AUTO_WRITE
            ),
            *this
        );
    }

374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
    // Time objects not registered so do like objectRegistry::checkIn ourselves.
    if (runTimeModifiable_)
    {
        monitorPtr_.reset
        (
            new fileMonitor
            (
                regIOobject::fileModificationChecking == inotify
             || regIOobject::fileModificationChecking == inotifyMaster
            )
        );

        // Monitor all files that controlDict depends on
        addWatches(controlDict_, controlDict_.files());
    }

    // Clear dependent files - not needed now
    controlDict_.files().clear();
}


Henry's avatar
Henry committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::Time::Time
(
    const word& controlDictName,
    const fileName& rootPath,
    const fileName& caseName,
    const word& systemName,
    const word& constantName,
    const bool enableFunctionObjects
)
:
    TimePaths
    (
        rootPath,
        caseName,
        systemName,
        constantName
    ),

    objectRegistry(*this),

    libs_(),

    controlDict_
    (
        IOobject
        (
            controlDictName,
            system(),
            *this,
            IOobject::MUST_READ_IF_MODIFIED,
            IOobject::NO_WRITE,
            false
        )
    ),

    startTimeIndex_(0),
    startTime_(0),
    endTime_(0),

    stopAt_(saEndTime),
    writeControl_(wcTimeStep),
    writeInterval_(GREAT),
    purgeWrite_(0),
    writeOnce_(false),
    subCycling_(false),
    sigWriteNow_(true, *this),
    sigStopAtWriteNow_(true, *this),

    writeFormat_(IOstream::ASCII),
    writeVersion_(IOstream::currentVersion),
    writeCompression_(IOstream::UNCOMPRESSED),
    graphFormat_("raw"),
    runTimeModifiable_(false),

    functionObjects_(*this, enableFunctionObjects)
{
    libs_.open(controlDict_, "libs");

    // Explicitly set read flags on objectRegistry so anything constructed
    // from it reads as well (e.g. fvSolution).
    readOpt() = IOobject::MUST_READ_IF_MODIFIED;

    setControls();
460
    setMonitoring();
Henry's avatar
Henry committed
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
}


Foam::Time::Time
(
    const word& controlDictName,
    const argList& args,
    const word& systemName,
    const word& constantName
)
:
    TimePaths
    (
        args.parRunControl().parRun(),
        args.rootPath(),
476
        args.distributed(),
Henry's avatar
Henry committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
        args.globalCaseName(),
        args.caseName(),
        systemName,
        constantName
    ),

    objectRegistry(*this),

    libs_(),

    controlDict_
    (
        IOobject
        (
            controlDictName,
            system(),
            *this,
            IOobject::MUST_READ_IF_MODIFIED,
            IOobject::NO_WRITE,
            false
        )
    ),

    startTimeIndex_(0),
    startTime_(0),
    endTime_(0),

    stopAt_(saEndTime),
    writeControl_(wcTimeStep),
    writeInterval_(GREAT),
    purgeWrite_(0),
    writeOnce_(false),
    subCycling_(false),
    sigWriteNow_(true, *this),
    sigStopAtWriteNow_(true, *this),

    writeFormat_(IOstream::ASCII),
    writeVersion_(IOstream::currentVersion),
    writeCompression_(IOstream::UNCOMPRESSED),
    graphFormat_("raw"),
    runTimeModifiable_(false),

519
520
521
522
523
    functionObjects_
    (
        *this,
        argList::validOptions.found("withFunctionObjects")
      ? args.optionFound("withFunctionObjects")
524
525
526
      : argList::validOptions.found("noFunctionObjects")
      ? !args.optionFound("noFunctionObjects")
      : false
527
    )
Henry's avatar
Henry committed
528
529
530
531
532
533
534
535
{
    libs_.open(controlDict_, "libs");

    // Explicitly set read flags on objectRegistry so anything constructed
    // from it reads as well (e.g. fvSolution).
    readOpt() = IOobject::MUST_READ_IF_MODIFIED;

    setControls();
536
537
538

    // '-profiling' = force profiling, ignore controlDict entry
    setMonitoring(args.optionFound("profiling"));
Henry's avatar
Henry committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
}


Foam::Time::Time
(
    const dictionary& dict,
    const fileName& rootPath,
    const fileName& caseName,
    const word& systemName,
    const word& constantName,
    const bool enableFunctionObjects
)
:
    TimePaths
    (
        rootPath,
        caseName,
        systemName,
        constantName
    ),

    objectRegistry(*this),

    libs_(),

    controlDict_
    (
        IOobject
        (
            controlDictName,
            system(),
            *this,
            IOobject::NO_READ,
            IOobject::NO_WRITE,
            false
        ),
        dict
    ),

    startTimeIndex_(0),
    startTime_(0),
    endTime_(0),

    stopAt_(saEndTime),
    writeControl_(wcTimeStep),
    writeInterval_(GREAT),
    purgeWrite_(0),
    writeOnce_(false),
    subCycling_(false),
    sigWriteNow_(true, *this),
    sigStopAtWriteNow_(true, *this),

    writeFormat_(IOstream::ASCII),
    writeVersion_(IOstream::currentVersion),
    writeCompression_(IOstream::UNCOMPRESSED),
    graphFormat_("raw"),
    runTimeModifiable_(false),

    functionObjects_(*this, enableFunctionObjects)
{
    libs_.open(controlDict_, "libs");

    // Explicitly set read flags on objectRegistry so anything constructed
    // from it reads as well (e.g. fvSolution).
    readOpt() = IOobject::MUST_READ_IF_MODIFIED;

    // Since could not construct regIOobject with setting:
    controlDict_.readOpt() = IOobject::MUST_READ_IF_MODIFIED;

    setControls();
609
    setMonitoring();
Henry's avatar
Henry committed
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
}


Foam::Time::Time
(
    const fileName& rootPath,
    const fileName& caseName,
    const word& systemName,
    const word& constantName,
    const bool enableFunctionObjects
)
:
    TimePaths
    (
        rootPath,
        caseName,
        systemName,
        constantName
    ),

    objectRegistry(*this),

    libs_(),

    controlDict_
    (
        IOobject
        (
            controlDictName,
            system(),
            *this,
            IOobject::NO_READ,
            IOobject::NO_WRITE,
            false
        )
    ),

    startTimeIndex_(0),
    startTime_(0),
    endTime_(0),

    stopAt_(saEndTime),
    writeControl_(wcTimeStep),
    writeInterval_(GREAT),
    purgeWrite_(0),
    writeOnce_(false),
    subCycling_(false),

    writeFormat_(IOstream::ASCII),
    writeVersion_(IOstream::currentVersion),
    writeCompression_(IOstream::UNCOMPRESSED),
    graphFormat_("raw"),
    runTimeModifiable_(false),

    functionObjects_(*this, enableFunctionObjects)
{
    libs_.open(controlDict_, "libs");
667
    setMonitoring(); // for profiling etc
Henry's avatar
Henry committed
668
669
670
671
672
673
674
}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::Time::~Time()
{
675
    forAllReverse(controlDict_.watchIndices(), i)
Henry's avatar
Henry committed
676
    {
677
        removeWatch(controlDict_.watchIndices()[i]);
Henry's avatar
Henry committed
678
679
    }

680
    // Destroy function objects first
Henry's avatar
Henry committed
681
    functionObjects_.clear();
682

683
    // Clean up profiling
mark's avatar
mark committed
684
    profiling::stop(*this);
Henry's avatar
Henry committed
685
686
687
688
689
}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
void Foam::Time::addWatches(regIOobject& rio, const fileNameList& files) const
{
    const labelList& watchIndices = rio.watchIndices();

    DynamicList<label> newWatchIndices;
    labelHashSet removedWatches(watchIndices);

    forAll(files, i)
    {
        const fileName& f = files[i];
        label index = findWatch(watchIndices, f);

        if (index == -1)
        {
            newWatchIndices.append(addTimeWatch(f));
        }
        else
        {
            // Existing watch
            newWatchIndices.append(watchIndices[index]);
            removedWatches.erase(index);
        }
    }

    // Remove any unused watches
    forAllConstIter(labelHashSet, removedWatches, iter)
    {
        removeWatch(watchIndices[iter.key()]);
    }

    rio.watchIndices() = newWatchIndices;
}


Foam::label Foam::Time::findWatch
(
    const labelList& watchIndices,
    const fileName& fName
) const
{
    forAll(watchIndices, i)
    {
        if (getFile(watchIndices[i]) == fName)
        {
            return i;
        }
    }
    return -1;
}


Foam::label Foam::Time::addTimeWatch(const fileName& fName) const
Henry's avatar
Henry committed
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
{
    return monitorPtr_().addWatch(fName);
}


bool Foam::Time::removeWatch(const label watchIndex) const
{
    return monitorPtr_().removeWatch(watchIndex);
}

const Foam::fileName& Foam::Time::getFile(const label watchIndex) const
{
    return monitorPtr_().getFile(watchIndex);
}


758
Foam::fileMonitor::fileState Foam::Time::getState(const label watchIndex) const
Henry's avatar
Henry committed
759
{
760
    return monitorPtr_().getState(watchIndex);
Henry's avatar
Henry committed
761
762
763
}


764
void Foam::Time::setUnmodified(const label watchIndex) const
Henry's avatar
Henry committed
765
{
766
    monitorPtr_().setUnmodified(watchIndex);
Henry's avatar
Henry committed
767
768
769
}


770
Foam::word Foam::Time::timeName(const scalar t, const int precision)
Henry's avatar
Henry committed
771
772
773
{
    std::ostringstream buf;
    buf.setf(ios_base::fmtflags(format_), ios_base::floatfield);
774
    buf.precision(precision);
Henry's avatar
Henry committed
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    buf << t;
    return buf.str();
}


Foam::word Foam::Time::timeName() const
{
    return dimensionedScalar::name();
}


Foam::instantList Foam::Time::times() const
{
    return findTimes(path(), constant());
}


792
793
794
795
796
Foam::word Foam::Time::findInstancePath
(
    const fileName& directory,
    const instant& t
) const
Henry's avatar
Henry committed
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
{
    // Read directory entries into a list
    fileNameList dirEntries(readDir(directory, fileName::DIRECTORY));

    forAll(dirEntries, i)
    {
        scalar timeValue;
        if (readScalar(dirEntries[i].c_str(), timeValue) && t.equal(timeValue))
        {
            return dirEntries[i];
        }
    }

    if (t.equal(0.0))
    {
812
813
        const word& constantName = constant();

Henry's avatar
Henry committed
814
815
816
817
818
819
820
821
822
823
824
        // Looking for 0 or constant. 0 already checked above.
        if (isDir(directory/constantName))
        {
            return constantName;
        }
    }

    return word::null;
}


825
826
827
828
829
830
Foam::word Foam::Time::findInstancePath(const instant& t) const
{
    return findInstancePath(path(), t);
}


Henry's avatar
Henry committed
831
832
833
834
Foam::instant Foam::Time::findClosestTime(const scalar t) const
{
    instantList timeDirs = findTimes(path(), constant());

835
    // There is only one time (likely "constant") so return it
Henry's avatar
Henry committed
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
    if (timeDirs.size() == 1)
    {
        return timeDirs[0];
    }

    if (t < timeDirs[1].value())
    {
        return timeDirs[1];
    }
    else if (t > timeDirs.last().value())
    {
        return timeDirs.last();
    }

    label nearestIndex = -1;
    scalar deltaT = GREAT;

853
    for (label timei=1; timei < timeDirs.size(); ++timei)
Henry's avatar
Henry committed
854
    {
855
        scalar diff = mag(timeDirs[timei].value() - t);
Henry's avatar
Henry committed
856
857
858
        if (diff < deltaT)
        {
            deltaT = diff;
859
            nearestIndex = timei;
Henry's avatar
Henry committed
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
        }
    }

    return timeDirs[nearestIndex];
}


Foam::label Foam::Time::findClosestTimeIndex
(
    const instantList& timeDirs,
    const scalar t,
    const word& constantName
)
{
    label nearestIndex = -1;
    scalar deltaT = GREAT;

877
    forAll(timeDirs, timei)
Henry's avatar
Henry committed
878
    {
879
        if (timeDirs[timei].name() == constantName) continue;
Henry's avatar
Henry committed
880

881
        scalar diff = mag(timeDirs[timei].value() - t);
Henry's avatar
Henry committed
882
883
884
        if (diff < deltaT)
        {
            deltaT = diff;
885
            nearestIndex = timei;
Henry's avatar
Henry committed
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
        }
    }

    return nearestIndex;
}


Foam::label Foam::Time::startTimeIndex() const
{
    return startTimeIndex_;
}


Foam::dimensionedScalar Foam::Time::startTime() const
{
    return dimensionedScalar("startTime", dimTime, startTime_);
}


Foam::dimensionedScalar Foam::Time::endTime() const
{
    return dimensionedScalar("endTime", dimTime, endTime_);
}


bool Foam::Time::run() const
{
913
    bool isRunning = value() < (endTime_ - 0.5*deltaT_);
Henry's avatar
Henry committed
914
915
916

    if (!subCycling_)
    {
917
        // Only execute when the condition is no longer true
Henry's avatar
Henry committed
918
        // ie, when exiting the control loop
919
        if (!isRunning && timeIndex_ != startTimeIndex_)
Henry's avatar
Henry committed
920
        {
921
922
            // Ensure functionObjects execute on last time step
            // (and hence write uptodate functionObjectProperties)
923
            addProfiling(foExec, "functionObjects.execute()");
924
            functionObjects_.execute();
925
            endProfiling(foExec);
926

927
            addProfiling(foEnd, "functionObjects.end()");
Henry's avatar
Henry committed
928
            functionObjects_.end();
929
            endProfiling(foEnd);
Henry's avatar
Henry committed
930
931
932
        }
    }

933
    if (isRunning)
Henry's avatar
Henry committed
934
935
936
937
938
939
940
    {
        if (!subCycling_)
        {
            const_cast<Time&>(*this).readModifiedObjects();

            if (timeIndex_ == startTimeIndex_)
            {
941
                addProfiling(functionObjects, "functionObjects.start()");
Henry's avatar
Henry committed
942
943
944
945
                functionObjects_.start();
            }
            else
            {
946
                addProfiling(functionObjects, "functionObjects.execute()");
Henry's avatar
Henry committed
947
948
                functionObjects_.execute();
            }
949
950
951
952
953
954
955
956
957
958
959

            // Check if the execution of functionObjects require re-reading
            // any files. This moves effect of e.g. 'timeActivatedFileUpdate'
            // one time step forward. Note that we cannot call
            // readModifiedObjects from within timeActivatedFileUpdate since
            // it might re-read the functionObjects themselves (and delete
            // the timeActivatedFileUpdate one)
            if (functionObjects_.filesModified())
            {
                const_cast<Time&>(*this).readModifiedObjects();
            }
Henry's avatar
Henry committed
960
961
        }

962
        // Update the "is-running" status following the
Henry's avatar
Henry committed
963
        // possible side-effects from functionObjects
964
        isRunning = value() < (endTime_ - 0.5*deltaT_);
Henry's avatar
Henry committed
965
966
    }

967
    return isRunning;
Henry's avatar
Henry committed
968
969
970
971
972
}


bool Foam::Time::loop()
{
973
    const bool isRunning = run();
Henry's avatar
Henry committed
974

975
    if (isRunning)
Henry's avatar
Henry committed
976
977
978
979
    {
        operator++();
    }

980
    return isRunning;
Henry's avatar
Henry committed
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
}


bool Foam::Time::end() const
{
    return value() > (endTime_ + 0.5*deltaT_);
}


bool Foam::Time::stopAt(const stopAtControls sa) const
{
    const bool changed = (stopAt_ != sa);
    stopAt_ = sa;

    // adjust endTime
    if (sa == saEndTime)
    {
        controlDict_.lookup("endTime") >> endTime_;
    }
    else
    {
        endTime_ = GREAT;
    }
    return changed;
}


void Foam::Time::setTime(const Time& t)
{
    value() = t.value();
    dimensionedScalar::name() = t.dimensionedScalar::name();
    timeIndex_ = t.timeIndex_;
}


void Foam::Time::setTime(const instant& inst, const label newIndex)
{
    value() = inst.value();
    dimensionedScalar::name() = inst.name();
    timeIndex_ = newIndex;

    IOdictionary timeDict
    (
        IOobject
        (
            "time",
            timeName(),
            "uniform",
            *this,
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE,
            false
        )
    );

    timeDict.readIfPresent("deltaT", deltaT_);
    timeDict.readIfPresent("deltaT0", deltaT0_);
    timeDict.readIfPresent("index", timeIndex_);
}


void Foam::Time::setTime(const dimensionedScalar& newTime, const label newIndex)
{
    setTime(newTime.value(), newIndex);
}


void Foam::Time::setTime(const scalar newTime, const label newIndex)
{
    value() = newTime;
    dimensionedScalar::name() = timeName(timeToUserTime(newTime));
    timeIndex_ = newIndex;
}


void Foam::Time::setEndTime(const dimensionedScalar& endTime)
{
    setEndTime(endTime.value());
}


void Foam::Time::setEndTime(const scalar endTime)
{
    endTime_ = endTime;
}


void Foam::Time::setDeltaT
(
    const dimensionedScalar& deltaT,
1071
    const bool adjust
Henry's avatar
Henry committed
1072
1073
)
{
1074
    setDeltaT(deltaT.value(), adjust);
Henry's avatar
Henry committed
1075
1076
1077
}


1078
void Foam::Time::setDeltaT(const scalar deltaT, const bool adjust)
Henry's avatar
Henry committed
1079
1080
1081
1082
{
    deltaT_ = deltaT;
    deltaTchanged_ = true;

1083
    if (adjust)
Henry's avatar
Henry committed
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
    {
        adjustDeltaT();
    }
}


Foam::TimeState Foam::Time::subCycle(const label nSubCycles)
{
    subCycling_ = true;
    prevTimeState_.set(new TimeState(*this));

    setTime(*this - deltaT(), (timeIndex() - 1)*nSubCycles);
    deltaT_ /= nSubCycles;
    deltaT0_ /= nSubCycles;
    deltaTSave_ = deltaT0_;

    return prevTimeState();
}


void Foam::Time::endSubCycle()
{
    if (subCycling_)
    {
        subCycling_ = false;
        TimeState::operator=(prevTimeState());
        prevTimeState_.clear();
    }
}


// * * * * * * * * * * * * * * * Member Operators  * * * * * * * * * * * * * //

Foam::Time& Foam::Time::operator+=(const dimensionedScalar& deltaT)
{
    return operator+=(deltaT.value());
}


Foam::Time& Foam::Time::operator+=(const scalar deltaT)
{
    setDeltaT(deltaT);
    return operator++();
}


Foam::Time& Foam::Time::operator++()
{
    deltaT0_ = deltaTSave_;
    deltaTSave_ = deltaT_;

1135
    // Save old time value and name
1136
    const scalar oldTimeValue = timeToUserTime(value());
Henry's avatar
Henry committed
1137
1138
    const word oldTimeName = dimensionedScalar::name();

1139
    // Increment time
Henry's avatar
Henry committed
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
    setTime(value() + deltaT_, timeIndex_ + 1);

    if (!subCycling_)
    {
        // If the time is very close to zero reset to zero
        if (mag(value()) < 10*SMALL*deltaT_)
        {
            setTime(0.0, timeIndex_);
        }

        if (sigStopAtWriteNow_.active() || sigWriteNow_.active())
        {
            // A signal might have been sent on one processor only
            // Reduce so all decide the same.

            label flag = 0;
            if (sigStopAtWriteNow_.active() && stopAt_ == saWriteNow)
            {
                flag += 1;
            }
            if (sigWriteNow_.active() && writeOnce_)
            {
                flag += 2;
            }
            reduce(flag, maxOp<label>());

            if (flag & 1)
            {
                stopAt_ = saWriteNow;
            }
            if (flag & 2)
            {
                writeOnce_ = true;
            }
        }

1176
        writeTime_ = false;
Henry's avatar
Henry committed
1177
1178
1179
1180

        switch (writeControl_)
        {
            case wcTimeStep:
1181
                writeTime_ = !(timeIndex_ % label(writeInterval_));
Henry's avatar
Henry committed
1182
1183
1184
1185
1186
            break;

            case wcRunTime:
            case wcAdjustableRunTime:
            {
1187
                label writeIndex = label
Henry's avatar
Henry committed
1188
1189
1190
1191
1192
                (
                    ((value() - startTime_) + 0.5*deltaT_)
                  / writeInterval_
                );

1193
                if (writeIndex > writeTimeIndex_)
Henry's avatar
Henry committed
1194
                {
1195
1196
                    writeTime_ = true;
                    writeTimeIndex_ = writeIndex;
Henry's avatar
Henry committed
1197
1198
1199
1200
1201
1202
                }
            }
            break;

            case wcCpuTime:
            {
1203
                label writeIndex = label
Henry's avatar
Henry committed
1204
1205
1206
1207
                (
                    returnReduce(elapsedCpuTime(), maxOp<double>())
                  / writeInterval_
                );
1208
                if (writeIndex > writeTimeIndex_)
Henry's avatar
Henry committed
1209
                {
1210
1211
                    writeTime_ = true;
                    writeTimeIndex_ = writeIndex;
Henry's avatar
Henry committed
1212
1213
1214
1215
1216
1217
                }
            }
            break;

            case wcClockTime:
            {
1218
                label writeIndex = label
Henry's avatar
Henry committed
1219
1220
1221
1222
                (
                    returnReduce(label(elapsedClockTime()), maxOp<label>())
                  / writeInterval_
                );
1223
                if (writeIndex > writeTimeIndex_)
Henry's avatar
Henry committed
1224
                {
1225
1226
                    writeTime_ = true;
                    writeTimeIndex_ = writeIndex;
Henry's avatar
Henry committed
1227
1228
1229
1230
1231
1232
                }
            }
            break;
        }


1233
        // Check if endTime needs adjustment to stop at the next run()/end()
Henry's avatar
Henry committed
1234
1235
1236
1237
1238
1239
1240
1241
1242
        if (!end())
        {
            if (stopAt_ == saNoWriteNow)
            {
                endTime_ = value();
            }
            else if (stopAt_ == saWriteNow)
            {
                endTime_ = value();
1243
                writeTime_ = true;
Henry's avatar
Henry committed
1244
            }
1245
            else if (stopAt_ == saNextWrite && writeTime_ == true)
Henry's avatar
Henry committed
1246
1247
1248
1249
1250
            {
                endTime_ = value();
            }
        }

1251
        // Override writeTime if one-shot writing
Henry's avatar
Henry committed
1252
1253
        if (writeOnce_)
        {
1254
            writeTime_ = true;
Henry's avatar
Henry committed
1255
1256
1257
            writeOnce_ = false;
        }

1258
        // Adjust the precision of the time directory name if necessary
1259
        if (writeTime_)
1260
1261
        {
            // Tolerance used when testing time equivalence
1262
            const scalar timeTol =
1263
1264
                max(min(pow(10.0, -precision_), 0.1*deltaT_), SMALL);

1265
1266
1267
1268
1269
1270
            // User-time equivalent of deltaT
            const scalar userDeltaT = timeToUserTime(deltaT_);

            // Time value obtained by reading timeName
            scalar timeNameValue = -VGREAT;

1271
1272
1273
1274
1275
            // Check that new time representation differs from old one
            // reinterpretation of the word
            if
            (
                readScalar(dimensionedScalar::name().c_str(), timeNameValue)
1276
             && (mag(timeNameValue - oldTimeValue - userDeltaT) > timeTol)
1277
1278
1279
1280
1281
1282
1283
            )
            {
                int oldPrecision = precision_;
                while
                (
                    precision_ < maxPrecision_
                 && readScalar(dimensionedScalar::name().c_str(), timeNameValue)
1284
                 && (mag(timeNameValue - oldTimeValue - userDeltaT) > timeTol)
1285
1286
1287
1288
1289
1290
1291
1292
                )
                {
                    precision_++;
                    setTime(value(), timeIndex());
                }

                if (precision_ != oldPrecision)
                {
1293
                    WarningInFunction
1294
1295
1296
1297
1298
1299
1300
1301
1302
                        << "Increased the timePrecision from " << oldPrecision
                        << " to " << precision_
                        << " to distinguish between timeNames at time "
                        << dimensionedScalar::name()
                        << endl;

                    if (precision_ == maxPrecision_)
                    {
                        // Reached maxPrecision limit
1303
                        WarningInFunction
1304
1305
                            << "Current time name " << dimensionedScalar::name()
                            << nl
1306
1307
1308
                            << "    The maximum time precision has been reached"
                               " which might result in overwriting previous"
                               " results."
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
                            << endl;
                    }

                    // Check if round-off error caused time-reversal
                    scalar oldTimeNameValue = -VGREAT;
                    if
                    (
                        readScalar(oldTimeName.c_str(), oldTimeNameValue)
                     && (
                            sign(timeNameValue - oldTimeNameValue)
                         != sign(deltaT_)
                        )
                    )
                    {
1323
                        WarningInFunction
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
                            << "Current time name " << dimensionedScalar::name()
                            << " is set to an instance prior to the "
                               "previous one "
                            << oldTimeName << nl
                            << "    This might result in temporal "
                               "discontinuities."
                            << endl;
                    }
                }
            }
        }
Henry's avatar
Henry committed
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
    }

    return *this;
}


Foam::Time& Foam::Time::operator++(int)
{
    return operator++();
}


// ************************************************************************* //