Class: AddCentralIceStorage

Inherits:
OpenStudio::Measure::ModelMeasure
  • Object
show all
Defined in:
lib/measures/add_central_ice_storage/measure.rb

Overview

start the measure

Instance Method Summary collapse

Instance Method Details

#arguments(model) ⇒ Object

define the arguments that the user will input



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
# File 'lib/measures/add_central_ice_storage/measure.rb', line 74

def arguments(model)
  args = OpenStudio::Measure::OSArgumentVector.new

  # Make choice argument for energy storage objective

  objective = OpenStudio::Measure::OSArgument.makeChoiceArgument('objective', ['Full Storage', 'Partial Storage'], true)
  objective.setDisplayName('Select Energy Storage Objective:')
  objective.setDefaultValue('Partial Storage')
  args << objective

  # Make choice argument for component layout

  upstream = OpenStudio::Measure::OSArgument.makeChoiceArgument('upstream', ['Chiller', 'Storage'])
  upstream.setDisplayName('Select Upstream Device:')
  upstream.setDescription('Partial Storage Only. See documentation for control implementation.')
  upstream.setDefaultValue('Chiller')
  args << upstream

  # Make double argument for thermal energy storage capacity

  storage_capacity = OpenStudio::Measure::OSArgument.makeDoubleArgument('storage_capacity', true)
  storage_capacity.setDisplayName('Enter Thermal Energy Storage Capacity for Ice Tank [ton-hours]:')
  storage_capacity.setDefaultValue(2000)
  args << storage_capacity

  # Make choice argument for ice melt process indicator

  melt_indicator = OpenStudio::Measure::OSArgument.makeChoiceArgument('melt_indicator', ['InsideMelt', 'OutsideMelt'], true)
  melt_indicator.setDisplayName('Select Thaw Process Indicator for Ice Storage:')
  melt_indicator.setDescription('')
  melt_indicator.setDefaultValue('InsideMelt')
  args << melt_indicator

  # Make list of chilled water loop(s) from which user can select

  plant_loops = model.getPlantLoops
  loop_choices = OpenStudio::StringVector.new
  plant_loops.each do |loop|
    if loop.sizingPlant.loopType.to_s == 'Cooling'
      loop_choices << loop.name.to_s
    end
  end

  # Make choice argument for loop selection

  selected_loop = OpenStudio::Measure::OSArgument.makeChoiceArgument('selected_loop', loop_choices, true)
  selected_loop.setDisplayName('Select Loop:')
  selected_loop.setDescription('This is the cooling loop on which the ice tank will be added.')
  if loop_choices.include?('Chilled Water Loop')
    selected_loop.setDefaultValue('Chilled Water Loop')
  else
    selected_loop.setDescription('Error: No Cooling Loop Found')
  end
  args << selected_loop

  # Make list of available chillers from which the user can select

  chillers = model.getChillerElectricEIRs
  chillers += model.getChillerAbsorptions
  chillers += model.getChillerAbsorptionIndirects
  chiller_choices = OpenStudio::StringVector.new
  chillers.each do |chill|
    chiller_choices << chill.name.to_s
  end

  # Make choice argument for chiller selection

  selected_chiller = OpenStudio::Measure::OSArgument.makeChoiceArgument('selected_chiller', chiller_choices, true)
  selected_chiller.setDisplayName('Select Chiller:')
  selected_chiller.setDescription('The ice tank will be placed in series with this chiller.')
  if !chillers.empty?
    selected_chiller.setDefaultValue(chiller_choices[0])
  else
    selected_chiller.setDescription('Error: No Chiller Found')
  end
  args << selected_chiller

  # Make double argument for ice chiller resizing factor - relative to selected chiller capacity

  chiller_resize_factor = OpenStudio::Measure::OSArgument.makeDoubleArgument('chiller_resize_factor', false)
  chiller_resize_factor.setDisplayName('Enter Chiller Sizing Factor:')
  chiller_resize_factor.setDefaultValue(0.75)
  args << chiller_resize_factor

  # Make double argument for chiller max capacity limit during ice discharge

  chiller_limit = OpenStudio::Measure::OSArgument.makeDoubleArgument('chiller_limit', false)
  chiller_limit.setDisplayName('Enter Chiller Max Capacity Limit During Ice Discharge:')
  chiller_limit.setDescription('Enter as a fraction of chiller capacity (0.0 - 1.0).')
  chiller_limit.setDefaultValue(1.0)
  args << chiller_limit

  # Make choice argument for schedule options

  old = OpenStudio::Measure::OSArgument.makeBoolArgument('old', false)
  old.setDisplayName('Use Existing (Pre-Defined) Temperature Control Schedules')
  old.setDescription('Use drop-down selections below.')
  old.setDefaultValue(false)
  args << old

  # Find All Existing Schedules with Type Limits of "Temperature"

  sched_options = []
  sched_options2 = []
  all_scheds = model.getSchedules
  all_scheds.each do |sched|
    sched.to_ScheduleBase.get
    unless sched.scheduleTypeLimits.empty?
      if sched.scheduleTypeLimits.get.unitType.to_s == 'Temperature'
        sched_options << sched.name.to_s
      elsif sched.scheduleTypeLimits.get.unitType.to_s == 'Availability' ||
            sched.scheduleTypeLimits.get.unitType.to_s == 'OnOff'
        sched_options2 << sched.name.to_s
      end
    end
  end
  sched_options = ['N/A'] + sched_options.sort
  sched_options2 = ['N/A'] + sched_options2.sort

  # Create choice argument for ice availability schedule (old = true)

  ctes_av = OpenStudio::Measure::OSArgument.makeChoiceArgument('ctes_av', sched_options2, false)
  ctes_av.setDisplayName('Select Pre-Defined Ice Availability Schedule')
  if sched_options2.empty?
    ctes_av.setDescription('Warning: No availability schedules found')
  end
  ctes_av.setDefaultValue('N/A')
  args << ctes_av

  # Create choice argument for ice tank component setpoint sched (old = true)

  ctes_sch = OpenStudio::Measure::OSArgument.makeChoiceArgument('ctes_sch', sched_options, false)
  ctes_sch.setDisplayName('Select Pre-Defined Ice Tank Component Setpoint Schedule')
  if sched_options.empty?
    ctes_sch.setDescription('Warning: No temperature setpoint schedules found')
  end
  ctes_sch.setDefaultValue('N/A')
  args << ctes_sch

  # Create choice argument for chiller component setpoint sched (old = true)

  chill_sch = OpenStudio::Measure::OSArgument.makeChoiceArgument('chill_sch', sched_options, false)
  chill_sch.setDisplayName('Select Pre-Defined Chiller Component Setpoint Schedule')
  if sched_options.empty?
    chill_sch.setDescription('Warning: No temperature setpoint schedules found')
  end
  chill_sch.setDefaultValue('N/A')
  args << chill_sch

  # Make bool argument for creating new schedules

  new = OpenStudio::Measure::OSArgument.makeBoolArgument('new', false)
  new.setDisplayName('Create New (Simple) Temperature Control Schedules')
  new.setDescription('Use entry fields below. If Pre-Defined is also selected, these new schedules will be created' \
                     ' but not applied.')
  new.setDefaultValue(true)
  args << new

  # Make double argument for loop setpoint temperature

  loop_sp = OpenStudio::Measure::OSArgument.makeDoubleArgument('loop_sp', true)
  loop_sp.setDisplayName('Loop Setpoint Temperature F:')
  loop_sp.setDescription('This value replaces the existing loop temperature setpoint manager; the old manager will ' \
                         'be disconnected but not deleted from the model.')
  loop_sp.setDefaultValue(44)
  args << loop_sp

  # Make double argument for ice chiller outlet temp during partial storage operation

  inter_sp = OpenStudio::Measure::OSArgument.makeDoubleArgument('inter_sp', false)
  inter_sp.setDisplayName('Enter Intermediate Setpoint for Upstream Cooling Device During Ice Discharge F:')
  inter_sp.setDescription('Partial storage only')
  inter_sp.setDefaultValue(47)
  args << inter_sp

  # Make double argument for loop temperature for ice charging

  chg_sp = OpenStudio::Measure::OSArgument.makeDoubleArgument('chg_sp', true)
  chg_sp.setDisplayName('Ice Charging Setpoint Temperature F:')
  chg_sp.setDefaultValue(25)
  args << chg_sp

  # Make double argument for loop design delta T

  delta_t = OpenStudio::Measure::OSArgument.makeStringArgument('delta_t', true)
  delta_t.setDisplayName('Loop Design Temperature Difference F:')
  delta_t.setDescription('Enter numeric value to adjust selected loop settings.')
  delta_t.setDefaultValue('Use Existing Loop Value')
  args << delta_t

  # Make string argument for ctes seasonal availabilty

  ctes_season = OpenStudio::Measure::OSArgument.makeStringArgument('ctes_season', true)
  ctes_season.setDisplayName('Enter Seasonal Availabity of Ice Storage:')
  ctes_season.setDescription('Use MM/DD-MM/DD format')
  ctes_season.setDefaultValue('01/01-12/31')
  args << ctes_season

  # Make string arguments for ctes discharge times

  discharge_start = OpenStudio::Measure::OSArgument.makeStringArgument('discharge_start', true)
  discharge_start.setDisplayName('Enter Starting Time for Ice Discharge:')
  discharge_start.setDescription('Use 24 hour format (HR:MM)')
  discharge_start.setDefaultValue('08:00')
  args << discharge_start

  discharge_end = OpenStudio::Measure::OSArgument.makeStringArgument('discharge_end', true)
  discharge_end.setDisplayName('Enter End Time for Ice Discharge:')
  discharge_end.setDescription('Use 24 hour format (HR:MM)')
  discharge_end.setDefaultValue('21:00')
  args << discharge_end

  # Make string arguments for ctes charge times

  charge_start = OpenStudio::Measure::OSArgument.makeStringArgument('charge_start', true)
  charge_start.setDisplayName('Enter Starting Time for Ice charge:')
  charge_start.setDescription('Use 24 hour format (HR:MM)')
  charge_start.setDefaultValue('23:00')
  args << charge_start

  charge_end = OpenStudio::Measure::OSArgument.makeStringArgument('charge_end', true)
  charge_end.setDisplayName('Enter End Time for Ice charge:')
  charge_end.setDescription('Use 24 hour format (HR:MM)')
  charge_end.setDefaultValue('07:00')
  args << charge_end

  # Make boolean arguments for ctes dischage days

  wknds = OpenStudio::Measure::OSArgument.makeBoolArgument('wknds', true)
  wknds.setDisplayName('Allow Ice Discharge on Weekends')
  wknds.setDefaultValue(false)
  args << wknds

  # Make choice argument for output variable reporting frequency

  report_choices = ['Detailed', 'Timestep', 'Hourly', 'Daily', 'Monthly', 'RunPeriod']
  report_freq = OpenStudio::Measure::OSArgument.makeChoiceArgument('report_freq', report_choices, false)
  report_freq.setDisplayName('Select Reporting Frequency for New Output Variables')
  report_freq.setDescription('This will not change reporting frequency for existing output variables in the model.')
  report_freq.setDefaultValue('Timestep')
  args << report_freq

  ## DR TESTER INPUTS -----------------------------------------

  # Make boolean argument for use of demand response event test

  dr = OpenStudio::Measure::OSArgument.makeBoolArgument('dr', false)
  dr.setDisplayName('Test Demand Reponse Event')
  dr.setDefaultValue(false)
  args << dr

  # Make choice argument for type of demand response event (add or shed)

  dr_add_shed = OpenStudio::Measure::OSArgument.makeChoiceArgument('dr_add_shed', ['Add', 'Shed'], false)
  dr_add_shed.setDisplayName('Select if a Load Add or Load Shed Event')
  dr_add_shed.setDefaultValue('Shed')
  args << dr_add_shed

  # Make string argument for DR event date

  dr_date = OpenStudio::Measure::OSArgument.makeStringArgument('dr_date', false)
  dr_date.setDisplayName('Enter date of demand response event:')
  dr_date.setDescription('Use MM/DD format.')
  dr_date.setDefaultValue('9/19')
  args << dr_date

  # Make string argument for DR Event time

  dr_time = OpenStudio::Measure::OSArgument.makeStringArgument('dr_time', false)
  dr_time.setDisplayName('Enter start time of demand response event:')
  dr_time.setDescription('Use 24 hour format (HR:MM)')
  dr_time.setDefaultValue('11:30')
  args << dr_time

  # Make double argument for DR event duration

  dr_dur = OpenStudio::Measure::OSArgument.makeDoubleArgument('dr_dur', false)
  dr_dur.setDisplayName('Enter duration of demand response event [hr]:')
  dr_dur.setDefaultValue(3)
  args << dr_dur

  # Make boolean argument for allowing chiller to back-up ice

  dr_chill = OpenStudio::Measure::OSArgument.makeBoolArgument('dr_chill', false)
  dr_chill.setDisplayName('Allow chiller to back-up ice during DR event')
  dr_chill.setDescription('Unselection may result in unmet cooling hours')
  dr_chill.setDefaultValue('false')
  args << dr_chill
  ## END DR TESTER INPUTS --------------------------------------


  args
end

#descriptionObject

human readable description



60
61
62
# File 'lib/measures/add_central_ice_storage/measure.rb', line 60

def description
  'This measure adds an ice storage tank to a chilled water loop for the purpose of thermal energy storage.'
end

#modeler_descriptionObject

human readable description of modeling approach



65
66
67
68
69
70
71
# File 'lib/measures/add_central_ice_storage/measure.rb', line 65

def modeler_description
  'This measure adds the necessary components and performs required model articulations to add an ice ' \
          'thermal storage tank (ITS) to an existing chilled water loop. Special consideration is given to ' \
          'implementing configuration and control options. Refer to the ASHRAE CTES Design Guide or manufacturer ' \
          'applications guides for detailed implementation info. A user guide document is included in the docs ' \
          'folder of this measure to help translate design objectives into measure argument input values.'
end

#nameObject

human readable name



54
55
56
57
# File 'lib/measures/add_central_ice_storage/measure.rb', line 54

def name
  # Measure name should be the title case of the class name.

  'Add Ice Storage Tank'
end

#run(model, runner, user_arguments) ⇒ Object

define what happens when the measure is run



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
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
# File 'lib/measures/add_central_ice_storage/measure.rb', line 336

def run(model, runner, user_arguments)
  super(model, runner, user_arguments)

  # use the built-in error checking

  unless runner.validateUserArguments(arguments(model), user_arguments)
    return false
  end

  ## Arguments and Declarations---------------------------------------------------------------------------------------

  # Assign user arguments to variables

  objective = runner.getStringArgumentValue('objective', user_arguments)
  upstream = runner.getStringArgumentValue('upstream', user_arguments)
  storage_capacity = runner.getDoubleArgumentValue('storage_capacity', user_arguments)
  melt_indicator = runner.getStringArgumentValue('melt_indicator', user_arguments)
  selected_loop = runner.getStringArgumentValue('selected_loop', user_arguments)
  selected_chiller = runner.getStringArgumentValue('selected_chiller', user_arguments)
  chiller_resize_factor = runner.getDoubleArgumentValue('chiller_resize_factor', user_arguments)
  chiller_limit = runner.getDoubleArgumentValue('chiller_limit', user_arguments)
  old = runner.getBoolArgumentValue('old', user_arguments)
  ctes_av = runner.getStringArgumentValue('ctes_av', user_arguments)
  ctes_sch = runner.getStringArgumentValue('ctes_sch', user_arguments)
  chill_sch = runner.getStringArgumentValue('chill_sch', user_arguments)
  new = runner.getBoolArgumentValue('new', user_arguments)
  loop_sp = runner.getDoubleArgumentValue('loop_sp', user_arguments)
  inter_sp = runner.getDoubleArgumentValue('inter_sp', user_arguments)
  chg_sp = runner.getDoubleArgumentValue('chg_sp', user_arguments)
  delta_t = runner.getStringArgumentValue('delta_t', user_arguments)
  ctes_season = runner.getStringArgumentValue('ctes_season', user_arguments)
  discharge_start = runner.getStringArgumentValue('discharge_start', user_arguments)
  discharge_end = runner.getStringArgumentValue('discharge_end', user_arguments)
  charge_start = runner.getStringArgumentValue('charge_start', user_arguments)
  charge_end = runner.getStringArgumentValue('charge_end', user_arguments)
  wknds = runner.getBoolArgumentValue('wknds', user_arguments)
  report_freq = runner.getStringArgumentValue('report_freq', user_arguments)

  ## DR TESTER INPUTS ----------------------------------

  dr = runner.getBoolArgumentValue('dr', user_arguments)
  dr_add_shed = runner.getStringArgumentValue('dr_add_shed', user_arguments)
  (dr_mon, dr_day) = runner.getStringArgumentValue('dr_date', user_arguments).split('/')
  (dr_hr, dr_min) = runner.getStringArgumentValue('dr_time', user_arguments).split(':')
  dr_dur = runner.getDoubleArgumentValue('dr_dur', user_arguments)
  dr_chill = runner.getBoolArgumentValue('dr_chill', user_arguments)
  dr_time = (dr_hr.to_f + (dr_min.to_f / 60)).round(2)
  ## END DR TESTER INPUTS ------------------------------


  # Declare useful variables with values set within do-loops

  cond_loop = ''
  ctes_sp_sched = ''
  ctes_setpoint = 99.0 # This is a flag value and should be overwritten later

  demand_sp_mgr = ''

  ## Validate User Inputs---------------------------------------------------------------------------------------------


  # Convert thermal storage capacity from ton-hours to GJ

  storage_capacity = 12_660_670.23144e-9 * storage_capacity

  # Check for existence of charging setpoint temperature, reset to default if left blank.

  if chg_sp.nil? || chg_sp >= 32.0
    runner.registerWarning('An invalid ice charging temperature was entered. Value reset to -3.88 C (25.0 F).')
    chg_sp = 25.0
  elsif chg_sp < 20.0
    runner.registerWarning('The ice charging temperature is set below 20 F; this is atypically low. Verify input.')
  end

  # Convert setpoint temperature inputs from F to C

  loop_sp = (loop_sp - 32.0) / 1.8
  inter_sp = (inter_sp - 32.0) / 1.8
  chg_sp = (chg_sp - 32.0) / 1.8

  # Check if both old and new are false, set new = true and report error

  if !old && !new
    runner.registerError('No CTES schedule option was selected; either use old schedules or the create new option. ' \
                         'Measure aborted.')
    return false
  end

  # Locate selected chiller and verify loop connection

  if !model.getChillerElectricEIRByName(selected_chiller).empty?
    ctes_chiller = model.getChillerElectricEIRByName(selected_chiller).get
  elsif !model.getChillerAbsorptionByName(selected_chiller).empty?
    ctes_chiller = model.getChillerAbsorptionByName(selected_chiller).get
  elsif !model.getChillerAbsorptionIndirectByName(selected_chiller).empty?
    ctes_chiller = model.getChillerAbsorptionIndirectByName(selected_chiller).get
  end

  ctes_loop = model.getModelObjectByName(selected_loop).get.to_PlantLoop.get

  unless ctes_loop.components.include?(ctes_chiller)
    runner.registerError('The selected chiller is not located on the selected chilled water loop. Measure aborted.')
    return false
  end

  # Convert Delta T if needed from F to C (Overwrites string variables as floats)

  if delta_t != 'Use Existing Loop Value' && delta_t.to_f != 0.0
    delta_t = delta_t.to_f / 1.8
  else
    # Could add additional checks here for invalid (non-numerical) entries

    delta_t = ctes_loop.sizingPlant.loopDesignTemperatureDifference
  end

  # Check chiller limit input values

  if chiller_limit > 1.0
    runner.registerWarning('Chiller limit must be a ratio less than 1. Limit set to 1.0.')
    chiller_limit = 1.0
  elsif chiller_limit < 0
    runner.registerWarning('Chiller limit must be a ratio greater than or equal to 0. Limit set to 0.0' \
                            ' (i.e. full storage).')
    chiller_limit = 0.0
  elsif chiller_limit < 0.15
    runner.registerInfo('Chiller limit is below 15%; this may be outside the reasonable part load operating " \
                        "window for the device. Consider increasing or setting to 0.')
  end

  # Convert chiller limit to a temperature value based on delta_t variable if != 1. Otherwise, use as flag for EMS

  if chiller_limit != 1.0
    dt_max = chiller_limit * delta_t # degrees C

    runner.registerInfo("Max chiller dT during ice discharge is set to: #{dt_max.round(2)} C " \
                        "(#{(dt_max * 1.8).round(2)} F).")
  else
    dt_max = delta_t
  end

  # Check limits of chiller performance curves and adjust if necessary - Notify user with WARNING

  curve_output_check = false
  cap_ft = ctes_chiller.coolingCapacityFunctionOfTemperature
  min_x = cap_ft.minimumValueofx.to_f
  if min_x > chg_sp
    cap_ft.setMinimumValueofx(chg_sp)
    runner.registerWarning("VERIFY CURVE VALIDITY: The input range for the '#{cap_ft.name}' curve is too " \
                          'restrictive for use with ice charging. The provided curve has been ' \
                          "extrapolated to a lower limit of #{chg_sp.round(2)} C for the 'x' variable.")
    curve_output_check = true
  end

  eir_ft = ctes_chiller.electricInputToCoolingOutputRatioFunctionOfTemperature
  min_x = eir_ft.minimumValueofx.to_f
  if min_x > chg_sp
    runner.registerWarning("VERIFY CURVE VALIDITY: The input range for the '#{eir_ft.name}' curve is too " \
                          'restrictive for use with ice charging. The provided curve has been ' \
                          "extrapolated to a lower limit of #{chg_sp.round(2)} C for the 'x' variable.")
  end

  # Report chiller performance derate at the ice-making conditions.

  if curve_output_check == true
    derate = cap_ft.evaluate(chg_sp, ctes_chiller.referenceEnteringCondenserFluidTemperature)
    runner.registerInfo('A curve extrapolation warning was registered for the chiller capacity as a function ' \
                        'of temperature curve. At normal ice making temperatures, a chiller derate to 60-70% ' \
                        'of nominal capacity is expected. Using a condenser entering water temperature of ' \
                        "#{ctes_chiller.referenceEnteringCondenserFluidTemperature.round(1)} C and the ice " \
                        "charging temperature of #{chg_sp.round(1)} C, a derate to #{(derate * 100).round(1)}% is " \
                        'returned. This value will increase with lower condenser fluid return temperatures.')
  end

  # Check to ensure schedules are selected if old = true

  if old
    if ctes_av == 'N/A'
      runner.registerError('Pre-Defined schedule option chosen, but no availabity schedule was selected.')
      runner.registerWarning('Measure terminated early; no storage was applied.')
      return false
    end
    if ctes_sch == 'N/A'
      runner.registerError('Pre-Defined schedule option chosen, but no ice tank setpoint schedule was selected.')
      runner.registerWarning('Measure terminated early; no storage was applied.')
      return false
    end
    if chill_sch == 'N/A'
      runner.registerError('Pre-Defined schedule option chosen, but no chiller setpoint schedule was selected.')
      runner.registerWarning('Measure terminated early; no storage was applied.')
      return false
    end
  end

  # Parse and verify schedule inputs

  # Remove potential spaces from date inputs

  ctes_season = ctes_season.delete(' ')

  # Convert HR:MM format into HR.fraction format

  (d_start_hr, d_start_min) = discharge_start.split(':')
  (d_end_hr, d_end_min) = discharge_end.split(':')
  (c_start_hr, c_start_min) = charge_start.split(':')
  (c_end_hr, c_end_min) = charge_end.split(':')

  # Store re-formatted time values in shorthand variables for use in schedule

  # building

  ds = (d_start_hr.to_f + d_start_min.to_f / 60).round(2)
  de = (d_end_hr.to_f + d_end_min.to_f / 60).round(2)
  cs = (c_start_hr.to_f + c_start_min.to_f / 60).round(2)
  ce = (c_end_hr.to_f + c_end_min.to_f / 60).round(2)

  # Verify that input times make sense

  if ds > de
    runner.registerWarning('Dischage start time is later than discharge ' \
                           'end time (your ice will discharge overnight). ' \
                           'Verify schedule inputs.')
  end

  if cs.between?(ds - 0.01, de + 0.01) || ce.between?(ds - 0.01, de + 0.01)
    runner.registerWarning('The tank charge and discharge periods overlap. ' \
                           'Examine results for unexpected operation; ' \
                           'verify schedule inputs.')
  end

  if [ds, de, cs, ce].any? { |i| i > 24 }
    runner.registerError('One of you time enteries exceeds 24:00, ' \
                         'resulting in a schedule error. Measure aborted.')
    return false
  end

  ## Report Initial Condition of the Model----------------------------------------------------------------------------

  total_storage = model.getThermalStorageIceDetaileds.size
  runner.registerInitialCondition("The model started with #{total_storage} ice storage device(s).")

  runner.registerInfo("Chiller '#{selected_chiller}' on Loop '#{selected_loop}' was selected for the addition " \
                      "of a #{storage_capacity.round(2)} GJ (#{(storage_capacity / 12_660_670.23144e-9).round(0)} " \
                      'ton-hours) ice thermal energy storage object.')

  ## Modify Chiller Settings------------------------------------------------------------------------------------------


  # Adjust ctes chiller minimum outlet temperature

  ctes_chiller.setLeavingChilledWaterLowerTemperatureLimit(chg_sp)
  runner.registerInfo("Selected chiller minimum setpoint temperature was adjusted to #{chg_sp.round(2)} C " \
                      "(#{(chg_sp * 1.8) + 32} F).")

  # Adjust ctes chiller sizing factor based on user input

  if ctes_chiller.isReferenceCapacityAutosized
    ctes_chiller.setSizingFactor(chiller_resize_factor)
    runner.registerInfo("Selected chiller has been resized to #{chiller_resize_factor * 100}% of autosized " \
                        'capacity.')
  else
    ctes_chiller.setReferenceCapacity(
      chiller_resize_factor * ctes_chiller.referenceCapacity.to_f
    )
    runner.registerInfo("Selected chiller has been resized to #{chiller_resize_factor * 100}% of original " \
                        '(hardsized) capacity.')
  end

  ## Modify Loop Settings---------------------------------------------------------------------------------------------


  # Adjust minimum loop temperature

  ctes_loop.setMinimumLoopTemperature(chg_sp)
  runner.registerInfo("Selected loop minimum temperature was adjusted to #{chg_sp.round(2)} C " \
                      "(#{(chg_sp * 1.8) + 32} F).")

  # Adjust plant load distribution scheme

  if ctes_loop.loadDistributionScheme != 'SequentialLoad'
    ctes_loop.setLoadDistributionScheme('SequentialLoad')
    runner.registerInfo("Selected loop load distribution scheme was set to 'SequentialLoad'.")
  end

  # Adjust loop design temperature difference

  if ctes_loop.sizingPlant.loopDesignTemperatureDifference.to_f != delta_t
    ctes_loop.sizingPlant.setLoopDesignTemperatureDifference(delta_t)
    runner.registerInfo("Selected loop design temperature difference was adjusted to #{delta_t.round(2)} C " \
                        "(#{(delta_t * 1.8)} F).")
  end

  # Adjust loop gylcol solution percentage and set glycol - if necessary

  if ctes_loop.fluidType == 'Water'
    ctes_loop.setFluidType('EthyleneGlycol')
    ctes_loop.setGlycolConcentration(25)
    runner.registerInfo('Selected loop working fluid changed to ethylene glycol at a 25% concentration.')
  elsif ctes_loop.glycolConcentration < 25
    runner.registerInfo('Selected loop gylycol concentration is less than 25%. Consider increasing to 25-30%.')
  end

  # Adjust loop to two-way common pipe simulation - if necessary

  if ctes_loop.commonPipeSimulation != 'TwoWayCommonPipe'
    ctes_loop.setCommonPipeSimulation('TwoWayCommonPipe')
    runner.registerInfo("Selected loop common pipe simulation changed to 'TwoWayCommonPipe'.")

    # Add setpoint manager at inlet of demand loop (req'd for two-way common pipe sim.)

    if old # Only applies if old curves are used, regardless of whether new curves are created (old takes precedence)

      loop_sp_node = ctes_loop.loopTemperatureSetpointNode
      loop_sp_mgrs = loop_sp_node.setpointManagers
      loop_sp_mgrs.each do |spm|
        if spm.controlVariable == 'Temperature'
          demand_sp_mgr = spm.clone.to_SetpointManagerScheduled.get
        end
      end
      demand_sp_mgr.addToNode(ctes_loop.demandInletNode)
      runner.registerInfo('Original loop temperature setpoint manager duplicated and added to demand loop inlet node.')
    end

  end

  ## Create CTES Hardware---------------------------------------------------------------------------------------------


  # Create ice tank (aka ctes)

  ctes = OpenStudio::Model::ThermalStorageIceDetailed.new(model)
  ctes.setCapacity(storage_capacity)
  ctes.setThawProcessIndicator(melt_indicator)

  # Add ice tank to loop based on user-selected objective option and upstream device

  if objective == 'Full Storage'
    # Full storage places the ice tank upstream of the chiller with no user option to change.

    ctes.addToNode(ctes_chiller.supplyInletModelObject.get.to_Node.get)
  elsif objective == 'Partial Storage' && upstream == 'Storage'
    ctes.addToNode(ctes_chiller.supplyInletModelObject.get.to_Node.get)
  elsif objective == 'Partial Storage' && upstream == 'Chiller'
    ctes.addToNode(ctes_chiller.supplyOutletModelObject.get.to_Node.get)
  end

  ## Create New Schedules if Necessary--------------------------------------------------------------------------------

  #-------------------------------------------------------------------------------------------------------------------

  if new
    ## Check for Schedule Type Limits and Create if Needed------------------------------------------------------------

    if model.getModelObjectByName('OnOff').get.initialized
      sched_limits_onoff = model.getModelObjectByName('OnOff').get.to_ScheduleTypeLimits.get
    else
      sched_limits_onoff = OpenStudio::Model::ScheduleTypeLimits.new(model)
      sched_limits_onoff.setName('OnOff')
      sched_limits_onoff.setNumericType('Discrete')
      sched_limits_onoff.setUnitType('Availability')
      sched_limits_onoff.setLowerLimitValue(0.0)
      sched_limits_onoff.setUpperLimitValue(1.0)
    end

    if model.getModelObjectByName('Temperature').get.initialized
      sched_limits_temp = model.getModelObjectByName('Temperature').get.to_ScheduleTypeLimits.get
      if sched_limits_temp.lowerLimitValue.to_f > chg_sp
        sched_limits_temp.setLowerLimitValue(chg_sp)
      end
    else
      sched_limits_temp = OpenStudio::Model::ScheduleTypeLimits.new(model)
      sched_limits_temp.setName('Temperature')
      sched_limits_temp.setNumericType('Continuous')
      sched_limits_temp.setUnitType('Temperature')
    end

    ## Create Schedules-----------------------------------------------------------------------------------------------


    # Create key-value sets based on user inputs for charge/discharge times

    # cs = charge start, ce = charge end, ds = discharge start, de = discharge end


    # Set chiller and ice discharge setpoints for partial storage configs

    if objective == 'Full Storage'
      chiller_setpoint = loop_sp
      ctes_setpoint = loop_sp
    elsif objective == 'Partial Storage'
      if upstream == 'Chiller'
        chiller_setpoint = inter_sp
        ctes_setpoint = loop_sp
      elsif upstream == 'Storage'
        chiller_setpoint = loop_sp
        ctes_setpoint = inter_sp
      end
    end

    # Handle overnight charging and discharging

    if ce < cs
      midnight_av = [24, 1]
      midnight_chiller = [24, chg_sp]
      midnight_ctes = [24, loop_sp]
    elsif de < ds
      midnight_av = [24, 1]
      midnight_chiller = [24, chiller_setpoint]
      midnight_ctes = [24, ctes_setpoint]
    else
      midnight_av = [24, 0]
      midnight_chiller = [24, loop_sp]
      midnight_ctes = [24, 99]
    end

    # Availablity k-v sets for CTES

    wk_av = [[cs, 0], [ce, 1], [ds, 0], [de, 1], midnight_av].sort
    wknd_av = [[cs, 0], [ce, 1], midnight_av].sort

    # Temperature k-v sets for CTES

    wk_ctes = [[cs, 99], [ce, loop_sp], [ds, 99], [de, ctes_setpoint], midnight_ctes].sort
    wknd_ctes = [[cs, 99], [ce, loop_sp], midnight_ctes].sort

    # Temperature k-v set for Chiller

    wk_chiller = [[cs, loop_sp], [ce, chg_sp], [ds, loop_sp], [de, chiller_setpoint], midnight_chiller].sort
    wknd_chiller = [[cs, loop_sp], [ce, chg_sp], midnight_chiller].sort

    # Apply weekends modifer if necessary

    if wknds
      wknd_av = wk_av
      wknd_ctes = wk_ctes
      wknd_chiller = wk_chiller
    end

    # Create ice availability schedule

    ruleset_name = 'Ice Availability Schedule (New)'
    winter_design_day = [[24, 0]]
    summer_design_day = wk_av
    default_day = ['AllDays'] + [[24, 0]]
    rules = []
    rules << ['Weekend', ctes_season, 'Sat/Sun'] + wknd_av
    rules << ['Summer Weekday', ctes_season, 'Mon/Tue/Wed/Thu/Fri'] + wk_av
    options_ctes = { 'name' => ruleset_name,
                     'winter_design_day' => winter_design_day,
                     'summer_design_day' => summer_design_day,
                     'default_day' => default_day,
                     'rules' => rules }
    ctes_av_new = OsLib_Schedules.createComplexSchedule(model, options_ctes)
    ctes_av_new.setScheduleTypeLimits(sched_limits_onoff)

    # Create ctes setpoint temperature schedule

    ruleset_name = "#{ctes.name} Setpoint Schedule (New)"
    winter_design_day = [[24, 99]]
    summer_design_day = wk_ctes
    default_day = ['AllDays'] + [[24, 99]]
    rules = []
    rules << ['Weekend', ctes_season, 'Sat/Sun'] + wknd_ctes
    rules << ['Summer Weekday', ctes_season, 'Mon/Tue/Wed/Thu/Fri'] + wk_ctes
    options_ctes_ctes = { 'name' => ruleset_name,
                          'winter_design_day' => winter_design_day,
                          'summer_design_day' => summer_design_day,
                          'default_day' => default_day,
                          'rules' => rules }
    ctes_sch_new = OsLib_Schedules.createComplexSchedule(model, options_ctes_ctes)
    ctes_sch_new.setScheduleTypeLimits(sched_limits_temp)

    # Create chiller setpoint temperature schedule

    ruleset_name = "#{ctes_chiller.name} Setpoint Schedule (New)"
    winter_design_day = [[24, loop_sp]]
    summer_design_day = wk_chiller
    default_day = ['AllDays'] + [[24, loop_sp]]
    rules = []
    rules << ['Weekend', ctes_season, 'Sat/Sun'] + wknd_chiller
    rules << ['Summer Weekday', ctes_season, 'Mon/Tue/Wed/Thu/Fri'] + wk_chiller
    options_ctes_chiller = { 'name' => ruleset_name,
                             'winter_design_day' => winter_design_day,
                             'summer_design_day' => summer_design_day,
                             'default_day' => default_day,
                             'rules' => rules }
    chill_sch_new = OsLib_Schedules.createComplexSchedule(model, options_ctes_chiller)
    chill_sch_new.setScheduleTypeLimits(sched_limits_temp)

    # Create loop setpoint temperature schedule - if new = true

    if new
      ruleset_name = "#{ctes_loop.name} Setpoint Schedule (New)"
      options_ctes_loop = { 'name' => ruleset_name,
                            'winterTimeValuePairs' => [[24, loop_sp]],
                            'summerTimeValuePairs' => [[24, loop_sp]],
                            'defaultTimeValuePairs' => [[24, loop_sp]] }
      loop_sch_new = OsLib_Schedules.createSimpleSchedule(model, options_ctes_loop)
      loop_sch_new.setScheduleTypeLimits(sched_limits_temp)
    end

    # Register info about new schedule objects

    runner.registerInfo("The following schedules were added to the model:\n" \
                        "   * #{ctes_av_new.name}\n" \
                        "   * #{ctes_sch_new.name}\n" \
                        "   * #{chill_sch_new.name}\n" \
                        "   * #{loop_sch_new.name}")

    if old
      runner.registerInfo('However, these schedules are not used in favor of those pre-defined by the user.')
    end

  end
  # end of new schedule build-----------------------------------------------------------------------------------------

  #-------------------------------------------------------------------------------------------------------------------


  ## Create Component Setpoint Objects--------------------------------------------------------------------------------


  if old
    ctes_avail_sched = model.getScheduleRulesetByName(ctes_av).get
    ctes_temp_sched = model.getScheduleRulesetByName(ctes_sch).get
    chill_temp_sched = model.getScheduleRulesetByName(chill_sch).get
  elsif new
    ctes_avail_sched = ctes_av_new
    ctes_temp_sched = ctes_sch_new
    chill_temp_sched = chill_sch_new
  end

  # Apply ice availability schedule

  ctes.setAvailabilitySchedule(ctes_avail_sched)

  # Add component setpoint manager for ice tank

  ctes_sp_mgr = OpenStudio::Model::SetpointManagerScheduled.new(model, ctes_temp_sched)
  ctes_sp_mgr.addToNode(ctes.outletModelObject.get.to_Node.get)
  ctes_sp_mgr.setName("#{ctes.name} Setpoint Manager")

  # Add component setpoint manager for ctes chiller

  chill_sp_mgr = OpenStudio::Model::SetpointManagerScheduled.new(model, chill_temp_sched)
  chill_sp_mgr.addToNode(ctes_chiller.supplyOutletModelObject.get.to_Node.get)
  chill_sp_mgr.setName("#{ctes_chiller.name} Setpoint Manager")

  # Replace existing loop setpoint manager - if new = true and old = false

  if new && !old
    loop_sp_node = ctes_loop.loopTemperatureSetpointNode
    loop_sp_mgrs = loop_sp_node.setpointManagers
    loop_sp_mgrs.each do |spm|
      next unless ['Temperature', 'MinimumTemperature', 'MaximumTemperature'].include?(spm.controlVariable)
      spm.disconnect
      runner.registerInfo("Selected loop temperature setpoint manager '#{spm.name}' " \
              "with control variable '#{spm.controlVariable}' was disconnected.")
    end

    loop_sp_mgr = OpenStudio::Model::SetpointManagerScheduled.new(model, loop_sch_new)
    loop_sp_mgr.addToNode(loop_sp_node)
    loop_sp_mgr.setName("#{ctes_loop.name} Setpoint Manager (New)")

    demand_sp_mgr = loop_sp_mgr.clone.to_SetpointManagerScheduled.get
    demand_sp_mgr.addToNode(ctes_loop.demandInletNode)
    demand_sp_mgr.setName("#{ctes_loop.name} Demand Side Setpoint Manager (New)")
  end

  # Register info about new schedule objects

  runner.registerInfo('The following component temperature setpoint managers were added to the ' \
                      "model:\n" \
                      "   * #{ctes_sp_mgr.name}\n" \
                      "   * #{chill_sp_mgr.name}")

  if old # Old Schedules always take precedence, even if new ones are also created

    runner.registerInfo("The following schedules ared used in the model:\n" \
                      "   * #{ctes_avail_sched.name}\n" \
                      "   * #{ctes_temp_sched.name}\n" \
                      "   * #{chill_temp_sched.name}")
    runner.registerInfo('The following loop temperature setpoint manager was added to the ' \
                      "model:\n" \
                      "   * #{demand_sp_mgr.name}")
  elsif new && !old
    runner.registerInfo('The following loop temperature setpoint managers were added to the ' \
                      "model:\n" \
                      "   * #{loop_sp_mgr.name}\n" \
                      "   * #{demand_sp_mgr.name}")
  end

  ## Create General EMS Variables for Chiller and TES Capacities------------------------------------------------------


  # Chiller Nominal Capacity Internal Variable

  evar_chiller_cap = OpenStudio::Model::EnergyManagementSystemInternalVariable.new(model, 'Chiller Nominal Capacity')
  evar_chiller_cap.setInternalDataIndexKeyName(ctes_chiller.name.to_s)
  evar_chiller_cap.setName('CTES_Chiller_Capacity')

  # Ice Tank thermal storage capacity - Empty Global Variable

  evar_tes_cap = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'TES_Cap')

  # Set TES Capacity from User Inputs

  set_tes_cap = OpenStudio::Model::EnergyManagementSystemProgram.new(model)
  set_tes_cap.setName('Set_TES_Cap')
  body = "    SET TES_Cap = \#{storage_capacity}\n  EMS\n  set_tes_cap.setBody(body)\n\n  set_tes_cap_pcm = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n  set_tes_cap_pcm.setName('Set_TES_Cap_CallMgr')\n  set_tes_cap_pcm.setCallingPoint('BeginNewEnvironment')\n  set_tes_cap_pcm.addProgram(set_tes_cap)\n\n  ## Create EMS Components to Control Load on Upstream (Priority) Device----------------------------------------------\n\n  # Flag value indicating that a chiller limiter is required or DR Test is Activated\n  if chiller_limit != 1.0 || dr == true\n\n    # Set up EMS output\n    output_ems = model.getOutputEnergyManagementSystem\n    output_ems.setActuatorAvailabilityDictionaryReporting('Verbose')\n    output_ems.setInternalVariableAvailabilityDictionaryReporting('Verbose')\n    output_ems.setEMSRuntimeLanguageDebugOutputLevel('None')\n\n    runner.registerInfo(\"A \#{(chiller_limit * 100).round(2)}% capacity limit has been placed on the chiller \" \\\n                      'during ice discharge. EMS scripting is employed to actuate this control via chiller ' \\\n                      'outlet setpoint. ')\n\n    # Internal and Global Variable(s)\n\n    # Chiller Limited Capacity for Ice Discharge Period - Empty Global Variable\n    evar_chiller_limit = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'Chiller_Limited_Capacity')\n\n    # Instances of Chiller Limit Application - Empty Global Variable\n    evar_limit_counter = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'Limit_Counter')\n\n    # Max Delta-T for Chiller De-Rate - Empty Global Variable\n    dt_ems = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'DT_Max')\n\n    # DR In-Progress Flag - Empty Global Variable\n    dr_flag = OpenStudio::Model::EnergyManagementSystemGlobalVariable.new(model, 'DR_Flag')\n\n    # Sensor(s)\n    # Evaporator Entering Water Temperature\n    eewt = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Chiller Evaporator Inlet Temperature')\n    eewt.setName('EEWT')\n    eewt.setKeyName(ctes_chiller.name.to_s)\n\n    # Evaporator Leaving Water Temperature\n    elwt = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Chiller Evaporator Outlet Temperature')\n    elwt.setName('ELWT')\n    elwt.setKeyName(ctes_chiller.name.to_s)\n\n    # Evaporator Leave Water Temperature Setpoint\n    elwt_sp = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n    elwt_sp.setName('SP')\n    elwt_sp.setKeyName(chill_temp_sched.name.to_s)\n\n    # Supply Water Temperature Setpoint\n    swt_sp = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'System Node Setpoint Temperature')\n    swt_sp.setName('SWT_SP')\n    swt_sp.setKeyName(ctes_loop.supplyOutletNode.name.to_s)\n\n    # Ice Tank Availability Schedule\n    av_sp = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Schedule Value')\n    av_sp.setName('ICE_AV')\n    av_sp.setKeyName(ctes.availabilitySchedule.get.name.to_s)\n\n    # Ice Tank Leaving Water Temperature\n    ilwt = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'System Node Temperature')\n    ilwt.setName('ILWT')\n    ilwt.setKeyName(ctes.outletModelObject.get.name.to_s)\n\n    # Ice Tank State of Charge\n    soc = OpenStudio::Model::EnergyManagementSystemSensor.new(model, 'Ice Thermal Storage End Fraction')\n    soc.setName('SOC')\n    soc.setKeyName(ctes.name.to_s)\n\n    # Actuator(s)\n    # Evaporator Leaving Water Temperature Septoint Node Actuator\n    elwt = OpenStudio::Model::EnergyManagementSystemActuator.new(ctes_chiller.supplyOutletModelObject.get,\n                                                                 'System Node Setpoint', 'Temperature Setpoint')\n    elwt.setName('ELWT_SP')\n  end\n\n  if chiller_limit != 1\n    # Program(s)\n    # Apply Chiller Capacity Limit During Ice Discharge\n    chiller_limit_program = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n    chiller_limit_program.setName('Chiller_Limiter')\n    body = <<-EMS\n    IF ( ICE_AV == 1 ) && ( SP >= SWT_SP ) && ( DR_Flag <> 1 )\n      IF ( EEWT - SP ) > DT_Max\n          SET ELWT_SP = ( EEWT - DT_Max )\n          SET Limit_Counter = ( Limit_Counter + ( SystemTimeStep / ZoneTimeStep ) )\n        ELSE\n          SET ELWT_SP = SP\n        ENDIF\n    ELSE\n        SET ELWT_SP = SP\n    ENDIF\n    EMS\n    chiller_limit_program.setBody(body)\n\n    # Determine Capacity Limit of the Chiller in Watts (Also initializes limit counter)\n    chiller_limit_calculation = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n    chiller_limit_calculation.setName('Chiller_Limit_Calc')\n    body = <<-EMS\n      SET Chiller_Limited_Capacity = ( \#{chiller_limit} * CTES_Chiller_Capacity )\n      SET Limit_Counter = 0\n      SET DR_Flag = 0\n      SET DT_Max = \#{dt_max}\n    EMS\n    chiller_limit_calculation.setBody(body)\n\n    # Program Calling Manager(s)\n    chiller_limit_pcm = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n    chiller_limit_pcm.setName('Chiller_Limiter_CallMgr')\n    chiller_limit_pcm.setCallingPoint('InsideHVACSystemIterationLoop')\n    chiller_limit_pcm.addProgram(chiller_limit_program)\n\n    chiller_limit_calc_pcm = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n    chiller_limit_calc_pcm.setName('Chiller_Limit_Calc_CallMgr')\n    chiller_limit_calc_pcm.setCallingPoint('BeginNewEnvironment')\n    chiller_limit_calc_pcm.addProgram(chiller_limit_calculation)\n\n    # EMS Output Variable(s) - Chiller Limiter Dependent\n    eout_chiller_limit = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, evar_chiller_limit)\n    eout_chiller_limit.setName('Chiller Limited Capacity')\n\n    eout_limit_counter = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, evar_limit_counter)\n    eout_limit_counter.setName('Chiller Limit Counter')\n\n  end\n\n  ## DR EVENT TESTER EMS --------------------------\n  ## Add Demand Response Event Tester if Applicable (EMS Controller Override)-----------------------------------------\n\n  if dr\n\n    # Create EMS Script that:\n    # => 1. Determines if DR Event has been triggered (inspects date/time)\n    # => 2. Actuates full storage if in a Load Shed DR event\n    # => 3. Actuates ice charging/chiller @ max if in a Load Add DR event\n    # => 4. Allows staged chiller ramp if ice runs out (if selected by user)\n\n    # Create DR EMS Program\n    dr_program = OpenStudio::Model::EnergyManagementSystemProgram.new(model)\n    dr_program.setName('Demand_Response_Pgm')\n\n    # Define Program Script Based on Permission of Chiller to Operate to Meet Load\n    if dr_chill && dr_add_shed == 'Shed'  # Chiller is permitted to pick up unmet load\n      body = <<-EMS\n  IF ( Month == \#{dr_mon} ) && ( DayOfMonth == \#{dr_day} )\n    IF ( CurrentTime > \#{dr_time} ) && ( CurrentTime <= \#{dr_time + dr_dur} )\n      SET DR_Flag = 1\n        IF ( ILWT - SWT_SP < 0.05 )\n        SET ELWT_SP = EEWT\n        ELSEIF ( ILWT - SWT_SP <= 0.33 * DT_Max )\n          SET ELWT_SP = EEWT - ( 0.33 * DT_Max )\n        ELSEIF ( ILWT - SWT_SP <= 0.67 * DT_Max )\n          SET ELWT_SP = EEWT - ( 0.67 * DT_Max )\n        ELSE\n          SET ELWT_SP = ( EEWT - DT_Max )\n          SET Limit_Counter = ( Limit_Counter + ( SystemTimeStep / ZoneTimeStep ) )\n      ENDIF\n    ELSEIF ( DR_Flag == 1 )\n      SET DR_Flag = 0\n        SET ELWT_SP = SP\n    ENDIF\n  ENDIF\n  EMS\n      dr_program.setBody(body)\n    elsif !dr_chill && dr_add_shed == 'Shed'  # Chiller is not permitted to pick up unmet load when ice is deficient\n      body = <<-EMS\n  IF ( Month == \#{dr_mon} ) && ( DayOfMonth == \#{dr_day} )\n    IF ( CurrentTime > \#{dr_time} ) && ( CurrentTime <= \#{dr_time + dr_dur} )\n      SET DR_Flag = 1\n      SET ELWT_SP = EEWT + 10.0\n    ELSEIF ( DR_Flag == 1 )\n      SET DR_Flag = 0\n    ENDIF\n  ENDIF\n  EMS\n      dr_program.setBody(body)\n    elsif dr_add_shed == 'Add'\n      body = <<-EMS\n    IF ( Month == \#{dr_mon} ) && ( DayOfMonth == \#{dr_day} )\n    IF ( CurrentTime > \#{dr_time} ) && ( CurrentTime <= \#{dr_time + dr_dur} )\n        SET DR_Flag = 1\n        IF ( SOC < 0.99 ) && ( ICE_AV == 1 )\n          SET ELWT_SP = \#{chg_sp}\n        ELSEIF SOC > 0.95\n          SET ELWT_SP = SWT_SP\n        ENDIF\n      ELSEIF ( DR_Flag == 1 )\n        SET DR_Flag = 0\n      ENDIF\n    ENDIF\n    EMS\n      dr_program.setBody(body)\n    end\n\n    # Create DR EMS Program Calling Manager\n    dr_pcm = OpenStudio::Model::EnergyManagementSystemProgramCallingManager.new(model)\n    dr_pcm.setName('Demand_Response_PCM')\n    dr_pcm.setCallingPoint('InsideHVACSystemIterationLoop')\n    dr_pcm.addProgram(dr_program)\n\n    # EMS Output Variable(s)\n    eout_drflag = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, dr_flag)\n    eout_drflag.setName('Demand Response Flag')\n  end\n  ## END DR EVENT TESTER EMS ---------------------\n\n  ## Add Output Variables and Meters----------------------------------------------------------------------------------\n\n  # EMS Output Variable(s) - Chiller Limit Independent\n  eout_chiller_cap = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, evar_chiller_cap)\n  eout_chiller_cap.setName('Chiller Nominal Capacity')\n\n  eout_tes_cap = OpenStudio::Model::EnergyManagementSystemOutputVariable.new(model, evar_tes_cap)\n  eout_tes_cap.setName('Ice Thermal Storage Capacity')\n\n  # Identify existing output variables\n  vars = model.getOutputVariables\n  var_names = []\n  vars.each do |v|\n    var_names << v.variableName\n  end\n\n  # List names of desired output variables\n  ovar_names = ['Ice Thermal Storage Cooling Rate',\n                'Ice Thermal Storage Cooling Charge Rate',\n                'Ice Thermal Storage Cooling Discharge Rate',\n                'Ice Thermal Storage Cooling Charge Energy',\n                'Ice Thermal Storage Cooling Discharge Energy',\n                'Ice Thermal Storage Cooling Discharge Energy',\n                'Ice Thermal Storage End Fraction',\n                'Ice Thermal Storage On Coil Fraction',\n                'Ice Thermal Storage Mass Flow Rate',\n                'Ice Thermal Storage Tank Mass Flow Rate',\n                'Ice Thermal Storage Bypass Mass Flow Rate',\n                'Ice Thermal Storage Fluid Inlet Temperature',\n                'Ice Thermal Storage Tank Outlet Temperature',\n                'Ice Thermal Storage Blended Outlet Temperature',\n                'Ice Thermal Storage Ancillary Electric Power',\n                'Ice Thermal Storage Ancillary Electric Energy',\n                'Chiller COP',\n                'Chiller Cycling Ratio',\n                'Chiller Part Load Ratio',\n                'Chiller Electric Power',\n                'Chiller Electric Energy',\n                'Chiller Evaporator Cooling Rate',\n                'Chiller Evaporator Cooling Energy',\n                'Chiller Condenser Heat Transfer Rate',\n                'Chiller Condenser Heat Transfer Energy',\n                'Chiller False Load Heat Transfer Rate',\n                'Chiller False Load Heat Transfer Energy',\n                'Chiller Evaporator Inlet Temperature',\n                'Chiller Evaporator Outlet Temperature',\n                'Chiller Evaporator Mass Flow Rate',\n                'Site Outdoor Air Drybulb Temperature',\n                'Site Outdoor Air Wetbulb Temperature']\n\n  # Create new output variables if they do not already exist\n  ovars = []\n  ovar_names.each do |nm|\n    # if !var_names.include?(nm)\n    ovars << OpenStudio::Model::OutputVariable.new(nm, model)\n    # end\n  end\n\n  # Create output variable for loop demand inlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes_loop.demandInletNode.name.to_s)\n  ovars << v\n\n  # Create output variable for loop demand outlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes_loop.demandOutletNode.name.to_s)\n  ovars << v\n\n  # Create output variable for loop supply inlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes_loop.supplyInletNode.name.to_s)\n  ovars << v\n\n  # Create output variable for loop supply outlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes_loop.supplyOutletNode.name.to_s)\n  ovars << v\n\n  # Create output variable for chiller inlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes_chiller.supplyInletModelObject.get.name.to_s)\n  ovars << v\n\n  # Create output variable for chiller outlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes_chiller.supplyOutletModelObject.get.name.to_s)\n  ovars << v\n\n  # Create output variable for ice tank inlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes.inletModelObject.get.name.to_s)\n  ovars << v\n\n  # Create output variable for ice tank outlet temperature\n  v = OpenStudio::Model::OutputVariable.new('System Node Temperature', model)\n  v.setKeyValue(ctes.outletModelObject.get.name.to_s)\n  ovars << v\n\n  # Create output variables for the new operating schedules\n  v = OpenStudio::Model::OutputVariable.new('Schedule Value', model)\n  v.setKeyValue(ctes_avail_sched.name.to_s)\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Schedule Value', model)\n  v.setKeyValue(ctes_temp_sched.name.to_s)\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Schedule Value', model)\n  v.setKeyValue(chill_temp_sched.name.to_s)\n  ovars << v\n\n  # Create output variable for plant loop setpoint temperature - if new = true\n  if new\n    v = OpenStudio::Model::OutputVariable.new('Schedule Value', model)\n    v.setKeyValue(loop_sch_new.name.to_s)\n    ovars << v\n  end\n\n  # Create output variables for ice discharge performance curve\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Input Variable 1 Value', model)\n  v.setKeyValue(ctes.dischargingCurve.name.to_s)\n  v.setName('Discharge Curve Input Value 1')\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Input Variable 2 Value', model)\n  v.setKeyValue(ctes.dischargingCurve.name.to_s)\n  v.setName('Discharge Curve Input Value 2')\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Output Value', model)\n  v.setKeyValue(ctes.dischargingCurve.name.to_s)\n  v.setName('Discharge Curve Output Value')\n  ovars << v\n\n  # Create output variables for ice charge performance curve\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Input Variable 1 Value', model)\n  v.setKeyValue(ctes.chargingCurve.name.to_s)\n  v.setName('Charge Curve Input Value 1')\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Input Variable 2 Value', model)\n  v.setKeyValue(ctes.chargingCurve.name.to_s)\n  v.setName('Charge Curve Input Value 2')\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Output Value', model)\n  v.setKeyValue(ctes.chargingCurve.name.to_s)\n  v.setName('Charge Curve Output Value')\n  ovars << v\n\n  # Create output variables for chiller performance\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Output Value', model)\n  v.setKeyValue(ctes_chiller.coolingCapacityFunctionOfTemperature.name.to_s)\n  v.setName('Charge Curve Output Value')\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Output Value', model)\n  v.setKeyValue(ctes_chiller.electricInputToCoolingOutputRatioFunctionOfTemperature.name.to_s)\n  v.setName('Charge Curve Output Value')\n  ovars << v\n\n  v = OpenStudio::Model::OutputVariable.new('Performance Curve Output Value', model)\n  v.setKeyValue(ctes_chiller.electricInputToCoolingOutputRatioFunctionOfPLR.name.to_s)\n  v.setName('Charge Curve Output Value')\n  ovars << v\n\n  if chiller_limit != 1.0 # flag for EMS use, following EMS vars only exist if previous script ran\n\n    # Create output variable for chiller limited capacity (from EMS Output Variable)\n    v = OpenStudio::Model::OutputVariable.new(eout_chiller_limit.name.to_s, model)\n    v.setName(\"\#{ctes_chiller.name} Limited Capacity\")\n    v.setVariableName('Chiller Limited Capacity')\n    ovars << v\n\n    # Create output variable for chiller limit counter (from EMS Output Variable)\n    v = OpenStudio::Model::OutputVariable.new(eout_limit_counter.name.to_s, model)\n    v.setName(\"\#{ctes_chiller.name} Limit Counter [Zone Timesteps]\")\n    v.setVariableName('Chiller Limit Counter')\n    ovars << v\n\n  end\n\n  # Create output variable for Demand Response Flag (from EMS Output Variable)\n  if dr\n\n    v = OpenStudio::Model::OutputVariable.new(eout_drflag.name.to_s, model)\n    v.setName('Demand Response Event Flag')\n    v.setVariableName('Demand Response Flag')\n    ovars << v\n\n  end\n\n  # Create output variable for TES Capacity (from EMS Global Variable)\n  v = OpenStudio::Model::OutputVariable.new(eout_tes_cap.name.to_s, model)\n  v.setName(\"\#{ctes.name} Ice Thermal Storage Capacity [GJ]\")\n  v.setVariableName('Ice Thermal Storage Capacity')\n  ovars << v\n\n  # Create output variable for chiller nominal capacity (from EMS Output Variable)\n  v = OpenStudio::Model::OutputVariable.new(eout_chiller_cap.name.to_s, model)\n  v.setName(\"\#{ctes_chiller.name} Nominal Capacity [W]\")\n  v.setVariableName('Chiller Nominal Capacity')\n  ovars << v\n\n  # Set variable reporting frequency for newly created output variables\n  ovars.each do |var|\n    var.setReportingFrequency(report_freq)\n  end\n\n  # Register info about new output variables\n  runner.registerInfo(\"\#{ovars.size} chiller and ice storage output variables were added to the model.\")\n\n  # Create new energy/specific end use meters\n  omet_names = ['Pumps:Electricity',\n                'Fans:Electricity',\n                'Cooling:Electricity',\n                'Electricity:HVAC',\n                'Electricity:Plant',\n                'Electricity:Building',\n                'Electricity:Facility']\n\n  omet_names.each do |nm|\n    omet = OpenStudio::Model::OutputMeter.new(model)\n    omet.setName(nm)\n    omet.setReportingFrequency(report_freq)\n    omet.setMeterFileOnly(false)\n    omet.setCumulative(false)\n  end\n\n  # Register info about new output meters\n  runner.registerInfo(\"\#{omet_names.size} output meters were added to the model.\")\n\n  ## Report Final Condition of Model----------------------------------------------------------------------------------\n  total_storage = model.getThermalStorageIceDetaileds.size\n  runner.registerFinalCondition(\"The model finished with \#{total_storage} ice energy storage device(s).\")\n\n  true\nend\n"