Skip to content

Commit

Permalink
more pep8 fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
samgdotson committed Mar 14, 2024
1 parent 1071031 commit a8ba80e
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 65 deletions.
7 changes: 3 additions & 4 deletions nrelpy/atb.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from urllib.error import HTTPError
import pandas as pd
import numpy as np
from nrelpy.utils.data_io import check_stored_data, save_local
import warnings

Expand Down Expand Up @@ -48,7 +47,7 @@ def as_dataframe(year, database, verbose=False, **kwargs):
print(f"Dropping column {drop_col}")
try:
df.drop(columns=drop_col, inplace=True)
except KeyError as err:
except KeyError:
if verbose:
print(f'No column {drop_col}.')
else:
Expand Down Expand Up @@ -136,7 +135,7 @@ def get_index_values(self, key):
try:
key_list = self.dataframe.index.get_level_values(
key).unique().to_list()
except KeyError as err:
except KeyError:
msg = f"Key not found. Try one of {print(self.index_names)}"
raise KeyError(msg)

Expand All @@ -159,7 +158,7 @@ def acronyms(self):
f"https://atb.nrel.gov/electricity/{self.year}/acronyms")[0]
acro_df.columns = ['acronym', 'long name']
acro_df.set_index("acronym", inplace=True, drop=True)
except HTTPError as e:
except HTTPError:
msg = f"Year {self.year} not in [2021,2022,2023]."
warnings.warn(msg, RuntimeWarning)

Expand Down
49 changes: 24 additions & 25 deletions nrelpy/tests/test_atb.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@
bad_detail = 'PlanetExpress'
bad_metric = 'Kajiggers'


def test_as_dataframe_electricity_good_year():
database = 'electricity'

df = as_dataframe(good_year, database)
as_dataframe(good_year, database)

return

Expand All @@ -38,7 +39,7 @@ def test_as_dataframe_electricity_nonexistent():
database = 'electricity'

with pytest.raises(HTTPError) as e:
df = as_dataframe(nonexistent_year, database)
as_dataframe(nonexistent_year, database)

assert (e.type == HTTPError)

Expand All @@ -48,7 +49,7 @@ def test_as_dataframe_electricity_nonexistent():
def test_as_dataframe_transportation_good_year():
database = 'transportation'

df = as_dataframe(good_year, database)
as_dataframe(good_year, database)

return

Expand All @@ -57,7 +58,7 @@ def test_as_dataframe_transportation_nonexistent():
database = 'transportation'

with pytest.raises(HTTPError) as e:
df = as_dataframe(nonexistent_year, database)
as_dataframe(nonexistent_year, database)

assert (e.type == HTTPError)

Expand All @@ -68,7 +69,7 @@ def test_as_dataframe_transportation_bad_year():
database = 'transportation'

with pytest.raises(HTTPError) as e:
df = as_dataframe(bad_year, database)
as_dataframe(bad_year, database)

assert (e.type == HTTPError)

Expand All @@ -79,7 +80,7 @@ def test_as_dataframe_bad_database():
database = 'heating'

with pytest.raises(KeyError) as e:
df = as_dataframe(bad_year, database)
as_dataframe(bad_year, database)

assert (e.type == KeyError)

Expand All @@ -89,46 +90,44 @@ def test_as_dataframe_bad_database():
def test_ATB_init():
atb_class = ATBe(year=good_year)
assert atb_class.year == good_year

with pytest.raises(HTTPError) as e:
atb_class = ATBe(bad_year)

with pytest.raises(HTTPError) as e:
atb_class = ATBe(nonexistent_year)

return


def test_ATB_acronyms():

atb_class = ATBe(2023)
assert isinstance(atb_class.acronyms, pd.DataFrame)
with pytest.warns(RuntimeWarning) as w:

with pytest.warns(RuntimeWarning):
atb_class = ATBe(good_year)
acros_df = atb_class.acronyms
atb_class.acronyms

return


def test_ATB_access():
atb_class = ATBe(good_year)

subset = atb_class(technology='Nuclear')
assert subset.shape == (6534,2)
assert subset.shape == (6534, 2)
return



def test_ATB_value_access():
atbe2020 = ATBe(good_year)
mask = (
(atbe2020.raw_dataframe['technology']=='Nuclear')&
(atbe2020.raw_dataframe['core_metric_parameter']=='LCOE')&
(atbe2020.raw_dataframe['core_metric_case']=='Market')&
(atbe2020.raw_dataframe['core_metric_variable']==2020)&
(atbe2020.raw_dataframe['crpyears']==20)
)
(atbe2020.raw_dataframe['technology'] == 'Nuclear') &
(atbe2020.raw_dataframe['core_metric_parameter'] == 'LCOE') &
(atbe2020.raw_dataframe['core_metric_case'] == 'Market') &
(atbe2020.raw_dataframe['core_metric_variable'] == 2020) &
(atbe2020.raw_dataframe['crpyears'] == 20)
)
value = atbe2020.raw_dataframe[mask]['value'].values[0]
assert np.isclose(value, 88.22242)



21 changes: 10 additions & 11 deletions nrelpy/tests/test_data_io.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
from nrelpy.utils.data_io import save_local, check_stored_data, DATA_PATH
from pathlib import Path
import sys
from nrelpy.utils.data_io import save_local, check_stored_data, DATA_PATH
import os
import glob
import pandas as pd

# set up test data
data = {'tech': ['nuclear', 'solar', 'wind', 'naturalgas'],
'variable_cost': [20, 0, 0, 180], # $/GWh
'fixed_cost': [92, 4, 11, 21],
'capital_cost': [5.9, 0.8, 1.4, 1.0],
'capacity_GW': [12, 3, 7, 5],
'capacity_factor': [0.93, 0.17, 0.33, 0.45],
'resentment': [100, 20, 50, 70]
}
'variable_cost': [20, 0, 0, 180], # $/GWh
'fixed_cost': [92, 4, 11, 21],
'capital_cost': [5.9, 0.8, 1.4, 1.0],
'capacity_GW': [12, 3, 7, 5],
'capacity_factor': [0.93, 0.17, 0.33, 0.45],
'resentment': [100, 20, 50, 70]
}
tech_df = pd.DataFrame(data)

db = 'electricity'
Expand All @@ -37,6 +35,7 @@ def test_save_local_case1():
assert len(files) == 1
return


def test_save_local_case2():
"""
This tests a standard use case of `save_local`
Expand Down Expand Up @@ -100,4 +99,4 @@ def test_check_stored_data_case3():
file_name_no_yr = str(DATA_PATH / f'ATBe.csv')
os.remove(file_name_no_yr)
assert df.equals(tech_df)
return
return
8 changes: 4 additions & 4 deletions nrelpy/tests/test_re_potential.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def test_as_dataframe_standard():

df = as_dataframe()

assert type(df) == pd.DataFrame
assert isinstance(df, pd.DataFrame)

return

Expand All @@ -24,19 +24,19 @@ def test_as_dataframe_bad_url():

bad_url = "https://www.nrel.gov/gis/assets/docs/us-re-technical-potential"
with pytest.raises(HTTPError) as e:
df = as_dataframe(url=bad_url)
as_dataframe(url=bad_url)

return


@pytest.mark.filterwarnings("ignore")
def test_as_dataframe_verbose():
"""
This tests the verbosity setting of
This tests the verbosity setting of
"""

df = as_dataframe(verbose=True)

assert type(df) == pd.DataFrame
assert isinstance(df, pd.DataFrame)

return
42 changes: 21 additions & 21 deletions nrelpy/utils/user_data.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from pathlib import Path
import warnings


class User():
"""
Class that stores user data for NRELPY.
Expand All @@ -16,15 +16,16 @@ class User():
mailing_list : boolean or str
api_key : str
"""

def __init__(self,
first_name=None,
last_name=None,
reason=None,
email=None,
affiliation=None,
mailing_list=False,
api_key=None,
) -> None:
first_name=None,
last_name=None,
reason=None,
email=None,
affiliation=None,
mailing_list=False,
api_key=None,
) -> None:

self.first_name = first_name
self.last_name = last_name
Expand All @@ -34,7 +35,6 @@ def __init__(self,
self.mailing_list = mailing_list
self.api_key = api_key


def _replace_space(self, string_value):
string_value = string_value.replace(" ", "+")
return string_value
Expand All @@ -44,22 +44,22 @@ def full_name(self):
name = "+".join([self.first_name, self.last_name])
name = self._replace_space(name)
return name

@property
def personal_data(self):
data = {'api_key':self.api_key,
'name':self._replace_space(str(self.full_name)),
'reason':self._replace_space(str(self.reason)),
'affiliation':self._replace_space(str(self.affiliation)),
'email':self.email,
'mailing_list':str(self.mailing_list).lower()}
data = {'api_key': self.api_key,
'name': self._replace_space(str(self.full_name)),
'reason': self._replace_space(str(self.reason)),
'affiliation': self._replace_space(str(self.affiliation)),
'email': self.email,
'mailing_list': str(self.mailing_list).lower()}
if (not all(list(data.values())) or ('None' in data.values())):
for k, v in data.items():
if (not v) or (v == 'None'):
msg = f"Missing field: {k} is empty ({v})."
print(msg)
warnings.warn(
"Some fields are missing. API queries may be rejected.",
UserWarning
)
return data
"Some fields are missing. API queries may be rejected.",
UserWarning
)
return data

0 comments on commit a8ba80e

Please sign in to comment.