Module: OsLib_HelperMethods

Defined in:
lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb

Overview

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

Class Method Summary collapse

Class Method Details

.check_upstream_measure_for_arg(runner, arg_name) ⇒ Object



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
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 223

def self.check_upstream_measure_for_arg(runner, arg_name)
  # 2.x methods (currently setup for measure display name but snake_case arg names)
  arg_name_value = {}
  runner.workflow.workflowSteps.each do |step|
    if step.to_MeasureStep.is_initialized
      measure_step = step.to_MeasureStep.get

      measure_name = measure_step.measureDirName
      if measure_step.name.is_initialized
        measure_name = measure_step.name.get # this is instance name in PAT
      end
      if measure_step.result.is_initialized
        result = measure_step.result.get
        result.stepValues.each do |arg|
          name = arg.name
          # check if value, double, int, or bool
          value_type = arg.variantType.valueDescription
          if value_type == "Double"
            value = arg.valueAsDouble
          elsif value_type == "Integer"
            value = arg.valueAsInteger
          elsif value_type == "Boolean"
            value = arg.valueAsBoolean
          elsif value_type == "String"
            value = arg.valueAsString
          else
            # catchall for unexpected value types
            value = arg.valueAsVariant.to_s
          end
          if name == arg_name
            arg_name_value[:value] = value
            arg_name_value[:measure_name] = measure_name
            return arg_name_value # stop after find first one
          end
        end
      else
        # puts "No result for #{measure_name}"
      end
    else
      # puts "This step is not a measure"
    end
  end

  return arg_name_value
end

.checkChoiceArgFromModelObjects(object, variableName, to_ObjectType, runner, user_arguments) ⇒ Object

check choice argument made from model objects



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 70

def self.checkChoiceArgFromModelObjects(object, variableName, to_ObjectType, runner, user_arguments)
  apply_to_building = false
  modelObject = nil
  if object.empty?
    handle = runner.getStringArgumentValue(variableName, user_arguments)
    if handle.empty?
      runner.registerError("No #{variableName} was chosen.") # this logic makes this not work on an optional model object argument
    else
      runner.registerError("The selected #{variableName} with handle '#{handle}' was not found in the model. It may have been removed by another measure.")
    end
    return false
  else
    if !eval("object.get.#{to_ObjectType}").empty?
      modelObject = eval("object.get.#{to_ObjectType}").get
    elsif !object.get.to_Building.empty?
      apply_to_building = true
    else
      runner.registerError("Script Error - argument not showing up as #{variableName}.")
      return false
    end
  end

  result = { 'modelObject' => modelObject, 'apply_to_building' => apply_to_building }
end

.checkDoubleAndIntegerArguments(runner, user_arguments, arg_check_hash) ⇒ Object

check value of double arguments



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
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 125

def self.checkDoubleAndIntegerArguments(runner, user_arguments, arg_check_hash)
  error = false

  # get hash values
  min = arg_check_hash['min']
  max = arg_check_hash['max']
  min_eq_bool = arg_check_hash['min_eq_bool']
  max_eq_bool = arg_check_hash['max_eq_bool']

  arg_check_hash['arg_array'].each do |argument|
    argument = user_arguments[argument]

    # get arg values
    arg_value = nil
    if argument.hasValue
      arg_value = argument.valueDisplayName.to_f # instead of valueAsDouble so it allows integer arguments as well
    elsif argument.hasDefaultValue
      arg_value = argument.defaultValueDisplayName.to_f
    end
    arg_display = argument.displayName

    unless min.nil?
      if min_eq_bool
        if arg_value < min
          runner.registerError("Please enter value greater than or equal to #{min} for #{arg_display}.") # add in argument display name
          error = true
        end
      else
        if arg_value <= min
          runner.registerError("Please enter value greater than #{min} for #{arg_display}.") # add in argument display name
          error = true
        end
      end
    end
    unless max.nil?
      if max_eq_bool
        if arg_value > max
          runner.registerError("Please enter value less than or equal to #{max} for #{arg_display}.") # add in argument display name
          error = true
        end
      else
        if arg_value >= max
          runner.registerError("Please enter value less than #{max} for #{arg_display}.") # add in argument display name
          error = true
        end
      end
    end
  end

  # check for any errors
  if error
    return false
  else
    return true
  end
end

.checkOptionalChoiceArgFromModelObjects(object, variableName, to_ObjectType, runner, user_arguments) ⇒ Object

check choice argument made from model objects



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
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 96

def self.checkOptionalChoiceArgFromModelObjects(object, variableName, to_ObjectType, runner, user_arguments)
  apply_to_building = false
  modelObject = nil
  if object.empty?
    handle = runner.getOptionalStringArgumentValue(variableName, user_arguments)
    if handle.empty?
      # do nothing, this is a valid option
      puts 'hello'
      modelObject = nil
      apply_to_building = false
    else
      runner.registerError("The selected #{variableName} with handle '#{handle}' was not found in the model. It may have been removed by another measure.")
      return false
    end
  else
    if !eval("object.get.#{to_ObjectType}").empty?
      modelObject = eval("object.get.#{to_ObjectType}").get
    elsif !object.get.to_Building.empty?
      apply_to_building = true
    else
      runner.registerError("Script Error - argument not showing up as #{variableName}.")
      return false
    end
  end

  result = { 'modelObject' => modelObject, 'apply_to_building' => apply_to_building }
end

.createRunVariables(runner, model, user_arguments, arguments) ⇒ Object

create variables in run from user arguments



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
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 31

def self.createRunVariables(runner, model, user_arguments, arguments)
  result = {}

  error = false
  # use the built-in error checking
  unless runner.validateUserArguments(arguments, user_arguments)
    error = true
    runner.registerError('Invalid argument values.')
  end

  user_arguments.each do |argument|
    # get argument info
    arg = user_arguments[argument]
    arg_type = arg.print.lines($/)[1]

    # create argument variable
    if arg_type.include? 'Double, Required'
      eval("result[\"#{arg.name}\"] = runner.getDoubleArgumentValue(\"#{arg.name}\", user_arguments)")
    elsif arg_type.include? 'Integer, Required'
      eval("result[\"#{arg.name}\"] = runner.getIntegerArgumentValue(\"#{arg.name}\", user_arguments)")
    elsif arg_type.include? 'String, Required'
      eval("result[\"#{arg.name}\"] = runner.getStringArgumentValue(\"#{arg.name}\", user_arguments)")
    elsif arg_type.include? 'Boolean, Required'
      eval("result[\"#{arg.name}\"] = runner.getBoolArgumentValue(\"#{arg.name}\", user_arguments)")
    elsif arg_type.include? 'Choice, Required'
      eval("result[\"#{arg.name}\"] = runner.getStringArgumentValue(\"#{arg.name}\", user_arguments)")
    else
      puts 'not setup to handle all argument types yet, or any optional arguments'
    end
  end

  if error
    return false
  else
    return result
  end
end

.getAreaOfSpacesInArray(model, spaceArray, areaType = 'floorArea') ⇒ Object

populate choice argument from model objects. areaType should be string like “floorArea” or “exteriorArea” note: it seems like spaceType.floorArea does account for multiplier, so I don’t have to call this method unless I have a custom collection of spaces.



271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 271

def self.getAreaOfSpacesInArray(model, spaceArray, areaType = 'floorArea')
  # find selected floor spaces, make array and get floor area.
  totalArea = 0
  spaceAreaHash = {}
  spaceArray.each do |space|
    spaceArea = eval("space.#{areaType}*space.multiplier")
    spaceAreaHash[space] = spaceArea
    totalArea += spaceArea
  end

  result = { 'totalArea' => totalArea, 'spaceAreaHash' => spaceAreaHash }
  return result
end

.getSpaceTypeStandardsInformation(spaceTypeArray) ⇒ Object

helper that loops through lifecycle costs getting total costs under “Construction” and add to counter if occurs during year 0



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
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 351

def self.getSpaceTypeStandardsInformation(spaceTypeArray)
  # hash of space types
  spaceTypeStandardsInfoHash = {}

  spaceTypeArray.each do |spaceType|
    # get standards building
    if !spaceType.standardsBuildingType.empty?
      standardsBuilding = spaceType.standardsBuildingType.get
    else
      standardsBuilding = nil
    end

    # get standards space type
    if !spaceType.standardsSpaceType.empty?
      standardsSpaceType = spaceType.standardsSpaceType.get
    else
      standardsSpaceType = nil
    end

    # populate hash
    spaceTypeStandardsInfoHash[spaceType] = [standardsBuilding, standardsSpaceType]
  end

  return spaceTypeStandardsInfoHash
end

.getTotalCostForObjects(objectArray, category = 'Construction', onlyYearFromStartZero = true) ⇒ Object

helper that loops through lifecycle costs getting total costs under “Construction” and add to counter if occurs during year 0



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 334

def self.getTotalCostForObjects(objectArray, category = 'Construction', onlyYearFromStartZero = true)
  counter = 0
  objectArray.each do |object|
    object_LCCs = object.lifeCycleCosts
    object_LCCs.each do |object_LCC|
      if object_LCC.category == category
        if onlyYearFromStartZero == false || object_LCC.yearsFromStart == 0
          counter += object_LCC.totalCost
        end
      end
    end
  end

  return counter
end

.log_msgsObject

Get all the log messages and put into output for users to see.



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
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 197

def self.log_msgs
  @msg_log.logMessages.each do |msg|
    # DLM: you can filter on log channel here for now
    if /openstudio.*/.match(msg.logChannel) # /openstudio\.model\..*/
      # Skip certain messages that are irrelevant/misleading
      next if msg.logMessage.include?('Skipping layer') || # Annoying/bogus "Skipping layer" warnings
              msg.logChannel.include?('runmanager') || # RunManager messages
              msg.logChannel.include?('setFileExtension') || # .ddy extension unexpected
              msg.logChannel.include?('Translator') || # Forward translator and geometry translator
              msg.logMessage.include?('UseWeatherFile') # 'UseWeatherFile' is not yet a supported option for YearDescription

      # Report the message in the correct way
      if msg.logLevel == OpenStudio::Info
        @runner.registerInfo(msg.logMessage)
      elsif msg.logLevel == OpenStudio::Warn
        @runner.registerWarning("[#{msg.logChannel}] #{msg.logMessage}")
      elsif msg.logLevel == OpenStudio::Error
        @runner.registerError("[#{msg.logChannel}] #{msg.logMessage}")
      elsif msg.logLevel == OpenStudio::Debug && @debug
        @runner.registerInfo("DEBUG - #{msg.logMessage}")
      end
    end
  end
  @runner.registerInfo("Total Time = #{(Time.new - @start_time).round}sec.")
end

.neatConvertWithUnitDisplay(double, fromString, toString, digits, unitBefore = false, unitAfter = true, space = true, parentheses = true) ⇒ Object

runs conversion and neat string, and returns value with units in string, optionally before or after the value



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
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 286

def self.neatConvertWithUnitDisplay(double, fromString, toString, digits, unitBefore = false, unitAfter = true, space = true, parentheses = true)
  # convert units
  doubleConverted = OpenStudio.convert(double, fromString, toString)
  if !doubleConverted.nil?
    doubleConverted = doubleConverted.get
  else
    puts "Couldn't convert values, check string choices passed in. From: #{fromString}, To: #{toString}"
  end

  # get neat version of converted
  neatConverted = OpenStudio.toNeatString(doubleConverted, digits, true)

  # add prefix
  if unitBefore
    if space == true && parentheses == true
      prefix = "(#{toString}) "
    elsif space == true && parentheses == false
      prefix = "(#{toString})"
    elsif space == false && parentheses == true
      prefix = "#{toString} "
    else
      prefix = toString.to_s
    end
  else
    prefix = ''
  end

  # add suffix
  if unitAfter
    if space == true && parentheses == true
      suffix = " (#{toString})"
    elsif space == true && parentheses == false
      suffix = "(#{toString})"
    elsif space == false && parentheses == true
      suffix = " #{toString}"
    else
      suffix = toString.to_s
    end
  else
    suffix = ''
  end

  finalString = "#{prefix}#{neatConverted}#{suffix}"

  return finalString
end

.populateChoiceArgFromModelObjects(model, modelObject_args_hash, includeBuilding = nil) ⇒ Object

populate choice argument from model objects



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 8

def self.populateChoiceArgFromModelObjects(model, modelObject_args_hash, includeBuilding = nil)
  # populate choice argument for constructions that are applied to surfaces in the model
  modelObject_handles = OpenStudio::StringVector.new
  modelObject_display_names = OpenStudio::StringVector.new

  # looping through sorted hash of constructions
  modelObject_args_hash.sort.map do |key, value|
    modelObject_handles << value.handle.to_s
    modelObject_display_names << key
  end

  unless includeBuilding.nil?
    # add building to string vector with space type
    building = model.getBuilding
    modelObject_handles << building.handle.to_s
    modelObject_display_names << includeBuilding
  end

  result = { 'modelObject_handles' => modelObject_handles, 'modelObject_display_names' => modelObject_display_names }
  return result
end

.setup_log_msgs(runner, debug = false) ⇒ Object

open channel to log info/warning/error messages



183
184
185
186
187
188
189
190
191
192
193
# File 'lib/measures/openstudio_extension_test_measure/resources/os_lib_helper_methods.rb', line 183

def self.setup_log_msgs(runner, debug = false)
  # Open a channel to log info/warning/error messages
  @msg_log = OpenStudio::StringStreamLogSink.new
  if debug
    @msg_log.setLogLevel(OpenStudio::Debug)
  else
    @msg_log.setLogLevel(OpenStudio::Info)
  end
  @start_time = Time.new
  @runner = runner
end