-
Notifications
You must be signed in to change notification settings - Fork 472
Expand file tree
/
Copy pathUtilityRoutines.cc
More file actions
1822 lines (1571 loc) · 80.3 KB
/
UtilityRoutines.cc
File metadata and controls
1822 lines (1571 loc) · 80.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
170
171
172
173
174
175
176
177
178
179
180
181
182
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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
609
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// EnergyPlus, Copyright (c) 1996-present, The Board of Trustees of the University of Illinois,
// The Regents of the University of California, through Lawrence Berkeley National Laboratory
// (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge
// National Laboratory, managed by UT-Battelle, Alliance for Energy Innovation, LLC, and other
// contributors. All rights reserved.
//
// NOTICE: This Software was developed under funding from the U.S. Department of Energy and the
// U.S. Government consequently retains certain rights. As such, the U.S. Government has been
// granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable,
// worldwide license in the Software to reproduce, distribute copies to the public, prepare
// derivative works, and perform publicly and display publicly, and to permit others to do so.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory,
// the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form
// without changes from the version obtained under this License, or (ii) Licensee makes a
// reference solely to the software portion of its product, Licensee must refer to the
// software as "EnergyPlus version X" software, where "X" is the version number Licensee
// obtained under this License and may not use a different name for the software. Except as
// specifically required in this Section (4), Licensee shall not use in a company name, a
// product name, in advertising, publicity, or other promotional activities any name, trade
// name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly
// similar designation, without the U.S. Department of Energy's prior written consent.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// FMI-Related Headers
extern "C" {
#include <FMI/main.h>
}
// C++ Headers
#include <cstdlib>
#include <iostream>
// ObjexxFCL Headers
#include <ObjexxFCL/Array1D.hh>
#include <ObjexxFCL/Array1S.hh>
#include <ObjexxFCL/char.functions.hh>
#include <ObjexxFCL/string.functions.hh>
// EnergyPlus Headers
#include <EnergyPlus/BranchInputManager.hh>
#include <EnergyPlus/BranchNodeConnections.hh>
#include <EnergyPlus/DataEnvironment.hh>
#include <EnergyPlus/DataErrorTracking.hh>
#include <EnergyPlus/DataReportingFlags.hh>
#include <EnergyPlus/DataStringGlobals.hh>
#include <EnergyPlus/DataSystemVariables.hh>
#include <EnergyPlus/DaylightingManager.hh>
#include <EnergyPlus/ExternalInterface.hh>
#include <EnergyPlus/FileSystem.hh>
#include <EnergyPlus/General.hh>
#include <EnergyPlus/GeneralRoutines.hh>
#include <EnergyPlus/NodeInputManager.hh>
#include <EnergyPlus/OutputReports.hh>
#include <EnergyPlus/Plant/PlantManager.hh>
#include <EnergyPlus/ResultsFramework.hh>
#include <EnergyPlus/SQLiteProcedures.hh>
#include <EnergyPlus/SimulationManager.hh>
#include <EnergyPlus/SolarShading.hh>
#include <EnergyPlus/SystemReports.hh>
#include <EnergyPlus/Timer.hh>
#include <EnergyPlus/UtilityRoutines.hh>
// Third Party Headers
#include <fast_float/fast_float.h>
namespace EnergyPlus {
namespace Util {
Real64 ProcessNumber(std::string_view String, bool &ErrorFlag)
{
// FUNCTION INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS FUNCTION:
// This function processes a string that should be numeric and
// returns the real value of the string.
// METHODOLOGY EMPLOYED:
// FUNCTION ProcessNumber translates the argument (a string)
// into a real number. The string should consist of all
// numeric characters (except a decimal point). Numerics
// with exponentiation (i.e. 1.2345E+03) are allowed but if
// it is not a valid number an error message along with the
// string causing the error is printed out and 0.0 is returned
// as the value.
// REFERENCES:
// List directed Fortran input/output.
// SUBROUTINE PARAMETER DEFINITIONS:
Real64 rProcessNumber = 0.0;
ErrorFlag = false;
if (String.empty()) {
return rProcessNumber;
}
size_t const front_trim = String.find_first_not_of(' ');
size_t const back_trim = String.find_last_not_of(' ');
if (front_trim == std::string::npos || back_trim == std::string::npos) {
return rProcessNumber;
}
String = String.substr(front_trim, back_trim - front_trim + 1);
auto result = fast_float::from_chars(String.data(), String.data() + String.size(), rProcessNumber); // (AUTO_OK_OBJ)
size_t remaining_size = result.ptr - String.data();
if (result.ec == std::errc::result_out_of_range || result.ec == std::errc::invalid_argument) {
rProcessNumber = 0.0;
ErrorFlag = true;
} else if (remaining_size != String.size()) {
if (*result.ptr == '+' || *result.ptr == '-') {
++result.ptr;
remaining_size = result.ptr - String.data();
if (remaining_size == String.size()) {
rProcessNumber = 0.0;
ErrorFlag = true;
}
}
if (*result.ptr == 'd' || *result.ptr == 'D') {
// make FORTRAN floating point number (containing 'd' or 'D')
// standardized by replacing 'd' or 'D' with 'e'
std::string str{String};
std::replace_if(str.begin(), str.end(), [](const char c) { return c == 'D' || c == 'd'; }, 'e');
return ProcessNumber(str, ErrorFlag);
}
if (*result.ptr == 'e' || *result.ptr == 'E') {
++result.ptr;
remaining_size = result.ptr - String.data();
for (size_t i = remaining_size; i < String.size(); ++i, ++result.ptr) {
if (std::isdigit(*result.ptr) == 0) {
rProcessNumber = 0.0;
ErrorFlag = true;
return rProcessNumber;
}
}
} else {
rProcessNumber = 0.0;
ErrorFlag = true;
}
} else if (!std::isfinite(rProcessNumber)) {
rProcessNumber = 0.0;
ErrorFlag = true;
}
return rProcessNumber;
}
int FindItemInList(std::string_view const String, Array1_string const &ListOfItems, int const NumItems)
{
// FUNCTION INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS FUNCTION:
// This function looks up a string in a similar list of
// items and returns the index of the item in the list, if
// found. This routine is not case insensitive and doesn't need
// for most inputs -- they are automatically turned to UPPERCASE.
// If you need case insensitivity use FindItem.
for (int Count = 1; Count <= NumItems; ++Count) {
if (String == ListOfItems(Count)) {
return Count;
}
}
return 0; // Not found
}
int FindItemInList(std::string_view const String, Array1S_string const ListOfItems, int const NumItems)
{
// FUNCTION INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS FUNCTION:
// This function looks up a string in a similar list of
// items and returns the index of the item in the list, if
// found. This routine is not case insensitive and doesn't need
// for most inputs -- they are automatically turned to UPPERCASE.
// If you need case insensitivity use FindItem.
for (int Count = 1; Count <= NumItems; ++Count) {
if (String == ListOfItems(Count)) {
return Count;
}
}
return 0; // Not found
}
int FindItem(std::string_view const String, Array1D_string const &ListOfItems, int const NumItems)
{
// FUNCTION INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN April 1999
// PURPOSE OF THIS FUNCTION:
// This function looks up a string in a similar list of
// items and returns the index of the item in the list, if
// found. This routine is case insensitive.
int FindItem = Util::FindItemInList(String, ListOfItems, NumItems);
if (FindItem != 0) {
return FindItem;
}
for (int Count = 1; Count <= NumItems; ++Count) {
if (equali(String, ListOfItems(Count))) {
return Count;
}
}
return 0; // Not found
}
int FindItem(std::string_view const String, Array1S_string const ListOfItems, int const NumItems)
{
// FUNCTION INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN April 1999
// PURPOSE OF THIS FUNCTION:
// This function looks up a string in a similar list of
// items and returns the index of the item in the list, if
// found. This routine is case insensitive.
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
int FindItem = Util::FindItemInList(String, ListOfItems, NumItems);
if (FindItem != 0) {
return FindItem;
}
for (int Count = 1; Count <= NumItems; ++Count) {
if (equali(String, ListOfItems(Count))) {
return Count;
}
}
return 0; // Not found
}
void setDesignObjectNameAndPointer(EnergyPlusData &state,
std::string &nameToBeSet,
int &ptrToBeSet,
std::string const &userName,
Array1S_string const &listOfNames,
std::string const &itemType,
std::string const &itemName,
bool &errorFound)
{
nameToBeSet = userName;
ptrToBeSet = FindItemInList(nameToBeSet, listOfNames);
// If ptrToBeSet is greater than zero, everything is fine--a valid match was found, continue on.
// If ptrToBeSet is less than or equal to zero, either the user entered a blank or an invalid name. When this
// happens, error out and provide user with some indication as to what the problem was using the type and names
// sent to this routine.
if (ptrToBeSet <= 0) { // No valid pointer--error in user input
errorFound = true;
ShowSevereError(
state, EnergyPlus::format("Object = {} with the Name = {} has an invalid Design Object Name = {}.", itemType, itemName, nameToBeSet));
ShowContinueError(state, " The Design Object Name was not found or was left blank. This is not allowed.");
ShowContinueError(state, EnergyPlus::format(" A valid Design Object Name must be provided for any {} object.", itemType));
}
}
size_t case_insensitive_hasher::operator()(std::string_view const key) const noexcept
{
std::string keyCopy = makeUPPER(key);
return std::hash<std::string>()(keyCopy);
}
bool case_insensitive_comparator::operator()(std::string_view const a, std::string_view const b) const noexcept
{
return lessthani(a, b); // SameString(a, b);
}
void appendPerfLog(EnergyPlusData &state, std::string const &colHeader, std::string const &colValue, bool finalColumn)
// Add column to the performance log file (comma separated) which is appended to existing log.
// The finalColumn (an optional argument) being true triggers the actual file to be written or appended.
// J.Glazer February 2020
{
// the following was added for unit testing to clear the static strings
if (colHeader == "RESET" && colValue == "RESET") {
state.dataUtilityRoutines->appendPerfLog_headerRow = "";
state.dataUtilityRoutines->appendPerfLog_valuesRow = "";
return;
}
// accumulate the row until ready to be written to the file.
state.dataUtilityRoutines->appendPerfLog_headerRow = state.dataUtilityRoutines->appendPerfLog_headerRow + colHeader + ",";
state.dataUtilityRoutines->appendPerfLog_valuesRow = state.dataUtilityRoutines->appendPerfLog_valuesRow + colValue + ",";
if (finalColumn) {
std::fstream fsPerfLog;
if (!FileSystem::fileExists(state.dataStrGlobals->outputPerfLogFilePath)) {
if (state.files.outputControl.perflog) {
fsPerfLog.open(state.dataStrGlobals->outputPerfLogFilePath, std::fstream::out); // open file normally
if (!fsPerfLog) {
ShowFatalError(state,
EnergyPlus::format("appendPerfLog: Could not open file \"{}\" for output (write).",
state.dataStrGlobals->outputPerfLogFilePath));
}
fsPerfLog << state.dataUtilityRoutines->appendPerfLog_headerRow << std::endl;
fsPerfLog << state.dataUtilityRoutines->appendPerfLog_valuesRow << std::endl;
}
} else {
if (state.files.outputControl.perflog) {
fsPerfLog.open(state.dataStrGlobals->outputPerfLogFilePath, std::fstream::app); // append to already existing file
if (!fsPerfLog) {
ShowFatalError(state,
EnergyPlus::format("appendPerfLog: Could not open file \"{}\" for output (append).",
state.dataStrGlobals->outputPerfLogFilePath));
}
fsPerfLog << state.dataUtilityRoutines->appendPerfLog_valuesRow << std::endl;
}
}
fsPerfLog.close();
}
}
} // namespace Util
int AbortEnergyPlus(EnergyPlusData &state)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN December 1997
// PURPOSE OF THIS SUBROUTINE:
// This subroutine causes the program to halt due to a fatal error.
// METHODOLOGY EMPLOYED:
// Puts a message on output files. Closes files. Stops the program.
// SUBROUTINE PARAMETER DEFINITIONS:
std::string NumWarnings;
std::string NumSevere;
std::string NumWarningsDuringWarmup;
std::string NumSevereDuringWarmup;
std::string NumWarningsDuringSizing;
std::string NumSevereDuringSizing;
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->updateSQLiteSimulationRecord(true, false);
}
state.dataErrTracking->AbortProcessing = true;
if (state.dataErrTracking->AskForConnectionsReport) {
state.dataErrTracking->AskForConnectionsReport = false; // Set false here in case any further fatal errors in below processing...
ShowMessage(state, "Fatal error -- final processing. More error messages may appear.");
Node::SetupNodeVarsForReporting(state);
bool ErrFound = false;
bool TerminalError = false;
BranchInputManager::TestBranchIntegrity(state, ErrFound);
if (ErrFound) {
TerminalError = true;
}
TestAirPathIntegrity(state, ErrFound);
if (ErrFound) {
TerminalError = true;
}
Node::CheckMarkedNodes(state, ErrFound);
if (ErrFound) {
TerminalError = true;
}
Node::CheckNodeConnections(state, ErrFound);
if (ErrFound) {
TerminalError = true;
}
Node::TestCompSetInletOutletNodes(state, ErrFound);
if (ErrFound) {
TerminalError = true;
}
if (!TerminalError) {
SystemReports::ReportAirLoopConnections(state);
SimulationManager::ReportLoopConnections(state);
}
} else if (!state.dataErrTracking->ExitDuringSimulations) {
ShowMessage(state, "Warning: Node connection errors not checked - most system input has not been read (see previous warning).");
ShowMessage(state, "Fatal error -- final processing. Program exited before simulations began. See previous error messages.");
}
if (state.dataErrTracking->AskForSurfacesReport) {
ReportSurfaces(state);
}
SolarShading::ReportSurfaceErrors(state);
PlantManager::CheckPlantOnAbort(state);
ShowRecurringErrors(state);
SummarizeErrors(state);
CloseMiscOpenFiles(state);
NumWarnings = fmt::to_string(state.dataErrTracking->TotalWarningErrors);
NumSevere = fmt::to_string(state.dataErrTracking->TotalSevereErrors);
NumWarningsDuringWarmup = fmt::to_string(state.dataErrTracking->TotalWarningErrorsDuringWarmup);
NumSevereDuringWarmup = fmt::to_string(state.dataErrTracking->TotalSevereErrorsDuringWarmup);
NumWarningsDuringSizing = fmt::to_string(state.dataErrTracking->TotalWarningErrorsDuringSizing);
NumSevereDuringSizing = fmt::to_string(state.dataErrTracking->TotalSevereErrorsDuringSizing);
// catch up with timings if in middle
state.dataSysVars->runtimeTimer.tock();
const std::string Elapsed = state.dataSysVars->runtimeTimer.formatAsHourMinSecs();
state.dataResultsFramework->resultsFramework->SimulationInformation.setRunTime(Elapsed);
state.dataResultsFramework->resultsFramework->SimulationInformation.setNumErrorsWarmup(NumWarningsDuringWarmup, NumSevereDuringWarmup);
state.dataResultsFramework->resultsFramework->SimulationInformation.setNumErrorsSizing(NumWarningsDuringSizing, NumSevereDuringSizing);
state.dataResultsFramework->resultsFramework->SimulationInformation.setNumErrorsSummary(NumWarnings, NumSevere);
ShowMessage(state,
EnergyPlus::format(
"EnergyPlus Warmup Error Summary. During Warmup: {} Warning; {} Severe Errors.", NumWarningsDuringWarmup, NumSevereDuringWarmup));
ShowMessage(state,
EnergyPlus::format(
"EnergyPlus Sizing Error Summary. During Sizing: {} Warning; {} Severe Errors.", NumWarningsDuringSizing, NumSevereDuringSizing));
ShowMessage(state,
EnergyPlus::format(
"EnergyPlus Terminated--Fatal Error Detected. {} Warning; {} Severe Errors; Elapsed Time={}", NumWarnings, NumSevere, Elapsed));
DisplayString(state, "EnergyPlus Run Time=" + Elapsed);
{
auto tempfl = state.files.endFile.try_open(state.files.outputControl.end);
if (!tempfl.good()) {
DisplayString(state, fmt::format("AbortEnergyPlus: Could not open file {} for output (write).", tempfl.filePath));
}
print(
tempfl, "EnergyPlus Terminated--Fatal Error Detected. {} Warning; {} Severe Errors; Elapsed Time={}\n", NumWarnings, NumSevere, Elapsed);
}
state.dataResultsFramework->resultsFramework->writeOutputs(state);
std::cerr << "Program terminated: " << "EnergyPlus Terminated--Error(s) Detected." << std::endl;
// Close the socket used by ExternalInterface. This call also sends the flag "-1" to the ExternalInterface,
// indicating that E+ terminated with an error.
if (state.dataExternalInterface->NumExternalInterfaces > 0) {
ExternalInterface::CloseSocket(state, -1);
}
if (state.dataGlobal->eplusRunningViaAPI) {
state.files.flushAll();
}
// The audit file seems to be held open in some cases, make sure it is closed before leaving.
// EnergyPlus can close through two paths: EndEnergyPlus and AbortEnergyPlus, so do the same thing there.
state.files.audit.close();
return EXIT_FAILURE;
}
void CloseMiscOpenFiles(EnergyPlusData &state)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN December 1997
// PURPOSE OF THIS SUBROUTINE:
// This subroutine scans potential unit numbers and closes
// any that are still open.
// METHODOLOGY EMPLOYED:
// Use INQUIRE to determine if file is open.
Dayltg::CloseReportIllumMaps(state);
Dayltg::CloseDFSFile(state);
if (state.dataReportFlag->DebugOutput || (state.files.debug.good() && state.files.debug.position() > 0)) {
state.files.debug.close();
} else {
state.files.debug.del();
}
}
int EndEnergyPlus(EnergyPlusData &state)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN December 1997
// PURPOSE OF THIS SUBROUTINE:
// This subroutine causes the program to terminate when complete (no errors).
// METHODOLOGY EMPLOYED:
// Puts a message on output files. Closes files. Stops the program.
std::string NumWarnings;
std::string NumSevere;
std::string NumWarningsDuringWarmup;
std::string NumSevereDuringWarmup;
std::string NumWarningsDuringSizing;
std::string NumSevereDuringSizing;
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->updateSQLiteSimulationRecord(true, true);
}
SolarShading::ReportSurfaceErrors(state);
ShowRecurringErrors(state);
SummarizeErrors(state);
CloseMiscOpenFiles(state);
NumWarnings = fmt::to_string(state.dataErrTracking->TotalWarningErrors);
strip(NumWarnings);
NumSevere = fmt::to_string(state.dataErrTracking->TotalSevereErrors);
strip(NumSevere);
NumWarningsDuringWarmup = fmt::to_string(state.dataErrTracking->TotalWarningErrorsDuringWarmup);
strip(NumWarningsDuringWarmup);
NumSevereDuringWarmup = fmt::to_string(state.dataErrTracking->TotalSevereErrorsDuringWarmup);
strip(NumSevereDuringWarmup);
NumWarningsDuringSizing = fmt::to_string(state.dataErrTracking->TotalWarningErrorsDuringSizing);
strip(NumWarningsDuringSizing);
NumSevereDuringSizing = fmt::to_string(state.dataErrTracking->TotalSevereErrorsDuringSizing);
strip(NumSevereDuringSizing);
state.dataSysVars->runtimeTimer.tock();
if (state.dataGlobal->createPerfLog) {
Util::appendPerfLog(state, "Run Time [seconds]", EnergyPlus::format("{:.2R}", state.dataSysVars->runtimeTimer.elapsedSeconds()));
}
const std::string Elapsed = state.dataSysVars->runtimeTimer.formatAsHourMinSecs();
state.dataResultsFramework->resultsFramework->SimulationInformation.setRunTime(Elapsed);
state.dataResultsFramework->resultsFramework->SimulationInformation.setNumErrorsWarmup(NumWarningsDuringWarmup, NumSevereDuringWarmup);
state.dataResultsFramework->resultsFramework->SimulationInformation.setNumErrorsSizing(NumWarningsDuringSizing, NumSevereDuringSizing);
state.dataResultsFramework->resultsFramework->SimulationInformation.setNumErrorsSummary(NumWarnings, NumSevere);
if (state.dataGlobal->createPerfLog) {
Util::appendPerfLog(state, "Run Time [string]", Elapsed);
Util::appendPerfLog(state, "Number of Warnings", NumWarnings);
Util::appendPerfLog(state, "Number of Severe", NumSevere, true); // last item so write the perfLog file
}
ShowMessage(state,
EnergyPlus::format(
"EnergyPlus Warmup Error Summary. During Warmup: {} Warning; {} Severe Errors.", NumWarningsDuringWarmup, NumSevereDuringWarmup));
ShowMessage(state,
EnergyPlus::format(
"EnergyPlus Sizing Error Summary. During Sizing: {} Warning; {} Severe Errors.", NumWarningsDuringSizing, NumSevereDuringSizing));
ShowMessage(
state,
EnergyPlus::format("EnergyPlus Completed Successfully-- {} Warning; {} Severe Errors; Elapsed Time={}", NumWarnings, NumSevere, Elapsed));
DisplayString(state, "EnergyPlus Run Time=" + Elapsed);
{
auto tempfl = state.files.endFile.try_open(state.files.outputControl.end);
if (!tempfl.good()) {
DisplayString(state, fmt::format("EndEnergyPlus: Could not open file {} for output (write).", tempfl.filePath));
}
print(tempfl, "EnergyPlus Completed Successfully-- {} Warning; {} Severe Errors; Elapsed Time={}\n", NumWarnings, NumSevere, Elapsed);
}
state.dataResultsFramework->resultsFramework->writeOutputs(state);
if (state.dataGlobal->printConsoleOutput) {
std::cerr << "EnergyPlus Completed Successfully." << std::endl;
}
// Close the ExternalInterface socket. This call also sends the flag "1" to the ExternalInterface,
// indicating that E+ finished its simulation
if ((state.dataExternalInterface->NumExternalInterfaces > 0) && state.dataExternalInterface->haveExternalInterfaceBCVTB) {
ExternalInterface::CloseSocket(state, 1);
}
if (state.dataGlobal->fProgressPtr != nullptr) {
state.dataGlobal->fProgressPtr(100);
}
if (state.dataGlobal->progressCallback) {
state.dataGlobal->progressCallback(100);
}
if (state.dataGlobal->eplusRunningViaAPI) {
state.files.flushAll();
}
// The audit file seems to be held open in some cases, make sure it is closed before leaving.
// EnergyPlus can close through two paths: EndEnergyPlus and AbortEnergyPlus, so do the same thing there.
state.files.audit.close();
return EXIT_SUCCESS;
}
void ConvertCaseToUpper(std::string_view InputString, // Input string
std::string &OutputString // Output string (in UpperCase)
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS SUBROUTINE:
// Convert a string to upper case
// METHODOLOGY EMPLOYED:
// This routine is not dependent upon the ASCII
// code. It works by storing the upper and lower case alphabet. It
// scans the whole input string. If it finds a character in the lower
// case alphabet, it makes an appropriate substitution.
// Using/Aliasing
static constexpr std::string_view UpperCase("ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝ");
static constexpr std::string_view LowerCase("abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüý");
OutputString = InputString;
for (std::string::size_type A = 0; A < len(InputString); ++A) {
std::string::size_type const B = index(LowerCase, InputString[A]);
if (B != std::string::npos) {
OutputString[A] = UpperCase[B];
}
}
}
void ConvertCaseToLower(std::string_view InputString, // Input string
std::string &OutputString // Output string (in LowerCase)
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS SUBROUTINE:
// Convert a string to lower case
// METHODOLOGY EMPLOYED:
// This routine is not dependent upon the ASCII
// code. It works by storing the upper and lower case alphabet. It
// scans the whole input string. If it finds a character in the lower
// case alphabet, it makes an appropriate substitution.
// Using/Aliasing
static constexpr std::string_view UpperCase("ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝ");
static constexpr std::string_view LowerCase("abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüý");
OutputString = InputString;
for (std::string::size_type A = 0; A < len(InputString); ++A) {
std::string::size_type const B = index(UpperCase, InputString[A]);
if (B != std::string::npos) {
OutputString[A] = LowerCase[B];
}
}
}
std::string::size_type FindNonSpace(std::string const &String) // String to be scanned
{
// FUNCTION INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS FUNCTION:
// This function finds the first non-space character in the passed string
// and returns that position as the result to the calling program.
// METHODOLOGY EMPLOYED:
// Scan string for character not equal to blank.
return String.find_first_not_of(' ');
}
bool env_var_on(std::string const &env_var_str)
{
// FUNCTION INFORMATION:
// AUTHOR Stuart G. Mentzer
// DATE WRITTEN April 2014
// PURPOSE OF THIS FUNCTION:
// Test if a boolean environment variable value is "on" (has value starting with Y or T)
return ((!env_var_str.empty()) && is_any_of(env_var_str[0], "YyTt"));
}
void emitErrorMessage(EnergyPlusData &state, [[maybe_unused]] ErrorMessageCategory category, std::string const &msg, bool shouldFatal)
{
if (!shouldFatal) {
ShowSevereError(state, msg);
} else { // should fatal
ShowFatalError(state, msg);
}
}
void emitErrorMessages(EnergyPlusData &state,
[[maybe_unused]] ErrorMessageCategory category,
std::initializer_list<std::string> const &msgs,
bool const shouldFatal,
int const zeroBasedTimeStampIndex)
{
for (auto msg = msgs.begin(); msg != msgs.end(); ++msg) {
if (msg - msgs.begin() == zeroBasedTimeStampIndex) {
ShowContinueErrorTimeStamp(state, *msg);
continue;
}
if (msg == msgs.begin()) {
ShowSevereError(state, *msg);
} else if (std::next(msg) == msgs.end() && shouldFatal) {
ShowFatalError(state, *msg);
} else { // should be an intermediate message, or a final one where there is no fatal
ShowContinueError(state, *msg);
}
}
}
void emitWarningMessage(EnergyPlusData &state, [[maybe_unused]] ErrorMessageCategory category, std::string const &msg, bool const countAsError)
{
if (countAsError) { // ideally this path goes away and we just have distinct warnings and errors
ShowWarningError(state, msg);
} else {
ShowWarningMessage(state, msg);
}
}
void emitWarningMessages(EnergyPlusData &state,
[[maybe_unused]] ErrorMessageCategory category,
std::initializer_list<std::string> const &msgs,
bool const countAsError)
{
for (auto msg = msgs.begin(); msg != msgs.end(); ++msg) {
if (msg == msgs.begin()) {
if (countAsError) { // ideally this path goes away and we just have distinct warnings and errors
ShowWarningError(state, *msg);
} else {
ShowWarningMessage(state, *msg);
}
} else {
ShowContinueError(state, *msg);
}
}
}
[[noreturn]] void
ShowFatalError(EnergyPlusData &state, std::string const &ErrorMessage, OptionalOutputFileRef OutUnit1, OptionalOutputFileRef OutUnit2)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// MODIFIED Kyle Benne August 2010 Added sqlite output
// PURPOSE OF THIS SUBROUTINE:
// This subroutine puts ErrorMessage with a Fatal designation on
// designated output files. Then, the program is aborted.
// METHODOLOGY EMPLOYED:
// Calls ShowErrorMessage utility routine.
// Calls AbortEnergyPlus
using namespace DataErrorTracking;
ShowErrorMessage(state, EnergyPlus::format(" ** Fatal ** {}", ErrorMessage), OutUnit1, OutUnit2);
DisplayString(state, "**FATAL:" + ErrorMessage);
ShowErrorMessage(state, " ...Summary of Errors that led to program termination:", OutUnit1, OutUnit2);
ShowErrorMessage(
state, EnergyPlus::format(" ..... Reference severe error count={}", state.dataErrTracking->TotalSevereErrors), OutUnit1, OutUnit2);
ShowErrorMessage(state, EnergyPlus::format(" ..... Last severe error={}", state.dataErrTracking->LastSevereError), OutUnit1, OutUnit2);
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->createSQLiteErrorRecord(1, 2, ErrorMessage, 1);
if (state.dataSQLiteProcedures->sqlite->sqliteWithinTransaction()) {
state.dataSQLiteProcedures->sqlite->sqliteCommit();
}
}
if (state.dataGlobal->errorCallback) {
state.dataGlobal->errorCallback(Error::Fatal, ErrorMessage);
}
throw FatalError(ErrorMessage);
}
void ShowSevereError(EnergyPlusData &state, std::string const &ErrorMessage, OptionalOutputFileRef OutUnit1, OptionalOutputFileRef OutUnit2)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS SUBROUTINE:
// This subroutine puts ErrorMessage with a Severe designation on
// designated output files.
// METHODOLOGY EMPLOYED:
// Calls ShowErrorMessage utility routine.
for (int Loop = 1; Loop <= DataErrorTracking::SearchCounts; ++Loop) {
if (has(ErrorMessage, DataErrorTracking::MessageSearch[Loop])) {
++state.dataErrTracking->MatchCounts(Loop);
}
}
++state.dataErrTracking->TotalSevereErrors;
if (state.dataGlobal->WarmupFlag && !state.dataGlobal->DoingSizing && !state.dataGlobal->KickOffSimulation &&
!state.dataErrTracking->AbortProcessing) {
++state.dataErrTracking->TotalSevereErrorsDuringWarmup;
}
if (state.dataGlobal->DoingSizing) {
++state.dataErrTracking->TotalSevereErrorsDuringSizing;
}
ShowErrorMessage(state, EnergyPlus::format(" ** Severe ** {}", ErrorMessage), OutUnit1, OutUnit2);
state.dataErrTracking->LastSevereError = ErrorMessage;
// Could set a variable here that gets checked at some point?
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->createSQLiteErrorRecord(1, 1, ErrorMessage, 1);
}
if (state.dataGlobal->errorCallback) {
state.dataGlobal->errorCallback(Error::Severe, ErrorMessage);
}
}
void ShowSevereMessage(EnergyPlusData &state, std::string const &ErrorMessage, OptionalOutputFileRef OutUnit1, OptionalOutputFileRef OutUnit2)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 2009
// PURPOSE OF THIS SUBROUTINE:
// This subroutine puts ErrorMessage with a Severe designation on designated output files.
// But does not bump the error count so can be used in conjunction with recurring error calls.
// METHODOLOGY EMPLOYED:
// Calls ShowErrorMessage utility routine.
for (int Loop = 1; Loop <= DataErrorTracking::SearchCounts; ++Loop) {
if (has(ErrorMessage, DataErrorTracking::MessageSearch[Loop])) {
++state.dataErrTracking->MatchCounts(Loop);
}
}
ShowErrorMessage(state, EnergyPlus::format(" ** Severe ** {}", ErrorMessage), OutUnit1, OutUnit2);
state.dataErrTracking->LastSevereError = ErrorMessage;
// Could set a variable here that gets checked at some point?
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->createSQLiteErrorRecord(1, 1, ErrorMessage, 0);
}
if (state.dataGlobal->errorCallback) {
state.dataGlobal->errorCallback(Error::Severe, ErrorMessage);
}
}
void ShowContinueError(EnergyPlusData &state, std::string const &Message, OptionalOutputFileRef OutUnit1, OptionalOutputFileRef OutUnit2)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN October 2001
// PURPOSE OF THIS SUBROUTINE:
// This subroutine displays a 'continued error' message on designated output files.
// METHODOLOGY EMPLOYED:
// Calls ShowErrorMessage utility routine.
ShowErrorMessage(state, EnergyPlus::format(" ** ~~~ ** {}", Message), OutUnit1, OutUnit2);
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->updateSQLiteErrorRecord(Message);
}
if (state.dataGlobal->errorCallback) {
state.dataGlobal->errorCallback(Error::Continue, Message);
}
}
void ShowContinueErrorTimeStamp(EnergyPlusData &state, std::string const &Message, OptionalOutputFileRef OutUnit1, OptionalOutputFileRef OutUnit2)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN February 2004
// PURPOSE OF THIS SUBROUTINE:
// This subroutine displays a 'continued error' timestamp message on designated output files.
// METHODOLOGY EMPLOYED:
// Calls ShowErrorMessage utility routine.
std::string cEnvHeader;
if (state.dataGlobal->WarmupFlag) {
if (!state.dataGlobal->SetupFlag) {
if (!state.dataGlobal->DoingSizing) {
cEnvHeader = " During Warmup, Environment=";
} else {
cEnvHeader = " During Warmup & Sizing, Environment=";
}
} else {
if (!state.dataGlobal->DoingSizing) {
cEnvHeader = " During Setup, Environment=";
} else {
cEnvHeader = " During Setup & Sizing, Environment=";
}
}
} else {
if (!state.dataGlobal->DoingSizing) {
cEnvHeader = " Environment=";
} else {
cEnvHeader = " During Sizing, Environment=";
}
}
if (len(Message) < 50) {
const std::string m = EnergyPlus::format("{}{}{}, at Simulation time={} {}",
Message,
cEnvHeader,
state.dataEnvrn->EnvironmentName,
state.dataEnvrn->CurMnDy,
General::CreateSysTimeIntervalString(state));
ShowErrorMessage(state, EnergyPlus::format(" ** ~~~ ** {}", m), OutUnit1, OutUnit2);
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->updateSQLiteErrorRecord(m);
}
if (state.dataGlobal->errorCallback) {
state.dataGlobal->errorCallback(Error::Continue, m);
}
} else {
const std::string postfix = EnergyPlus::format("{}{}, at Simulation time={} {}",
cEnvHeader,
state.dataEnvrn->EnvironmentName,
state.dataEnvrn->CurMnDy,
General::CreateSysTimeIntervalString(state));
ShowErrorMessage(state, EnergyPlus::format(" ** ~~~ ** {}", Message));
ShowErrorMessage(state, EnergyPlus::format(" ** ~~~ ** {}", postfix), OutUnit1, OutUnit2);
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->updateSQLiteErrorRecord(Message);
}
if (state.dataGlobal->errorCallback) {
state.dataGlobal->errorCallback(Error::Continue, Message);
state.dataGlobal->errorCallback(Error::Continue, postfix);
}
}
}
void ShowMessage(EnergyPlusData &state, std::string const &Message, OptionalOutputFileRef OutUnit1, OptionalOutputFileRef OutUnit2)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS SUBROUTINE:
// This subroutine displays a simple message on designated output files.
// METHODOLOGY EMPLOYED:
// Calls ShowErrorMessage utility routine.
if (Message.empty()) {
ShowErrorMessage(state, " *************", OutUnit1, OutUnit2);
} else {
ShowErrorMessage(state, EnergyPlus::format(" ************* {}", Message), OutUnit1, OutUnit2);
if (state.dataSQLiteProcedures->sqlite) {
state.dataSQLiteProcedures->sqlite->createSQLiteErrorRecord(1, -1, Message, 0);
}
if (state.dataGlobal->errorCallback) {
state.dataGlobal->errorCallback(Error::Info, Message);
}
}
}
void ShowWarningError(EnergyPlusData &state, std::string const &ErrorMessage, OptionalOutputFileRef OutUnit1, OptionalOutputFileRef OutUnit2)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda K. Lawrie
// DATE WRITTEN September 1997
// PURPOSE OF THIS SUBROUTINE:
// This subroutine puts ErrorMessage with a Warning designation on
// designated output files.
// METHODOLOGY EMPLOYED:
// Calls ShowErrorMessage utility routine.