Skip to content

Commit

Permalink
fix: Fix API and data conversion problems in get air pollution function
Browse files Browse the repository at this point in the history
  • Loading branch information
danfke committed Jan 21, 2022
1 parent dba9d3d commit 2ad4cc3
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 67 deletions.
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

128 changes: 62 additions & 66 deletions src/airpyllution/airpyllution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
from airpyllution.utils import *
import plotly.express as px
import altair as alt
alt.renderers.enable('mimetype')

alt.renderers.enable("mimetype")

# import constants
OPEN_WEATHER_MAP_URL = 'http://api.openweathermap.org/data/2.5/air_pollution'
OPEN_WEATHER_MAP_URL = "http://api.openweathermap.org/data/2.5/air_pollution"


def get_pollution_history(start_date, end_date, lat, lon, api_key):
"""Returns a dataframe of pollution history for a location between a specified date range
Given a specified date range, the function makes an API request to the OpenWeather Air Pollution API and fetches
historic pollution data for a given location.
Expand Down Expand Up @@ -50,7 +52,7 @@ def get_pollution_history(start_date, end_date, lat, lon, api_key):
0 1606482000 270.367 5.867 43.184 4.783 14.544 13.448 15.524 0.289
1 1606478400 280.38 8.605 42.155 2.459 14.901 15.103 17.249 0.162
2 1606474800 293.732 13.523 41.47 1.173 15.14 17.727 19.929 0.072
"""
"""

# api_key = app.config["OPEN_WEATHER_MAP_API_KEY"]

Expand All @@ -59,37 +61,36 @@ def get_pollution_history(start_date, end_date, lat, lon, api_key):

if not isinstance(lon, float):
return "Longitude input should be a float"

if not isinstance(start_date, int):
return "start_date input should be an int"

if not isinstance(end_date, int):
return "end_date input should be an int"

url = OPEN_WEATHER_MAP_URL + '/history'
url = OPEN_WEATHER_MAP_URL + "/history"
params = {
'lat': lat,
'lon': lon,
'start': start_date,
'end': end_date,
'appid': api_key
"lat": lat,
"lon": lon,
"start": start_date,
"end": end_date,
"appid": api_key,
}


response = requests.get(url=url, params=params)
response_obj = response.json()

try:
try:
data = convert_data_to_pandas(response_obj)

return data

except:
if 'cod' in response_obj:
return response_obj['message']
except:
if "cod" in response_obj:
return response_obj["message"]

return "An error occurred requesting data from the API"


def get_air_pollution(lat, lon, api_key, fig_title=""):
"""Returns a map depicting varying pollution levels for a specified location.
Expand Down Expand Up @@ -122,7 +123,7 @@ def get_air_pollution(lat, lon, api_key, fig_title=""):

if not isinstance(lon, (float, int)):
return "Longitude input should be a float or an integer"

if not isinstance(api_key, str):
return "API Key should be a string"

Expand All @@ -132,6 +133,9 @@ def get_air_pollution(lat, lon, api_key, fig_title=""):
if lon < -180.0 or lon > 180.0:
return "Enter valid longitude values (Range should be -180<Longitude<180)"

if not isinstance(fig_title, str):
return "Figure title should be a string"

url = OPEN_WEATHER_MAP_URL
params = {
"lat": lat,
Expand All @@ -144,6 +148,8 @@ def get_air_pollution(lat, lon, api_key, fig_title=""):
response_obj = response.json()
data = convert_data_to_pandas(response_obj)
except:
response = requests.get(url=url, params=params)
response_obj = response.json()
if "cod" in response_obj:
return response_obj["message"]
return "An error occurred requesting data from API"
Expand Down Expand Up @@ -179,29 +185,20 @@ def get_air_pollution(lat, lon, api_key, fig_title=""):
"variable": "Pollutant",
"value": "Conc. (µg/m^3)",
},
title = fig_title
title=fig_title,
)

fig.update_layout(
legend={
'yanchor':"middle",
'y':0.72,
'xanchor':"right",
'x':1.2
},
title={
'y':0.85,
'x':0.47,
'xanchor': 'center',
'yanchor': 'top'
}
legend={"yanchor": "middle", "y": 0.72, "xanchor": "right", "x": 1.2},
title={"y": 0.85, "x": 0.47, "xanchor": "center", "yanchor": "top"},
)

return fig


def get_pollution_forecast(lat, lon, api_key):
"""Returns a time series plot showing predicted pollutant levels for the next 5 days.
Performs an API request to OpenWeather Air Pollution API,
retrieves weather forecast for the next 5 days, and
creates a time series graph of the pollutants with their concentration levels.
Expand All @@ -218,9 +215,9 @@ def get_pollution_forecast(lat, lon, api_key):
Returns
-------
altair.Chart
altair chart object with the x axis as time/UNIX timestamp and
altair chart object with the x axis as time/UNIX timestamp and
y axis as pollutant concentration.
Examples
--------
>>> get_pollution_forecast(50, 50, "APIKEY_example")
Expand All @@ -230,7 +227,7 @@ def get_pollution_forecast(lat, lon, api_key):

if not isinstance(lon, float):
return "Longitude input should be a float"

if not isinstance(api_key, str):
return "API Key should be a string"

Expand All @@ -241,44 +238,43 @@ def get_pollution_forecast(lat, lon, api_key):
return "Enter valid longitude values (Range should be -180<Longitude<180)"

url = OPEN_WEATHER_MAP_URL + "/forecast"
params = {
'lat': lat,
'lon': lon,
'appid': api_key
}
params = {"lat": lat, "lon": lon, "appid": api_key}

try:
response = requests.get(url=url, params=params)
response_obj = response.json()
data = convert_data_to_pandas(response_obj)
except:
if 'cod' in response_obj:
return response_obj['message']
if "cod" in response_obj:
return response_obj["message"]
return "An error occurred requesting data from API"

if len(data) >= 1:
try:
data = data.melt(id_vars=['dt'], value_vars=['co', 'no', 'no2', 'o3', 'so2',
'pm2_5', 'pm10', 'nh3'],
var_name='Pollutants', value_name='Concentration')
data["dt"]= pd.to_datetime(data['dt'])
chart = alt.Chart(data).mark_line().encode(
x = alt.X("dt", title="date"),
y = alt.Y("Concentration", title="Concentration"),
color = alt.Color("Pollutants")).properties(
width=180,
height=180
).facet(
facet='Pollutants:N',
columns=4
).resolve_axis(
x='independent',
y='independent'
).resolve_scale(
x='independent',
y='independent'
).properties(title = "Pollutant concentration for the next 5 days",
).configure_title(fontSize=24, anchor='middle')
data = data.melt(
id_vars=["dt"],
value_vars=["co", "no", "no2", "o3", "so2", "pm2_5", "pm10", "nh3"],
var_name="Pollutants",
value_name="Concentration",
)
data["dt"] = pd.to_datetime(data["dt"])
chart = (
alt.Chart(data)
.mark_line()
.encode(
x=alt.X("dt", title="date"),
y=alt.Y("Concentration", title="Concentration"),
color=alt.Color("Pollutants"),
)
.properties(width=180, height=180)
.facet(facet="Pollutants:N", columns=4)
.resolve_axis(x="independent", y="independent")
.resolve_scale(x="independent", y="independent")
.properties(
title="Pollutant concentration for the next 5 days",
)
.configure_title(fontSize=24, anchor="middle")
)
except:
return "An error occured in plotting"
return chart
Expand Down

0 comments on commit 2ad4cc3

Please sign in to comment.