Method: OpenStudio::Workflow::Util::Measure#apply_measure

Defined in:
lib/openstudio/workflow/util/measure.rb

#apply_measure(registry, step, options = {}, energyplus_output_requests = false) ⇒ Hash, String

Method to allow for a single measure of any type to be run

Parameters:

  • directory (String)

    Location of the datapoint directory to run. This is needed independent of the adapter that is being used. Note that the simulation will actually run in ‘run’

  • adapter (Object)

    An instance of the adapter class

  • current_weather_filepath (String)

    The path which will be used to set the runner and returned to update the OSW for future measures and the simulation

  • model (Object)

    The model object being used in the measure, either a OSM or IDF

  • step (Hash)

    Definition of the to be run by the workflow

  • output_attributes (Hash)

    The results of previous measure applications which are persisted through the runner to allow measures to react to previous events in the workflow

  • options (Hash) (defaults to: {})

    ({}) User-specified options used to override defaults

  • energyplus_output_requests (Boolean) (defaults to: false)

    If true then the energyPlusOutputRequests is called instead of the run method

Options Hash (step):

  • :measure_dir_name (String)

    The name of the directory which contains the measure files

  • :arguments (Object)

    name value hash which defines the arguments to the measure, e.g. true, cost: 3.1

Options Hash (options):

  • :measure_search_array (Array)

    Ordered set of measure directories used to search for step, e.g. [‘measures’, ‘../../measures’]

  • :time_logger (Object)

    Special logger used to debug performance issues

Returns:

  • (Hash, String)

    Returns two objects. The first is the (potentially) updated output_attributes hash, and the second is the (potentially) updated current_weather_filepath



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
# File 'lib/openstudio/workflow/util/measure.rb', line 228

def apply_measure(registry, step, options = {}, energyplus_output_requests = false)

  logger = registry[:logger]
  runner = registry[:runner]
  workflow_json = registry[:workflow_json]
  measure_dir_name = step.measureDirName
     
  run_dir = registry[:run_dir]
  fail 'No run directory set in the registry' unless run_dir
  
  output_attributes = registry[:output_attributes]
  
  # todo: get weather file from appropriate location 
  @wf = registry[:wf]
  @model = registry[:model]
  @model_idf = registry[:model_idf]
  @sql_filename = registry[:sql]
  
  runner.setLastOpenStudioModel(@model) if @model
  #runner.setLastOpenStudioModelPath(const openstudio::path& lastOpenStudioModelPath); #DLM - deprecate?
  runner.setLastEnergyPlusWorkspace(@model_idf) if @model_idf
  #runner.setLastEnergyPlusWorkspacePath(const openstudio::path& lastEnergyPlusWorkspacePath); #DLM - deprecate?
  runner.setLastEnergyPlusSqlFilePath(@sql_filename) if @sql_filename
  runner.setLastEpwFilePath(@wf) if @wf

  logger.debug "Starting #{__method__} for #{measure_dir_name}"
  registry[:time_logger].start("Measure:#{measure_dir_name}") if registry[:time_logger]
  current_dir = Dir.pwd

  success = nil
  begin
  
    measure_dir = workflow_json.findMeasure(measure_dir_name)
    fail "Cannot find #{measure_dir_name}" if measure_dir.empty?
    measure_dir = measure_dir.get
    
    measure = OpenStudio::BCLMeasure.load(measure_dir)
    fail "Cannot load measure at #{measure_dir}" if measure.empty?
    measure = measure.get
    
    step_index = workflow_json.currentStepIndex

    measure_run_dir = File.join(run_dir, "#{step_index.to_s.rjust(3,'0')}_#{measure_dir_name}")
    logger.debug "Creating run directory for measure in #{measure_run_dir}"
    FileUtils.mkdir_p measure_run_dir
    Dir.chdir measure_run_dir
    
    if energyplus_output_requests
      logger.debug "energyPlusOutputRequests running in #{Dir.pwd}"
    else
      logger.debug "Apply measure running in #{Dir.pwd}"
    end

    class_name = measure.className
    measure_type = measure.measureType
    
    measure_path = measure.primaryRubyScriptPath
    fail "Measure does not have a primary ruby script specified" if measure_path.empty?
    measure_path = measure_path.get
    fail "#{measure_path} file does not exist" unless File.exist?(measure_path.to_s)
    
    logger.debug "Loading Measure from #{measure_path}"

    measure_object = nil
    result = nil
    begin
      load measure_path.to_s
      measure_object = Object.const_get(class_name).new
    rescue => e
 
      # add the error to the osw.out
      runner.registerError("#{e.message}\n\t#{e.backtrace.join("\n\t")}")
      
      # @todo (rhorsey) Clean up the error class here.
      log_message = "Error requiring measure #{__FILE__}. Failed with #{e.message}, #{e.backtrace.join("\n")}"
      raise log_message
    end

    arguments = nil
    skip_measure = false
    begin

      # Initialize arguments which may be model dependent, don't allow arguments method access to real model in case it changes something
      if measure_type == 'ModelMeasure'.to_MeasureType
        arguments = measure_object.arguments(@model.clone(true).to_Model)
      elsif measure_type == 'EnergyPlusMeasure'.to_MeasureType
        arguments = measure_object.arguments(@model_idf.clone(true))
      else measure_type == 'ReportingMeasure'.to_MeasureType
        arguments = measure_object.arguments
      end

      # Create argument map and initialize all the arguments
      argument_map = OpenStudio::Ruleset::OSArgumentMap.new
      if arguments
        arguments.each do |v|
          argument_map[v.name] = v.clone
        end
      end

      # Set argument values if they exist
      logger.debug "Iterating over arguments for workflow item '#{measure_dir_name}'"
      if step.arguments 
        step.arguments.each do |argument_name, argument_value|
          if argument_name.to_s == '__SKIP__'
            if registry[:openstudio_2]
              variant_type = argument_value.variantType
              if variant_type == "String".to_VariantType
                argument_value = argument_value.valueAsString
              elsif variant_type == "Double".to_VariantType
                argument_value = argument_value.valueAsDouble
              elsif variant_type == "Integer".to_VariantType
                argument_value = argument_value.valueAsInteger
              elsif variant_type == "Boolean".to_VariantType
                argument_value = argument_value.valueAsBoolean
              end
            end
            
            if argument_value.class == String
              argument_value = argument_value.downcase
              if argument_value == "false"
                skip_measure = false
              else
                skip_measure = true
              end
            elsif argument_value.class == Fixnum
              skip_measure = (argument_value != 0)
            elsif argument_value.class == Float
              skip_measure = (argument_value != 0.0)
            elsif argument_value.class == FalseClass
              skip_measure = false
            elsif argument_value.class == TrueClass
              skip_measure = true
            elsif argument_value.class == NilClass
              skip_measure = false
            end
          else
            # regular argument
            if registry[:openstudio_2]
              success = apply_arguments_2(argument_map, argument_name, argument_value, logger)
            else
              success = apply_arguments(argument_map, argument_name, argument_value, logger)
            end
            fail 'Could not set arguments' unless success
          end
        end
      end

      # map any choice display names to choice values, in either set values or defaults
      argument_map.each_key do |argument_name|
        v = argument_map[argument_name]
        choice_values = v.choiceValues
        if !choice_values.empty?
          value = nil
          value = v.defaultValueAsString if v.hasDefaultValue
          value = v.valueAsString if v.hasValue
          if value && choice_values.index(value).nil?
            display_names = v.choiceValueDisplayNames
            i = display_names.index(value)
            if i && choice_values[i]
              logger.debug "Mapping display name '#{value}' to value '#{choice_values[i]}' for argument '#{argument_name}'"
              value_set = v.setValue(choice_values[i])
              fail "Could not set argument '#{argument_name}' to mapped value '#{choice_values[i]}'" unless value_set
              argument_map[argument_name.to_s] = v.clone
            end
          end
        end
      end
      
    rescue => e

      # add the error to the osw.out
      runner.registerError("#{e.message}\n\t#{e.backtrace.join("\n\t")}")
        
      log_message = "Error assigning argument in measure #{__FILE__}. Failed with #{e.message}, #{e.backtrace.join("\n")}"
      raise log_message
    end

    if skip_measure
      if !energyplus_output_requests
        # just increment
        logger.debug "Skipping measure '#{measure_dir_name}'"
        
        # required to update current step
        runner.prepareForUserScriptRun(measure_object)
        
        # don't want to log errors about arguments passed to skipped measures
        #runner.validateUserArguments(arguments, argument_map)
        
        current_result = runner.result
        runner.incrementStep
        add_result_measure_info(current_result, measure)
        current_result.setStepResult('Skip'.to_StepResult)
      end
    else
    
      begin
        if energyplus_output_requests
          logger.debug "Calling measure.energyPlusOutputRequests for '#{measure_dir_name}'"
          idf_objects = measure_object.energyPlusOutputRequests(runner, argument_map)
          num_added = 0
          idf_objects.each do |idf_object|
            num_added += OpenStudio::Workflow::Util::EnergyPlus.add_energyplus_output_request(@model_idf, idf_object)
          end
          logger.debug "Finished measure.energyPlusOutputRequests for '#{measure_dir_name}', #{num_added} output requests added"
        else
          logger.debug "Calling measure.run for '#{measure_dir_name}'"
          if measure_type == 'ModelMeasure'.to_MeasureType
            measure_object.run(@model, runner, argument_map)
          elsif measure_type == 'EnergyPlusMeasure'.to_MeasureType
            measure_object.run(@model_idf, runner, argument_map)
          elsif measure_type == 'ReportingMeasure'.to_MeasureType
            measure_object.run(runner, argument_map)
          end
          logger.debug "Finished measure.run for '#{measure_dir_name}'"
        end

        # Run garbage collector after every measure to help address race conditions
        GC.start
      rescue => e

        # add the error to the osw.out
        runner.registerError("#{e.message}\n\t#{e.backtrace.join("\n\t")}")
        
        result = runner.result
        
        if !energyplus_output_requests
          # incrementStep must be called after run
          runner.incrementStep
          
          add_result_measure_info(result, measure)
        end
        
        options[:output_adapter].communicate_measure_result(result) if options[:output_adapter]
        
        log_message = "Runner error #{__FILE__} failed with #{e.message}, #{e.backtrace.join("\n")}"
        raise log_message
      end
      
      # if doing output requests we are done now
      if energyplus_output_requests
        registry.register(:model_idf) { @model_idf }
        return 
      end

      result = nil
      begin
        result = runner.result
        
        # incrementStep must be called after run
        runner.incrementStep
        
        add_result_measure_info(result, measure)
        
        options[:output_adapter].communicate_measure_result(result) if options[:output_adapter]

        errors = result.stepErrors
        
        fail "Measure #{measure_dir_name} reported an error with #{errors}" if errors.size != 0
        logger.debug "Running of measure '#{measure_dir_name}' completed. Post-processing measure output"
        
        # TODO: fix this
        #unless @wf == runner.weatherfile_path
        #  logger.debug "Updating the weather file to be '#{runner.weatherfile_path}'"
        #  registry.register(:wf) { runner.weatherfile_path }
        #end

        # @todo add note about why reassignment and not eval
        registry.register(:model) { @model }
        registry.register(:model_idf) { @model_idf }
        registry.register(:sql) { @sql_filename }
        
        if measure_type == 'ModelMeasure'.to_MeasureType
          # check if weather file has changed
          weather_file = @model.getOptionalWeatherFile
          if !weather_file.empty?
            weather_file_path = weather_file.get.path
            if weather_file_path.empty?
              logger.debug "Weather file object found in model but no path is given"
            else
              weather_file_path2 = workflow_json.findFile(weather_file_path.get)
              if weather_file_path2.empty?
                logger.warn "Could not find weather file '#{weather_file_path}' referenced in model"
              else
                if weather_file_path2.get.to_s != @wf
                  logger.debug "Updating weather file path to '#{weather_file_path2.get.to_s}'"
                  @wf = weather_file_path2.get.to_s
                  registry.register(:wf) { @wf }
                end
              end
            end
          end
        end

      rescue => e
        log_message = "Runner error #{__FILE__} failed with #{e.message}, #{e.backtrace.join("\n")}"
        raise log_message
      end

      # DLM: this section creates the measure_attributes.json file which should be deprecated
      begin
        # DLM: which name do we want?
        measure_name = class_name
        #measure_name = measure_dir_name
        
        # DLM: do measure results from sequential measures with the same name clobber each other?
        output_attributes[measure_name.to_sym] = {} if output_attributes[measure_name.to_sym].nil?
        
        result.stepValues.each do |step_value|
          step_value_name = step_value.name
          step_value_type = step_value.variantType
        
          value = nil
          if (step_value_type == "String".to_VariantType)
            value = step_value.valueAsString
          elsif (step_value_type == "Double".to_VariantType)
            value = step_value.valueAsDouble
          elsif (step_value_type == "Integer".to_VariantType)
            value = step_value.valueAsInteger
          elsif (step_value_type == "Boolean".to_VariantType)
            value = step_value.valueAsBoolean
          end
    
          output_attributes[measure_name.to_sym][step_value_name] = value
        end
      
        # Add an applicability flag to all the measure results
        step_result = result.stepResult
        fail "Step Result not set" if step_result.empty?
        step_result = step_result.get
        
        if (step_result == "Skip".to_StepResult) || (step_result == "NA".to_StepResult)
          output_attributes[measure_name.to_sym][:applicable] = false
        else
          output_attributes[measure_name.to_sym][:applicable] = true
        end
        registry.register(:output_attributes) { output_attributes }
      rescue => e
        log_message = "#{__FILE__} failed with #{e.message}, #{e.backtrace.join("\n")}"
        logger.error log_message
        raise log_message
      end
      
    end
    
  rescue => e
    log_message = "#{__FILE__} failed with message #{e.message} in #{e.backtrace.join("\n")}"
    logger.error log_message
    raise log_message
  ensure
    Dir.chdir current_dir
    registry[:time_logger].stop("Measure:#{measure_dir_name}") if registry[:time_logger]

    logger.info "Finished #{__method__} for #{measure_dir_name} in #{@registry[:time_logger].delta("Measure:#{measure_dir_name}")} s" if registry[:time_logger]
  end
end