Module: OsLib_CreateResults

Defined in:
lib/openstudio/extension/core/CreateResults.rb

Overview

******************************************************************************* OpenStudio®, Copyright © Alliance for Sustainable Energy, LLC. See also openstudio.net/license *******************************************************************************

Instance Method Summary collapse

Instance Method Details

#create_results(skip_weekends = true, skip_holidays = true, start_mo = 'June', start_day = 1, start_hr = 14, end_mo = 'September', end_day = 30, end_hr = 18, electricity_consumption_tou_periods = []) ⇒ OpenStudio::AttributeVector

Reports out the detailed simulation results needed by EDAPT. Results are output as both OpenStudio::Attributes (for OpenStudio 1.X) and runner.registerValue (for OpenStudio 2.X). time-of-use electricity consumption values to the annual consumption information. Periods may overlap, but should be listed in the order in which they must be checked, where the value will be assigned to the first encountered period it falls into. An example hash looks like this:

{
  'tou_name' => 'system_peak',
  'tou_id' => 1,
  'skip_weekends' => true,
  'skip_holidays' => true,
  'start_mo' => 'July',
  'start_day' => 1,
  'start_hr' => 14,
  'end_mo' => 'August',
  'end_day' => 31,
  'end_hr' => 18
}

Parameters:

  • skip_weekends (Bool) (defaults to: true)

    if true, weekends will not be included in the peak demand window

  • skip_holidays (Bool) (defaults to: true)

    if true, holidays will not be included in the peak demand window

  • start_mo (String) (defaults to: 'June')

    the start month for the peak demand window

  • start_day (Integer) (defaults to: 1)

    the start day for the peak demand window

  • start_hr (Integer) (defaults to: 14)

    the start hour for the peak demand window, using 24-hr clock

  • end_mo (String) (defaults to: 'September')

    the end month for the peak demand window

  • end_day (Integer) (defaults to: 30)

    the end day for the peak demand window

  • end_hr (Integer) (defaults to: 18)

    the end hour for the peak demand window, using 24-hr clock

  • electricity_consumption_tou_periods (Array<Hash>) (defaults to: [])

    optional array of hashes to add

Returns:

  • (OpenStudio::AttributeVector)

    a vector of results needed by EDAPT



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
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
# File 'lib/openstudio/extension/core/CreateResults.rb', line 36

def create_results(skip_weekends = true,
                 skip_holidays = true,
                 start_mo = 'June',
                 start_day = 1,
                 start_hr = 14,
                 end_mo = 'September',
                 end_day = 30,
                 end_hr = 18,
                 electricity_consumption_tou_periods = [])

# get the current version of OS being used to determine if sql query
# changes are needed (for when E+ changes).
os_version = OpenStudio::VersionString.new(OpenStudio.openStudioVersion)

# create an attribute vector to hold results
result_elems = OpenStudio::AttributeVector.new

# floor_area
floor_area_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='AnnualBuildingUtilityPerformanceSummary' AND ReportForString='Entire Facility' AND TableName='Building Area' AND RowName='Net Conditioned Building Area' AND ColumnName='Area' AND Units='m2'"
floor_area = @sql.execAndReturnFirstDouble(floor_area_query)
if floor_area.is_initialized
  result_elems << OpenStudio::Attribute.new('floor_area', floor_area.get, 'm^2')
  @runner.registerValue('charsfloor_area', floor_area.get, 'm^2')
else
  @runner.registerWarning('Building floor area not found')
  return false
end

# inflation approach
inf_appr_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='Life-Cycle Cost Report' AND ReportForString='Entire Facility' AND TableName='Life-Cycle Cost Parameters' AND RowName='Inflation Approach' AND ColumnName='Value'"
inf_appr = @sql.execAndReturnFirstString(inf_appr_query)
if inf_appr.is_initialized
  if inf_appr.get == 'ConstantDollar'
    inf_appr = 'Constant Dollar'
  elsif inf_appr.get == 'CurrentDollar'
    inf_appr = 'Current Dollar'
  else
    @runner.registerError("Inflation approach: #{inf_appr.get} not recognized")
    return OpenStudio::Attribute.new('report', result_elems)
  end
  @runner.registerInfo("Inflation approach = #{inf_appr}")
else
  @runner.registerError('Could not determine inflation approach used')
  return OpenStudio::Attribute.new('report', result_elems)
end

# base year
base_yr_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='Life-Cycle Cost Report' AND ReportForString='Entire Facility' AND TableName='Life-Cycle Cost Parameters' AND RowName='Base Date' AND ColumnName='Value'"
base_yr = @sql.execAndReturnFirstString(base_yr_query)
if base_yr.is_initialized
  if base_yr.get =~ /\d\d\d\d/
    base_yr = base_yr.get.match(/\d\d\d\d/)[0].to_f
  else
    @runner.registerError("Could not determine the analysis start year from #{base_yr.get}")
    return OpenStudio::Attribute.new('report', result_elems)
  end
else
  @runner.registerError('Could not determine analysis start year')
  return OpenStudio::Attribute.new('report', result_elems)
end

# analysis length
length_yrs_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='Life-Cycle Cost Report' AND ReportForString='Entire Facility' AND TableName='Life-Cycle Cost Parameters' AND RowName='Length of Study Period in Years' AND ColumnName='Value'"
length_yrs = @sql.execAndReturnFirstInt(length_yrs_query)
if length_yrs.is_initialized
  @runner.registerInfo "Analysis length = #{length_yrs.get} yrs"
  length_yrs = length_yrs.get
else
  @runner.registerError('Could not determine analysis length')
  return OpenStudio::Attribute.new('report', result_elems)
end

# cash flows
cash_flow_elems = OpenStudio::AttributeVector.new

# setup a vector for each type of cash flow
cap_cash_flow_elems = OpenStudio::AttributeVector.new
om_cash_flow_elems = OpenStudio::AttributeVector.new
energy_cash_flow_elems = OpenStudio::AttributeVector.new
water_cash_flow_elems = OpenStudio::AttributeVector.new
tot_cash_flow_elems = OpenStudio::AttributeVector.new

# add the type to the element
cap_cash_flow_elems << OpenStudio::Attribute.new('type', "#{inf_appr} Capital Costs")
om_cash_flow_elems << OpenStudio::Attribute.new('type', "#{inf_appr} Operating Costs")
energy_cash_flow_elems << OpenStudio::Attribute.new('type', "#{inf_appr} Energy Costs")
water_cash_flow_elems << OpenStudio::Attribute.new('type', "#{inf_appr} Water Costs")
tot_cash_flow_elems << OpenStudio::Attribute.new('type', "#{inf_appr} Total Costs")

@runner.registerValue('cash_flows_capital_type', "#{inf_appr} Capital Costs")
@runner.registerValue('cash_flows_operating_type', "#{inf_appr} Operating Costs")
@runner.registerValue('cash_flows_energy_type', "#{inf_appr} Energy Costs")
@runner.registerValue('cash_flows_water_type', "#{inf_appr} Water Costs")
@runner.registerValue('cash_flows_total_type', "#{inf_appr} Total Costs")

# record the cash flow in these hashes
cap_cash_flow = {}
om_cash_flow = {}
energy_cash_flow = {}
water_cash_flow = {}
tot_cash_flow = {}

# loop through each year and record the cash flow
for i in 0..(length_yrs - 1) do
  new_yr = base_yr + i

  yr = nil
  if os_version > OpenStudio::VersionString.new('1.5.3')
    yr = "January         #{new_yr.round}"
  else
    yr = "January           #{new_yr.round}"
  end

  ann_cap_cash = 0.0
  ann_om_cash = 0.0
  ann_energy_cash = 0.0
  ann_water_cash = 0.0
  ann_tot_cash = 0.0

  # capital cash flow
  cap_cash_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='Life-Cycle Cost Report' AND ReportForString='Entire Facility' AND TableName='Capital Cash Flow by Category (Without Escalation)' AND RowName='#{yr}' AND ColumnName='Total'"
  cap_cash = @sql.execAndReturnFirstDouble(cap_cash_query)
  if cap_cash.is_initialized
    ann_cap_cash += cap_cash.get
    ann_tot_cash += cap_cash.get
  end

  # o&m cash flow (excluding utility costs)
  om_types = ['Maintenance', 'Repair', 'Operation', 'Replacement', 'MinorOverhaul', 'MajorOverhaul', 'OtherOperational']
  om_types.each do |om_type|
    om_cash_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='Life-Cycle Cost Report' AND ReportForString='Entire Facility' AND TableName='Operating Cash Flow by Category (Without Escalation)' AND RowName='#{yr}' AND ColumnName='#{om_type}'"
    om_cash = @sql.execAndReturnFirstDouble(om_cash_query)
    if om_cash.is_initialized
      ann_om_cash += om_cash.get
      ann_tot_cash += om_cash.get
    end
  end

  # energy cash flow
  energy_cash_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='Life-Cycle Cost Report' AND ReportForString='Entire Facility' AND TableName='Operating Cash Flow by Category (Without Escalation)' AND RowName='#{yr}' AND ColumnName='Energy'"
  energy_cash = @sql.execAndReturnFirstDouble(energy_cash_query)
  if energy_cash.is_initialized
    ann_energy_cash += energy_cash.get
    ann_tot_cash += energy_cash.get
  end

  # water cash flow
  water_cash_query = "SELECT Value FROM tabulardatawithstrings WHERE ReportName='Life-Cycle Cost Report' AND ReportForString='Entire Facility' AND TableName='Operating Cash Flow by Category (Without Escalation)' AND RowName='#{yr}' AND ColumnName='Water'"
  water_cash = @sql.execAndReturnFirstDouble(water_cash_query)
  if water_cash.is_initialized
    ann_water_cash += water_cash.get
    ann_tot_cash += water_cash.get
  end

  # log the values for this year
  cap_cash_flow[yr] = ann_cap_cash
  om_cash_flow[yr] = ann_om_cash
  energy_cash_flow[yr] = ann_energy_cash
  water_cash_flow[yr] = ann_water_cash
  tot_cash_flow[yr] = ann_tot_cash

  cap_cash_flow_elems << OpenStudio::Attribute.new('year', ann_cap_cash, 'dollars')
  om_cash_flow_elems << OpenStudio::Attribute.new('year', ann_om_cash, 'dollars')
  energy_cash_flow_elems << OpenStudio::Attribute.new('year', ann_energy_cash, 'dollars')
  water_cash_flow_elems << OpenStudio::Attribute.new('year', ann_water_cash, 'dollars')
  tot_cash_flow_elems << OpenStudio::Attribute.new('year', ann_tot_cash, 'dollars')

  @runner.registerValue("cash_flows_capital_year_#{i + 1}", ann_cap_cash, 'dollars')
  @runner.registerValue("cash_flows_operating_year_#{i + 1}", ann_om_cash, 'dollars')
  @runner.registerValue("cash_flows_energy_year_#{i + 1}", ann_energy_cash, 'dollars')
  @runner.registerValue("cash_flows_water_year_#{i + 1}", ann_water_cash, 'dollars')
  @runner.registerValue("cash_flows_total_year_#{i + 1}", ann_tot_cash, 'dollars')

end # next year

# end cash flows
cash_flow_elems << OpenStudio::Attribute.new('cash_flow', cap_cash_flow_elems)
cash_flow_elems << OpenStudio::Attribute.new('cash_flow', om_cash_flow_elems)
cash_flow_elems << OpenStudio::Attribute.new('cash_flow', energy_cash_flow_elems)
cash_flow_elems << OpenStudio::Attribute.new('cash_flow', water_cash_flow_elems)
cash_flow_elems << OpenStudio::Attribute.new('cash_flow', tot_cash_flow_elems)
result_elems << OpenStudio::Attribute.new('cash_flows', cash_flow_elems)

# list of all end uses in OpenStudio
end_use_cat_types = []
OpenStudio::EndUseCategoryType.getValues.each do |end_use_val|
  end_use_cat_types << OpenStudio::EndUseCategoryType.new(end_use_val)
end

# list of all end use fule types in OpenStudio
end_use_fuel_types = []
OpenStudio::EndUseFuelType.getValues.each do |end_use_fuel_type_val|
  end_use_fuel_types << OpenStudio::EndUseFuelType.new(end_use_fuel_type_val)
end

# list of the 12 months of the year in OpenStudio
months = []
OpenStudio::MonthOfYear.getValues.each do |month_of_year_val|
  if (month_of_year_val >= 1) && (month_of_year_val <= 12)
    months << OpenStudio::MonthOfYear.new(month_of_year_val)
  end
end

# map each end use category type to the name that will be used in the xml
end_use_map = {
  OpenStudio::EndUseCategoryType.new('Heating').value => 'heating',
  OpenStudio::EndUseCategoryType.new('Cooling').value => 'cooling',
  OpenStudio::EndUseCategoryType.new('InteriorLights').value => 'lighting_interior',
  OpenStudio::EndUseCategoryType.new('ExteriorLights').value => 'lighting_exterior',
  OpenStudio::EndUseCategoryType.new('InteriorEquipment').value => 'equipment_interior',
  OpenStudio::EndUseCategoryType.new('ExteriorEquipment').value => 'equipment_exterior',
  OpenStudio::EndUseCategoryType.new('Fans').value => 'fans',
  OpenStudio::EndUseCategoryType.new('Pumps').value => 'pumps',
  OpenStudio::EndUseCategoryType.new('HeatRejection').value => 'heat_rejection',
  OpenStudio::EndUseCategoryType.new('Humidifier').value => 'humidification',
  OpenStudio::EndUseCategoryType.new('HeatRecovery').value => 'heat_recovery',
  OpenStudio::EndUseCategoryType.new('WaterSystems').value => 'water_systems',
  OpenStudio::EndUseCategoryType.new('Refrigeration').value => 'refrigeration',
  OpenStudio::EndUseCategoryType.new('Generators').value => 'generators'
}

# map each fuel type in EndUseFuelTypes to a specific FuelTypes
fuel_type_map = {
  OpenStudio::EndUseFuelType.new('Electricity').value => OpenStudio::FuelType.new('Electricity'),
  OpenStudio::EndUseFuelType.new('Gas').value => OpenStudio::FuelType.new('Gas'),
  OpenStudio::EndUseFuelType.new('AdditionalFuel').value => OpenStudio::FuelType.new('Diesel'), # TODO: add other fuel types
  OpenStudio::EndUseFuelType.new('DistrictCooling').value => OpenStudio::FuelType.new('DistrictCooling'),
  OpenStudio::EndUseFuelType.new('DistrictHeating').value => OpenStudio::FuelType.new('DistrictHeating'),
  OpenStudio::EndUseFuelType.new('Water').value => OpenStudio::FuelType.new('Water')
}

# map each fuel type in EndUseFuelTypes to a specific FuelTypes
fuel_type_alias_map = {
  OpenStudio::EndUseFuelType.new('Electricity').value => 'electricity',
  OpenStudio::EndUseFuelType.new('Gas').value => 'gas',
  OpenStudio::EndUseFuelType.new('AdditionalFuel').value => 'other_energy',
  OpenStudio::EndUseFuelType.new('DistrictCooling').value => 'district_cooling',
  OpenStudio::EndUseFuelType.new('DistrictHeating').value => 'district_heating',
  OpenStudio::EndUseFuelType.new('Water').value => 'water'
}

# annual "annual"
annual_elems = OpenStudio::AttributeVector.new

# consumption "consumption"
cons_elems = OpenStudio::AttributeVector.new

# electricity
electricity = @sql.electricityTotalEndUses
if electricity.is_initialized
  cons_elems << OpenStudio::Attribute.new('electricity', electricity.get, 'GJ')
  @runner.registerValue('annual_consumption_electricity', electricity.get, 'GJ')
else
  cons_elems << OpenStudio::Attribute.new('electricity', 0.0, 'GJ')
  @runner.registerValue('annual_consumption_electricity', 0.0, 'GJ')
end

# gas
gas = @sql.naturalGasTotalEndUses
if gas.is_initialized
  cons_elems << OpenStudio::Attribute.new('gas', gas.get, 'GJ')
  @runner.registerValue('annual_consumption_gas', gas.get, 'GJ')
else
  cons_elems << OpenStudio::Attribute.new('gas', 0.0, 'GJ')
  @runner.registerValue('annual_consumption_gas', 0.0, 'GJ')
end

# other_energy
other_energy = @sql.otherFuelTotalEndUses
if other_energy.is_initialized
  cons_elems << OpenStudio::Attribute.new('other_energy', other_energy.get, 'GJ')
  @runner.registerValue('annual_consumption_other_energy', other_energy.get, 'GJ')
else
  cons_elems << OpenStudio::Attribute.new('other_energy', 0.0, 'GJ')
  @runner.registerValue('annual_consumption_other_energy', 0.0, 'GJ')
end

# district_cooling
district_cooling = @sql.districtCoolingTotalEndUses
if district_cooling.is_initialized
  cons_elems << OpenStudio::Attribute.new('district_cooling', district_cooling.get, 'GJ')
  @runner.registerValue('annual_consumption_district_cooling', district_cooling.get, 'GJ')
else
  cons_elems << OpenStudio::Attribute.new('district_cooling', 0.0, 'GJ')
  @runner.registerValue('annual_consumption_district_cooling', 0.0, 'GJ')
end

# district_heating
district_heating = @sql.districtHeatingTotalEndUses
if district_heating.is_initialized
  cons_elems << OpenStudio::Attribute.new('district_heating', district_heating.get, 'GJ')
  @runner.registerValue('annual_consumption_district_heating', district_heating.get, 'GJ')
else
  cons_elems << OpenStudio::Attribute.new('district_heating', 0.0, 'GJ')
  @runner.registerValue('annual_consumption_district_heating', 0.0, 'GJ')
end

# water
water = @sql.waterTotalEndUses
if water.is_initialized
  cons_elems << OpenStudio::Attribute.new('water', water.get, 'm^3')
  @runner.registerValue('annual_consumption_water', water.get, 'm^3')
else
  cons_elems << OpenStudio::Attribute.new('water', 0.0, 'm^3')
  @runner.registerValue('annual_consumption_water', 0.0, 'm^3')
end

# end consumption
annual_elems << OpenStudio::Attribute.new('consumption', cons_elems)

# demand "demand"
demand_elems = OpenStudio::AttributeVector.new

# get the weather file run period (as opposed to design day run period)
ann_env_pd = nil
@sql.availableEnvPeriods.each do |env_pd|
  env_type = @sql.environmentType(env_pd)
  if env_type.is_initialized
    if env_type.get == OpenStudio::EnvironmentType.new('WeatherRunPeriod')
      ann_env_pd = env_pd
    end
  end
end

# only try to get the annual peak demand if an annual simulation was run
if ann_env_pd

  # create some units to use
  joule_unit = OpenStudio.createUnit('J').get
  gigajoule_unit = OpenStudio.createUnit('GJ').get
  hrs_unit = OpenStudio.createUnit('h').get
  kilowatt_unit = OpenStudio.createUnit('kW').get

  # get the annual hours simulated
  hrs_sim = '(0 - no partial annual simulation)'
  if @sql.hoursSimulated.is_initialized
    hrs_sim = @sql.hoursSimulated.get
    if hrs_sim != 8760
      @runner.registerError("Simulation was only #{hrs_sim} hrs; EDA requires an annual simulation (8760 hrs)")
      return OpenStudio::Attribute.new('report', result_elems)
    end
  end

  # Get the electricity timeseries to determine the year used
  elec = @sql.timeSeries(ann_env_pd, 'Zone Timestep', 'Electricity:Facility', '')
  timeseries_yr = nil
  if elec.is_initialized
    timeseries_yr = elec.get.dateTimes[0].date.year
  else
    @runner.registerError('Peak Demand timeseries (Electricity:Facility at zone timestep) could not be found, cannot determine the informatino needed to calculate savings or incentives.')
  end
  # Setup the peak demand time window based on input arguments.
  # Note that holidays and weekends are not excluded because
  # of a bug in EnergyPlus dates.
  # This will only impact corner-case buildings that have
  # peak demand on weekends or holidays, which is unusual.
  @runner.registerInfo("Peak Demand window is #{start_mo} #{start_day} to #{end_mo} #{end_day} from #{start_hr}:00 to #{end_hr}:00.")
  start_date = OpenStudio::DateTime.new(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(start_mo), start_day, timeseries_yr), OpenStudio::Time.new(0, 0, 0, 0))
  end_date = OpenStudio::DateTime.new(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(end_mo), end_day, timeseries_yr), OpenStudio::Time.new(0, 24, 0, 0))
  start_time = OpenStudio::Time.new(0, start_hr, 0, 0)
  end_time = OpenStudio::Time.new(0, end_hr, 0, 0)

  # Get the day type timeseries.
  day_types = nil
  day_type_indices = @sql.timeSeries(ann_env_pd, 'Zone Timestep', 'Site Day Type Index', 'Environment')
  if day_type_indices.is_initialized
    # Put values into array
    day_types = []
    day_type_vals = day_type_indices.get.values
    for i in 0..(day_type_vals.size - 1)
      day_types << day_type_vals[i]
    end
  else
    @runner.registerError('Day Type timeseries (Site Day Type Index at zone timestep) could not be found, cannot accurately determine the peak demand.')
  end

  # electricity_peak_demand
  electricity_peak_demand = -1.0
  electricity_peak_demand_time = nil
  # deduce the timestep based on the hours simulated and the number of datapoints in the timeseries
  if elec.is_initialized && day_types
    elec = elec.get
    num_int = elec.values.size
    int_len_hrs = OpenStudio::Quantity.new(hrs_sim / num_int, hrs_unit)

    # Put timeseries into array
    elec_vals = []
    ann_elec_vals = elec.values
    for i in 0..(ann_elec_vals.size - 1)
      elec_vals << ann_elec_vals[i]
    end

    # Put values into array
    elec_times = []
    ann_elec_times = elec.dateTimes
    for i in 0..(ann_elec_times.size - 1)
      elec_times << ann_elec_times[i]
    end

    # Loop through the time/value pairs and find the peak
    # excluding the times outside of the Xcel peak demand window
    elec_times.zip(elec_vals).each_with_index do |vs, ind|
      date_time = vs[0]
      val = vs[1]
      day_type = day_types[ind]
      time = date_time.time
      date = date_time.date
      day_of_week = date.dayOfWeek
      # Convert the peak demand to kW
      val_J_per_hr = val / int_len_hrs.value
      val_kW = OpenStudio.convert(val_J_per_hr, 'J/h', 'kW').get

      # puts("#{val_kW}kW; #{date}; #{time}; #{day_of_week.valueName}")

      # Skip times outside of the correct months
      next if date_time < start_date || date_time > end_date
      # Skip times before 2pm and after 6pm
      next if time < start_time || time > end_time
      # Skip weekends if asked
      if skip_weekends
        # Sunday = 1, Saturday = 7
        next if day_type == 1 || day_type == 7
      end
      # Skip holidays if asked
      if skip_holidays
        # Holiday = 8
        next if day_type == 8
      end

      # puts("VALID #{val_kW}kW; #{date}; #{time}; #{day_of_week.valueName}")

      # Check peak demand against this timestep
      # and update if this timestep is higher.
      if val > electricity_peak_demand
        electricity_peak_demand = val
        electricity_peak_demand_time = date_time
      end
    end
    elec_peak_demand_timestep_J = OpenStudio::Quantity.new(electricity_peak_demand, joule_unit)
    num_int = elec.values.size
    int_len_hrs = OpenStudio::Quantity.new(hrs_sim / num_int, hrs_unit)
    elec_peak_demand_hourly_J_per_hr = elec_peak_demand_timestep_J / int_len_hrs
    electricity_peak_demand = OpenStudio.convert(elec_peak_demand_hourly_J_per_hr, kilowatt_unit).get.value
    demand_elems << OpenStudio::Attribute.new('electricity_peak_demand', electricity_peak_demand, 'kW')
    @runner.registerValue('annual_demand_electricity_peak_demand', electricity_peak_demand, 'kW')
    @runner.registerInfo("Peak Demand = #{electricity_peak_demand.round(2)}kW on #{electricity_peak_demand_time}")
  else
    @runner.registerError('Peak Demand timeseries (Electricity:Facility at zone timestep) could not be found, cannot determine the informatino needed to calculate savings or incentives.')
    demand_elems << OpenStudio::Attribute.new('electricity_peak_demand', 0.0, 'kW')
    @runner.registerValue('annual_demand_electricity_peak_demand', 0.0, 'kW')
  end

  # Describe the TOU periods
  electricity_consumption_tou_periods.each do |tou_pd|
    @runner.registerInfo("TOU period #{tou_pd['tou_id']} represents #{tou_pd['tou_name']} and covers #{tou_pd['start_mo']}-#{tou_pd['start_day']} to #{tou_pd['end_mo']}-#{tou_pd['end_day']} from #{tou_pd['start_hr']} to #{tou_pd['end_hr']}, skip weekends = #{tou_pd['skip_weekends']}, skip holidays = #{tou_pd['skip_holidays']}")
  end

  # electricity time-of-use periods
  elec = @sql.timeSeries(ann_env_pd, 'Zone Timestep', 'Electricity:Facility', '')
  if elec.is_initialized && day_types
    elec = elec.get
    # Put timeseries into array
    elec_vals = []
    ann_elec_vals = elec.values
    for i in 0..(ann_elec_vals.size - 1)
      elec_vals << ann_elec_vals[i]
    end

    # Put values into array
    elec_times = []
    ann_elec_times = elec.dateTimes
    for i in 0..(ann_elec_times.size - 1)
      elec_times << ann_elec_times[i]
    end

    # Loop through the time/value pairs and find the peak
    # excluding the times outside of the Xcel peak demand window
    electricity_tou_vals = Hash.new(0)
    elec_times.zip(elec_vals).each_with_index do |vs, ind|
      date_time = vs[0]
      joules = vs[1]
      day_type = day_types[ind]
      time = date_time.time
      date = date_time.date

      # puts("#{val_kW}kW; #{date}; #{time}; #{day_of_week.valueName}")

      # Determine which TOU period this hour falls into
      tou_period_assigned = false
      electricity_consumption_tou_periods.each do |tou_pd|
        pd_start_date = OpenStudio::DateTime.new(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(tou_pd['start_mo']), tou_pd['start_day'], timeseries_yr), OpenStudio::Time.new(0, 0, 0, 0))
        pd_end_date = OpenStudio::DateTime.new(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(tou_pd['end_mo']), tou_pd['end_day'], timeseries_yr), OpenStudio::Time.new(0, 24, 0, 0))
        pd_start_time = OpenStudio::Time.new(0, tou_pd['start_hr'], 0, 0)
        pd_end_time = OpenStudio::Time.new(0, tou_pd['end_hr'], 0, 0)
        # Skip times outside of the correct months
        next if date_time < pd_start_date || date_time > pd_end_date
        # Skip times before some time and after another time
        next if time < pd_start_time || time > pd_end_time
        # Skip weekends if asked
        if tou_pd['skip_weekends']
          # Sunday = 1, Saturday = 7
          next if day_type == 1 || day_type == 7
        end
        # Skip holidays if asked
        if tou_pd['skip_holidays']
          # Holiday = 8
          next if day_type == 8
        end
        # If here, this hour falls into the specified period
        tou_period_assigned = true
        electricity_tou_vals[tou_pd['tou_id']] += joules
        break
      end
      # Ensure that the value fell into a period
      unless tou_period_assigned
        @runner.registerError("Did not find a TOU period covering #{time} on #{date}, kWh will not be included in any TOU period.")
      end
    end
    # Register values for any time-of-use period with kWh
    electricity_tou_vals.each do |tou_pd_id, joules_in_pd|
      gj_in_pd = OpenStudio.convert(joules_in_pd, 'J', 'GJ').get
      kwh_in_pd = OpenStudio.convert(joules_in_pd, 'J', 'kWh').get
      @runner.registerValue("annual_consumption_electricity_tou_#{tou_pd_id}", gj_in_pd, 'GJ')
      @runner.registerInfo("TOU period #{tou_pd_id} annual electricity consumption = #{kwh_in_pd} kWh.")
    end
  else
    @runner.registerError('Electricity timeseries (Electricity:Facility at zone timestep) could not be found, cannot determine the information needed to calculate savings or incentives.')
  end

  # electricity_annual_avg_peak_demand
  val = @sql.electricityTotalEndUses
  if val.is_initialized
    ann_elec_gj = OpenStudio::Quantity.new(val.get, gigajoule_unit)
    ann_hrs = OpenStudio::Quantity.new(hrs_sim, hrs_unit)
    elec_ann_avg_peak_demand_hourly_GJ_per_hr = ann_elec_gj / ann_hrs
    electricity_annual_avg_peak_demand = OpenStudio.convert(elec_ann_avg_peak_demand_hourly_GJ_per_hr, kilowatt_unit).get.value
    demand_elems << OpenStudio::Attribute.new('electricity_annual_avg_peak_demand', electricity_annual_avg_peak_demand, 'kW')
    @runner.registerValue('annual_demand_electricity_annual_avg_peak_demand', electricity_annual_avg_peak_demand, 'kW')
  else
    demand_elems << OpenStudio::Attribute.new('electricity_annual_avg_peak_demand', 0.0, 'kW')
    @runner.registerValue('annual_demand_electricity_annual_avg_peak_demand', 0.0, 'kW')
  end

  # district_cooling_peak_demand
  district_cooling_peak_demand = -1.0
  ann_dist_clg_peak_demand_time = nil
  dist_clg = @sql.timeSeries(ann_env_pd, 'Zone Timestep', 'DistrictCooling:Facility', '')
  # deduce the timestep based on the hours simulated and the number of datapoints in the timeseries
  if dist_clg.is_initialized && day_types
    dist_clg = dist_clg.get
    num_int = dist_clg.values.size
    int_len_hrs = OpenStudio::Quantity.new(hrs_sim / num_int, hrs_unit)

    # Put timeseries into array
    dist_clg_vals = []
    ann_dist_clg_vals = dist_clg.values
    for i in 0..(ann_dist_clg_vals.size - 1)
      dist_clg_vals << ann_dist_clg_vals[i]
    end

    # Put values into array
    dist_clg_times = []
    ann_dist_clg_times = dist_clg.dateTimes
    for i in 0..(ann_dist_clg_times.size - 1)
      dist_clg_times << ann_dist_clg_times[i]
    end

    # Loop through the time/value pairs and find the peak
    # excluding the times outside of the Xcel peak demand window
    dist_clg_times.zip(dist_clg_vals).each_with_index do |vs, ind|
      date_time = vs[0]
      val = vs[1]
      day_type = day_types[ind]
      time = date_time.time
      date = date_time.date
      day_of_week = date.dayOfWeek
      # Convert the peak demand to kW
      val_J_per_hr = val / int_len_hrs.value
      val_kW = OpenStudio.convert(val_J_per_hr, 'J/h', 'kW').get

      # puts("#{val_kW}kW; #{date}; #{time}; #{day_of_week.valueName}")

      # Skip times outside of the correct months
      next if date_time < start_date || date_time > end_date
      # Skip times before 2pm and after 6pm
      next if time < start_time || time > end_time
      # Skip weekends if asked
      if skip_weekends
        # Sunday = 1, Saturday = 7
        next if day_type == 1 || day_type == 7
      end
      # Skip holidays if asked
      if skip_holidays
        # Holiday = 8
        next if day_type == 8
      end

      # puts("VALID #{val_kW}kW; #{date}; #{time}; #{day_of_week.valueName}")

      # Check peak demand against this timestep
      # and update if this timestep is higher.
      if val > district_cooling_peak_demand
        district_cooling_peak_demand = val
        ann_dist_clg_peak_demand_time = date_time
      end
    end
    dist_clg_peak_demand_timestep_J = OpenStudio::Quantity.new(district_cooling_peak_demand, joule_unit)
    num_int = dist_clg.values.size
    int_len_hrs = OpenStudio::Quantity.new(hrs_sim / num_int, hrs_unit)
    dist_clg_peak_demand_hourly_J_per_hr = dist_clg_peak_demand_timestep_J / int_len_hrs
    district_cooling_peak_demand = OpenStudio.convert(dist_clg_peak_demand_hourly_J_per_hr, kilowatt_unit).get.value
    demand_elems << OpenStudio::Attribute.new('district_cooling_peak_demand', district_cooling_peak_demand, 'kW')
    @runner.registerValue('annual_demand_district_cooling_peak_demand', district_cooling_peak_demand, 'kW')
    @runner.registerInfo("District Cooling Peak Demand = #{district_cooling_peak_demand.round(2)}kW on #{ann_dist_clg_peak_demand_time}")
  else
    demand_elems << OpenStudio::Attribute.new('district_cooling_peak_demand', 0.0, 'kW')
    @runner.registerValue('annual_demand_district_cooling_peak_demand', 0.0, 'kW')
  end

  # district cooling time-of-use periods
  dist_clg = @sql.timeSeries(ann_env_pd, 'Zone Timestep', 'DistrictCooling:Facility', '')
  if dist_clg.is_initialized && day_types
    dist_clg = dist_clg.get
    # Put timeseries into array
    dist_clg_vals = []
    ann_dist_clg_vals = dist_clg.values
    for i in 0..(ann_dist_clg_vals.size - 1)
      dist_clg_vals << ann_dist_clg_vals[i]
    end

    # Put values into array
    dist_clg_times = []
    ann_dist_clg_times = dist_clg.dateTimes
    for i in 0..(ann_dist_clg_times.size - 1)
      dist_clg_times << ann_dist_clg_times[i]
    end

    # Loop through the time/value pairs and find the peak
    # excluding the times outside of the Xcel peak demand window
    dist_clg_tou_vals = Hash.new(0)
    dist_clg_times.zip(dist_clg_vals).each_with_index do |vs, ind|
      date_time = vs[0]
      joules = vs[1]
      day_type = day_types[ind]
      time = date_time.time
      date = date_time.date

      # puts("#{val_kW}kW; #{date}; #{time}; #{day_of_week.valueName}")

      # Determine which TOU period this hour falls into
      tou_period_assigned = false
      electricity_consumption_tou_periods.each do |tou_pd|
        pd_start_date = OpenStudio::DateTime.new(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(tou_pd['start_mo']), tou_pd['start_day'], timeseries_yr), OpenStudio::Time.new(0, 0, 0, 0))
        pd_end_date = OpenStudio::DateTime.new(OpenStudio::Date.new(OpenStudio::MonthOfYear.new(tou_pd['end_mo']), tou_pd['end_day'], timeseries_yr), OpenStudio::Time.new(0, 24, 0, 0))
        pd_start_time = OpenStudio::Time.new(0, tou_pd['start_hr'], 0, 0)
        pd_end_time = OpenStudio::Time.new(0, tou_pd['end_hr'], 0, 0)
        # Skip times outside of the correct months
        next if date_time < pd_start_date || date_time > pd_end_date
        # Skip times before some time and after another time
        next if time < pd_start_time || time > pd_end_time
        # Skip weekends if asked
        if tou_pd['skip_weekends']
          # Sunday = 1, Saturday = 7
          next if day_type == 1 || day_type == 7
        end
        # Skip holidays if asked
        if tou_pd['skip_holidays']
          # Holiday = 8
          next if day_type == 8
        end
        # If here, this hour falls into the specified period
        tou_period_assigned = true
        dist_clg_tou_vals[tou_pd['tou_id']] += joules
        break
      end
      # Ensure that the value fell into a period
      unless tou_period_assigned
        @runner.registerError("Did not find a TOU period covering #{time} on #{date}, kWh will not be included in any TOU period.")
      end
    end
    # Register values for any time-of-use period with kWh
    dist_clg_tou_vals.each do |tou_pd_id, joules_in_pd|
      gj_in_pd = OpenStudio.convert(joules_in_pd, 'J', 'GJ').get
      kwh_in_pd = OpenStudio.convert(joules_in_pd, 'J', 'kWh').get
      @runner.registerValue("annual_consumption_district_cooling_tou_#{tou_pd_id}", gj_in_pd, 'GJ')
      @runner.registerInfo("TOU period #{tou_pd_id} annual district cooling consumption = #{kwh_in_pd} kWh.")
    end
  else
    # If TOU periods were specified but this model has no district cooling, report zeroes
    if electricity_consumption_tou_periods.size > 0
      # Get the TOU ids
      tou_ids = []
      electricity_consumption_tou_periods.each do |tou_pd|
        tou_ids << tou_pd['tou_id']
      end
      tou_ids.uniq.each do |tou_id|
        @runner.registerValue("annual_consumption_district_cooling_tou_#{tou_id}", 0.0, 'GJ')
      end
    end
  end

else
  @runner.registerError('Could not find an annual run period')
  return OpenStudio::Attribute.new('report', result_elems)
end

# end demand
annual_elems << OpenStudio::Attribute.new('demand', demand_elems)

# utility_cost
utility_cost_elems = OpenStudio::AttributeVector.new
annual_utility_cost_map = {}

# electricity
electricity = @sql.annualTotalCost(OpenStudio::FuelType.new('Electricity'))
if electricity.is_initialized
  utility_cost_elems << OpenStudio::Attribute.new('electricity', electricity.get, 'dollars')
  @runner.registerValue('annual_utility_cost_electricity', electricity.get, 'dollars')
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Electricity').valueName] = electricity.get
else
  utility_cost_elems << OpenStudio::Attribute.new('electricity', 0.0, 'dollars')
  @runner.registerValue('annual_utility_cost_electricity', 0.0, 'dollars')
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Electricity').valueName] = 0.0
end

# electricity_consumption_charge and electricity_demand_charge
electric_consumption_charge = 0.0
electric_demand_charge = 0.0

electric_rate_query = "SELECT value FROM tabulardatawithstrings WHERE ReportName='LEEDsummary' AND ReportForString='Entire Facility' AND TableName='EAp2-3. Energy Type Summary' AND RowName='Electricity' AND ColumnName='Utility Rate'"
electric_rate_name = @sql.execAndReturnFirstString(electric_rate_query)
if electric_rate_name.is_initialized
  electric_rate_name = electric_rate_name.get.strip

  # electricity_consumption_charge
  electric_consumption_charge_query = "SELECT value FROM tabulardatawithstrings WHERE ReportName='Tariff Report' AND ReportForString='#{electric_rate_name}' AND TableName='Categories' AND RowName='EnergyCharges (~~$~~)' AND ColumnName='Sum'"
  val = @sql.execAndReturnFirstDouble(electric_consumption_charge_query)
  if val.is_initialized
    electric_consumption_charge = val.get
  end

  # electricity_demand_charge
  electric_demand_charge_query = "SELECT value FROM tabulardatawithstrings WHERE ReportName='Tariff Report' AND ReportForString='#{electric_rate_name}' AND TableName='Categories' AND RowName='DemandCharges (~~$~~)' AND ColumnName='Sum'"
  val = @sql.execAndReturnFirstDouble(electric_demand_charge_query)
  if val.is_initialized
    electric_demand_charge = val.get
  end

end
utility_cost_elems << OpenStudio::Attribute.new('electricity_consumption_charge', electric_consumption_charge, 'dollars')
@runner.registerValue('annual_utility_cost_electricity_consumption_charge', electric_consumption_charge, 'dollars')
utility_cost_elems << OpenStudio::Attribute.new('electricity_demand_charge', electric_demand_charge, 'dollars')
@runner.registerValue('annual_utility_cost_electricity_demand_charge', electric_demand_charge, 'dollars')

# gas
gas = @sql.annualTotalCost(OpenStudio::FuelType.new('Gas'))
if gas.is_initialized
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Gas').valueName] = gas.get
else
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Gas').valueName] = 0.0
end

# district_cooling
district_cooling_charge = 0.0

district_cooling_rate_query = "SELECT value FROM tabulardatawithstrings WHERE ReportName='LEEDsummary' AND ReportForString='Entire Facility' AND TableName='EAp2-3. Energy Type Summary' AND RowName='District Cooling' AND ColumnName='Utility Rate'"
district_cooling_rate_name = @sql.execAndReturnFirstString(district_cooling_rate_query)
if district_cooling_rate_name.is_initialized
  district_cooling_rate_name = district_cooling_rate_name.get.strip

  # district_cooling_charge
  district_cooling_charge_query = "SELECT value FROM tabulardatawithstrings WHERE ReportName='Tariff Report' AND ReportForString='#{district_cooling_rate_name}' AND TableName='Categories' AND RowName='Basis (~~$~~)' AND ColumnName='Sum'"
  val = @sql.execAndReturnFirstDouble(district_cooling_charge_query)
  if val.is_initialized
    district_cooling_charge = val.get
  end

end
annual_utility_cost_map[OpenStudio::EndUseFuelType.new('DistrictCooling').valueName] = district_cooling_charge

# district_heating
district_heating_charge = 0.0

district_heating_rate_query = "SELECT value FROM tabulardatawithstrings WHERE ReportName='LEEDsummary' AND ReportForString='Entire Facility' AND TableName='EAp2-3. Energy Type Summary' AND RowName='District Heating' AND ColumnName='Utility Rate'"
district_heating_rate_name = @sql.execAndReturnFirstString(district_heating_rate_query)
if district_heating_rate_name.is_initialized
  district_heating_rate_name = district_heating_rate_name.get.strip

  # district_heating_charge
  district_heating_charge_query = "SELECT value FROM tabulardatawithstrings WHERE ReportName='Tariff Report' AND ReportForString='#{district_heating_rate_name}' AND TableName='Categories' AND RowName='Basis (~~$~~)' AND ColumnName='Sum'"
  val = @sql.execAndReturnFirstDouble(district_heating_charge_query)
  if val.is_initialized
    district_heating_charge = val.get
  end

end
annual_utility_cost_map[OpenStudio::EndUseFuelType.new('DistrictHeating').valueName] = district_heating_charge

# water
water = @sql.annualTotalCost(OpenStudio::FuelType.new('Water'))
if water.is_initialized
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Water').valueName] = water.get
else
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Water').valueName] = 0.0
end

# total
total_query = "SELECT Value from tabulardatawithstrings where (reportname = 'Economics Results Summary Report') and (ReportForString = 'Entire Facility') and (TableName = 'Annual Cost') and (ColumnName ='Total') and (((RowName = 'Cost') and (Units = '~~$~~')) or (RowName = 'Cost (~~$~~)'))"
total = @sql.execAndReturnFirstDouble(total_query)

# other_energy
# Subtract off the already accounted for fuel types from the total
# to account for fuels on custom meters where the fuel type is not known.
prev_tot = 0.0
annual_utility_cost_map.each do |fuel, val|
  prev_tot += val
end
if total.is_initialized
  other_val = total.get - prev_tot
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('AdditionalFuel').valueName] = other_val
else
  annual_utility_cost_map[OpenStudio::EndUseFuelType.new('AdditionalFuel').valueName] = 0.0
end

# export remaining costs in the correct order
# gas
utility_cost_elems << OpenStudio::Attribute.new('gas', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Gas').valueName], 'dollars')
@runner.registerValue('annual_utility_cost_gas', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Gas').valueName], 'dollars')
# other_energy
utility_cost_elems << OpenStudio::Attribute.new('other_energy', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('AdditionalFuel').valueName], 'dollars')
@runner.registerValue('annual_utility_cost_other_energy', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('AdditionalFuel').valueName], 'dollars')
# district_cooling
utility_cost_elems << OpenStudio::Attribute.new('district_cooling', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('DistrictCooling').valueName], 'dollars')
@runner.registerValue('annual_utility_cost_district_cooling', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('DistrictCooling').valueName], 'dollars')
# district_heating
utility_cost_elems << OpenStudio::Attribute.new('district_heating', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('DistrictHeating').valueName], 'dollars')
@runner.registerValue('annual_utility_cost_district_heating', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('DistrictHeating').valueName], 'dollars')
# water
utility_cost_elems << OpenStudio::Attribute.new('water', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Water').valueName], 'dollars')
@runner.registerValue('annual_utility_cost_water', annual_utility_cost_map[OpenStudio::EndUseFuelType.new('Water').valueName], 'dollars')
# total
if total.is_initialized
  utility_cost_elems << OpenStudio::Attribute.new('total', total.get, 'dollars')
  @runner.registerValue('annual_utility_cost_total', total.get, 'dollars')
else
  utility_cost_elems << OpenStudio::Attribute.new('total', 0.0, 'dollars')
  @runner.registerValue('annual_utility_cost_total', 0.0, 'dollars')
end

# end_uses - utility costs by end use using average blended cost
end_uses_elems = OpenStudio::AttributeVector.new
# map to store the costs by end use
cost_by_end_use = {}

# fill the map with 0.0's to start
end_use_cat_types.each do |end_use_cat_type|
  cost_by_end_use[end_use_cat_type] = 0.0
end

# only attempt to get monthly data if enduses table is available
if @sql.endUses.is_initialized
  end_uses_table = @sql.endUses.get
  # loop through all the fuel types
  end_use_fuel_types.each do |end_use_fuel_type|
    # get the annual total cost for this fuel type
    ann_cost = annual_utility_cost_map[end_use_fuel_type.valueName]
    # get the total annual usage for this fuel type in all end use categories
    # loop through all end uses, adding the annual usage value to the aggregator
    ann_usg = 0.0
    end_use_cat_types.each do |end_use_cat_type|
      ann_usg += end_uses_table.getEndUse(end_use_fuel_type, end_use_cat_type)
    end
    # figure out the annual blended rate for this fuel type
    avg_ann_rate = 0.0
    if ann_cost > 0 && ann_usg > 0
      avg_ann_rate = ann_cost / ann_usg
    end
    # for each end use category, figure out the cost if using
    # the avg ann rate; add this cost to the map
    end_use_cat_types.each do |end_use_cat_type|
      cost_by_end_use[end_use_cat_type] += end_uses_table.getEndUse(end_use_fuel_type, end_use_cat_type) * avg_ann_rate
    end
  end
  # loop through the end uses and record the annual total cost based on the avg annual rate
  end_use_cat_types.each do |end_use_cat_type|
    # record the value
    end_uses_elems << OpenStudio::Attribute.new(end_use_map[end_use_cat_type.value], cost_by_end_use[end_use_cat_type], 'dollars')
    @runner.registerValue("annual_utility_cost_end_uses_#{end_use_map[end_use_cat_type.value]}", cost_by_end_use[end_use_cat_type], 'dollars')
  end
else
  @runner.registerError('End-Use table not available in results; could not retrieve monthly costs by end use')
  return OpenStudio::Attribute.new('report', result_elems)
end

# end end_uses
utility_cost_elems << OpenStudio::Attribute.new('end_uses', end_uses_elems)

# end utility_costs
annual_elems << OpenStudio::Attribute.new('utility_cost', utility_cost_elems)

# end annual
result_elems << OpenStudio::Attribute.new('annual', annual_elems)

# monthly
monthly_elems = OpenStudio::AttributeVector.new

# consumption
cons_elems = OpenStudio::AttributeVector.new
# loop through all end uses
end_use_cat_types.each do |end_use_cat|
  end_use_elems = OpenStudio::AttributeVector.new
  end_use_name = end_use_map[end_use_cat.value]
  # in each end use, loop through all fuel types
  end_use_fuel_types.each do |end_use_fuel_type|
    fuel_type_elems = OpenStudio::AttributeVector.new
    fuel_type_name = fuel_type_alias_map[end_use_fuel_type.value]
    ann_energy_cons = 0.0
    # in each end use, loop through months and get monthly enedy consumption
    months.each_with_index do |month, i|
      mon_energy_cons = 0.0
      val = @sql.energyConsumptionByMonth(end_use_fuel_type, end_use_cat, month)
      if val.is_initialized
        monthly_consumption_J = OpenStudio::Quantity.new(val.get, joule_unit)
        monthly_consumption_GJ = OpenStudio.convert(monthly_consumption_J, gigajoule_unit).get.value
        mon_energy_cons = monthly_consumption_GJ
        ann_energy_cons += monthly_consumption_GJ
      end
      # record the monthly value
      if end_use_fuel_type == OpenStudio::EndUseFuelType.new('Water')
        fuel_type_elems << OpenStudio::Attribute.new('month', mon_energy_cons, 'm^3')
        @runner.registerValue("monthly_consumption_#{end_use_name}_#{fuel_type_name}_month_#{i + 1}", mon_energy_cons, 'm^3')
      else
        fuel_type_elems << OpenStudio::Attribute.new('month', mon_energy_cons, 'GJ')
        @runner.registerValue("monthly_consumption_#{end_use_name}_#{fuel_type_name}_month_#{i + 1}", mon_energy_cons, 'GJ')
      end
    end
    # record the annual total
    fuel_type_elems << OpenStudio::Attribute.new('year', ann_energy_cons, 'GJ')
    @runner.registerValue("monthly_consumption_#{end_use_name}_#{fuel_type_name}_year", ann_energy_cons, 'GJ')
    # add this fuel type
    end_use_elems << OpenStudio::Attribute.new(fuel_type_alias_map[end_use_fuel_type.value], fuel_type_elems)
  end
  # add this end use
  cons_elems << OpenStudio::Attribute.new(end_use_map[end_use_cat.value], end_use_elems)
end
# end consumption
monthly_elems << OpenStudio::Attribute.new('consumption', cons_elems)

# create a unit to use
watt_unit = OpenStudio.createUnit('W').get
kilowatt_unit = OpenStudio.createUnit('kW').get

# demand
demand_elems = OpenStudio::AttributeVector.new
# loop through all end uses
end_use_cat_types.each do |end_use_cat|
  end_use_elems = OpenStudio::AttributeVector.new
  end_use_name = end_use_map[end_use_cat.value]
  # in each end use, loop through all fuel types
  end_use_fuel_types.each do |end_use_fuel_type|
    fuel_type_elems = OpenStudio::AttributeVector.new
    fuel_type_name = fuel_type_alias_map[end_use_fuel_type.value]
    ann_peak_demand = 0.0
    # in each end use, loop through months and get monthly enedy consumption
    months.each_with_index do |month, i|
      mon_peak_demand = 0.0
      val = @sql.peakEnergyDemandByMonth(end_use_fuel_type, end_use_cat, month)
      if val.is_initialized
        mon_peak_demand_W = OpenStudio::Quantity.new(val.get, watt_unit)
        mon_peak_demand = OpenStudio.convert(mon_peak_demand_W, kilowatt_unit).get.value
      end
      # record the monthly value
      fuel_type_elems << OpenStudio::Attribute.new('month', mon_peak_demand, 'kW')
      @runner.registerValue("monthly_demand_#{end_use_name}_#{fuel_type_name}_month_#{i + 1}", mon_peak_demand, 'kW')
      # if month peak demand > ann peak demand make this new ann peak demand
      if mon_peak_demand > ann_peak_demand
        ann_peak_demand = mon_peak_demand
      end
    end
    # record the annual peak demand
    fuel_type_elems << OpenStudio::Attribute.new('year', ann_peak_demand, 'kW')
    @runner.registerValue("monthly_demand_#{end_use_name}_#{fuel_type_name}_year", ann_peak_demand, 'kW')
    # add this fuel type
    end_use_elems << OpenStudio::Attribute.new(fuel_type_alias_map[end_use_fuel_type.value], fuel_type_elems)
  end
  # add this end use
  demand_elems << OpenStudio::Attribute.new(end_use_map[end_use_cat.value], end_use_elems)
end
# end demand
monthly_elems << OpenStudio::Attribute.new('demand', demand_elems)

# end monthly
result_elems << OpenStudio::Attribute.new('monthly', monthly_elems)

result_elem = OpenStudio::Attribute.new('results', result_elems)
return result_elem
end