Class: URBANopt::RNM::ApiClient
- Inherits:
-
Object
- Object
- URBANopt::RNM::ApiClient
- Defined in:
- lib/urbanopt/rnm/api_client.rb
Overview
Client to interface with the RNM-US API
Instance Method Summary collapse
-
#delete_inputs ⇒ Object
Delete input files once they are zipped up.
-
#download_results(sim_id = nil) ⇒ Object
Download results of a specific simulation from RNM-US API.
-
#get_results ⇒ Object
Poll for results of RNM-US simulation and download when simulation is completed, results.zip file is downloaded to rnm_dir directory.
-
#initialize(name, rnm_dir, use_localhost = false, reopt = false) ⇒ ApiClient
constructor
Initialize ApiClient attributes:
name
,rnm_dir
,template_inputs
, anduse_localhost
. -
#prepare_results_dir ⇒ Object
Prepare results directory Delete existing results.
-
#submit_simulation ⇒ Object
Submit simulation to RNM-US API Stores sim_id in the class instance.
-
#zip_input_files ⇒ Object
Check and Zip files.
Constructor Details
#initialize(name, rnm_dir, use_localhost = false, reopt = false) ⇒ ApiClient
Initialize ApiClient attributes: name
, rnm_dir
, template_inputs
, and use_localhost
- parameters:
-
name
- String - Human readable scenario name. -
rnm_dir
- String - Full path to the rnm_directory of inputs/results for the scenario -
template_inputs
- String - Location of template inputs for the RNM-US simulation (unused) -
use_localhost
- Bool - Flag to use localhost API vs production API
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 |
# File 'lib/urbanopt/rnm/api_client.rb', line 24 def initialize(name, rnm_dir, use_localhost = false, reopt = false) # TODO: eventually add NREL developer api key support @use_localhost = use_localhost if @use_localhost @base_api = 'http://0.0.0.0:8080/api/v2/' else @base_api = 'https://rnm.urbanopt.net/api/v2/' end puts "Running RNM-US at #{@base_api}" # params @name = name @rnm_dir = rnm_dir @reopt = reopt # default input files for generic and reopt simulations @input_files = ['cust_profile_p.txt', 'cust_profile_p_extendido.txt', 'cust_profile_q.txt', 'cust_profile_q_extendido.txt', 'customers.txt', 'customers_ext.txt', 'ficheros_entrada.txt', 'ficheros_entrada_inc.txt', 'primary_substations.txt', 'streetmapAS.txt', 'udcons.csv'] @reopt_files = ['gen_profile_p.txt', 'gen_profile_p_extendido.txt', 'gen_profile_q.txt', 'gen_profile_q_extendido.txt', 'generators.txt'] if @reopt @input_files += @reopt_files end # initialize @@logger @@logger ||= URBANopt::RNM.logger # simulation data @sim_id = '' # results are not really used in memory. results.json is saved to rnm_dir when results are downloaded @results = {} end |
Instance Method Details
#delete_inputs ⇒ Object
Delete input files once they are zipped up
280 281 282 283 284 |
# File 'lib/urbanopt/rnm/api_client.rb', line 280 def delete_inputs @input_files.each do |filename| File.delete(File.join(@rnm_dir, filename)) if File.exist?(File.join(@rnm_dir, filename)) end end |
#download_results(sim_id = nil) ⇒ Object
Download results of a specific simulation from RNM-US API. attributes: sim_id
Results.zip file is downloaded to the rnm_dir directory
- parameters:
-
sim_id
- String - Simulation ID to retrieve. If not nil, will override id stored in class instance
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 |
# File 'lib/urbanopt/rnm/api_client.rb', line 218 def download_results(sim_id = nil) conn = Faraday.new(url: @base_api) streamed = [] the_sim_id = sim_id.nil? ? @sim_id : sim_id resp = conn.get("download/#{the_sim_id}") do |req| req..on_data = proc do |chunk, overall_received_bytes| # puts "Received #{overall_received_bytes} characters" streamed << chunk end end if resp.status == 200 file_path = File.join(@rnm_dir, 'results', 'results.zip') File.open(file_path, 'wb') { |f| f.write streamed.join } puts "RNM-US results.zip downloaded to #{@rnm_dir}" # unzip Zip::File.open(file_path) do |zip_file| zip_file.each do |f| f_path = File.join(@rnm_dir, 'results', f.name) FileUtils.mkdir_p(File.dirname(f_path)) zip_file.extract(f, f_path) unless File.exist?(f_path) end end puts 'results.zip extracted' # delete zip File.delete(file_path) # check if zip is empty if Dir.empty? File.join(@rnm_dir, 'results') msg = "Error in simulation: Results.zip empty" @@logger.error(msg) raise msg end else msg = "Error retrieving results for #{the_sim_id}. error code: #{resp.status}. #{resp.body}" @@logger.error(msg) raise msg end end |
#get_results ⇒ Object
Poll for results of RNM-US simulation and download when simulation is completed, results.zip file is downloaded to rnm_dir directory
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 |
# File 'lib/urbanopt/rnm/api_client.rb', line 138 def get_results # poll until results are returned done = false conn = Faraday.new(url: @base_api) # prepare results directory prepare_results_dir max_tries = 20 tries = 0 puts "attempting to retrieve results for simulation #{@sim_id}" while !done && (max_tries != tries) begin resp = conn.get("simulations/#{@sim_id}") if resp.status == 200 data = JSON.parse(resp.body) if data['status'] && ['failed', 'completed'].include?(data['status']) # done done = true if data['status'] == 'failed' if data['results'] && data['results']['message'] puts "Simulation Error: #{data['results']['message']}" else puts 'Simulation Error!' end else # edge case, check for results if data['results'].nil? puts 'got a 200 but results are null...trying again' tries += 1 sleep(3) else # get results @results = data['results'] || [] puts 'downloading results' # download results download_results return @results end end else puts 'no status yet...trying again' tries += 1 sleep(3) end else puts("ERROR retrieving: #{resp.body}") tries += 1 if tries == max_tries # now raise the error msg = "Error retrieving simulation #{@sim_id}. error code: #{resp.status}" @@logger.error(msg) raise msg else # try again puts("TRYING AGAIN...#{tries}") sleep(3) end end rescue StandardError => e @@logger.error("Error retrieving simulation #{@sim_id}.") @@logger.error(e.) raise e. end end if !done @@logger.error("Error retrieving simulation #{@sim_id}.") raise 'Simulation not retrieved...maximum tries reached' end end |
#prepare_results_dir ⇒ Object
Prepare results directory Delete existing results
268 269 270 271 272 273 274 275 |
# File 'lib/urbanopt/rnm/api_client.rb', line 268 def prepare_results_dir if !Dir.exist?(File.join(@rnm_dir, 'results')) Dir.mkdir(File.join(@rnm_dir, 'results')) else del_path = File.join(@rnm_dir, 'results', '*') FileUtils.rm_rf Dir.glob(del_path) end end |
#submit_simulation ⇒ Object
Submit simulation to RNM-US API Stores sim_id in the class instance
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/urbanopt/rnm/api_client.rb', line 110 def submit_simulation conn = Faraday.new(url: @base_api) do |f| f.request :multipart end # add post data payload = { name: @name } files = { 'inputs': 'inputs.zip' } files.each do |key, the_file| payload[key] = Faraday::FilePart.new(File.join(@rnm_dir, the_file), the_file) end resp = conn.post('simulations', payload) data = JSON.parse(resp.body) if resp.status != 200 msg = "Error submitting simulation to RNM-US API: status code #{resp.status} #{data['status']} - #{data['message']}" @@logger.error(msg) raise msg end @sim_id = data['simulation_id'] end |
#zip_input_files ⇒ Object
Check and Zip files
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 |
# File 'lib/urbanopt/rnm/api_client.rb', line 64 def zip_input_files # puts "INPUT FILES: #{input_files}" # check that all files exist in folder missing_files = [] @input_files.each do |f| if !File.exist?(File.join(@rnm_dir, f)) missing_files << f end end if !missing_files.empty? puts "RNM DIR: #{@rnm_dir}" raise "Input Files missing in directory: #{missing_files.join(',')}" end # delete zip only if already exists AND input files also exist inputs_zip = File.join(@rnm_dir, 'inputs.zip') if File.exist?(inputs_zip) if File.exist?(File.join(@rnm_dir, @input_files[0])) File.delete(inputs_zip) else # inputs.zip exists but input files do not. keep existing and do nothing else puts 'inputs.zip already exists...keeping existing file' return end end # zip up Zip::File.open(inputs_zip, Zip::File::CREATE) do |zipfile| @input_files.each do |filename| # Two arguments: # - The name of the file as it will appear in the archive # - The original file, including the path to find it zipfile.add(filename, File.join(@rnm_dir, filename)) end end # delete input files now that they are zipped up delete_inputs end |