<jupyter_start><jupyter_text>Run a REopt API evaluation  Initialization<jupyter_code>import pandas as pd
import numpy as np
import json
import requests
import copy
import os
from src.post_and_poll import get_api_results
API_KEY = 'DEMO_KEY'  # REPLACE WITH YOUR API KEY
# following is not necessary but silences warnings:
# InsecureRequestWarning: Unverified HTTPS request is being made to host 'developer.nrel.gov'. Adding certificate verification is strongly advised.
import urllib3
urllib3.disable_warnings()
"""
Here are some convenience definitions for using the Multi-scenario capabilities
"""
##############################################################################################################
inputs_path = os.path.join(".", 'inputs')
outputs_path = os.path.join(".", 'outputs')
loads_path = os.path.join(".", 'load_profiles')
rates_path = os.path.join(".", 'electric_rates')
##############################################################################################################<jupyter_output><empty_output><jupyter_text>Load a previously saved API response .json file instead of running REopt<jupyter_code>response_json = 'results'
with open(os.path.join(outputs_path, response_json + '.json'), 'rb') as handle:
    api_response = json.load(handle)<jupyter_output><empty_output><jupyter_text>Scenario Inputs (POST), if wanting to do a new API call<jupyter_code>post_1 = {"Scenario": {
    "Site": {
        "longitude": -118.116,
        "latitude": 34.579,
        "roof_squarefeet": 5000.0,
        "land_acres": 1.0,
    "PV": {
        "macrs_bonus_pct": 0.4,
        "installed_cost_us_dollars_per_kw": 2000.0,
        "tilt": 34.579,
        "degradation_pct": 0.005,
        "macrs_option_years": 5,
        "federal_itc_pct": 0.3,
        "module_type": 0,
        "array_type": 1,
        "om_cost_us_dollars_per_kw": 16.0,
        "macrs_itc_reduction": 0.5,
        "azimuth": 180.0,
        "federal_rebate_us_dollars_per_kw": 350.0,
        "dc_ac_ratio": 1.1
    },
    "LoadProfile": {
        "doe_reference_name": "RetailStore",
        "annual_kwh": 10000000.0,
        "city": "LosAngeles"
    },
    "Storage": {
        "total_rebate_per_kw": 100.0,
        "macrs_option_years": 5,
        "can_grid_charge": True,
        "macrs_bonus_pct": 0.4,
        "macrs_itc_reduction": 0.5,
        "total_itc_pct": 0,
        "installed_cost_us_dollars_per_kw": 1000.0,
        "installed_cost_us_dollars_per_kwh": 500.0,
        "replace_cost_us_dollars_per_kw": 460.0,
        "replace_cost_us_dollars_per_kwh": 230.0
    },
    "ElectricTariff": {
        "urdb_label": "5ed6c1a15457a3367add15ae"
    },
    "Financial": {
        "escalation_pct": 0.026,
        "offtaker_discount_pct": 0.081,
        "owner_discount_pct": 0.081,
        "analysis_years": 20,
        "offtaker_tax_pct": 0.4,
        "owner_tax_pct": 0.4,
        "om_cost_escalation_pct": 0.025
    }
}}}<jupyter_output><empty_output><jupyter_text>Load in a custom electric rate generated from https://reopt.nrel.gov/tool/custom_tariffs<jupyter_code>load_electric_rate = "PGE_E20"
with open(os.path.join(rates_path, load_electric_rate + ".json"), 'r') as fp:
    rate_1 = json.load(fp)
post_1["Scenario"]["Site"]["ElectricTariff"]["urdb_response"] = rate_1<jupyter_output><empty_output><jupyter_text>Save the POST to a .json file for sharing or future loading in<jupyter_code># Convert python dictionary post into json and save to a .json file
post_save = post_1
post_name = "post_1"
with open(os.path.join(inputs_path, post_name + ".json"), 'w') as fp:
    json.dump(post_save, fp)<jupyter_output><empty_output><jupyter_text>Or load in a saved .json file for the inputs/POST<jupyter_code># Load a json into a python dictionary
load_post = "post_1"
with open(os.path.join(inputs_path, load_post + ".json"), 'r') as fp:
    post_1 = json.load(fp)<jupyter_output><empty_output><jupyter_text>POST and poll (periodic GET request) the API to GET a new result, if not loading in a previous response. This may take a while!  Note, the `api_url` in the `get_api_results` function below calls the **production server** hosted API (master/main branch/version, publicly accessible) For calling a locally-hosted (localhost) API, see:- https://github.com/NREL/REopt_Lite_API/wiki/localhost-URLs-for-calling-locally-hosted-API For calling an API hosted on an NREL-internal server (only NREL users can access this), see:- https://github.nrel.gov/REopt/API_scripts/wiki/API-URLs-for-NREL-internal-servers `get_api_results` POST's your inputs to the API `job` endpoint, which provides a `run_uuid` if the input is valid, and then polls the `results` endpoint using the `run_uuid` until the results come back with a status other than `Optimizing...`.`get_api_results` also saves the results (full API response, including inputs) to the `results_file`.A log file is also created in the current working directory.<jupyter_code>outputs_file_name = "results_file"
root_url = "https://developer.nrel.gov/api/reopt/v1"
api_response = get_api_results(post=post_1, 
                               API_KEY=API_KEY, 
                               api_url=root_url, 
                               results_file=os.path.join(outputs_path, outputs_file_name + ".json"), 
                               run_id=None)<jupyter_output>main         INFO     Response OK from https://developer.nrel.gov/api/reopt/v1/job/?api_key=DEMO_KEY.
main         INFO     Polling https://developer.nrel.gov/api/reopt/v1/job/61f4822c-e213-4751-bf08-3f9faae184fb/results/?api_key=DEMO_KEY for results with interval of 5s...
main         INFO     Saved results to ./outputs/results_file.json<jupyter_text>If you get disconnected from the polling function but you think it ran, copy the run_uuid from the log above to manually GET the results:<jupyter_code>run_uuid = api_response["outputs"]["Scenario"]["run_uuid"]
results_url = root_url + '/job/' + run_uuid + '/results/?api_key=' + API_KEY
resp = requests.get(url=results_url, verify=False)
api_response = json.loads(resp.text)<jupyter_output><empty_output><jupyter_text>Get summary of results<jupyter_code>print("NPV ($) = ", api_response["outputs"]["Scenario"]["Site"]["Financial"]["npv_us_dollars"])
print("Capital Cost, Net ($) = ", api_response["outputs"]["Scenario"]["Site"]["Financial"]["net_capital_costs"])
tech_list = ["PV", "Wind", "Storage", "CHP", "Generator", "HotTES", "ColdTES", "AbsorptionChiller", "GHP", "NewBoiler", "SteamTurbine"]
for tech in tech_list:
    if tech in post_1["Scenario"]["Site"].keys():
        if tech == "GHP":
            print("GHX Number of Boreholes = ", api_response["outputs"]["Scenario"]["Site"][tech]["ghpghx_chosen_outputs"].get("number_of_boreholes"))
            print("GHP Heat Pump Capacity (ton) = ", api_response["outputs"]["Scenario"]["Site"][tech]["ghpghx_chosen_outputs"].get("peak_combined_heatpump_thermal_ton"))
        # PV and Storage are considered if the POST does not explicitly make max_[size] == 0
        for size_name_value in [(key, val) for key, val in api_response["outputs"]["Scenario"]["Site"][tech].items() if "size" in key]:
                print(tech + " " + size_name_value[0], " = ", size_name_value[1])
    elif tech in ["PV", "Storage"]:
        for size_name_value in [(key, val) for key, val in api_response["outputs"]["Scenario"]["Site"][tech].items() if "size" in key]:
                print(tech + " " + size_name_value[0], " = ", size_name_value[1])<jupyter_output>NPV ($) =  550779.0
Capital Cost, Net ($) =  294265.01
PV size_kw  =  216.6667
Storage size_kw  =  96.4996266256644
Storage size_kwh  =  273.818171101346<jupyter_text>Here are some results keys examples:<jupyter_code>api_response.keys()
api_response["outputs"]["Scenario"]["status"]
for k in api_response["outputs"]["Scenario"]["Site"].keys():
    print(k)<jupyter_output>year_one_emissions_lb_C02
year_one_emissions_bau_lb_C02
outdoor_air_temp_degF
renewable_electricity_energy_pct
Financial
LoadProfile
LoadProfileBoilerFuel
LoadProfileChillerThermal
ElectricTariff
FuelTariff
Storage
Generator
Wind
CHP
Boiler
ElectricChiller
AbsorptionChiller
HotTES
ColdTES
NewBoiler
SteamTurbine
GHP
PV<jupyter_text>Save API response into a JSON file for later use<jupyter_code>response_save = api_response
file_name_to_save = "response_1"
with open(os.path.join(outputs_path, file_name_to_save + ".json"), 'w') as fp:
    json.dump(response_save, fp)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14962682146665088, 'fraction_numerical': 0.026774078900604195, 'mean_word_length': 4.457013574660634, 'pattern_counts': {'":': 46, '<': 42, '<?xml version=': 0, '>': 42, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '217189', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3039, 'n_tokens_neox': 2864, 'n_words': 638, 'path': 'single_scenario_example.ipynb', 'repo_name': 'NREL/REopt-API-Analysis', 'size': '8441'}