Class: ViewData

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

Overview

start the measure

Instance Method Summary collapse

Instance Method Details

#arguments(model = nil) ⇒ Object

define the arguments that the user will input



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

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

  chs = OpenStudio::StringVector.new
  chs << 'Last OSM'
  chs << 'Last IDF'
  file_source = OpenStudio::Measure::OSArgument.makeChoiceArgument('file_source', chs, true)
  file_source.setDisplayName('Model Source')
  file_source.setDefaultValue('Last OSM')
  args << file_source

  chs = OpenStudio::StringVector.new
  chs << 'Timestep'
  chs << 'Hourly'
  reporting_frequency = OpenStudio::Measure::OSArgument.makeChoiceArgument('reporting_frequency', chs, true)
  reporting_frequency.setDisplayName('Reporting Frequency')
  reporting_frequency.setDefaultValue('Hourly')
  args << reporting_frequency

  variable1_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable1_name', true)
  variable1_name.setDisplayName('Variable 1 Name')
  variable1_name.setDefaultValue('Surface Outside Face Temperature')
  args << variable1_name

  variable2_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable2_name', true)
  variable2_name.setDisplayName('Variable 2 Name')
  variable2_name.setDefaultValue('Surface Inside Face Temperature')
  args << variable2_name

  variable3_name = OpenStudio::Measure::OSArgument.makeStringArgument('variable3_name', true)
  variable3_name.setDisplayName('Variable 3 Name')
  variable3_name.setDefaultValue('Zone Mean Radiant Temperature')
  args << variable3_name

  if Gem::Version.new(OpenStudio.openStudioVersion) > Gem::Version.new('3.6.1')
    use_geometry_diagnostics = OpenStudio::Measure::OSArgument.makeBoolArgument('use_geometry_diagnostics', true)
    use_geometry_diagnostics.setDisplayName("Enable Geometry Diagnostics")
    use_geometry_diagnostics.setDescription("Enables checks for Surface/Space Convexity. The ThreeJS export is slightly slower.")
    use_geometry_diagnostics.setDefaultValue(false)
    args << use_geometry_diagnostics
  end

  return args
end

#datetimes_to_array(dateTimes) ⇒ Object



100
101
102
103
104
105
106
107
108
109
# File 'lib/measures/view_data/measure.rb', line 100

def datetimes_to_array(dateTimes)
  result = []

  dateTimes.each do |d|
    date = d.date
    time = d.time
    result << DateTime.new(date.year, date.monthOfYear.value, date.dayOfMonth, time.hours, time.minutes, time.seconds).strftime('%s').to_i
  end
  return result
end

#descriptionObject

human readable description



21
22
23
# File 'lib/measures/view_data/measure.rb', line 21

def description
  return 'Visualize energy simulation data plotted on an OpenStudio model in a web based viewer'
end

#energyPlusOutputRequests(runner, user_arguments) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/measures/view_data/measure.rb', line 30

def energyPlusOutputRequests(runner, user_arguments)
  super(runner, user_arguments)

  result = OpenStudio::IdfObjectVector.new

  # use the built-in error checking
  if !runner.validateUserArguments(arguments, user_arguments)
    return result
  end

  reporting_frequency = runner.getStringArgumentValue('reporting_frequency', user_arguments)

  variable1_name = runner.getStringArgumentValue('variable1_name', user_arguments)
  result << OpenStudio::IdfObject.load("Output:Variable,*,#{variable1_name},#{reporting_frequency};").get

  variable2_name = runner.getStringArgumentValue('variable2_name', user_arguments)
  result << OpenStudio::IdfObject.load("Output:Variable,*,#{variable2_name},#{reporting_frequency};").get

  variable3_name = runner.getStringArgumentValue('variable3_name', user_arguments)
  result << OpenStudio::IdfObject.load("Output:Variable,*,#{variable3_name},#{reporting_frequency};").get

  return result
end

#format_array(vector) ⇒ Object



119
120
121
122
123
124
125
# File 'lib/measures/view_data/measure.rb', line 119

def format_array(vector)
  result = []
  vector.each do |x|
    result << format('%.6g', x).to_f
  end
  return result
end

#modeler_descriptionObject

human readable description of modeling approach



26
27
28
# File 'lib/measures/view_data/measure.rb', line 26

def modeler_description
  return 'Converts the OpenStudio model to vA3C JSON format and renders using Three.js, simulation data is applied to surfaces of the model'
end

#nameObject

define the name that a user will see



16
17
18
# File 'lib/measures/view_data/measure.rb', line 16

def name
  return 'ViewData'
end

#run(runner, user_arguments) ⇒ Object

define what happens when the measure is run



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

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

  # use the built-in error checking
  if !runner.validateUserArguments(arguments, user_arguments)
    return false
  end

  file_source = runner.getStringArgumentValue('file_source', user_arguments)
  from_idf = (file_source == 'Last IDF')
  reporting_frequency = runner.getStringArgumentValue('reporting_frequency', user_arguments)
  variable1_name = runner.getStringArgumentValue('variable1_name', user_arguments)
  variable2_name = runner.getStringArgumentValue('variable2_name', user_arguments)
  variable3_name = runner.getStringArgumentValue('variable3_name', user_arguments)
  if Gem::Version.new(OpenStudio.openStudioVersion) > Gem::Version.new('3.6.1')
    use_geometry_diagnostics = runner.getBoolArgumentValue('use_geometry_diagnostics', user_arguments)
  end

  # 'Timestep' is the key in the input file, 'Zone Timestep' is the key in the SqlFile
  if reporting_frequency == 'Timestep'
    reporting_frequency = 'Zone Timestep'
  end

  variable_names = []

  if /Zone/.match(variable1_name) || /Surface/.match(variable1_name)
    variable_names << variable1_name
  else
    if !variable1_name.empty?
      runner.registerWarning("Variable '#{variable1_name}' is not a zone or surface variable, skipping")
    end
  end

  if variable_names.include?(variable2_name)
    runner.registerWarning("Variable '#{variable2_name}' already requested, skipping")
  elsif /Zone/.match(variable2_name) || /Surface/.match(variable2_name)
    variable_names << variable2_name
  else
    if !variable2_name.empty?
      runner.registerWarning("Variable '#{variable2_name}' is not a zone or surface variable, skipping")
    end
  end

  if variable_names.include?(variable3_name)
    runner.registerWarning("Variable '#{variable3_name}' already requested, skipping")
  elsif /Zone/.match(variable3_name) || /Surface/.match(variable3_name)
    variable_names << variable3_name
  else
    if !variable3_name.empty?
      runner.registerWarning("Variable '#{variable3_name}' is not a zone or surface variable, skipping")
    end
  end

  model = nil
  if from_idf
    # get the last workspace
    workspace = runner.lastEnergyPlusWorkspace
    if workspace.empty?
      runner.registerError('Cannot find last workspace.')
      return false
    end
    workspace = workspace.get
    rt = OpenStudio::EnergyPlus::ReverseTranslator.new
    model = rt.translateWorkspace(workspace)
    runner.registerInfo("Loaded model with '#{model.getSpaces.size}' spaces")
  else
    # get the last model
    model = runner.lastOpenStudioModel
    if model.empty?
      runner.registerError('Cannot find last model.')
      return false
    end
    model = model.get
    runner.registerInfo("Loaded model with '#{model.getSpaces.size}' spaces")
  end

  # get the last sql file
  sqlFile = runner.lastEnergyPlusSqlFile
  if sqlFile.empty?
    runner.registerError('Cannot find last sql file.')
    return false
  end
  sqlFile = sqlFile.get
  model.setSqlFile(sqlFile)

  # find the environment period
  env_period = nil
  sqlFile.availableEnvPeriods.each do |p|
    if 'WeatherRunPeriod'.to_EnvironmentType == sqlFile.environmentType(p).get
      env_period = p
      break
    end
  end

  if !env_period
    runner.registerError('No WeatherRunPeriods found in results')
    return false
  end
  runner.registerInfo("Gathering results for run period '#{env_period}'")

  start_time = Time.now
  # puts "printing variables"
  # print all variables for reference
  sqlFile.availableVariableNames(env_period, reporting_frequency).each do |variable|
    runner.registerInfo("Available variable name '#{variable}'")
  end
  # puts "done printing variables, elapsed time #{Time.now-start_time}"

  # start_time = Time.now
  # puts "computing surface_data"
  # list surface and thermal zone name for each surface
  # surface_data is a temporary variable, it is not written to JSON
  surface_data = []
  model.getPlanarSurfaces.each do |surface|
    surface_name = surface.name.to_s.upcase
    thermal_zone_name = nil
    if (space = surface.space) && !space.empty?
      if from_idf
        # if we translated from IDF, the space name will be the E+ zone name
        thermal_zone_name = space.get.name.to_s.upcase
      else
        if (thermal_zone = space.get.thermalZone) && !thermal_zone.empty?
          thermal_zone_name = thermal_zone.get.name.to_s.upcase
        end
      end
    end

    surface_data << { surface_name: surface_name, thermal_zone_name: thermal_zone_name, variables: [] }
  end
  # puts "done computing surface_data, elapsed time #{Time.now-start_time}"

  # same across all variables for given timestep
  times = nil
  hoursPerInterval = nil
  intervalsPerHour = nil
  intervalsPerDay = nil
  numDays = nil

  # changes for each variable
  start_time = Time.now
  meta_variables = []
  variables = []
  variable_names.each do |variable_name|
    units = nil
    values = []
    data_range = [Float::MAX, Float::MIN] # data max, data min

    # puts "getting keys for variable, #{variable_name}"
    keys = sqlFile.availableKeyValues(env_period, reporting_frequency, variable_name)
    # puts "done getting #{keys.size} keys, elapsed time #{Time.now-start_time}"

    if keys.empty?
      runner.registerWarning("No data available for variable '#{variable_name}', skipping")
      next
    end

    keys.each do |key|
      runner.registerInfo("Available key '#{key}' for variable name '#{variable_name}'")

      # puts "getting timeseries for key, #{key}"
      ts = sqlFile.timeSeries(env_period, reporting_frequency, variable_name, key).get
      units = ts.units
      # puts "done getting timeseries, elapsed time #{Time.now-start_time}"

      if times.nil?
        times = datetimes_to_array(ts.dateTimes)
        if !ts.intervalLength.empty?
          hoursPerInterval = ts.intervalLength.get.totalHours
          intervalsPerHour = 1.0 / hoursPerInterval.to_f
          intervalsPerDay = 1.0 / ts.intervalLength.get.totalDays
          numDays = times.size * ts.intervalLength.get.totalDays
        end
      end

      this_values = vector_to_array(ts.values)

      min = this_values.min
      max = this_values.max
      if min < data_range[0]
        data_range[0] = min
      end
      if max > data_range[1]
        data_range[1] = max
      end

      valueIndex = values.length
      values << format_array(this_values)

      if i = surface_data.index { |s| s[:surface_name] == key }
        surface_data[i][:variables] << { name: variable_name, valueIndex: valueIndex, keyName: key }
      else
        surface_data.each do |s|
          if s[:thermal_zone_name] == key
            s[:variables] << { name: variable_name, valueIndex: valueIndex, keyName: key }
          end
        end
      end

      # puts "finished with key #{key}, elapsed time #{Time.now-start_time}"
    end

    meta_variables << { name: variable_name, intervalsPerHour: intervalsPerHour, intervalsPerDay: intervalsPerDay,
                        hoursPerInterval: hoursPerInterval, numDays: numDays, units: units,
                        valueMin: data_range[0], valueMax: data_range[1] }

    variables << { name: variable_name, intervalsPerHour: intervalsPerHour, intervalsPerDay: intervalsPerDay,
                   hoursPerInterval: hoursPerInterval, numDays: numDays, units: units,
                   valueMin: data_range[0], valueMax: data_range[1], timeIndex: 0, values: values }

    # puts "finished with variable #{variable_name}, elapsed time #{Time.now-start_time}"
  end

  # convert the model to vA3C JSON format
  start_time = Time.now
  # puts "converting model to vA3C"
  json = nil
  model_clone = model.clone(true).to_Model
  begin
    # try to use new implementation
    ft = OpenStudio::Model::ThreeJSForwardTranslator.new
    if Gem::Version.new(OpenStudio.openStudioVersion) > Gem::Version.new('3.6.1')
      ft.setIncludeGeometryDiagnostics(use_geometry_diagnostics)
    end
    three_scene = ft.modelToThreeJS(model_clone, true)
    json = JSON.parse(three_scene.toJSON(false), symbolize_names: true)
    runner.registerInfo('Used new ThreeScene translator.')
  rescue NameError, StandardError
    # use old Ruby implementation
    runner.registerInfo('Using Ruby VA3C translator.')
    json = VA3C.convert_model(model_clone)
  end
  # puts "finished converting model, elapsed time #{Time.now-start_time}"

  json[:metadata][:variables] = meta_variables
  json[:times] = [times]
  json[:variables] = variables

  json[:object][:children].each do |child|
    name = child[:userData][:name].upcase

    surface = surface_data.find { |x| x[:surface_name] == name }

    valueIndex = nil
    keyName = nil
    if surface
      child[:userData][:variables] = surface[:variables]
    end
  end

  # write json file
  # start_time = Time.now
  # puts "writing JSON"
  json_out_path = './report.json'
  File.open(json_out_path, 'w') do |file|
    file << JSON.generate(json, object_nl: "\n", array_nl: '', indent: '  ')
    # file << JSON::generate(json, {:object_nl=>"", :array_nl=>"", :indent=>""})
    # make sure data is written to the disk one way or the other
    begin
      file.fsync
    rescue StandardError
      file.flush
    end
  end
  # puts "finished writing JSON, elapsed time #{Time.now-start_time}"

  # read in template
  # start_time = Time.now
  # puts "writing html"
  html_in_path = "#{File.dirname(__FILE__)}/resources/report.html.in"
  if File.exist?(html_in_path)
    html_in_path = html_in_path
  else
    html_in_path = "#{File.dirname(__FILE__)}/report.html.in"
  end
  html_in = ''
  File.open(html_in_path, 'r') do |file|
    html_in = file.read
  end

  # configure template with variable values
  os_data = JSON.generate(json, object_nl: '', array_nl: '', indent: '')
  title = 'View Data'

  # Embed js
  js_in_path = "#{File.dirname(__FILE__)}/resources/js"
  if !File.directory?(js_in_path)
    js_in_path = "#{File.dirname(__FILE__)}/js"
  end
  three_js = File.read(File.join(js_in_path, 'three.r98.min.js'))
  three_orbitcontrol_js = File.read(File.join(js_in_path, 'three.orbitcontrols.js'))
  dat_gui_js = File.read(File.join(js_in_path, 'dat.gui.0.7.9.min.js'))
  tweenlite_js = File.read(File.join(js_in_path, 'TweenLite.2.1.3.min.js'))

  renderer = ERB.new(html_in)
  html_out = renderer.result(binding)

  # write html file
  html_out_path = './report.html'
  File.open(html_out_path, 'w') do |file|
    file << html_out

    # make sure data is written to the disk one way or the other
    begin
      file.fsync
    rescue StandardError
      file.flush
    end
  end
  # puts "finished writing html, elapsed time #{Time.now-start_time}"

  # closing the sql file
  # sqlFile.close()

  # reporting final condition
  # runner.registerFinalCondition("Model written.")

  return true
end

#vector_to_array(vector) ⇒ Object



111
112
113
114
115
116
117
# File 'lib/measures/view_data/measure.rb', line 111

def vector_to_array(vector)
  result = []
  (0...vector.size).each do |i|
    result << vector[i]
  end
  return result
end