Class: RunRunmanager

Inherits:
Object
  • Object
show all
Includes:
OpenStudio::Workflow::ApplyMeasures
Defined in:
lib/openstudio/workflow/jobs/run_runmanager/run_runmanager.rb

Overview

TODO: I hear that measures can step on each other if not run in their own directory

Constant Summary

Constants included from OpenStudio::Workflow::ApplyMeasures

OpenStudio::Workflow::ApplyMeasures::MEASURE_TYPES

Instance Method Summary collapse

Methods included from OpenStudio::Workflow::ApplyMeasures

#apply_arguments, #apply_measure, #apply_measures, #apply_variables

Constructor Details

#initialize(directory, logger, time_logger, adapter, options = {}) ⇒ RunRunmanager

Initialize param directory: base directory where the simulation files are prepared param logger: logger object in which to write log messages



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
# File 'lib/openstudio/workflow/jobs/run_runmanager/run_runmanager.rb', line 30

def initialize(directory, logger, time_logger, adapter, options = {})
  energyplus_path = nil
  if /cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM
    energyplus_path = 'C:/EnergyPlus-8-2-0'
  else
    energyplus_path = '/usr/local/EnergyPlus-8-2-0'
  end

  defaults = {
    analysis_root_path: '.',
    energyplus_path: energyplus_path
  }
  @options = defaults.merge(options)

  @analysis_root_path = OpenStudio::Path.new(options[:analysis_root_path])
  @directory = OpenStudio::Path.new(directory)
  # TODO: there is a base number of arguments that each job will need including @run_directory. abstract it out.
  @run_directory = @directory / OpenStudio::Path.new('run')
  @adapter = adapter
  @results = {}
  @logger = logger
  @logger.info "#{self.class} passed the following options #{@options}"
  @time_logger = time_logger

  # initialize instance variables that are needed in the perform section
  @model = nil
  @model_idf = nil
  @initial_weather_file = nil
  @weather_file_path = nil
  @analysis_json = nil
  # TODO: rename datapoint_json to just datapoint
  @datapoint_json = nil
  @output_attributes = {}
  @report_measures = []
end

Instance Method Details

#performObject



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
# File 'lib/openstudio/workflow/jobs/run_runmanager/run_runmanager.rb', line 66

def perform
  @logger.info "Calling #{__method__} in the #{self.class} class"
  @logger.info "Current directory is #{@directory}"
  begin
    @logger.info 'Retrieving datapoint and problem'
    @datapoint_json = @adapter.get_datapoint(@directory.to_s, @options)
    @analysis_json = @adapter.get_problem(@directory.to_s, @options)

    # @results[:weather_filename]
    # File.open("#{@run_directory}/measure_attributes.json", 'w') do
    #    |f| f << JSON.pretty_generate(@output_attributes)
    # end

    if @analysis_json && @datapoint_json

      if @analysis_json[:openstudio_version].nil?
        @logger.info 'analysis_json missing openstudio_version'
        if @analysis_json[:analysis] && @analysis_json[:analysis][:openstudio_version]
          version = @analysis_json[:analysis][:openstudio_version]
          @logger.info "setting analysis_json openstudio_version to '#{version}'"
          @analysis_json[:openstudio_version] = version
        end
      end

      if @datapoint_json[:openstudio_version].nil?
        @logger.info 'datapoint_json missing openstudio_version'
        if @analysis_json[:analysis] && @analysis_json[:analysis][:openstudio_version]
          version = @analysis_json[:analysis][:openstudio_version]
          @logger.info "setting datapoint_json openstudio_version to '#{version}'"
          @datapoint_json[:openstudio_version] = version
        end
      end

      # set up log file
      logSink = OpenStudio::FileLogSink.new(@run_directory / OpenStudio::Path.new('openstudio.log'))
      # logSink.setLogLevel(OpenStudio::Debug)
      logSink.setLogLevel(OpenStudio::Trace)
      OpenStudio::Logger.instance.standardOutLogger.disable

      @logger.info 'Parsing Analysis JSON input'

      # load problem formulation
      loadResult = OpenStudio::Analysis.loadJSON(JSON.pretty_generate(@analysis_json))
      if loadResult.analysisObject.empty?
        loadResult.errors.each do |error|
          @logger.warn error.logMessage # DLM: is this right?
        end
        fail 'Unable to load analysis json.'
      end

      @logger.info 'Get Analysis From OpenStudio'
      analysis = loadResult.analysisObject.get.to_Analysis.get

      # fix up paths
      @logger.info 'Fix Paths'
      analysis.updateInputPathData(loadResult.projectDir, @analysis_root_path)

      # save for reference only
      analysis_options = OpenStudio::Analysis::AnalysisSerializationOptions.new(@analysis_root_path)
      analysis.saveJSON(@run_directory / OpenStudio::Path.new('formulation_final.json'), analysis_options, true)

      @logger.info 'Parsing DataPoint JSON input'

      # load data point to run
      loadResult = OpenStudio::Analysis.loadJSON(JSON.pretty_generate(@datapoint_json))
      if loadResult.analysisObject.empty?
        loadResult.errors.each do |error|
          @logger.warn error.logMessage
        end
        fail 'Unable to load data point json.'
      end
      data_point = loadResult.analysisObject.get.to_DataPoint.get
      analysis.addDataPoint(data_point) # also hooks up real copy of problem

      @logger.info 'Creating RunManager'

      # create a RunManager
      run_manager_path = @run_directory / OpenStudio::Path.new('run.db')
      run_manager = OpenStudio::Runmanager::RunManager.new(run_manager_path, true, false, false)

      # have problem create the workflow
      @logger.info 'Creating Workflow'
      workflow = analysis.problem.createWorkflow(data_point, OpenStudio::Path.new($OpenStudio_Dir))
      params = OpenStudio::Runmanager::JobParams.new
      params.append('cleanoutfiles', 'standard')
      workflow.add(params)

      tools = OpenStudio::Runmanager::ConfigOptions.makeTools(OpenStudio::Path.new(@options[:energyplus_path]),
                                                              OpenStudio::Path.new,
                                                              OpenStudio::Path.new,
                                                              $OpenStudio_RubyExeDir,
                                                              OpenStudio::Path.new)
      workflow.add(tools)
      # DLM: Elaine somehow we need to add info to data point to avoid this error:
      # [openstudio.analysis.AnalysisObject] <1> The json string cannot be parsed as an
      # OpenStudio analysis framework json file, because Unable to find ToolInfo object
      # at expected location.

      # queue the RunManager job
      @logger.info 'Queue RunManager Job'
      url_search_paths = OpenStudio::URLSearchPathVector.new
      weather_file_path = OpenStudio::Path.new
      if analysis.weatherFile
        weather_file_path = analysis.weatherFile.get.path
      end
      job = workflow.create(@run_directory, analysis.seed.path, weather_file_path, url_search_paths)
      OpenStudio::Runmanager::JobFactory.optimizeJobTree(job)
      analysis.setDataPointRunInformation(data_point, job, OpenStudio::PathVector.new)
      run_manager.enqueue(job, false)

      @logger.info 'Waiting for simulation to finish'

      if false
        # Get some introspection on what the current running job is. For now just
        # look at the directories that are being generated
        job_dirs = []
        while run_manager.workPending
          sleep 1
          OpenStudio::Application.instance.processEvents

          # check if there are any new folders that were creates
          temp_dirs = Dir[File.join(@run_directory.to_s, '*/')].map { |d| d.split('/').pop }.sort
          if (temp_dirs + job_dirs).uniq != job_dirs
            @logger.info "#{(temp_dirs - job_dirs).join(',')}"
            job_dirs = temp_dirs
          end
        end
      else
        run_manager.waitForFinished
      end

      @logger.info 'Simulation finished'

      # use the completed job to populate data_point with results
      @logger.info 'Updating OpenStudio DataPoint object'
      analysis.problem.updateDataPoint(data_point, job)

      @logger.info data_point

      @results = { pat_data_point: ::MultiJson.load(data_point.toJSON, symbolize_names: true) }

      # Savet this to the directory for debugging purposes
      File.open("#{@run_directory}/data_point_result.json", 'w') { |f| f << MultiJson.dump(@results, pretty: true) }

      fail 'Simulation Failed' if data_point.failed
    else
      fail 'Could not find analysis_json and datapoint_json'
    end

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

    # do not raise as the results will never end up in the datapoint
    # raise log_message
  end

  @results
end