Class: URBANopt::REopt::REoptGHPAPI

Inherits:
Object
  • Object
show all
Defined in:
lib/urbanopt/reopt/reopt_ghp_api.rb

Instance Method Summary collapse

Constructor Details

#initialize(reopt_input_file, api_key = nil, reopt_output_file) ⇒ REoptGHPAPI

Returns a new instance of REoptGHPAPI.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/urbanopt/reopt/reopt_ghp_api.rb', line 19

def initialize(reopt_input_file, api_key = nil, reopt_output_file)

    # Store developer key
    if [nil, '', '<insert your key here>'].include? api_key
        if [nil, '', '<insert your key here>'].include? DEVELOPER_API_KEY
            # Check if we need an API key based on the URL that will be used
            url_config_test = URLConfig.new
            if url_config_test.requires_api_key?
                raise 'A developer.nlr.gov API key is required. Please see https://developer.nlr.gov/signup/ then update the file developer_api_key.rb'
            end
        else
            api_key = DEVELOPER_API_KEY
        end
    end

    # Initialize URL configuration
    @url_config = URLConfig.new(api_key: api_key)

    # Store for backward compatibility
    @root_url = @url_config.base_url
    @api_key = api_key
    @reopt_input_file = reopt_input_file
    @reopt_output_file = reopt_output_file
    # initialize @@logger
    @@logger ||= URBANopt::REopt.reopt_logger
    @@logger.level = Logger::INFO
end

Instance Method Details

#get_api_results(run_id = nil) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/urbanopt/reopt/reopt_ghp_api.rb', line 48

def get_api_results(run_id=nil)

    reopt_input_file = @reopt_input_file
    api_key = @api_key
    root_url = @root_url
    reopt_output_file = @reopt_output_file

    if run_id.nil?
        run_id = get_run_uuid(reopt_input_file, api_key, reopt_output_file)
    end
    if !run_id.nil?
        results_url = @url_config.url_for('job', run_uuid: run_id)
        puts "This is results URL #{results_url}"
        results = reopt_request(results_url)

        File.open(reopt_output_file, 'w') do |f|
            f.write(JSON.pretty_generate(results))
            @@logger.info("Saved results to #{reopt_output_file}")
        end
    else
        results = nil
        @@logger.error("Unable to get results: no UUID returned.")
    end
    results
end

#get_run_uuid(reopt_input_file, api_key, root_url) ⇒ Object



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
# File 'lib/urbanopt/reopt/reopt_ghp_api.rb', line 74

def get_run_uuid(reopt_input_file, api_key, root_url)

    reopt_input_file = @reopt_input_file
    api_key = @api_key
    root_url = @root_url
    post_url = @url_config.url_for('job')
    puts "This is URL: #{post_url}"
    @@logger.info("Connecting to #{post_url}")

    # Parse the URL and prepare the HTTP request
    uri = URI.parse(post_url)
    request = Net::HTTP::Post.new(uri)
    request.content_type = 'application/json'

    # Add the JSON payload (assuming 'post' is the body data)
    request.body = reopt_input_file.to_json

    # Send the HTTP request
    response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
        http.request(request)
    end

    run_id = nil

    if !response.is_a?(Net::HTTPSuccess)
        @@logger.error("Status code #{response.code}. #{response.body}")
        @@logger.error("Status code #{response.code}")
    else
        @@logger.info("Response OK from #{post_url}.")
        run_id_dict = JSON.parse(response.body)

        begin
            run_id = run_id_dict['run_uuid']
        rescue KeyError
            msg = "Response from #{post_url} did not contain run_uuid."
            @@logger.error(msg)
        end
    end
    # Return run_id
    run_id
end

#reopt_request(results_url, poll_interval = 5, max_timeout = 600) ⇒ Object



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
# File 'lib/urbanopt/reopt/reopt_ghp_api.rb', line 116

def reopt_request(results_url, poll_interval = 5, max_timeout = 600)

    key_error_count = 0
    key_error_threshold = 3
    status = "Optimizing..."
    @@logger.info("Polling #{results_url} for results with interval of #{poll_interval}...")
    resp_dict = {}
    start_time = Time.now

    loop do
        uri = URI.parse(results_url)
        response = Net::HTTP.get_response(uri)
        resp_dict = JSON.parse(response.body)

        begin
          status = resp_dict['status']
        rescue KeyError
          key_error_count += 1
          @@logger.info("KeyError count: #{key_error_count}")
          if key_error_count > key_error_threshold
            @@logger.info("Breaking polling loop due to KeyError count threshold of #{key_error_threshold} exceeded.")
            break
          end
        end

        if status != "Optimizing..."
            break
        end

        if Time.now - start_time > max_timeout
            @@logger.info("Breaking polling loop due to max timeout of #{max_timeout} seconds exceeded.")
            break
        end

        sleep(poll_interval)

    end
    resp_dict
end