-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathSqlFile_Impl.cpp
More file actions
4406 lines (3722 loc) · 213 KB
/
SqlFile_Impl.cpp
File metadata and controls
4406 lines (3722 loc) · 213 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
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) Alliance for Energy Innovation, LLC.
* See also https://openstudio.net/license
***********************************************************************************************************************/
#include "SqlFile_Impl.hpp"
#include "SqlFileTimeSeriesQuery.hpp"
#include "PreparedStatement.hpp"
#include "../time/Calendar.hpp"
#include "../filetypes/EpwFile.hpp"
#include "../core/Containers.hpp"
#include "../core/Assert.hpp"
#include "../core/ASCIIStrings.hpp"
#include "../core/StringHelpers.hpp"
#include <OpenStudio.hxx>
#include <sqlite3.h>
using boost::multi_index_container;
using boost::multi_index::indexed_by;
using boost::multi_index::ordered_unique;
using boost::multi_index::ordered_non_unique;
using boost::multi_index::tag;
using boost::multi_index::composite_key;
using boost::multi_index::member;
namespace openstudio {
namespace detail {
std::string columnText(const unsigned char* column) {
if (column == nullptr) {
return {};
}
return {reinterpret_cast<const char*>(column)};
}
SqlFile_Impl::SqlFile_Impl(const openstudio::path& path, const bool createIndexes)
: m_path(path),
m_connectionOpen(false),
m_supportedVersion(false),
m_hasYear(true),
m_hasIlluminanceMapYear(true),
m_illuminanceMapHasOnly2RefPts(false) {
if (openstudio::filesystem::exists(m_path)) {
m_path = openstudio::filesystem::canonical(m_path);
}
reopen();
if (createIndexes) {
this->createIndexes();
}
}
SqlFile_Impl::SqlFile_Impl(const openstudio::path& t_path, const openstudio::EpwFile& t_epwFile, const openstudio::DateTime& t_simulationTime,
const openstudio::Calendar& t_calendar, const bool createIndexes)
: m_path(t_path) {
if (openstudio::filesystem::exists(m_path)) {
m_path = openstudio::filesystem::canonical(m_path);
}
m_sqliteFilename = toString(m_path.make_preferred().native());
std::string fileName = m_sqliteFilename;
m_hasYear = true;
m_hasIlluminanceMapYear = true;
m_illuminanceMapHasOnly2RefPts = false;
bool initschema = false;
if (!openstudio::filesystem::exists(m_path)) {
initschema = true;
}
int code = sqlite3_open_v2(fileName.c_str(), &m_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE, nullptr);
m_connectionOpen = (code == 0);
if (initschema) {
execAndThrowOnError(
/* extracted from real eplusout.sql */
"CREATE TABLE Simulations (SimulationIndex INTEGER PRIMARY KEY, EnergyPlusVersion TEXT, TimeStamp TEXT, NumTimestepsPerHour INTEGER, "
"Completed BOOL, CompletedSuccessfully BOOL);"
"CREATE TABLE EnvironmentPeriods ( EnvironmentPeriodIndex INTEGER PRIMARY KEY, SimulationIndex INTEGER, EnvironmentName TEXT, "
"EnvironmentType INTEGER, FOREIGN KEY(SimulationIndex) REFERENCES Simulations(SimulationIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE Errors ( ErrorIndex INTEGER PRIMARY KEY, SimulationIndex INTEGER, ErrorType INTEGER, ErrorMessage TEXT, Count INTEGER, FOREIGN "
"KEY(SimulationIndex) REFERENCES Simulations(SimulationIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE Time (TimeIndex INTEGER PRIMARY KEY, Year INTEGER, Month INTEGER, Day INTEGER, Hour INTEGER, Minute INTEGER, Dst INTEGER, "
"Interval INTEGER, IntervalType INTEGER, SimulationDays INTEGER, DayType TEXT, EnvironmentPeriodIndex INTEGER, WarmupFlag INTEGER);"
"CREATE TABLE Zones (ZoneIndex INTEGER PRIMARY KEY, ZoneName TEXT, RelNorth REAL, OriginX REAL, OriginY REAL, OriginZ REAL, CentroidX REAL, "
"CentroidY REAL, CentroidZ REAL, OfType INTEGER, Multiplier REAL, ListMultiplier REAL, MinimumX REAL, MaximumX REAL, MinimumY REAL, MaximumY "
"REAL, MinimumZ REAL, MaximumZ REAL, CeilingHeight REAL, Volume REAL, InsideConvectionAlgo INTEGER, OutsideConvectionAlgo INTEGER, FloorArea "
"REAL, ExtGrossWallArea REAL, ExtNetWallArea REAL, ExtWindowArea REAL, IsPartOfTotalArea INTEGER);"
"CREATE TABLE ZoneLists ( ZoneListIndex INTEGER PRIMARY KEY, Name TEXT);"
"CREATE TABLE ZoneGroups ( ZoneGroupIndex INTEGER PRIMARY KEY, ZoneGroupName TEXT, ZoneListIndex INTEGER, ZoneListMultiplier INTEGER, "
"FOREIGN KEY(ZoneListIndex) REFERENCES ZoneLists(ZoneListIndex) ON UPDATE CASCADE );"
"CREATE TABLE ZoneInfoZoneLists (ZoneListIndex INTEGER NOT NULL, ZoneIndex INTEGER NOT NULL, PRIMARY KEY(ZoneListIndex, ZoneIndex), FOREIGN "
"KEY(ZoneListIndex) REFERENCES ZoneLists(ZoneListIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ZoneIndex) REFERENCES "
"Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE Schedules (ScheduleIndex INTEGER PRIMARY KEY, ScheduleName TEXT, ScheduleType TEXT, ScheduleMinimum REAL, ScheduleMaximum "
"REAL);"
"CREATE TABLE Materials ( MaterialIndex INTEGER PRIMARY KEY, Name TEXT, MaterialType INTEGER, Roughness INTEGER, Conductivity REAL, Density "
"REAL, IsoMoistCap REAL, Porosity REAL, Resistance REAL, ROnly INTEGER, SpecHeat REAL, ThermGradCoef REAL, Thickness REAL, VaporDiffus REAL "
");"
"CREATE TABLE Constructions ( ConstructionIndex INTEGER PRIMARY KEY, Name TEXT, TotalLayers INTEGER, TotalSolidLayers INTEGER, "
"TotalGlassLayers INTEGER, InsideAbsorpVis REAL, OutsideAbsorpVis REAL, InsideAbsorpSolar REAL, OutsideAbsorpSolar REAL, InsideAbsorpThermal "
"REAL, OutsideAbsorpThermal REAL, OutsideRoughness INTEGER, TypeIsWindow INTEGER, Uvalue REAL);"
"CREATE TABLE ConstructionLayers ( ConstructionLayersIndex INTEGER PRIMARY KEY, ConstructionIndex INTEGER, LayerIndex INTEGER, MaterialIndex "
"INTEGER, FOREIGN KEY(ConstructionIndex) REFERENCES Constructions(ConstructionIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN "
"KEY(MaterialIndex) REFERENCES Materials(MaterialIndex) ON UPDATE CASCADE );"
"CREATE TABLE Surfaces ( SurfaceIndex INTEGER PRIMARY KEY, SurfaceName TEXT, ConstructionIndex INTEGER, ClassName TEXT, Area REAL, GrossArea "
"REAL, Perimeter REAL, Azimuth REAL, Height REAL, Reveal REAL, Shape INTEGER, Sides INTEGER, Tilt REAL, Width REAL, HeatTransferSurf "
"INTEGER, BaseSurfaceIndex INTEGER, ZoneIndex INTEGER, ExtBoundCond INTEGER, ExtSolar INTEGER, ExtWind INTEGER, FOREIGN "
"KEY(ConstructionIndex) REFERENCES Constructions(ConstructionIndex) ON UPDATE CASCADE, FOREIGN KEY(BaseSurfaceIndex) REFERENCES "
"Surfaces(SurfaceIndex) ON UPDATE CASCADE, FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE ReportDataDictionary(ReportDataDictionaryIndex INTEGER PRIMARY KEY, IsMeter INTEGER, Type TEXT, IndexGroup TEXT, TimestepType "
"TEXT, KeyValue TEXT, Name TEXT, ReportingFrequency TEXT, ScheduleName TEXT, Units TEXT);"
"CREATE TABLE ReportData (ReportDataIndex INTEGER PRIMARY KEY, TimeIndex INTEGER, ReportDataDictionaryIndex INTEGER, Value REAL, FOREIGN "
"KEY(TimeIndex) REFERENCES Time(TimeIndex) ON DELETE CASCADE ON UPDATE CASCADE FOREIGN KEY(ReportDataDictionaryIndex) REFERENCES "
"ReportDataDictionary(ReportDataDictionaryIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE ReportExtendedData (ReportExtendedDataIndex INTEGER PRIMARY KEY, ReportDataIndex INTEGER, MaxValue REAL, MaxMonth INTEGER, "
"MaxDay INTEGER, MaxHour INTEGER, MaxStartMinute INTEGER, MaxMinute INTEGER, MinValue REAL, MinMonth INTEGER, MinDay INTEGER, MinHour "
"INTEGER, MinStartMinute INTEGER, MinMinute INTEGER, FOREIGN KEY(ReportDataIndex) REFERENCES ReportData(ReportDataIndex) ON DELETE CASCADE "
"ON UPDATE CASCADE );"
"CREATE TABLE NominalPeople ( NominalPeopleIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER,NumberOfPeople INTEGER, "
"NumberOfPeopleScheduleIndex INTEGER, ActivityScheduleIndex INTEGER, FractionRadiant REAL, FractionConvected REAL, "
"WorkEfficiencyScheduleIndex INTEGER, ClothingEfficiencyScheduleIndex INTEGER, AirVelocityScheduleIndex INTEGER, Fanger INTEGER, Pierce "
"INTEGER, KSU INTEGER, MRTCalcType INTEGER, SurfaceIndex INTEGER, AngleFactorListName TEXT, AngleFactorList INTEGER, "
"UserSpecifeidSensibleFraction REAL, Show55Warning INTEGER, FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE "
"CASCADE, FOREIGN KEY(NumberOfPeopleScheduleIndex) REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE, FOREIGN KEY(ActivityScheduleIndex) "
"REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE, FOREIGN KEY(WorkEfficiencyScheduleIndex) REFERENCES Schedules(ScheduleIndex) ON "
"UPDATE CASCADE, FOREIGN KEY(ClothingEfficiencyScheduleIndex) REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE, FOREIGN "
"KEY(AirVelocityScheduleIndex) REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE, FOREIGN KEY(SurfaceIndex) REFERENCES "
"Surfaces(SurfaceIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalLighting ( NominalLightingIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex INTEGER, "
"DesignLevel REAL, FractionReturnAir REAL, FractionRadiant REAL, FractionShortWave REAL, FractionReplaceable REAL, FractionConvected REAL, "
"EndUseSubcategory TEXT, FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ScheduleIndex) "
"REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalElectricEquipment (NominalElectricEquipmentIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex "
"INTEGER, DesignLevel REAL, FractionLatent REAL, FractionRadiant REAL, FractionLost REAL, FractionConvected REAL, EndUseSubcategory TEXT, "
"FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ScheduleIndex) REFERENCES "
"Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalGasEquipment( NominalGasEquipmentIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex INTEGER, "
"DesignLevel REAL, FractionLatent REAL, FractionRadiant REAL, FractionLost REAL, FractionConvected REAL, EndUseSubcategory TEXT, FOREIGN "
"KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ScheduleIndex) REFERENCES "
"Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalSteamEquipment( NominalSteamEquipmentIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex "
"INTEGER, DesignLevel REAL, FractionLatent REAL, FractionRadiant REAL, FractionLost REAL, FractionConvected REAL, EndUseSubcategory TEXT, "
"FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ScheduleIndex) REFERENCES "
"Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalHotWaterEquipment(NominalHotWaterEquipmentIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, SchedNo "
"INTEGER, DesignLevel REAL, FractionLatent REAL, FractionRadiant REAL, FractionLost REAL, FractionConvected REAL, EndUseSubcategory TEXT, "
"FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(SchedNo) REFERENCES "
"Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalOtherEquipment( NominalOtherEquipmentIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex "
"INTEGER, DesignLevel REAL, FractionLatent REAL, FractionRadiant REAL, FractionLost REAL, FractionConvected REAL, EndUseSubcategory TEXT, "
"FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ScheduleIndex) REFERENCES "
"Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalBaseboardHeaters ( NominalBaseboardHeaterIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex "
"INTEGER, CapatLowTemperature REAL, LowTemperature REAL, CapatHighTemperature REAL, HighTemperature REAL, FractionRadiant REAL, "
"FractionConvected REAL, EndUseSubcategory TEXT, FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, "
"FOREIGN KEY(ScheduleIndex) REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalInfiltration ( NominalInfiltrationIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex INTEGER, "
"DesignLevel REAL, FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ScheduleIndex) "
"REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE NominalVentilation ( NominalVentilationIndex INTEGER PRIMARY KEY, ObjectName TEXT, ZoneIndex INTEGER, ScheduleIndex INTEGER, "
"DesignLevel REAL, FOREIGN KEY(ZoneIndex) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY(ScheduleIndex) "
"REFERENCES Schedules(ScheduleIndex) ON UPDATE CASCADE );"
"CREATE TABLE ZoneSizes ( ZoneSizesIndex INTEGER PRIMARY KEY, ZoneName TEXT, LoadType TEXT, CalcDesLoad REAL, UserDesLoad REAL, CalcDesFlow "
"REAL, UserDesFlow REAL, DesDayName TEXT, PeakHrMin TEXT, PeakTemp REAL, PeakHumRat REAL, CalcOutsideAirFlow REAL);"
"CREATE TABLE SystemSizes (SystemSizesIndex INTEGER PRIMARY KEY, SystemName TEXT, Description TEXT, Value REAL, Units TEXT);"
"CREATE TABLE ComponentSizes (ComponentSizesIndex INTEGER PRIMARY KEY, CompType TEXT, CompName TEXT, Description TEXT, Value REAL, Units "
"TEXT);"
"CREATE TABLE RoomAirModels (ZoneIndex INTEGER PRIMARY KEY, AirModelName TEXT, AirModelType INTEGER, TempCoupleScheme INTEGER, SimAirModel "
"INTEGER);"
"CREATE TABLE DaylightMaps ( MapNumber INTEGER PRIMARY KEY, MapName TEXT, Environment TEXT, Zone INTEGER, ReferencePt1 TEXT, ReferencePt2 "
"TEXT, Z REAL, FOREIGN KEY(Zone) REFERENCES Zones(ZoneIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE DaylightMapHourlyReports ( HourlyReportIndex INTEGER PRIMARY KEY, MapNumber INTEGER, Year INTEGER, Month INTEGER, DayOfMonth "
"INTEGER, Hour INTEGER, FOREIGN KEY(MapNumber) REFERENCES DaylightMaps(MapNumber) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE DaylightMapHourlyData ( HourlyDataIndex INTEGER PRIMARY KEY, HourlyReportIndex INTEGER, X REAL, Y REAL, Illuminance REAL, "
"FOREIGN KEY(HourlyReportIndex) REFERENCES DaylightMapHourlyReports(HourlyReportIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE TABLE StringTypes ( StringTypeIndex INTEGER PRIMARY KEY, Value TEXT);"
"CREATE TABLE Strings ( StringIndex INTEGER PRIMARY KEY, StringTypeIndex INTEGER, Value TEXT, UNIQUE(StringTypeIndex, Value), FOREIGN "
"KEY(StringTypeIndex) REFERENCES StringTypes(StringTypeIndex) ON UPDATE CASCADE );"
"CREATE TABLE TabularData ( TabularDataIndex INTEGER PRIMARY KEY, ReportNameIndex INTEGER, ReportForStringIndex INTEGER, TableNameIndex "
"INTEGER, RowNameIndex INTEGER, ColumnNameIndex INTEGER, UnitsIndex INTEGER, SimulationIndex INTEGER, RowId INTEGER, ColumnId INTEGER, Value "
"TEXT Value TEXT, FOREIGN KEY(ReportNameIndex) REFERENCES Strings(StringIndex) ON UPDATE CASCADE FOREIGN KEY(ReportForStringIndex) "
"REFERENCES Strings(StringIndex) ON UPDATE CASCADE FOREIGN KEY(TableNameIndex) REFERENCES Strings(StringIndex) ON UPDATE CASCADE FOREIGN "
"KEY(RowNameIndex) REFERENCES Strings(StringIndex) ON UPDATE CASCADE FOREIGN KEY(ColumnNameIndex) REFERENCES Strings(StringIndex) ON UPDATE "
"CASCADE FOREIGN KEY(UnitsIndex) REFERENCES Strings(StringIndex) ON UPDATE CASCADE FOREIGN KEY(SimulationIndex) REFERENCES "
"Simulations(SimulationIndex) ON DELETE CASCADE ON UPDATE CASCADE );"
"CREATE VIEW ReportVariableWithTime AS SELECT rd.ReportDataIndex, rd.TimeIndex, rd.ReportDataDictionaryIndex, red.ReportExtendedDataIndex, "
"rd.Value, t.Month, t.Day, t.Hour, t.Minute, t.Dst, t.Interval, t.IntervalType, t.SimulationDays, t.DayType, t.EnvironmentPeriodIndex, "
"t.WarmupFlag, rdd.IsMeter, rdd.Type, rdd.IndexGroup, rdd.TimestepType, rdd.KeyValue, rdd.Name, rdd.ReportingFrequency, rdd.ScheduleName, "
"rdd.Units, red.MaxValue, red.MaxMonth, red.MaxDay, red.MaxStartMinute, red.MaxMinute, red.MinValue, red.MinMonth, red.MinDay, "
"red.MinStartMinute, red.MinMinute FROM ReportData As rd INNER JOIN ReportDataDictionary As rdd ON rd.ReportDataDictionaryIndex = "
"rdd.ReportDataDictionaryIndex LEFT OUTER JOIN ReportExtendedData As red ON rd.ReportDataIndex = red.ReportDataIndex INNER JOIN Time As t ON "
"rd.TimeIndex = t.TimeIndex;"
"CREATE VIEW ReportVariableData AS SELECT rd.ReportDataIndex As rowid, rd.TimeIndex, rd.ReportDataDictionaryIndex As "
"ReportVariableDataDictionaryIndex, rd.Value As VariableValue, red.ReportExtendedDataIndex As ReportVariableExtendedDataIndex FROM "
"ReportData As rd LEFT OUTER JOIN ReportExtendedData As red ON rd.ReportDataIndex = red.ReportDataIndex;"
"CREATE VIEW ReportVariableDataDictionary AS SELECT rdd.ReportDataDictionaryIndex As ReportVariableDataDictionaryIndex, rdd.Type As "
"VariableType, rdd.IndexGroup, rdd.TimestepType, rdd.KeyValue, rdd.Name As VariableName, rdd.ReportingFrequency, rdd.ScheduleName, rdd.Units "
"As VariableUnits FROM ReportDataDictionary As rdd;"
"CREATE VIEW ReportVariableExtendedData AS SELECT red.ReportExtendedDataIndex As ReportVariableExtendedDataIndex, red.MaxValue, "
"red.MaxMonth, red.MaxDay, red.MaxStartMinute, red.MaxMinute, red.MinValue, red.MinMonth, red.MinDay, red.MinStartMinute, red.MinMinute FROM "
"ReportExtendedData As red;"
"CREATE VIEW ReportMeterData AS SELECT rd.ReportDataIndex As rowid, rd.TimeIndex, rd.ReportDataDictionaryIndex As "
"ReportMeterDataDictionaryIndex, rd.Value As VariableValue, red.ReportExtendedDataIndex As ReportVariableExtendedDataIndex FROM ReportData "
"As rd LEFT OUTER JOIN ReportExtendedData As red ON rd.ReportDataIndex = red.ReportDataIndex INNER JOIN ReportDataDictionary As rdd ON "
"rd.ReportDataDictionaryIndex = rdd.ReportDataDictionaryIndex WHERE rdd.IsMeter = 1;"
"CREATE VIEW ReportMeterDataDictionary AS SELECT rdd.ReportDataDictionaryIndex As ReportMeterDataDictionaryIndex, rdd.Type As VariableType, "
"rdd.IndexGroup, rdd.TimestepType, rdd.KeyValue, rdd.Name As VariableName, rdd.ReportingFrequency, rdd.ScheduleName, rdd.Units As "
"VariableUnits FROM ReportDataDictionary As rdd WHERE rdd.IsMeter = 1;"
"CREATE VIEW ReportMeterExtendedData AS SELECT red.ReportExtendedDataIndex As ReportMeterExtendedDataIndex, red.MaxValue, red.MaxMonth, "
"red.MaxDay, red.MaxStartMinute, red.MaxMinute, red.MinValue, red.MinMonth, red.MinDay, red.MinStartMinute, red.MinMinute FROM "
"ReportExtendedData As red LEFT OUTER JOIN ReportData As rd ON rd.ReportDataIndex = red.ReportDataIndex INNER JOIN ReportDataDictionary As "
"rdd ON rd.ReportDataDictionaryIndex = rdd.ReportDataDictionaryIndex WHERE rdd.IsMeter = 1;"
"CREATE VIEW TabularDataWithStrings AS SELECT td.TabularDataIndex, td.Value As Value, reportn.Value As ReportName, fs.Value As "
"ReportForString, tn.Value As TableName, rn.Value As RowName, cn.Value As ColumnName, u.Value As Units FROM TabularData As td INNER JOIN "
"Strings As reportn ON reportn.StringIndex=td.ReportNameIndex INNER JOIN Strings As fs ON fs.StringIndex=td.ReportForStringIndex INNER JOIN "
"Strings As tn ON tn.StringIndex=td.TableNameIndex INNER JOIN Strings As rn ON rn.StringIndex=td.RowNameIndex INNER JOIN Strings As cn ON "
"cn.StringIndex=td.ColumnNameIndex INNER JOIN Strings As u ON u.StringIndex=td.UnitsIndex;");
}
addSimulation(t_epwFile, t_simulationTime, t_calendar);
reopen();
if (createIndexes) {
this->createIndexes();
}
}
void SqlFile_Impl::removeIndexes() {
if (m_connectionOpen) {
try {
execAndThrowOnError("DROP INDEX IF EXISTS rddMTR;");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error dropping index: " + std::string(e.what()));
}
try {
execAndThrowOnError("DROP INDEX IF EXISTS redRD;");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error dropping index: " + std::string(e.what()));
}
try {
execAndThrowOnError("DROP INDEX IF EXISTS rdTI;");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error dropping index: " + std::string(e.what()));
}
try {
execAndThrowOnError("DROP INDEX IF EXISTS rdDI;");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error dropping index: " + std::string(e.what()));
}
try {
execAndThrowOnError("DROP INDEX IF EXISTS dmhdHRI;");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error dropping index: " + std::string(e.what()));
}
try {
execAndThrowOnError("DROP INDEX IF EXISTS dmhrMNI;");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error dropping index: " + std::string(e.what()));
}
}
}
void SqlFile_Impl::createIndexes() {
if (m_connectionOpen) {
try {
execAndThrowOnError("CREATE INDEX IF NOT EXISTS rddMTR ON ReportDataDictionary (IsMeter);");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error adding index: " + std::string(e.what()));
}
try {
execAndThrowOnError("CREATE INDEX IF NOT EXISTS redRD ON ReportExtendedData (ReportDataIndex);");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error adding index: " + std::string(e.what()));
}
try {
execAndThrowOnError("CREATE INDEX IF NOT EXISTS rdTI ON ReportData (TimeIndex ASC);");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error adding index: " + std::string(e.what()));
}
try {
execAndThrowOnError("CREATE INDEX IF NOT EXISTS rdDI ON ReportData (ReportDataDictionaryIndex ASC);");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error adding index: " + std::string(e.what()));
}
try {
execAndThrowOnError("CREATE INDEX IF NOT EXISTS dmhdHRI ON DaylightMapHourlyData (HourlyReportIndex ASC);");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error adding index: " + std::string(e.what()));
}
try {
execAndThrowOnError("CREATE INDEX IF NOT EXISTS dmhrMNI ON DaylightMapHourlyReports (MapNumber);");
} catch (const std::runtime_error& e) {
LOG(Trace, "Error adding index: " + std::string(e.what()));
}
}
}
SqlFile_Impl::~SqlFile_Impl() {
close();
}
void SqlFile_Impl::execAndThrowOnError(const std::string& t_stmt) {
char* err = nullptr;
if (sqlite3_exec(m_db, t_stmt.c_str(), nullptr, nullptr, &err) != SQLITE_OK) {
std::string errstr;
if (err) {
errstr = err;
sqlite3_free(err);
}
throw std::runtime_error("Error executing SQL statement: " + t_stmt + " " + errstr);
}
}
void SqlFile_Impl::addSimulation(const openstudio::EpwFile& t_epwFile, const openstudio::DateTime& t_simulationTime,
const openstudio::Calendar& t_calendar) {
int nextSimulationIndex = getNextIndex("simulations", "SimulationIndex");
std::stringstream timeStamp;
timeStamp << t_simulationTime.date().year() << "." << t_simulationTime.date().monthOfYear().value() << "." << t_simulationTime.date().dayOfMonth()
<< " " << t_simulationTime.time().toString();
std::stringstream version;
version << "EnergyPlus, VERSION " << energyPlusVersionMajor() << "." << energyPlusVersionMinor() << ", (OpenStudio) YMD=" << timeStamp.str();
std::string insertSimulation = R"(INSERT INTO Simulations (SimulationIndex, EnergyPlusVersion, TimeStamp,
NumTimestepsPerHour, Completed, CompletedSuccessfully)
VALUES (?, ?, ?, ?, ?, ?);)";
execAndThrowOnError(insertSimulation,
// bindArgs
nextSimulationIndex, version.str(), timeStamp.str(), 6, 6, 1);
int nextEnvironmentPeriodIndex = getNextIndex("EnvironmentPeriods", "EnvironmentPeriodIndex");
std::stringstream envName;
envName << t_epwFile.stateProvinceRegion() << " WMO#=" << t_epwFile.wmoNumber();
std::string insertEnvironment = R"(INSERT INTO EnvironmentPeriods (EnvironmentPeriodIndex, SimulationIndex,
EnvironmentName, EnvironmentType) VALUES (?, ?, ?, ?);)";
execAndThrowOnError(insertEnvironment,
// bindArgs
nextEnvironmentPeriodIndex, nextSimulationIndex, envName.str(), 3);
int nextTimeIndex = getNextIndex("time", "TimeIndex");
std::shared_ptr<PreparedStatement> stmt;
if (hasYear()) {
stmt = std::make_shared<PreparedStatement>(
"insert into time (TimeIndex, Year, Month, Day, Hour, Minute, Dst, Interval, IntervalType, SimulationDays, DayType, EnvironmentPeriodIndex, "
"WarmupFlag) values (?, ?, ?, ?, ?, 0, 0, 60, 1, ?, ?, ?, null)",
m_db, true);
} else {
stmt =
std::make_shared<PreparedStatement>("insert into time (TimeIndex, Month, Day, Hour, Minute, Dst, Interval, IntervalType, SimulationDays, "
"DayType, EnvironmentPeriodIndex, WarmupFlag) values (?, ?, ?, ?, 0, 0, 60, 1, ?, ?, ?, null)",
m_db, true);
}
int simulationDay = 1;
for (openstudio::Date d = t_calendar.startDate(); d <= t_calendar.endDate(); d += openstudio::Time(1, 0)) {
for (int i = 1; i <= 24; ++i) {
int b = 0;
stmt->bind(++b, nextTimeIndex);
if (hasYear()) {
stmt->bind(++b, d.year());
}
stmt->bind(++b, d.monthOfYear().value());
stmt->bind(++b, d.dayOfMonth());
stmt->bind(++b, i);
stmt->bind(++b, simulationDay);
if (t_calendar.isHoliday(d)) {
stmt->bind(++b, "Holiday");
} else {
stmt->bind(++b, d.dayOfWeek().valueName());
}
stmt->bind(++b, nextEnvironmentPeriodIndex);
stmt->execAndThrowOnError();
++nextTimeIndex;
}
++simulationDay;
}
}
bool SqlFile_Impl::connectionOpen() const {
return m_connectionOpen;
}
int SqlFile_Impl::getNextIndex(const std::string& t_tableName, const std::string& t_columnName) {
// Interestingly, you CANNOT bind any database identifier (such as the table name / column name) but only litteral values...
// boost::optional<int> maxindex = execAndReturnFirstInt("SELECT MAX( ? ) FROM ?", t_columnName, t_tableName);
std::string query = "SELECT MAX(" + t_columnName + ") FROM " + t_tableName + ";";
boost::optional<int> maxindex = execAndReturnFirstInt(query);
if (maxindex) {
return *maxindex + 1;
} else {
return 1;
}
}
openstudio::path SqlFile_Impl::path() const {
return m_path;
}
bool SqlFile_Impl::close() {
if (m_connectionOpen) {
sqlite3_close(m_db);
m_connectionOpen = false;
}
return true;
}
bool SqlFile_Impl::reopen() {
bool result = true;
try {
close();
init();
} catch (const std::exception& e) {
LOG(Error, "Exception while opening database at '" << toString(m_path) << "': " << e.what());
result = false;
}
return result;
}
void SqlFile_Impl::init() {
m_sqliteFilename = toString(m_path.make_preferred().native());
std::string fileName = m_sqliteFilename;
int code = sqlite3_open_v2(fileName.c_str(), &m_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE, nullptr);
m_connectionOpen = (code == 0);
if (m_connectionOpen) { // create index on dictionaryIndex for large table reportvariabledata
if (!isValidConnection()) {
sqlite3_close(m_db);
m_connectionOpen = false;
throw openstudio::Exception("OpenStudio is not compatible with this file.");
}
// set a 1 second timeout
code = sqlite3_busy_timeout(m_db, 1000);
// set locking mode to exclusive
//code = sqlite3_exec(m_db, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL, NULL);
// retrieve DataDictionaryTable
retrieveDataDictionary();
} else {
throw openstudio::Exception("File not successfully opened.");
}
}
bool SqlFile_Impl::isSupportedVersion() const {
return m_supportedVersion;
}
bool SqlFile_Impl::hasYear() const {
return m_hasYear;
}
bool SqlFile_Impl::hasIlluminanceMapYear() const {
return m_hasIlluminanceMapYear;
}
boost::optional<double> SqlFile_Impl::assemblyUFactor(const std::string& subSurfaceName) const {
return getExteriorFenestrationValue(subSurfaceName, "Assembly U-Factor");
}
boost::optional<double> SqlFile_Impl::assemblySHGC(const std::string& subSurfaceName) const {
return getExteriorFenestrationValue(subSurfaceName, "Assembly SHGC");
}
boost::optional<double> SqlFile_Impl::assemblyVisibleTransmittance(const std::string& subSurfaceName) const {
return getExteriorFenestrationValue(subSurfaceName, "Assembly Visible Transmittance");
}
boost::optional<double> SqlFile_Impl::getExteriorFenestrationValue(const std::string& subSurfaceName, const std::string& columnName) const {
boost::optional<double> result;
// Get the object name and transform to the way it is recorded
// in the sql file
std::string queryRowName = boost::to_upper_copy(subSurfaceName);
std::string s = R"(SELECT Value FROM TabularDataWithStrings
WHERE ReportName='EnvelopeSummary'
AND ReportForString='Entire Facility'
AND TableName='Exterior Fenestration'
AND RowName=?
AND ColumnName=?)";
result = execAndReturnFirstDouble(s, queryRowName, columnName);
return result;
}
bool SqlFile_Impl::isValidConnection() {
std::string energyPlusVersion = this->energyPlusVersion();
if (energyPlusVersion.empty()) {
return false;
}
VersionString version(energyPlusVersion);
if (version >= VersionString(7, 0) && version <= VersionString(energyPlusVersionMajor(), energyPlusVersionMinor())) {
m_supportedVersion = true;
} else {
m_supportedVersion = false;
LOG(Warn, "Using unsupported EnergyPlus version " << version.str());
}
// v8.9.0 added the year tag, but it seems it's always zero...
// IlluminanceMap Year started in 9.2.0
// m_hasYear & m_hasIlluminanceMapYear are both default initialized to true
if (version < VersionString(9, 2)) {
m_hasIlluminanceMapYear = false;
} else if (version < VersionString(9, 6)) {
m_illuminanceMapHasOnly2RefPts = true;
}
if (version < VersionString(8, 9)) {
m_hasYear = false;
} else {
// Check if zero
boost::optional<int> maxYear = execAndReturnFirstInt("SELECT MAX(Year) FROM Time");
if (!maxYear.is_initialized() || maxYear.get() <= 0) {
auto nOtherThanRunPeriod =
execAndReturnFirstInt("SELECT COUNT(ReportingFrequency) FROM ReportDataDictionary WHERE ReportingFrequency NOT LIKE '%Run Period%'");
if (nOtherThanRunPeriod > 0) {
LOG(Warn, "Using EnergyPlusVersion version " << version.str() << " which should have 'Year' field, but it's always zero");
} else {
LOG(Info, "Your SQLFile does not contain the 'Year' field since you did not request any outputs at a frequency lower than Run Period");
}
m_hasYear = false;
}
}
return true;
}
int SqlFile_Impl::insertZone(const std::string& t_name, double t_relNorth, double t_originX, double t_originY, double t_originZ, double t_centroidX,
double t_centroidY, double t_centroidZ, int t_ofType, double t_multiplier, double t_listMultiplier, double t_minimumX,
double t_maximumX, double t_minimumY, double t_maximumY, double t_minimumZ, double t_maximumZ, double t_ceilingHeight,
double t_volume, int t_insideConvectionAlgo, int t_outsideConvectionAlgo, double t_floorArea,
double t_extGrossWallArea, double t_extNetWallArea, double t_extWindowArea, bool t_isPartOfTotalArea) {
int zoneIndex = getNextIndex("zones", "ZoneIndex");
execAndThrowOnError("insert into zones (ZoneIndex, ZoneName, RelNorth, OriginX, OriginY, OriginZ, CentroidX, CentroidY, CentroidZ, OfType, "
"Multiplier, ListMultiplier, MinimumX, MaximumX, MinimumY, MaximumY, MinimumZ, MaximumZ, CeilingHeight, Volume, "
"InsideConvectionAlgo, OutsideConvectionAlgo, FloorArea, ExtGrossWallArea, ExtNetWallArea, ExtWindowArea, IsPartOfTotalArea) "
"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
// Bind Args
zoneIndex, t_name, t_relNorth, t_originX, t_originY, t_originZ, t_centroidX, t_centroidY, t_centroidZ, t_ofType, t_multiplier,
t_listMultiplier, t_minimumX, t_maximumX, t_minimumY, t_maximumY, t_minimumZ, t_maximumZ, t_ceilingHeight, t_volume,
t_insideConvectionAlgo, t_outsideConvectionAlgo, t_floorArea, t_extGrossWallArea, t_extNetWallArea, t_extWindowArea,
t_isPartOfTotalArea);
return zoneIndex;
}
void SqlFile_Impl::insertIlluminanceMap(const std::string& t_zoneName, const std::string& t_name, const std::string& t_environmentName,
const std::vector<DateTime>& t_times, const std::vector<double>& t_xs, const std::vector<double>& t_ys,
double t_z, const std::vector<Matrix>& t_maps) {
boost::optional<int> zoneIndex = execAndReturnFirstInt("select ZoneIndex from zones where ZoneName=?;", t_zoneName);
if (!zoneIndex) {
throw std::runtime_error("Unknown zone name: " + t_zoneName);
}
if (t_times.size() != t_maps.size()) {
throw std::runtime_error("Number of times does not match number of maps");
}
int mapIndex = getNextIndex("daylightmaps", "MapNumber");
std::string referencePt1 = "RefPt1=(" + boost::lexical_cast<std::string>(t_xs.front()) + ":" + boost::lexical_cast<std::string>(t_ys.front())
+ ":" + boost::lexical_cast<std::string>(t_z) + ")";
std::string referencePt2 = "RefPt1=(" + boost::lexical_cast<std::string>(t_xs.back()) + ":" + boost::lexical_cast<std::string>(t_ys.back()) + ":"
+ boost::lexical_cast<std::string>(t_z) + ")";
std::stringstream mapInsert;
mapInsert << "insert into daylightmaps (MapNumber, MapName, Environment, Zone, ReferencePt1, ReferencePt2, Z) values (" << mapIndex << ", " << "'"
<< t_name << "', " << "'" << t_environmentName << "', " << *zoneIndex << ", " << "'" << referencePt1 << "', " << "'" << referencePt2
<< "', " << t_z << ");";
execAndThrowOnError(mapInsert.str());
int hourlyReportIndex = getNextIndex("daylightmaphourlyreports", "HourlyReportIndex");
// E+ added the "Year" field to the DaylightMapHourlyReports in version 9.2.0 (NREL/EnergyPlus#7235)
// assignment of PreparedStatement does not work, so use a pointer to statement to handle the case where you do or do not have Year
std::shared_ptr<PreparedStatement> stmt1;
if (hasIlluminanceMapYear()) {
stmt1 = std::make_shared<PreparedStatement>(
"insert into daylightmaphourlyreports (HourlyReportIndex, MapNumber, Year, Month, DayOfMonth, Hour) values (?, ?, ?, ?, ?, ?)", m_db, true);
} else {
stmt1 = std::make_shared<PreparedStatement>(
"insert into daylightmaphourlyreports (HourlyReportIndex, MapNumber, Month, DayOfMonth, Hour) values (?, ?, ?, ?, ?)", m_db, true);
}
for (size_t dateidx = 0; dateidx < t_times.size(); ++dateidx) {
int b = 0;
stmt1->bind(++b, hourlyReportIndex);
stmt1->bind(++b, mapIndex);
DateTime dt = t_times[dateidx];
int year = dt.date().year();
int monthOfYear = dt.date().monthOfYear().value();
int dayOfMonth = dt.date().dayOfMonth();
int hours = dt.time().hours();
// EnergyPlus deals in a 00:00:01 -> 24:00:00 world instead of
// 00:00:00 -> 23:59:59 hrs that the real world uses, so
// we are going to adjust for that, so we subtract an hour,
// to get it back to the previous day, then we will replace
// the hours with 24
// \sa illuminanceMapHourlyReportIndex
if (hours == 0) {
dt -= Time(0, 1);
monthOfYear = dt.date().monthOfYear().value();
dayOfMonth = dt.date().dayOfMonth();
hours = 24;
}
if (hasIlluminanceMapYear()) {
stmt1->bind(++b, year);
}
stmt1->bind(++b, monthOfYear);
stmt1->bind(++b, dayOfMonth);
stmt1->bind(++b, hours);
stmt1->execAndThrowOnError();
if (t_xs.size() != t_maps[dateidx].size1() || t_ys.size() != t_maps[dateidx].size2()) {
throw std::runtime_error("map size does not match given x's and y's");
}
for (size_t xidx = 0; xidx < t_xs.size(); ++xidx) {
for (size_t yidx = 0; yidx < t_ys.size(); ++yidx) {
// we are already inside of a transaction from stmt1, so not creating a new one here
// DLM: when implementing option for hasYear, use pointer to statement, assignment of PreparedStatement does not work
PreparedStatement stmt2("insert into daylightmaphourlydata (HourlyReportIndex, X, Y, Illuminance) values (?, ?, ?, ?)", m_db, false);
stmt2.bind(1, hourlyReportIndex);
stmt2.bind(2, t_xs[xidx]);
stmt2.bind(3, t_ys[yidx]);
stmt2.bind(4, t_maps[dateidx](xidx, yidx));
stmt2.execAndThrowOnError();
}
}
++hourlyReportIndex;
}
}
void SqlFile_Impl::insertTimeSeriesData(const std::string& t_variableType, const std::string& t_indexGroup, const std::string& t_timestepType,
const std::string& t_keyValue, const std::string& t_variableName,
const openstudio::ReportingFrequency& t_reportingFrequency,
const boost::optional<std::string>& t_scheduleName, const std::string& t_variableUnits,
const openstudio::TimeSeries& t_timeSeries) {
int datadicindex = getNextIndex("reportdatadictionary", "ReportDataDictionaryIndex");
std::stringstream insertReportDataDictionary;
insertReportDataDictionary << "insert into reportdatadictionary (ReportDataDictionaryIndex, IsMeter, Type, IndexGroup, TimestepType, KeyValue, "
"Name, ReportingFrequency, ScheduleName, Units) values ("
<< datadicindex << ", " << "'0'," << "'" << t_variableType << "', " << "'" << t_indexGroup << "', " << "'"
<< t_timestepType << "', " << "'" << t_keyValue << "', " << "'" << t_variableName << "', " << "'"
<< t_reportingFrequency.valueName() << "', ";
if (t_scheduleName) {
insertReportDataDictionary << "'" << *t_scheduleName << "', ";
} else {
insertReportDataDictionary << "null, ";
}
insertReportDataDictionary << "'" << t_variableUnits << "');";
execAndThrowOnError(insertReportDataDictionary.str());
std::vector<double> values = toStandardVector(t_timeSeries.values());
std::vector<double> days = toStandardVector(t_timeSeries.daysFromFirstReport());
openstudio::DateTime firstdate = t_timeSeries.firstReportDateTime();
std::shared_ptr<PreparedStatement> stmt;
if (hasYear()) {
// we'll let stmt1 have the transaction
stmt =
std::make_shared<PreparedStatement>("insert into reportdata (ReportDataIndex, TimeIndex, ReportDataDictionaryIndex, Value) values ( ?, "
"(select TimeIndex from time where Year=? and Month=? and Day=? and Hour=? and Minute=? limit 1), ?, ?);",
m_db, true);
} else {
stmt = std::make_shared<PreparedStatement>("insert into reportdata (ReportDataIndex, TimeIndex, ReportDataDictionaryIndex, Value) values ( ?, "
"(select TimeIndex from time where Month=? and Day=? and Hour=? and Minute=? limit 1), ?, ?);",
m_db, true);
}
for (size_t i = 0; i < values.size(); ++i) {
openstudio::DateTime dt = firstdate + openstudio::Time(days[i]);
double value = values[i];
if (dt.time().seconds() == 59) {
// rounding error, let's help
dt += openstudio::Time(0, 0, 0, 1);
}
if (dt.time().seconds() == 1) {
// rounding error, let's help
dt -= openstudio::Time(0, 0, 0, 1);
}
int year = dt.date().year();
int month = dt.date().monthOfYear().value();
int day = dt.date().dayOfMonth();
int hour = dt.time().hours();
int minute = dt.time().minutes();
++hour; // energyplus says time goes from 1-24 not from 0-23
int reportdataindex = getNextIndex("reportdata", "ReportDataIndex");
int b = 0;
stmt->bind(++b, reportdataindex);
if (hasYear()) {
stmt->bind(++b, year);
}
stmt->bind(++b, month);
stmt->bind(++b, day);
stmt->bind(++b, hour);
stmt->bind(++b, minute);
stmt->bind(++b, datadicindex);
stmt->bind(++b, value);
stmt->execAndThrowOnError();
}
}
std::vector<SummaryData> SqlFile_Impl::getSummaryData() const {
std::vector<SummaryData> retval;
if (m_db) {
sqlite3_stmt* sqlStmtPtr;
std::string stmt = "select sum(VariableValue), VariableName, ReportingFrequency, VariableUnits "
"from ReportMeterData, ReportMeterDataDictionary "
"where (ReportMeterData.ReportMeterDataDictionaryIndex = ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) "
" and VariableType='Sum' "
" group by VariableName, ReportingFrequency, VariableUnits";
sqlite3_prepare_v2(m_db, stmt.c_str(), -1, &sqlStmtPtr, nullptr);
while (sqlite3_step(sqlStmtPtr) == SQLITE_ROW) {
double value = sqlite3_column_double(sqlStmtPtr, 0);
std::string variablename = columnText(sqlite3_column_text(sqlStmtPtr, 1));
std::string reportingfrequency = columnText(sqlite3_column_text(sqlStmtPtr, 2));
std::string units = columnText(sqlite3_column_text(sqlStmtPtr, 3));
size_t colon = variablename.find(':');
if (colon == std::string::npos) {
LOG(Error, "Unable to parse variable name, no ':' found " + variablename);
} else {
std::string fueltype = variablename.substr(0, colon);
std::string installlocation = variablename.substr(colon + 1);
try {
retval.push_back(SummaryData(value, openstudio::parseUnitString(units), openstudio::ReportingFrequency(reportingfrequency),
openstudio::FuelType(fueltype), openstudio::InstallLocationType(installlocation))
);
} catch (const std::exception& e) {
LOG(Error, "Error adding / parsing summary data: " << e.what());
}
}
}
sqlite3_finalize(sqlStmtPtr);
}
return retval;
}
void SqlFile_Impl::retrieveDataDictionary() {
std::string table;
std::string name;
std::string keyValue;
std::string units;
std::string rf;
if (m_db) {
int dictionaryIndex;
int code;
std::stringstream s;
sqlite3_stmt* sqlStmtPtr;
std::map<int, std::string> envPeriods;
std::map<int, std::string>::iterator envPeriodsItr;
s << "SELECT EnvironmentPeriodIndex, EnvironmentName FROM EnvironmentPeriods";
sqlite3_prepare_v2(m_db, s.str().c_str(), -1, &sqlStmtPtr, nullptr);
code = sqlite3_step(sqlStmtPtr);
while (code == SQLITE_ROW) {
std::string queryEnvPeriod = boost::to_upper_copy(columnText(sqlite3_column_text(sqlStmtPtr, 1)));
envPeriods.insert(std::pair<int, std::string>(sqlite3_column_int(sqlStmtPtr, 0), queryEnvPeriod));
code = sqlite3_step(sqlStmtPtr);
}
sqlite3_finalize(sqlStmtPtr);
s.str("");
s << "SELECT ReportMeterDataDictionaryIndex, VariableName, KeyValue, ReportingFrequency, VariableUnits";
s << " FROM ReportMeterDataDictionary";
code = sqlite3_prepare_v2(m_db, s.str().c_str(), -1, &sqlStmtPtr, nullptr);
table = "ReportMeterData";
code = sqlite3_step(sqlStmtPtr);
while (code == SQLITE_ROW) {
dictionaryIndex = sqlite3_column_int(sqlStmtPtr, 0);
name = columnText(sqlite3_column_text(sqlStmtPtr, 1));
keyValue = columnText(sqlite3_column_text(sqlStmtPtr, 2));
rf = columnText(sqlite3_column_text(sqlStmtPtr, 3));
units = columnText(sqlite3_column_text(sqlStmtPtr, 4));
for (envPeriodsItr = envPeriods.begin(); envPeriodsItr != envPeriods.end(); ++envPeriodsItr) {
std::string queryEnvPeriod = boost::to_upper_copy(envPeriodsItr->second);
m_dataDictionary.insert(DataDictionaryItem(dictionaryIndex, envPeriodsItr->first, name, keyValue, queryEnvPeriod, rf, units, table));
LOG(Trace, "Creating data dictionary item " << dictionaryIndex << ", " << (*envPeriodsItr).first << ", " << name << ", " << keyValue << ", "
<< queryEnvPeriod << ", " << rf << ", " << units << ", " << table << ".");
}
code = sqlite3_step(sqlStmtPtr);
}
sqlite3_finalize(sqlStmtPtr);
s.str("");
s << "SELECT ReportVariableDatadictionaryIndex, VariableName, KeyValue, ReportingFrequency, VariableUnits";
s << " FROM ReportVariableDatadictionary";
code = sqlite3_prepare_v2(m_db, s.str().c_str(), -1, &sqlStmtPtr, nullptr);
table = "ReportVariableData";
code = sqlite3_step(sqlStmtPtr);
while (code == SQLITE_ROW) {
dictionaryIndex = sqlite3_column_int(sqlStmtPtr, 0);
name = columnText(sqlite3_column_text(sqlStmtPtr, 1));
keyValue = columnText(sqlite3_column_text(sqlStmtPtr, 2));
rf = columnText(sqlite3_column_text(sqlStmtPtr, 3));
units = columnText(sqlite3_column_text(sqlStmtPtr, 4));
for (envPeriodsItr = envPeriods.begin(); envPeriodsItr != envPeriods.end(); ++envPeriodsItr) {
std::string queryEnvPeriod = boost::to_upper_copy(envPeriodsItr->second);
m_dataDictionary.insert(DataDictionaryItem(dictionaryIndex, envPeriodsItr->first, name, keyValue, queryEnvPeriod, rf, units, table));
}
// step to next row
code = sqlite3_step(sqlStmtPtr);
}
sqlite3_finalize(sqlStmtPtr);
}
LOG(Debug, "Dictionary Built");
}
boost::optional<double> SqlFile_Impl::energyConsumptionByMonth(const openstudio::EndUseFuelType& t_fuelType,
const openstudio::EndUseCategoryType& t_categoryType,
const openstudio::MonthOfYear& t_monthOfYear) const {
// For backward compatibilty, we had to preserve enum valueNames (first param in enum, ((valueName)(valueDescription))
// You need to be careful about what you are passing here... valueName or valueDescription
const std::string reportName = "BUILDING ENERGY PERFORMANCE - " + boost::algorithm::to_upper_copy(t_fuelType.valueDescription());
// So this gets tricky, but we have ((Gas)(Natural Gas)). We didn't want to change to ((NaturalGas)(Natural Gas))
// So here we take valueDescription ('Natural Gas', then remove the spaces to be NaturalGas)
const std::string columnName = boost::algorithm::to_upper_copy(t_categoryType.valueName()) + ":"
+ boost::algorithm::to_upper_copy(boost::algorithm::erase_all_copy(t_fuelType.valueDescription(), " "));
const std::string rowName = t_monthOfYear.valueDescription();
const std::string& s = R"(SELECT Value FROM TabularDataWithStrings
WHERE ReportName=?
AND ReportForString='Meter'
AND RowName=?
AND ColumnName=?
AND Units='J')";
return execAndReturnFirstDouble(s, reportName, rowName, columnName);
}
boost::optional<double> SqlFile_Impl::peakEnergyDemandByMonth(const openstudio::EndUseFuelType& t_fuelType,
const openstudio::EndUseCategoryType& t_categoryType,
const openstudio::MonthOfYear& t_monthOfYear) const {
const std::string reportName = "BUILDING ENERGY PERFORMANCE - " + boost::algorithm::to_upper_copy(t_fuelType.valueDescription()) + " PEAK DEMAND";
const std::string columnName = boost::algorithm::to_upper_copy(t_categoryType.valueName()) + ":"
+ boost::algorithm::to_upper_copy(boost::algorithm::erase_all_copy(t_fuelType.valueDescription(), " "))
+ " {AT MAX/MIN}";
const std::string rowName = t_monthOfYear.valueDescription();
const std::string& s = R"(SELECT Value FROM TabularDataWithStrings
WHERE ReportName=?
AND ReportForString='Meter'
AND RowName=?
AND ColumnName=?
AND Units='W')";
return execAndReturnFirstDouble(s, reportName, rowName, columnName);
}
/// hours simulated
boost::optional<double> SqlFile_Impl::hoursSimulated() const {
const std::string& s = R"(SELECT Value FROM TabularDataWithStrings
WHERE ReportName='InputVerificationandResultsSummary'
AND ReportForString='Entire Facility'
AND TableName='General'
AND RowName='Hours Simulated'
AND Units='hrs')";
boost::optional<double> ret = execAndReturnFirstDouble(s);
if (ret) {
return ret;
}
// Otherwise, let's try to calculate it:
return execAndReturnFirstDouble(
"select "
" (select max(t.hour + ((t.simulationdays-1) * 24)) as mintime from time t join reportmeterdata r on (t.timeindex=r.timeindex))"
" - (select min(t.hour + ((t.simulationdays-1) * 24)) as mintime from time t join reportmeterdata r on (t.timeindex=r.timeindex))"
" + 1;");
}
boost::optional<double> SqlFile_Impl::netSiteEnergy() const {
boost::optional<double> hours = hoursSimulated();
if (!hours) {
LOG(Warn, "Reporting Net Site Energy with unknown number of simulation hours");
} else if (*hours != 8760) {
LOG(Warn, "Reporting Net Site Energy with " << *hours << " hrs");
}
std::string s = R"(SELECT Value FROM TabularDataWithStrings
WHERE ReportName='AnnualBuildingUtilityPerformanceSummary'
AND ReportForString='Entire Facility'
AND TableName='Site and Source Energy'
AND RowName='Net Site Energy'
AND ColumnName='Total Energy'
AND Units='GJ')";
boost::optional<double> d = execAndReturnFirstDouble(s);
if (!d) {
LOG(Warn, "Tabular results were not found, trying to calculate it ourselves");
std::string s = " \
select sum(VariableValue)/1000000000 from ReportMeterData, ReportMeterDataDictionary \
where (ReportMeterData.ReportMeterDataDictionaryIndex = ReportMeterDataDictionary.ReportMeterDataDictionaryIndex and variablename not like '%EnergyTransfer%')\
group by ReportingFrequency;\
";
d = execAndReturnFirstDouble(s);
}
return d;
}
boost::optional<double> SqlFile_Impl::netSourceEnergy() const {
boost::optional<double> hours = hoursSimulated();
if (!hours) {
LOG(Warn, "Reporting Net Source Energy with unknown number of simulation hours");
} else if (*hours != 8760) {
LOG(Warn, "Reporting Net Source Energy with " << *hours << " hrs");
}
const std::string& s = R"(SELECT Value FROM TabularDataWithStrings
WHERE ReportName='AnnualBuildingUtilityPerformanceSummary'
AND ReportForString='Entire Facility'
AND TableName='Site and Source Energy'
AND RowName='Net Source Energy'
AND ColumnName='Total Energy'
AND Units='GJ')";
return execAndReturnFirstDouble(s);
}
boost::optional<double> SqlFile_Impl::totalSiteEnergy() const {
boost::optional<double> hours = hoursSimulated();
if (!hours) {
LOG(Warn, "Reporting Total Site Energy with unknown number of simulation hours");
} else if (*hours != 8760) {
LOG(Warn, "Reporting Total Site Energy with " << *hours << " hrs");
}
const std::string& s = R"(SELECT Value FROM TabularDataWithStrings
WHERE ReportName='AnnualBuildingUtilityPerformanceSummary'