/
measure.rb
2083 lines (1624 loc) · 79.5 KB
/
measure.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# see the URL below for information on how to write OpenStudio measures:
# http://nrel.github.io/OpenStudio-user-documentation/reference/measure_writing_guide/
# design document for this measure is at https://docs.google.com/document/d/16_TLRuhc4VFs2o0gRAp81hRObet7-s6fUEWo3HO7LpE/edit#
require 'fileutils'
require 'csv'
require 'tempfile'
require 'date'
require 'json'
require 'erb'
require 'matrix'
require 'open3'
class Array
def average
fail "Cannot average 0 items" if self.size == 0
sum = self.inject(:+)
(sum / self.size).to_f
end
end
# start the measure
class RadianceMeasure < OpenStudio::Ruleset::ModelUserScript
# human readable name
def name
return 'Radiance Daylighting Measure'
end
# human readable description
def description
return 'This measure uses Radiance instead of EnergyPlus for daylighting calculations with OpenStudio.'
end
# human readable description of modeling approach
def modeler_description
return 'The OpenStudio model is converted to Radiance format. All spaces containing daylighting objects (illuminance map, daylighting control point, and optionally glare sensors) will have annual illuminance calculated using Radiance, and the OS model\'s lighting schedules can be overwritten with those based on daylight responsive lighting controls.'
end
# define the arguments that the user will input
def arguments(model)
args = OpenStudio::Ruleset::OSArgumentVector.new
chs = OpenStudio::StringVector.new
chs << 'Yes'
chs << 'No'
apply_schedules = OpenStudio::Ruleset::OSArgument::makeChoiceArgument('apply_schedules', chs, true)
apply_schedules.setDisplayName('Apply schedules')
apply_schedules.setDefaultValue('Yes')
apply_schedules.setDescription('Update lighting load schedules with those computed by Radiance')
args << apply_schedules
chs = OpenStudio::StringVector.new
chs << 'Default'
chs << 'Min'
chs << 'Max'
use_cores = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('use_cores', chs, true)
use_cores.setDisplayName('Cores')
use_cores.setDefaultValue('Default')
use_cores.setDescription('Number of CPU cores to use for Radiance jobs. Default is to use all but one core, NOTE: this option is ignored on Windows.')
args << use_cores
chs = OpenStudio::StringVector.new
chs << 'Model'
chs << 'Testing'
rad_settings = OpenStudio::Ruleset::OSArgument.makeChoiceArgument('rad_settings', chs, true)
rad_settings.setDisplayName('Radiance Settings')
rad_settings.setDefaultValue('Model')
rad_settings.setDescription('The measure reads Radiance simulation parameters from the "Model" by default. The "Testing" option can be used for testing your model with the Radiance workflow; it uses very crude parameters for a fast simulation but produces very inaccurate results.')
args << rad_settings
debug_mode = OpenStudio::Ruleset::OSArgument::makeBoolArgument('debug_mode', false)
debug_mode.setDisplayName('Debug Mode')
debug_mode.setDefaultValue('false')
debug_mode.setDescription('Generates additional log messages, images for each window group, and saves all window group output.')
args << debug_mode
return args
end
def read_illuminance_file(filename, runner)
m = Matrix[]
data_section = false
header = []
data = []
print_statement("Reading '#{filename}'", runner)
fail "Could not find illuminance file #{filename}" unless File.exist?(filename)
File.read(filename).each_line do |line|
data_section = true if line =~ /^\s?\d/
if data_section
csv_line = CSV.parse_line(line.strip, {col_sep: " "})
m = Matrix.rows(m.to_a << csv_line)
else
header << "#{line}"
end
end
return m, header
end
def run(model, runner, user_arguments)
super(model, runner, user_arguments)
OpenStudio::Logger::instance().standardOutLogger().enable()
# Enable debug-level log messages
# OpenStudio::Logger::instance().standardOutLogger().setLogLevel(OpenStudio::Debug)
# use the built-in error checking
if !runner.validateUserArguments(arguments(model), user_arguments)
return false
end
# assign the user inputs to variables
apply_schedules = runner.getStringArgumentValue('apply_schedules', user_arguments)
use_cores = runner.getStringArgumentValue('use_cores', user_arguments)
rad_settings = runner.getStringArgumentValue('rad_settings', user_arguments)
debug_mode = runner.getBoolArgumentValue('debug_mode',user_arguments)
# Energyplus "pre-run" model dir
epout_dir = 'eplus_preprocess'
if !File.exist?(epout_dir)
FileUtils.mkdir_p(epout_dir)
end
# Radiance model dir
rad_dir = 'radiance'
if !File.exist?(rad_dir)
FileUtils.mkdir_p(rad_dir)
end
## Radiance Utilities
# print statement and execute as system call
def exec_statement(s, runner)
if /mswin/.match(RUBY_PLATFORM) || /mingw/.match(RUBY_PLATFORM)
s = s.tr("/", "\\")
end
runner.registerInfo("#{s}")
# additional puts for OSApp until v2.0...
puts "[Radiance Measure #{Time.now.getutc}]: \$ #{s}"
result = system(s)
return result
end
# print statement for OS-Server and OSApp
def print_statement(s, runner)
if /mswin/.match(RUBY_PLATFORM) || /mingw/.match(RUBY_PLATFORM)
s = s.tr("/", "\\")
end
runner.registerInfo("#{s}")
# additional puts for OSApp until v2.0...
puts "[Radiance Measure #{Time.now.getutc}]: #{s}"
end
# UNIX-style which
def which(cmd)
exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
exts.each do |ext|
exe = "#{path}/#{cmd}#{ext}"
return exe if File.executable? exe
end
end
return nil
end
# set up MP option
coreCount = OpenStudio::System::numberOfProcessors
sim_cores = '1'
if use_cores == 'Max'
sim_cores = coreCount
elsif use_cores == 'Min'
sim_cores = 1
else
sim_cores = coreCount - 1
end
if /mswin/.match(RUBY_PLATFORM) || /mingw/.match(RUBY_PLATFORM)
print_statement("Radiance multiprocessing features are not supported on Windows.", runner)
sim_cores = 1
end
print_statement("Using #{sim_cores} core(s) for Radiance jobs", runner)
# help those poor Windows users out
perlExtension = ""
catCommand = "cat"
osQuote = "\'"
if /mswin/.match(RUBY_PLATFORM) || /mingw/.match(RUBY_PLATFORM)
perlExtension = ".pl"
catCommand = "type"
osQuote = "\""
end
## END Radiance Utilities
print_statement("### DEBUG: running in debug mode", runner) if debug_mode
# setup environment for Radiance and Perl
co = OpenStudio::Runmanager::ConfigOptions.new(true);
co.fastFindRadiance();
radiancePath = co.getTools().getLastByName("rad").localBinPath.parent_path
path = OpenStudio::Path.new(radiancePath).to_s
raypath = (OpenStudio::Path.new(radiancePath).parent_path() /
OpenStudio::Path.new('lib')).to_s()
epw2weapath = (OpenStudio::Path.new(radiancePath) / OpenStudio::Path.new('epw2wea')).to_s
programExtension = ""
if /mswin/.match(RUBY_PLATFORM) || /mingw/.match(RUBY_PLATFORM)
programExtension = ".exe"
perlpath = ""
if OpenStudio::applicationIsRunningFromBuildDirectory()
perlpath = OpenStudio::getApplicationRunDirectory().parent_path().parent_path() /
OpenStudio::Path.new("strawberry-perl-5.16.2.1-32bit-portable-reduced/perl/bin")
else
perlpath = OpenStudio::getApplicationRunDirectory().parent_path() /
OpenStudio::Path.new("strawberry-perl-5.16.2.1-32bit-portable-reduced/perl/bin")
end
print_statement("Adding path for local perl: " + perlpath.to_s, runner)
ENV["PATH"] = path + ";" + ENV["PATH"] + ";" + perlpath.to_s
ENV["RAYPATH"] = path + ";" + raypath + ";."
else
ENV["PATH"] = path + ":" + ENV["PATH"]
ENV["RAYPATH"] = path + ":" + raypath + ":."
end
# Radiance version detection and environment reportage
ver = Open3.capture2("#{path}/rcontrib -version")
print_statement("Radiance version info: #{ver[0]}", runner)
print_statement("Radiance binary dir: #{path}", runner)
print_statement("Radiance library dir: #{raypath}", runner)
if Dir.glob(epw2weapath + programExtension).empty?
runner.registerError("Cannot find epw2wea tool in radiance installation at '#{radiancePath}'. You may need to install a newer version of Radiance.")
exit false
end
ENV["EPW2WEAPATH"] = epw2weapath + programExtension
if !which("perl")
runner.registerError('Perl could not be found in path, exiting')
exit false
end
# get the epw file
# TODO align with long-winded thread from 2015.07.28
epw_path = nil
# try runner first
if runner.lastEpwFilePath.is_initialized
test = runner.lastEpwFilePath.get.to_s
if File.exist?(test)
epw_path = test
end
end
# try model second
if !epw_path
if model.weatherFile.is_initialized
test = model.weatherFile.get.path
if test.is_initialized
# have a file name from the model
if File.exist?(test.get.to_s)
epw_path = test.get
else
# If this is an always-run Measure, need to check for file in different path
alt_weath_path = File.expand_path(File.join(File.dirname(__FILE__), \
"../../../resources"))
alt_epw_path = File.expand_path(File.join(alt_weath_path, test.get.to_s))
server_epw_path = File.expand_path(File.join(File.dirname(__FILE__), \
"../../weather/#{File.basename(test.get.to_s)}"))
if File.exist?(alt_epw_path)
epw_path = OpenStudio::Path.new(alt_epw_path)
elsif File.exist? server_epw_path
epw_path = OpenStudio::Path.new(server_epw_path)
else
runner.registerError("Model has been assigned a weather file, but the file is not in \
the specified location of '#{test.get}'. server_epw_path: #{server_epw_path}, test \
basename: #{File.basename(test.get.to_s)}, test: #{test}")
return false
end
end
else
runner.registerError('Model has a weather file assigned, but the weather file path has \
been deleted.')
return false
end
else
runner.registerError('Model has not been assigned a weather file.')
return false
end
end
## ModelToRad Workflow
# save osm for input to eplus pre-process
modelPath = OpenStudio::Path.new("eplusin.osm")
model.save(modelPath,true)
# find EnergyPlus
co = OpenStudio::Runmanager::ConfigOptions.new
co.fastFindEnergyPlus
# make a workflow (EnergyPlus "pre-run" to get constructions and weather)
workflow = OpenStudio::Runmanager::Workflow.new("ModelToRadPreprocess->ModelToIdf->ExpandObjects->EnergyPlus")
workflow.add(co.getTools)
# add model-to-rad workflow
modelToRad = OpenStudio::Runmanager::Workflow.new("ModelToRad")
workflow.addWorkflow(modelToRad)
# minimize file path lengths
workflow.addParam(OpenStudio::Runmanager::JobParam.new("flatoutdir"))
# make the run manager
runDir = OpenStudio::Path.new(epout_dir)
runmanager_path = OpenStudio::Path.new("runmanager.db")
runmanager = OpenStudio::Runmanager::RunManager.new(runmanager_path, true, true, false, false)
OpenStudio::makeParentFolder(runDir, OpenStudio::Path.new(), true)
print_statement('Creating workflow', runner)
jobtree = workflow.create(OpenStudio::system_complete(runDir), \
OpenStudio::system_complete(modelPath), OpenStudio::Path.new(epw_path))
runmanager.enqueue(jobtree, true)
print_statement("Running jobs in #{runDir}", runner)
runmanager.setPaused(false)
runmanager.waitForFinished()
if jobtree.treeErrors.succeeded
print_statement('OpenStudio to Radiance translation complete', runner)
else
jobtree.treeErrors.errors.each do |err|
print_statement("ERROR: #{err}", runner)
end
print_statement("Model issue(s) caused EnergyPlus preprocess failure, aborting.", runner)
abort()
end
## Radiance crap
modelPath = OpenStudio::system_complete(modelPath)
radPath = modelPath.parent_path / OpenStudio::Path.new("radiance")
windowControls = Dir.glob("scene/glazing/WG*.rad")
# set up output dirs
FileUtils.mkdir_p("#{radPath}/output/dc") unless File.exist?("#{radPath}/output/dc")
FileUtils.mkdir_p("#{radPath}/output/ts") unless File.exist?("#{radPath}/output/ts")
FileUtils.mkdir_p("#{radPath}/output/dc/merged_space/maps") unless \
File.exist?("#{radPath}/output/dc/merged_space/maps")
FileUtils.mkdir_p("#{radPath}/sql") unless File.exist?("#{radPath}/sql")
FileUtils.mkdir_p("#{radPath}/wx") unless File.exist?("#{radPath}/wx")
FileUtils.mkdir_p("#{radPath}/octrees") unless File.exist?("#{radPath}/octrees")
# copy Radiance model up
# TODO be smarter about this.
FileUtils.copy_entry("#{epout_dir}/4-ModelToRad-0", rad_dir)
FileUtils.cp("#{epout_dir}/3-EnergyPlus-0/eplusout.sql", "#{rad_dir}/sql")
# remove the E+ run dir so we don't confuse users
FileUtils.rm_rf(epout_dir)
# Set Radiance simulation settings
# TODO: read settings directly from model
options_tregVars = ""
options_dmx = ""
options_vmx = ""
if rad_settings == "Testing"
options_tregVars = "-e MF:1 -f tregenza.cal -b tbin -bn Ntbins"
options_dmx = "-ab 1 -ad 128 -as 56 -dj 1 -dp 1 -dt 0.1 -dc 0.1 -lw 0.1 "
options_vmx = "-ab 1 -ad 128 -as 56 -dj 1 -dp 1 -dt 0.1 -dc 0.1 -lw 0.1"
end
options_klemsDensity = ""
options_skyvecDensity = "1"
if rad_settings == "Model"
File.open("#{radPath}/options/treg.opt", "r") do |file|
tempIO = file.read
tempSettings = tempIO.split(" ")
options_klemsDensity = "#{tempSettings[0]} #{tempSettings[1]}"
options_skyvecDensity = tempSettings[3].split(":")[1]
options_tregVars = tempSettings[2..-1].join(" ")
end
File.open("#{radPath}/options/dmx.opt", "r") do |file|
tempIO = file.read
options_dmx = tempIO
end
File.open("#{radPath}/options/vmx.opt", "r") do |file|
tempIO = file.read
options_vmx = tempIO
end
end
# configure multiprocessing
procsUsed = ""
if /mswin/.match(RUBY_PLATFORM) or /mingw/.match(RUBY_PLATFORM)
procsUsed = ""
else
procsUsed = "-n #{sim_cores}"
end
# core functions
def calculateDaylightCoeffecients(radPath, sim_cores, t_catCommand, options_tregVars,
options_klemsDensity, options_skyvecDensity, options_dmx,
options_vmx, rad_settings, procsUsed, runner, debug_mode)
# get calculation points array size (needed for rmtxop later)
mapFile=File.open("numeric/merged_space.map","r")
rfluxmtxDim = mapFile.readlines.size.to_s
# sort out window groups, controls
haveWG0 = ""
haveWG1 = ""
windowGroupCheck = File.open("bsdf/mapping.rad")
windowGroupCheck.each do |row|
next if row[0] == "#"
wg=row.split(",")[0]
if wg == "WG0"
haveWG0 = "True"
elsif wg == "WG1"
haveWG1 = "True"
end
end
windowGroupCheck.close
print_statement("Passing #{rfluxmtxDim} calculation points to Radiance", runner)
# process individual window groups
print_statement("Computing daylight coefficient matrices", runner)
exec_statement("oconv materials/materials.rad model.rad > octrees/model_dc.oct", runner)
windowMaps = File::open("bsdf/mapping.rad")
windowMaps.each do |row|
next if row[0] == "#"
wg=row.split(",")[0]
rad_command = ""
if wg == "WG0" # window group zero (all uncontrolled windows)
print_statement("Computing view matrix for uncontrolled windows (WG0)", runner)
# make WG0 octree (with shade-controlled window groups blacked out, if any)
input_files = ""
if haveWG1 == "True"
input_files = "materials/materials.rad materials/materials_WG0.rad model.rad"
else
input_files = "materials/materials.rad model.rad skies/dc_sky.rad"
end
# for the calc, include unit sky
exec_statement("oconv #{input_files} skies/dc_sky.rad > octrees/model_WG0.oct", runner)
if debug_mode
# for check images (insert sky later, in genImages())
exec_statement("oconv #{input_files} > octrees/debug_model_WG0.oct", runner)
end
# use more aggro simulation parameters because this is basically a view matrix
rtrace_args = "#{options_vmx}"
rad_command = "#{t_catCommand} numeric/merged_space.map | rcontrib #{rtrace_args} #{procsUsed} -I+ -fo #{options_tregVars} -o output/dc/WG0.vmx -m skyglow octrees/model_WG0.oct"
exec_statement(rad_command, runner)
else # controlled window group
print_statement("Processing shade-controlled window group '#{wg}'", runner)
if row.split(",")[4].rstrip == "SWITCHABLE" # has switchable glazing
print_statement("Window Group '#{wg}' has switchable glazing control, calculating two view matrices", runner)
# black out WG0 and all other WG shades
# start with base materials, then black everything out
base_mats = "materials/materials.rad materials/materials_blackout.rad"
# do view matrices, one for each tint state
rtrace_args = "#{options_vmx}"
["clear", "tinted"].each do |state|
# for the calc
exec_statement("oconv #{base_mats} materials/#{wg}_#{state}.mat model.rad skies/dc_sky.rad > octrees/model_#{wg}_#{state}.oct", runner)
if debug_mode
# for check images
exec_statement("oconv #{base_mats} materials/#{wg}_#{state}.mat model.rad > octrees/debug_model_#{wg}_#{state}.oct", runner)
end
print_statement("Computing view matrix for window group '#{wg}' in #{state} state", runner)
exec_statement("#{t_catCommand} \"numeric/merged_space.map\" | rcontrib #{rtrace_args} #{procsUsed} -I+ -fo #{options_tregVars} -o \"output/dc/#{wg}_#{state}.vmx\" -m skyglow octrees/model_#{wg}_#{state}.oct", runner)
end
else # has shades
# use more chill sim parameters
rtrace_args = "#{options_dmx}"
# do daylight matrices for controlled windows
print_statement("Computing daylight matrix for window group '#{wg}'", runner)
if debug_mode
# make octrees for debug images
# load materials, then black out all materials, then add in scene geometry and glazing (no shades)
input_files = "materials/materials.rad materials/materials_blackout.rad"
# now reset window group glazing material and make an octree
exec_statement("oconv #{input_files} materials/#{wg}.mat scene/*.rad scene/glazing/*.rad > octrees/debug_model_#{wg}.oct", runner)
# now reset window group shade material to actual and make an octree
exec_statement("oconv #{input_files} materials/#{wg}.mat materials/#{wg}_SHADE.mat scene/*.rad scene/glazing/*.rad scene/shades/#{wg}_SHADE.rad > octrees/debug_model_#{wg}_shade.oct", runner)
end
rad_command = "rfluxmtx #{rtrace_args} -n #{sim_cores} -fa -v scene/shades/#{wg}_SHADE.rad skies/dc_sky.rad -i octrees/model_dc.oct > \"output/dc/#{wg}.dmx\""
exec_statement(rad_command, runner)
end
end # calculate DMX
end # individual window group processing
# do remaining view matrices, if applicable
shade_check = Dir.glob("scene/shades/WG*.rad")
if shade_check.length > 0
# compute view matrices for shade controlled window groups all at once
# use fine params
rtrace_args = "#{options_vmx}"
print_statement("Computing view matri(ces) for all remaining window groups", runner)
# get the shaded window groups' shade polygons
wgInput = []
# get the SHADE polygons for sampling (NOT the GLAZING ones!)
# this will automatically omit switchable glazing-controlled window groups. ;)
Dir.glob("scene/shades/WG*.rad") {|file|
wgInput << file
}
# make the receiver file
exec_statement("#{t_catCommand} \"materials/materials_vmx.rad\" #{wgInput.join(" ")} > receivers_vmx.rad", runner)
# make the octree
scene_files = []
Dir.glob("scene/*.rad").each {|f| scene_files << f}
exec_statement("oconv materials/materials.rad #{scene_files.join(' ')} > octrees/model_vmx.oct", runner)
# make rfluxmtx do all the work
rad_command = "rfluxmtx #{rtrace_args} -n #{sim_cores} -ds .15 -faa -y #{rfluxmtxDim} -I -v - receivers_vmx.rad -i octrees/model_vmx.oct < numeric/merged_space.map"
exec_statement(rad_command, runner)
FileUtils.rm('receivers_vmx.rad')
end # VMX for controlled window groups
if haveWG1 == "True"
# compute daylight coefficient matrix for window group control points
rtrace_args = "#{options_dmx}"
exec_statement("oconv \"materials/materials.rad\" model.rad skies/dc_sky.rad > octrees/model_wc.oct", runner)
print_statement("Computing DCs for window control points", runner)
rad_command = "#{t_catCommand} \"numeric/window_controls.map\" | rcontrib #{rtrace_args} #{procsUsed} -I+ -fo #{options_tregVars} " + \
"-o \"output/dc/window_controls.vmx\" -m skyglow octrees/model_wc.oct"
exec_statement(rad_command, runner)
end
print_statement("Daylight coefficient matrices computed.", runner)
end # calculateDaylightCoeffecients()
# annual simulation dealio
def runSimulation(t_space_names_to_calculate, t_sqlFile, t_simCores, t_options_skyvecDensity,
t_site_latitude, t_site_longitude, t_site_stdmeridian, t_radPath,
t_spaceWidths, t_spaceHeights, t_radGlareSensorViews, runner, debug_mode)
print_statement("Performing annual daylight simulation(s)", runner)
rawValues = {}
values = {}
dcVectors = {}
# sort out window groups, controls
haveWG0 = "False"
haveWG1 = "False"
windowGroupCheck = File.open("bsdf/mapping.rad")
windowGroupCheck.each do |row|
next if row[0] == "#"
wg=row.split(",")[0]
if wg == "WG0"
haveWG0 = "True"
elsif wg == "WG1"
haveWG1 = "True"
end
end
windowGroupCheck.close
# Run the simulation
simulations = []
rad_command = "gendaymtx -m #{t_options_skyvecDensity} \"wx/in.wea\" > annual-sky.mtx"
exec_statement(rad_command, runner)
windowMaps = File.open("bsdf/mapping.rad")
# do annual sim for each window group and state
windowMaps.each do |row|
# skip header
next if row[0] == "#"
wg = row.split(",")[0]
# do uncontrolled windows (WG0)
if wg == "WG0"
# if row.split(",")[2] == "n/a" || row.split(",")[2] == "AlwaysOff"
# keep header, convert to illuminance, but no transpose
rad_command = "dctimestep output/dc/#{wg}.vmx annual-sky.mtx | rmtxop -fa -c 47.4 120 11.6 - > output/ts/#{wg}.ill"
exec_statement(rad_command, runner)
else
# do all controlled window groups
if row.split(",")[4].rstrip == "SWITCHABLE"
# make single phase illuminance sched for each state
states = ["clear", "tinted"]
states.each_index do |i|
print_statement("Calculating annual iluminance for window group '#{wg}', state: #{states.index(states[i])} (switchable glazing - #{states[i]})", runner)
exec_statement("dctimestep output/dc/#{wg}_#{states[i]}.vmx annual-sky.mtx | rmtxop -fa -c 47.4 120 11.6 - > output/ts/#{wg}_#{states.index(states[i])}.ill", runner)
end
else
wgXMLs = row.split(",")[4..-1]
if wgXMLs.size > 2
print_statement("WARN: Window Group #{wg} has #{wgXMLs.size} BSDFs (2 max supported by OpenStudio application).", runner)
end
wgXMLs.each_index do |i|
#rad_command = "dctimestep output/dc/#{wg}.vmx bsdf/#{wgXMLs[i].strip} output/dc/#{wg}.dmx annual-sky.mtx | rmtxop -fa -c 47.4 120 11.6 - > output/ts/#{wg}_INDEX#{wgXMLs.index[i]}_#{wgXMLs[i].split[0]}.ill"
print_statement("Calculating annual iluminance for window group '#{wg}', state: #{wgXMLs.index(wgXMLs[i])} (BSDF filename: '#{wgXMLs[i].split[0]}'):", runner)
rad_command = "dctimestep output/dc/#{wg}.vmx bsdf/#{wgXMLs[i].strip} output/dc/#{wg}.dmx annual-sky.mtx | rmtxop -fa -c 47.4 120 11.6 - > output/ts/#{wg}_#{wgXMLs.index(wgXMLs[i])}.ill"
exec_statement(rad_command, runner)
end
end
end
end
if haveWG1 == "True"
# get annual values for window control sensors (note: convert to illuminance, no transpose, strip header)
exec_statement("dctimestep output/dc/window_controls.vmx annual-sky.mtx | rmtxop -fa -c 47.4 120 11.6 - | getinfo - > output/ts/window_controls.ill", runner)
print_statement("Blending window group results per shade control schedule", runner)
# do that window group/state merge thing
wg_index = 0
print_statement("### DEBUG: getting window shade control(s) values", runner)
filename = "output/ts/window_controls.ill"
windowControls, _header = read_illuminance_file(filename, runner)
print_statement("### DEBUG: windowControls matrix is #{windowControls.row_count} rows x #{windowControls.column_count} columns", runner)
windowGroups = File.open("bsdf/mapping.rad")
windowGroups.each do |wg|
next if wg[0] == "#" # skip header
windowGroup = wg.split(",")[0]
next if windowGroup == "WG0" # skip unshaded windows
wg_index += 1
wgIllumFiles = Dir.glob("output/ts/#{windowGroup}_*.ill").sort
shadeControlType = wg.split(",")[2].to_s
shadeControlSetpoint = wg.split(",")[3].to_f
wg_normal = wg.split(",")[1]
wg_normal_x = wg_normal.split(" ")[0].to_f
wg_normal_y = wg_normal.split(" ")[1].to_f
wg_normal_z = wg_normal.split(" ")[2].to_f
# DLM: hacktastic way to implement these options for now
if shadeControlType == "AlwaysOn"
shadeControlSetpoint = -1000
elsif
shadeControlType == "AlwaysOff"
shadeControlSetpoint = 10000000000
end
print_statement("Processing Window Group '#{windowGroup}', (exterior normal: '#{wg_normal_x * -1} #{wg_normal_y * -1} #{wg_normal_z * -1}', shade control setpoint: #{shadeControlSetpoint.round(0)} lux)", runner)
ill0, header = read_illuminance_file(wgIllumFiles[0], runner)
ill1, _header = read_illuminance_file(wgIllumFiles[1], runner)
wgMerge = Matrix.build(ill0.row_count, ill0.column_count) { 0 }
print_statement("### DEBUG: wgmerge is #{wgMerge.row_count} rows x #{wgMerge.column_count} columns", runner)
wgShadeSchedule = []
print_statement("### DEBUG: window group = '#{wg.split(",")[0]}', window controls matrix index = '#{wg_index-1}' (zero-based)", runner)
windowControls.row(wg_index-1).each_with_index do | illuminance, row_index|
window_illuminance = illuminance.to_f
if window_illuminance < shadeControlSetpoint
print_statement("### DEBUG: E(#{windowGroup}) is #{window_illuminance.round(0)} lux at index: #{row_index} /\\ STATE 0 (up/clear) /\\", runner) if row_index > 152 && row_index < 160 # print shade decisions for one day
ill0.column(row_index).each_with_index do |value, column_index|
wgMerge.send(:[]=, column_index, row_index, value)
end
wgShadeSchedule << "#{row_index},#{window_illuminance.round(0)},#{shadeControlSetpoint.round(0)},0\n"
else
print_statement("### DEBUG: E(#{windowGroup}) is #{window_illuminance.round(0)} lux at index: #{row_index} \\/ STATE 1 (dn/tinted) \\/", runner) if row_index > 152 && row_index < 160 # print shade decisions for one day
ill1.column(row_index).each_with_index do |value, column_index|
wgMerge.send(:[]=, column_index, row_index, value.to_f)
end
wgShadeSchedule << "#{row_index},#{window_illuminance.round(0)},#{shadeControlSetpoint.round(0)},1\n"
end
end
wgIllum = File.open("output/ts/m_#{windowGroup}.ill", "w")
wgShade = File.open("output/ts/#{windowGroup}.shd", "w")
header.each {|head| wgIllum.print "#{head}"}
wgMerge.to_a.each {|array_ts| wgIllum.print " #{array_ts.join(" ")}\n"} # note leading space, for compatibility with default rfluxmtx output
wgShadeSchedule.each {|sh| wgShade.print "#{sh}"}
wgIllum.close
wgShade.close
FileUtils.rm Dir.glob('*.tmp')
end
end
# make whole-building illuminance file
print_statement("Merging window group daylight illuminance schedules to building daylight illuminance schedule", runner)
addFiles = ""
# get the uncontrolled windows results, if any
if File.exist?("output/ts/WG0.ill")
print_statement("Adding uncontrolled window results", runner)
addFiles << "output/ts/WG0.ill "
else
print_statement("Model has no uncontrolled windows", runner)
end
# get the controlled window group results (m_*.ill), if any
mergedWindows = Dir.glob("output/ts/m_*.ill")
if mergedWindows.size > 0
print_statement("Adding shade-controlled window group(s) results", runner)
mergedWindows.each do |file|
addFiles << "+ #{file} "
end
else
print_statement("Model has no controlled window groups", runner)
end
# merge uncontrolled windows (WG0.ill) with blended controlled window groups (m_*.ill)
exec_statement("rmtxop -fa #{addFiles} -t | getinfo - > output/merged_space.ill", runner)
## window merge end
rawValues = parseResults(simulations, t_space_names_to_calculate, t_spaceWidths, t_spaceHeights, t_radGlareSensorViews, t_radPath, runner, debug_mode)
dcVectors = nil
# for each environment period (design days, annual, or arbitrary) you will create a directory for results
t_sqlFile.availableEnvPeriods.each do |envPeriod|
# DLM: all of these might be available directly from the EpwFile after Jason DeGraw's work
diffHorizIllumAll, dirNormIllumAll, diffEfficacyAll, dirNormEfficacyAll, solarAltitudeAll, solarAzimuthAll, diffHorizUnits, dirNormUnits = getTimeSeries(t_sqlFile, envPeriod)
# check that we have all timeseries
if (not diffHorizIllumAll) or (not dirNormIllumAll) or (not diffEfficacyAll) or (not dirNormEfficacyAll) or (not solarAltitudeAll) or (not solarAzimuthAll)
runner.registerError('Missing required timeseries')
exit false
end
simDateTimes, simTimes, diffHorizIllum, dirNormIllum, diffEfficacy, dirNormEfficacy, solarAltitude, solarAzimuth, firstReportDateTime = \
buildSimulationTimes(t_sqlFile, envPeriod, diffHorizIllumAll, dirNormIllumAll, diffEfficacyAll, dirNormEfficacyAll, solarAltitudeAll, solarAzimuthAll)
simTimes.each_index do |i|
datetime = simDateTimes[i]
hours = ((datetime.date().dayOfYear() - 1) * 24) + datetime.time().hours()
values[i] = rawValues[hours]
end
end
return values, dcVectors;
end # runSimulation()
# function renamed from execSimulation() to parseResults()
def parseResults(t_cmds, t_space_names_to_calculate, t_spaceWidths, t_spaceHeights, t_radGlareSensorViews, t_radPath, runner, debug_mode)
print_statement("Parsing daylighting results", runner)
allValues = []
values = []
# read illuminance values from file
values = []
valuesFile = File.open("#{t_radPath}/output/merged_space.ill")
valuesFile.each do |row|
values << row.split(" ")
end
allhours = []
# write out illuminance to individual space/map files
8760.times do |hour|
index = 0;
splitvalues = {}
t_space_names_to_calculate.each do |space_name|
space_size = t_spaceWidths[space_name] * t_spaceHeights[space_name]
space = []
illum = []
glaresensors ||= {} # TODO: you can probably remove this
glaresensors[space_name] ||= {}
if values.size > 0
subspace = values.slice(index, space_size)
index = index + space_size
print_statement("### DEBUG: starting illuminance map for '#{space_name}'. space_size: #{space_size}, index is now at: #{index}, ", runner) if hour == 0 if debug_mode
space = []
subspace.each do |subspacevalue|
space << subspacevalue[hour].to_f.round(1);
end
if File.exist?("#{t_radPath}/numeric/#{space_name}.sns")
if index >= values.size
print_statement("Index is #{index} but values.size is only #{values.size}", runner)
elsif hour >= values[index].size
print_statement("Hour is #{hour} but values.size[index] is only #{values[index].size}", runner)
end
illum = [values[index][hour].to_f.round(1)]
index = index + 1
print_statement("### DEBUG: finished space map and daylight sensor values, and index is now: #{index}", runner) if hour == 0 && debug_mode
end
# get ALL glare sensors for space
if t_radGlareSensorViews[space_name] && t_radGlareSensorViews[space_name].keys.size > 0
t_radGlareSensorViews[space_name].each do |sensor, views|
sensor_index = t_radGlareSensorViews[space_name].keys.index(sensor)
print_statement("### DEBUG: glare sensor '#{sensor}' has #{views.size} views", runner) if hour == 0 && debug_mode
views['view_definitions'].each_index do |view_index|
print_statement("### DEBUG: index is #{index}; view_index is #{view_index}", runner) if hour == 0 && debug_mode
t_radGlareSensorViews[space_name][sensor][hour] ||= {}
t_radGlareSensorViews[space_name][sensor][hour]["#{sensor_index}_#{view_index}"] ||= {}
view_values = values.slice(index, 1).first
adjustedval = 0.00
if view_values[hour].to_f != 0.00
adjustedval = [(0.0000622*view_values[hour].to_f)+0.184, 0].max.round(2)
end
t_radGlareSensorViews[space_name][sensor][hour]["#{sensor_index}_#{view_index}"]['dgp'] = adjustedval.round(2)
t_radGlareSensorViews[space_name][sensor][hour]["#{sensor_index}_#{view_index}"]['raw'] = view_values[hour].to_f.round(2)
index += 1
end
end
end
else
print_statement("An error has occurred; no results for space '#{space_name}'.", runner)
space = Array.new(space_size, 0)
if File.exist?("#{t_radPath}/numeric/#{space_name}.sns")
illum = Array.new(1, 0)
end
end
# make an array that will have all the views
splitvalues[space_name] = [space, illum]
# iterate over each sensor and combine the views together
new_hash = {}
if t_radGlareSensorViews[space_name]
t_radGlareSensorViews[space_name].each do |sensor, v|
new_hash[sensor] = v[hour]
end
end
splitvalues[space_name] += [new_hash]
end
allhours[hour] = splitvalues;
end
allhours
File.open('output/glare.json', 'w') { |f| f << JSON.pretty_generate(t_radGlareSensorViews)}
File.open('output/radout.json', 'w') { |f| f << JSON.pretty_generate( { all_hours: allhours } )}
print_statement("Returning annual results", runner)
return allhours
end # parseResults()
def getTimeSeries(t_sqlFile, t_envPeriod)
diffHorizIllumAll = []; dirNormIllumAll = [];
diffEfficacyAll = []; dirNormEfficacyAll = [];
solarAltitudeAll = []; solarAzimuthAll = [];
diffHorizUnits = nil; dirNormUnits = nil
# get the solar data
t_sqlFile.timeSeries(t_envPeriod, "Hourly", "Site Exterior Horizontal Sky Illuminance").each do |timeseries|
diffHorizIllumAll = timeseries.values
diffHorizUnits = timeseries.units if not diffHorizUnits
end
t_sqlFile.timeSeries(t_envPeriod, "Hourly", "Site Exterior Beam Normal Illuminance").each do |timeseries|
dirNormIllumAll = timeseries.values
dirNormUnits = timeseries.units if not dirNormUnits
end
t_sqlFile.timeSeries(t_envPeriod, "Hourly", "Site Sky Diffuse Solar Radiation Luminous Efficacy").each do |timeseries|
diffEfficacyAll = timeseries.values
diffEfficacyUnits = timeseries.units if not diffEfficacyUnits
end
t_sqlFile.timeSeries(t_envPeriod, "Hourly", "Site Beam Solar Radiation Luminous Efficacy").each do |timeseries|
dirNormEfficacyAll = timeseries.values
dirNormEfficacyUnits = timeseries.units if not dirNormEfficacyUnits
end
t_sqlFile.timeSeries(t_envPeriod, "Hourly", "Site Solar Altitude Angle").each do |timeseries|
solarAltitudeAll = timeseries.values
solarAltitudeUnits = timeseries.units if not solarAltitudeUnits
end
t_sqlFile.timeSeries(t_envPeriod, "Hourly", "Site Solar Azimuth Angle").each do |timeseries|
solarAzimuthAll = timeseries.values
solarAzimuthUnits = timeseries.units if not solarAzimuthUnits
end
return diffHorizIllumAll, dirNormIllumAll, diffEfficacyAll, dirNormEfficacyAll, solarAltitudeAll, solarAzimuthAll, diffHorizUnits, dirNormUnits
end # getTimeSeries()
def buildSimulationTimes(t_sqlFile, t_envPeriod, t_diffHorizIllumAll, t_dirNormIllumAll, t_diffEfficacyAll, t_dirNormEfficacyAll, t_solarAltitudeAll, t_solarAzimuthAll)
# we want simulation at these indices only
simDateTimes = OpenStudio::DateTimeVector.new();
simTimes = []
diffHorizIllum = []
dirNormIllum = []
diffEfficacy = []
dirNormEfficacy = []
solarAltitude = []
solarAzimuth = []
firstReportDateTime = nil
t_sqlFile.timeSeries(t_envPeriod, "Hourly", "Site Exterior Horizontal Sky Illuminance").each do |timeseries|
firstReportDateTime = timeseries.firstReportDateTime
daysFromFirstReport = timeseries.daysFromFirstReport
(0...daysFromFirstReport.size).each do |i|