Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 89 additions & 113 deletions act/discovery/airnow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,29 @@
import xarray as xr


def get_airnow_forecast(token, date, zipcode=None, latlon=None, distance=25):
def get_airnow_forecast(token, date=None, zipcode=None, latlon=None, distance=25):
"""
This tool will get current or historical AQI values and categories for a
This tool will get current AQI forecast values and categories for a
reporting area by either Zip code or Lat/Lon coordinate.
https://docs.airnowapi.org/

Parameters
----------
token : str
The access token for accesing the AirNowAPI web server
The access token for accessing the AirNowAPI web server
date : str
The date of the data to be acquired. Format is YYYY-MM-DD
The date of the forecast to be acquired. Format is YYYY-MM-DD.
Default is None.
zipcode : str
The zipcode of the location for the data request.
If zipcode is not defined then a latlon coordinate must be defined.
latlon : array
The latlon coordinate of the loaction for the data request.
The latlon coordinate of the location for the data request.
If latlon is not defined then a zipcode must be defined.
distance : int
If no reporting are is associated with the specified zipcode or latlon,
return a forcast from a nearby reporting area with this distance (in miles).
Default is 25 miles
If no reporting area is associated with the specified zipcode or latlon,
return a forecast from a nearby reporting area within this distance
(in miles). Default is 25 miles

Returns
-------
Expand All @@ -33,79 +34,70 @@ def get_airnow_forecast(token, date, zipcode=None, latlon=None, distance=25):

Example
-------
act.discovery.get_AirNow_forecast(token='XXXXXX', zipcode='60440', date='2012-05-31')
act.discovery.get_airnow_forecast(token='XXXXXX', zipcode='60440')

"""

# default beginning of the query url
query_url = 'https://www.airnowapi.org/aq/forecast/'
# The previous forecast/zipCode and forecast/latLong services are retired
# September 30, 2026. Both are replaced by forecast/current.
query_url = 'https://www.airnowapi.org/aq/forecast/current/?'

# checking is either a zipcode or latlon coordinate is defined
# if neither is defined then error is raised
# Check whether either a zipcode or latlon coordinate is defined.
if (zipcode is None) and (latlon is None):
raise NameError("Zipcode or latlon must be defined")

if zipcode:
url = query_url + (
'zipCode/?'
+ 'format=text/csv'
+ '&zipCode='
+ str(zipcode)
+ '&date='
+ str(date)
+ '&distance='
+ str(distance)
+ '&API_KEY='
+ str(token)
)

url = query_url + ('format=text/csv' + '&zipCode=' + str(zipcode))
if latlon:
url = query_url + (
'latLong/?'
+ 'format=text/csv'
+ '&latitude='
+ str(latlon[0])
+ '&longitude='
+ str(latlon[1])
+ '&date='
+ str(date)
+ '&distance='
+ str(distance)
+ '&API_KEY='
+ str(token)
'format=text/csv' + '&latitude=' + str(latlon[0]) + '&longitude=' + str(latlon[1])
)

# Retain the date argument for backwards compatibility. The new current
# forecast service can be queried without a date, so only append it when
# explicitly provided.
if date is not None:
url += '&date=' + str(date)

url += '&distance=' + str(distance) + '&API_KEY=' + str(token)

df = pd.read_csv(url)

# converting to xarray dataset object
if 'Aqi' in df.columns:
df = df.rename(columns={'Aqi': 'AQI'})

# Convert to xarray dataset object.
ds = df.to_xarray()

return ds


def get_airnow_obs(token, date=None, zipcode=None, latlon=None, distance=25):
def get_airnow_obs(token, date=None, zipcode=None, latlon=None, state=None, distance=25):
"""
This tool will get current or historical observed AQI values and categories for a
reporting area by either Zip code or Lat/Lon coordinate.
This tool will get current or historical observed AQI values and categories.
Current observations can be requested by Zip code or Lat/Lon coordinate.
Historical daily observations are requested by state.
https://docs.airnowapi.org/

Parameters
----------
token : str
The access token for accesing the AirNowAPI web server
The access token for accessing the AirNowAPI web server
date : str
The date of the data to be acquired. Format is YYYY-MM-DD
Default is None which will pull most recent observations
The date of the data to be acquired. Format is YYYY-MM-DD.
Default is None, which will pull the most recent observations.
zipcode : str
The zipcode of the location for the data request.
The zipcode of the location for a current data request.
If zipcode is not defined then a latlon coordinate must be defined.
latlon : array
The latlon coordinate of the loaction for the data request.
The latlon coordinate of the location for a current data request.
If latlon is not defined then a zipcode must be defined.
state : str
Two-letter state code used for historical daily observations.
Required when date is provided.
distance : int
If no reporting are is associated with the specified zipcode or latlon,
return a forcast from a nearby reporting area with this distance (in miles).
Default is 25 miles
For current observations, search for data within this distance
(in miles). Default is 25 miles.

Returns
-------
Expand All @@ -114,41 +106,37 @@ def get_airnow_obs(token, date=None, zipcode=None, latlon=None, distance=25):

Example
-------
act.discovery.get_AirNow_obs(token='XXXXXX', date='2021-12-01', zipcode='60440')
act.discovery.get_AirNow_obs(token='XXXXXX', latlon=[45,-87])
act.discovery.get_airnow_obs(token='XXXXXX', zipcode='60440')
act.discovery.get_airnow_obs(token='XXXXXX', latlon=[45, -87])
act.discovery.get_airnow_obs(token='XXXXXX', date='2025-05-01', state='IL')

"""

# default beginning of the query url
query_url = 'https://www.airnowapi.org/aq/observation/'

# checking is either a zipcode or latlon coordinate is defined
# if neither is defined then error is raised
if (zipcode is None) and (latlon is None):
raise NameError("Zipcode or latlon must be defined")

# setting the observation type to either current or historical based on the date
if date is None:
obs_type = 'current'
# The previous observation/zipCode/current and
# observation/latLong/current services are retired September 30, 2026.
# Both are replaced by observation/current/ziplatlong.
if (zipcode is None) and (latlon is None):
raise NameError("Zipcode or latlon must be defined")

query_url += 'current/ziplatlong/?'

if zipcode:
url = query_url + (
'zipCode/'
+ str(obs_type)
+ '/?'
+ 'format=text/csv'
'format=text/csv'
+ '&zipCode='
+ str(zipcode)
+ '&distance='
+ str(distance)
+ '&API_KEY='
+ str(token)
)

if latlon:
url = query_url + (
'latLong/'
+ str(obs_type)
+ '/?'
+ 'format=text/csv'
'format=text/csv'
+ '&latitude='
+ str(latlon[0])
+ '&longitude='
Expand All @@ -158,44 +146,33 @@ def get_airnow_obs(token, date=None, zipcode=None, latlon=None, distance=25):
+ '&API_KEY='
+ str(token)
)
else:
obs_type = 'historical'
if zipcode:
url = query_url + (
'zipCode/'
+ str(obs_type)
+ '/?'
+ 'format=text/csv'
+ '&zipCode='
+ str(zipcode)
+ '&date='
+ str(date)
+ 'T00-0000&distance='
+ str(distance)
+ '&API_KEY='
+ str(token)
)
if latlon:
url = query_url + (
'latLong/'
+ str(obs_type)
+ '/?'
+ 'format=text/csv'
+ '&latitude='
+ str(latlon[0])
+ '&longitude='
+ str(latlon[1])
+ '&date='
+ str(date)
+ 'T00-0000&distance='
+ str(distance)
+ '&API_KEY='
+ str(token)
)

else:
# Historical ZIP and Lat/Lon observation services are retired
# September 30, 2026. The replacement returns historical daily
# observations for Reporting Areas within a selected state.
if state is None:
raise NameError("State must be defined for historical observations")

url = (
query_url
+ 'historical/state/?'
+ 'format=text/csv'
+ '&stateCode='
+ str(state)
+ '&startDate='
+ str(date)
+ '&endDate='
+ str(date)
+ '&API_KEY='
+ str(token)
)
df = pd.read_csv(url)

# converting to xarray
if '' in df.columns:
df = df.rename(columns={'Aqi': 'AQI'})

# Convert to xarray.
ds = df.to_xarray()

return ds
Expand All @@ -206,29 +183,29 @@ def get_airnow_bounded_obs(
):
"""
Get AQI values or data concentrations for a specific date and time range and set of
parameters within a geographic area of intrest
parameters within a geographic area of interest.
https://docs.airnowapi.org/

Parameters
----------
token : str
The access token for accesing the AirNowAPI web server
The access token for accessing the AirNowAPI web server
start_date : str
The start date and hour (in UTC) of the data request.
Format is YYYY-MM-DDTHH
end_date : str
The end date and hour (in UTC) of the data request.
Format is YYYY-MM-DDTHH
latlon_bnds : str
Lat/Lon bounding box of the area of intrest.
Lat/Lon bounding box of the area of interest.
Format is 'minX,minY,maxX,maxY'
parameters : str
Parameters to return data for. Options are:
Ozone, PM25, PM10, CO, NO2, SO2
Format is 'PM25,PM10'
mon_type : int
The type of monitor to be returned. Default is 0
0-Permanent, 1-Mobile onlt, 2-Permanent & Mobile
0-Permanent, 1-Mobile only, 2-Permanent & Mobile
data_type : char
The type of data to be returned.
A-AQI, C-Concentrations, B-AQI & Concentrations
Expand All @@ -240,9 +217,9 @@ def get_airnow_bounded_obs(

"""

# The hourly aq/data service is not being retired in the 2026 API update.
verbose = 1
inc_raw_con = 1

url = (
'https://www.airnowapi.org/aq/data/?startDate='
+ str(start_date)
Expand All @@ -264,7 +241,6 @@ def get_airnow_bounded_obs(
+ '&API_KEY='
+ str(token)
)

# Set Column names
names = [
'latitude',
Expand All @@ -285,14 +261,16 @@ def get_airnow_bounded_obs(
# Read data into CSV
df = pd.read_csv(url, names=names)

if 'Aqi' in df.columns:
df = df.rename(columns={'Aqi': 'AQI'})

# Each line is a different time or site or variable so need to parse out
sites = df['site_name'].unique()
times = df['time'].unique()
variables = list(df['parameter'].unique()) + ['AQI', 'category', 'raw_concentration']
latitude = [list(df['latitude'].loc[df['site_name'] == s])[0] for s in sites]
longitude = [list(df['longitude'].loc[df['site_name'] == s])[0] for s in sites]
aqs_id = [list(df['aqs_id'].loc[df['site_name'] == s])[0] for s in sites]

# Set up the dataset ahead of time
ds = xr.Dataset(
data_vars={
Expand All @@ -303,10 +281,9 @@ def get_airnow_bounded_obs(
coords={'time': (['time'], times), 'sites': (['sites'], sites)},
)

# Set up emtpy data with nans
# Set up empty data with nans
data = np.empty((len(variables), len(times), len(sites)))
data[:] = np.nan

# For each variable, pull out the data from specific sites and times
for v in range(len(variables)):
for t in range(len(times)):
Expand All @@ -325,7 +302,6 @@ def get_airnow_bounded_obs(
if len(result['concentration']) > 0:
data[v, t, s] = list(result['concentration'])[0]
atts = {'units': list(result['unit'])[0]}

# Add variables to the dataset
ds[variables[v]] = xr.DataArray(data=data[v, :, :], dims=['time', 'sites'], attrs=atts)

Expand Down
Loading
Loading