API Reference¶
This section gives the documentation of all vayuayan classes and functions.
Core Classes¶
CPCBHistorical¶
- class vayuayan.CPCBHistorical[source]
Bases:
objectClient that gets historical Air Quality Index (AQI) data from CPCB.
- iter_stations(state: str = '', city: str = '') Iterator[Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]][source]
Yield (state, city, station) directory entries, with optional filters.
- Parameters:
state – State name or code. Empty means all states.
city – City name or code. Empty means all cities.
- get_complete_list() Dict[str, Any][source]
Get the complete list of stations and cities in India.
- Returns:
Dictionary with the station data and the city data.
- Raises:
requests.RequestException – If the HTTP request fails.
json.JSONDecodeError – If the response is not valid JSON.
- get_state_list() List[str][source]
Get the list of states that have AQI data.
- Returns:
Sorted list of state names.
- get_city_list(state: str) List[str][source]
Get the list of cities in a state that have AQI data.
- Parameters:
state – State name.
- Returns:
Sorted list of city names in the state.
- get_station_list(city: str) List[Dict][source]
Get the list of stations in a city that have AQI data.
- Parameters:
city – City name.
- Returns:
Sorted list of station dictionaries.
- get_file_path(station_id: str, station_name: str, state: str, city: str, year: str, frequency: str, data_type: str) List[Dict[str, Any]][source]
Get the data file paths for the query parameters.
- Parameters:
station_id – Station ID.
station_name – Station name.
state – State name.
city – City name.
year – Year for data.
frequency – Data frequency (‘hourly’ or ‘daily’).
data_type – Type of data (‘cityLevel’, ‘stationLevel’ or ‘raw’).
- Returns:
List of file entries, each with a file path.
- Raises:
requests.RequestException – If the HTTP request fails.
- download_raw_aqi_data_station_level(station_id: str, year: str, save_location: str, frequency: str = '15_minute', station_name: str = '', city: str = '', state: str = '') DataFrame[source]
Download raw CPCB station data, for example 15-minute observations.
- Parameters:
station_id – Station ID.
year – Year for data.
save_location – Path to save the CSV. If empty, no file is saved.
frequency – Raw data interval. CPCB supports values such as “15_minute”, “1H”, and “1D” for raw station files.
station_name – Optional station name. The client then does not look it up.
city – Optional city name. The client then examines only this city.
state – Optional state name, for cities with the same name.
- Returns:
DataFrame with the raw station observations.
- download_hourly_aqi_data_city_level(city: str, year: str, save_location: str, month: str | None = None, state: str = '') DataFrame[source]
Download hourly AQI data for a city.
- Parameters:
city – City name.
year – Year for data.
save_location – Path to save the combined CSV. If empty, no file is saved.
month – Optional month name, for example “January”. If None, the client combines all the monthly workbooks for the year.
state – Optional state name, for cities with the same name.
- Returns:
DataFrame with hourly AQI data.
- download_hourly_aqi_data_station_level(station_id: str, year: str, save_location: str, month: str | None = None, station_name: str = '', city: str = '', state: str = '') DataFrame[source]
Download hourly AQI data for a station.
- Parameters:
station_id – Station ID.
year – Year for data.
save_location – Path to save the combined CSV. If empty, no file is saved.
month – Optional month name, for example “January”. If None, the client combines all the monthly workbooks for the year.
station_name – Optional station name. The client then does not look it up.
city – Optional city name. The client then examines only this city.
state – Optional state name, for cities with the same name.
- Returns:
DataFrame with hourly AQI data.
- download_past_year_aqi_data_city_level(city: str, year: str, save_location: str) DataFrame[source]
Download past AQI data for a specific city.
- Parameters:
city – City name.
year – Year for data.
save_location – Path to save the downloaded data.
- Returns:
DataFrame preview of the downloaded data.
- Raises:
Exception – If the client cannot find or download the data.
- download_past_year_aqi_data_station_level(station_id: str, year: str, save_location: str) DataFrame[source]
Download past AQI data for a specific station.
- Parameters:
station_id – Station ID.
year – Year for data.
save_location – Path to save the downloaded data.
- Returns:
DataFrame preview of the downloaded data.
- Raises:
Exception – If the client cannot find the station or the data.
CPCBLive¶
- class vayuayan.CPCBLive[source]
Bases:
objectClient that gets live air quality data from CPCB.
- get_system_location() Tuple[float, float][source]
Get the location of this system from its IP address.
- Returns:
Tuple of (latitude, longitude).
- Raises:
Exception – If the client cannot find the location.
- get_nearest_station(coords: Tuple[float, float] | None = None) Tuple[str, str][source]
Get the nearest air quality monitoring station.
- Parameters:
coords – Optional tuple of (latitude, longitude). If None, the client finds the location from the IP address.
- Returns:
Tuple of (station_id, station_name).
- Raises:
Exception – If there is no station, or the coordinates are not valid.
- get_all_india() List[Dict[str, Any]][source]
Get all air quality monitoring stations in India.
- Returns:
List of station dictionaries.
- get_live_aqi_data_for_station(station_id: str, date_time: str) Dict[str, Any][source]
Get live air quality data for a specific station.
- Parameters:
station_id – Station ID.
date_time – Date and time in ‘YYYY-MM-DDTHH:00:00Z’ format.
- Returns:
Live air quality data dictionary.
- Raises:
ValueError – If a parameter is not valid.
Exception – If the request fails.
- get_live_aqi_data(station_id: str | None = None, coords: Tuple[float, float] | None = None, date: str | None = None, hour: int | None = None) Dict[str, Any][source]
Get live AQI data for a station or a location, a date, and an hour.
- Parameters:
station_id – Optional station ID. If None, the client uses the nearest station.
coords – Optional (latitude, longitude) tuple.
date – Optional date in ‘YYYY-MM-DD’ format. The default is today.
hour – Optional hour (0-23). The default is the current hour.
- Returns:
Processed live AQI data dictionary.
- Raises:
ValueError – If the hour is not valid.
Exception – If the client cannot get the data.
PM25Client¶
- class vayuayan.PM25Client(version: str = 'V6', cache_dir: str = 'pm25_data')[source]
Bases:
objectClient that processes PM2.5 satellite data from NetCDF files.
The client supports the V5.GL.05.02 (GWR) and V6.GL.02.04 (CNN) datasets from the WUSTL Atmospheric Composition Analysis Group (ACAG).
- __init__(version: str = 'V6', cache_dir: str = 'pm25_data') None[source]
Initialize the PM2.5 Client with data paths and AWS configuration.
- Parameters:
version –
Dataset version to use. Options: - “V6” (default): V6.GL.02.04 - CNN-based algorithm (1998-2023)
The most accurate model. Use it for new studies.
”V5”: V5.GL.05.02 - GWR-based algorithm (1998-2024) The older model. Use it to compare with published studies.
cache_dir – Directory for the cache of downloaded NetCDF files.
- Raises:
ValueError – If version is not “V5” or “V6”.
Example
>>> # Use V6 (default, recommended) >>> client = PM25Client()
>>> # Use V5 >>> client = PM25Client(version="V5")
- get_netcdf_path(year: int, month: int | None = None) str[source]
Get NetCDF file path for given year and optional month.
- Parameters:
year – Year for data.
month – Optional month (1-12). If None, the function returns the annual data path.
- Returns:
Path to NetCDF file (cached locally).
- download_netcdf_if_needed(year: int, month: int | None = None, force_download: bool = False) str[source]
Download the NetCDF file from AWS if it is not in the cache.
- Parameters:
year – Year for data.
month – Optional month (1-12). If None, the client downloads annual data.
force_download – If True, download the file again, also if it exists.
- Returns:
Path to the downloaded NetCDF or GeoTIFF file.
- Raises:
requests.RequestException – If the download fails.
IOError – If the client cannot write the file.
- get_pm25_at_point(latitude: float, longitude: float, year: int, month: int | None = None) float[source]
Get PM2.5 value at a specific latitude/longitude point.
The function uses the grid cell that is nearest to the coordinates.
- Parameters:
latitude – Latitude in decimal degrees.
longitude – Longitude in decimal degrees.
year – Year of the data.
month – Optional month (1-12). If None, the function uses annual data.
- Returns:
PM2.5 value in µg/m³ at the nearest grid cell.
- Raises:
ValueError – If the point is outside the data bounds, or there is no data.
requests.RequestException – If the download fails.
Example
>>> client = PM25Client() >>> pm25 = client.get_pm25_at_point(28.6139, 77.2090, year=2020, month=1) >>> print(f"PM2.5: {pm25:.2f} µg/m³")
- get_pm25_stats(geojson_file: str, year: int, month: int | None = None, group_by: str | None = None) Dict[str, float] | DataFrame[source]
Calculate PM2.5 statistics in a polygon region from a GeoJSON file.
If the NetCDF data is not in the local cache, this function downloads the data from AWS.
- Parameters:
geojson_file – Path to GeoJSON file with polygon.
year – Year of the NetCDF data.
month – Optional month of the NetCDF data.
group_by – Optional column name or names for the polygon groups. Give one column (for example ‘state_name’) or a comma-separated list of columns (for example ‘state_name,district_name’). If None, the function aggregates the full polygon boundary. If given, the function aggregates each unique combination.
- Returns:
Dictionary with mean, std, min, and max PM2.5 values. If group_by is given: DataFrame with statistics for each group.
- Return type:
If group_by is None
- Raises:
FileNotFoundError – If the GeoJSON file does not exist.
requests.RequestException – If the NetCDF download fails.
ValueError – If the GeoJSON file does not have the group_by column.
- get_pm25_stats_by_polygon(geojson_file: str, year: int, month: int | None = None, id_field: str | None = None) DataFrame[source]
Calculate PM2.5 statistics for each polygon in a GeoJSON file.
- Parameters:
geojson_file – Path to GeoJSON file with polygons.
year – Year of the NetCDF data.
month – Optional month of the NetCDF data.
id_field – Optional GeoJSON property to use as the identifier.
- Returns:
DataFrame with statistics for each polygon.
- Raises:
FileNotFoundError – If the NetCDF file or the GeoJSON file does not exist.
If the NetCDF data is not in the local cache, this function downloads the data from AWS.
CPCBClient¶
- class vayuayan.CPCBClient(use_test_endpoint: bool = True)[source]
Bases:
objectLegacy client that gets CPCB air quality data.
- __init__(use_test_endpoint: bool = True) None[source]
Initialize the CPCB Client.
- Parameters:
use_test_endpoint – Not used. The parameter stays for compatibility.
- list_stations(as_dataframe: bool = False) List[Dict] | DataFrame[source]
Get the list of all air quality monitoring stations.
- Parameters:
as_dataframe – If True, return the data as a pandas DataFrame.
- Returns:
List of station dictionaries or DataFrame if as_dataframe=True.
- Raises:
CPCBError – If the client cannot get the station data.
- download_raw_data(url: str | None = None, site_id: str | None = None, station_name: str | None = None, time_period: str | None = '15Min', year: str | None = None, output_dir: str = 'downloads', filename: str | None = None, return_dataframe: bool = False, verbose: bool = False) str | DataFrame | None[source]
Download a CSV file from the CPCB data repository.
- Parameters:
url – Direct URL of the file. If you give a URL, the client ignores the other parameters.
site_id – Station site ID (necessary if url is None).
station_name – Station name (necessary if url is None).
time_period – Time period for data (necessary if url is None).
year – Year for data (necessary if url is None).
output_dir – Directory for the downloaded file.
filename – Optional custom filename. If None, the client makes a filename.
return_dataframe – If True, return a pandas DataFrame and not a file path.
verbose – If True, print status messages.
- Returns:
Path to the downloaded file, a DataFrame, or None if the download fails.
- Raises:
CPCBError – If a necessary parameter is missing or the download fails.
NetworkError – If the network request fails.
Examples
>>> client = CPCBClient() >>> # Download with a direct URL >>> path = client.download_raw_data( ... url="https://airquality.cpcb.gov.in/.../Delhi_Punjabi_Bagh_2024.csv" ... ) >>> # Download with parameters >>> df = client.download_raw_data( ... site_id="DL001", ... station_name="Punjabi_Bagh", ... time_period="2024", ... year="2024", ... return_dataframe=True ... )
- get_nearest_station(lat: float, lon: float, return_distance: bool = False) str | Tuple[str, float][source]
Find the station that is nearest to the given coordinates.
- Parameters:
lat – Target latitude.
lon – Target longitude.
return_distance – If True, return the distance and the station ID.
- Returns:
Station ID of the nearest station, or a tuple of (station_id, distance) if return_distance is True.
- Raises:
CPCBError – If the client cannot get the station data, or there are no stations.
- get_k_nearest_stations(lat: float, lon: float, k: int = 5) List[Tuple[Dict, float]][source]
Find the k stations that are nearest to the given coordinates.
- Parameters:
lat – Target latitude.
lon – Target longitude.
k – Number of nearest stations to return.
- Returns:
[(station_info, distance), …], sorted by distance. Each station_info dict has: id, name, latitude, longitude, live, avg, cityID, and stateID.
- Return type:
List of tuples
- Raises:
CPCBError – If the client cannot get the station data, or there are no stations.
- get_nearest_station_within_radius(lat: float, lon: float, max_distance_km: float = 100) Tuple[str, float] | None[source]
Find the nearest station in a given radius.
- Parameters:
lat – Target latitude.
lon – Target longitude.
max_distance_km – Maximum radius in kilometers.
- Returns:
Tuple of (station_id, distance), or None if no station is in the radius.
- Raises:
CPCBError – If the client cannot get the station data.
Utility Functions¶
Utility functions for CPCB data.
The functions clean data, send network requests, parse dates, convert station data, and analyze station data.
- exception vayuayan.utils.DataProcessingError[source]
Error when the client cannot process the data.
- vayuayan.utils.clean_station_name(station_name: str) str[source]
Convert a station name to a clean name with underscores.
The function applies these rules: 1. Remove or replace special characters and punctuation 2. Replace spaces with underscores 3. Remove multiple consecutive underscores 4. Remove leading/trailing underscores 5. Change frequent patterns, for example “City - Organization”
- Parameters:
station_name – Original station name.
- Returns:
Cleaned station name with underscores.
Examples
>>> clean_station_name("Dr. Karni Singh Shooting Range, Delhi - DPCC") 'Dr_Karni_Singh_Shooting_Range_Delhi_DPCC' >>> clean_station_name("ITO, Delhi - DPCC") 'ITO_Delhi_DPCC'
- vayuayan.utils.sort_station_data(data: List[Dict]) List[Dict][source]
Sort the station data by live status and city name.
The function sorts the stations of each city by: 1. Live status (live stations first: True before False) 2. City name (alphabetical order)
- Parameters:
data – List of cities with nested stations from CPCB API.
- Returns:
Sorted list with the same structure, in order of live status and city name.
- vayuayan.utils.parse_cpcb_rss_station_data(data: Dict[str, Any]) List[Dict[str, Any]][source]
Convert CPCB RSS JSON station data to the package station shape.
- vayuayan.utils.station_data_to_dropdown(station_data: List[Dict[str, Any]]) Dict[str, Any][source]
Build historical-client dropdown data from normalized station data.
- vayuayan.utils.fetch_cpcb_rss_station_data(timeout: int = 10) List[Dict[str, Any]][source]
Get the current CPCB stations from the JSON RSS endpoint.
- vayuayan.utils.get_aqi_category(aqi_value: float) str[source]
Convert a numeric AQI value to a category.
- Parameters:
aqi_value – Numeric AQI value.
- Returns:
AQI category string.
- vayuayan.utils.stations_to_dataframe(data: List[Dict]) DataFrame[source]
Convert nested station data to a flat DataFrame.
- Parameters:
data – List of cities with nested stations from CPCB API.
- Returns:
- city_name, city_id, state_id, station_id,
station_name, longitude, latitude, live, avg_aqi.
- Return type:
DataFrame with columns
- vayuayan.utils.stations_to_city_summary(data: List[Dict]) DataFrame[source]
Convert station data to a DataFrame with a summary for each city.
- Parameters:
data – List of cities with nested stations.
- Returns:
DataFrame with aggregated statistics for each city.
- vayuayan.utils.stations_to_coordinates_dataframe(data: List[Dict]) DataFrame[source]
Convert station data to a DataFrame for maps.
- Parameters:
data – List of cities with nested stations.
- Returns:
DataFrame with the locations and the primary station data.
- vayuayan.utils.convert_station_data_to_dataframe(data: List[Dict], method: str = 'stations') DataFrame[source]
Convert station data to a DataFrame in one of three formats.
- Parameters:
data – List of cities with nested stations from CPCB API.
method – Conversion method (‘stations’, ‘city_summary’, ‘coordinates’).
- Returns:
DataFrame in the format of the given method.
- - 'stations'
Flat DataFrame with one row for each station (default)
- - 'city_summary'
Summary of each city, with aggregated statistics
- - 'coordinates'
DataFrame for maps, with the station locations
- vayuayan.utils.analyze_station_data(data: List[Dict]) Dict[str, Any][source]
Analyze the station data.
- Parameters:
data – List of cities with nested stations.
- Returns:
Dictionary with the results of the analysis.
- vayuayan.utils.safe_get(url: str, max_retries: int = 3, timeout: int = 10, verify_ssl: bool = True, allow_ssl_fallback: bool = False, verbose: bool = False) Response[source]
Send an HTTP GET request, and send it again if it fails.
- Parameters:
url – URL of the request.
max_retries – Maximum number of retries.
timeout – Request timeout in seconds.
verify_ssl – If True, verify the SSL certificates.
allow_ssl_fallback – If True, send the request again without SSL verification when the verification fails.
verbose – If True, print status messages.
- Returns:
requests.Response object.
- Raises:
NetworkError – If all the retries fail.
- vayuayan.utils.safe_post(url: str, headers: Dict[str, str], data: Dict[str, Any] | str | bytes, cookies: Dict[str, str] | None = None, max_retries: int = 3, backoff_factor: float = 0.3, timeout: int = 30, verify_ssl: bool = True, allow_ssl_fallback: bool = False, verbose: bool = False) Dict[str, Any][source]
Send a POST request with retries, and decode the base64 response.
- Parameters:
url – URL of the POST request.
headers – Request headers.
data – Request data (dict, string, or bytes).
cookies – Optional cookies dict.
max_retries – Maximum number of retry attempts.
backoff_factor – Factor for the exponential delay between retries.
timeout – Request timeout in seconds.
verify_ssl – If True, verify the SSL certificates.
allow_ssl_fallback – If True, send the request again without SSL verification when the verification fails.
verbose – If True, print status messages.
- Returns:
Parsed JSON response, as a dictionary.
- Raises:
NetworkError – If all retries fail, or there is a network problem.
DataProcessingError – If the client cannot decode the base64 or parse the JSON.
ValueError – If an input parameter is not valid.
- vayuayan.utils.url_encode(data_dict: Dict[str, Any]) str[source]
Encode a dictionary as a base64 JSON string.
- Parameters:
data_dict – Dictionary to encode.
- Returns:
Base64 encoded JSON string.
- vayuayan.utils.time_to_isodate(timestamp: int) str[source]
Convert a timestamp to the ISO date format.
- Parameters:
timestamp – Unix timestamp in milliseconds.
- Returns:
ISO formatted date string.
- vayuayan.utils.haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) float[source]
Calculate the great circle distance between two points (haversine formula).
For locations on the globe, this distance is more accurate than the Euclidean distance.
- Parameters:
lat1 – Latitude and longitude of first point.
lon1 – Latitude and longitude of first point.
lat2 – Latitude and longitude of second point.
lon2 – Latitude and longitude of second point.
- Returns:
Distance in kilometers.
- vayuayan.utils.euclidean_distance(lat1: float, lon1: float, lat2: float, lon2: float) float[source]
Calculate simple Euclidean distance.
This function is faster than haversine_distance, but less accurate for long distances.
- Parameters:
lat1 – Latitude and longitude of first point.
lon1 – Latitude and longitude of first point.
lat2 – Latitude and longitude of second point.
lon2 – Latitude and longitude of second point.
- Returns:
Euclidean distance (arbitrary units).
- vayuayan.utils.parse_date(date_text: str) str | None[source]
Parse a date in one of many formats to the standard format.
- Parameters:
date_text – Raw date text.
- Returns:
Date in YYYY-MM-DD format, or None if the parse fails.
Constants¶
Constants of the vayuayan package.
The constants are URL endpoints, headers, timeouts, and other configuration values.
- vayuayan.constants.get_config_dir() Path[source]
Get the standard configuration directory of vayuayan.
- Returns:
- Platform-specific config directory
Linux/macOS: ~/.config/vayuayan
Windows: ~/AppData/Local/vayuayan
- Return type:
Path
Exceptions¶
Exception classes of the vayuayan package.
Each class identifies one type of failure, so that callers can catch it.
- exception vayuayan.exceptions.CPCBError[source]
Bases:
ExceptionBase class for all vayuayan exceptions.
All other exceptions in the vayuayan package inherit from this class.
- exception vayuayan.exceptions.NetworkError[source]
Bases:
CPCBErrorError when a network request fails.
A network problem, a timeout, or a server error can cause this error.
- exception vayuayan.exceptions.DataParsingError[source]
Bases:
CPCBErrorError when the client cannot parse the data.
Malformed JSON, a corrupt Excel file, or an unknown data format can cause this error.
- exception vayuayan.exceptions.DataProcessingError[source]
Bases:
CPCBErrorError when a data operation fails.
Examples are a failed base64 decode, a failed data transformation, and a failed statistical calculation.
- exception vayuayan.exceptions.CityNotFoundError[source]
Bases:
CPCBErrorError when the CPCB database does not have a city.
The CPCB monitoring network does not have the requested city or location.
- exception vayuayan.exceptions.StationNotFoundError[source]
Bases:
CPCBErrorError when the client cannot find a monitoring station.
The CPCB monitoring network does not have the requested station ID or station name.
- exception vayuayan.exceptions.InvalidDataError[source]
Bases:
CPCBErrorError when the received data is not valid.
Examples are a missing necessary field, invalid coordinates, and data outside the expected range.
- exception vayuayan.exceptions.AuthenticationError[source]
Bases:
CPCBErrorError when the authentication with CPCB services fails.
The API authentication failed, or CPCB refused the access.
- exception vayuayan.exceptions.RateLimitError[source]
Bases:
CPCBErrorError when the client goes above the API rate limit.
The client sent too many requests to CPCB services in a short time.