|
| 1 | +import requests |
| 2 | +import pandas as pd |
| 3 | +from io import BytesIO, StringIO |
| 4 | +import zipfile |
| 5 | +import time |
| 6 | + |
| 7 | + |
| 8 | +VARIABLE_MAP = { |
| 9 | + # short names |
| 10 | + 'd2m': 'temp_dew', |
| 11 | + 't2m': 'temp_air', |
| 12 | + 'sp': 'pressure', |
| 13 | + 'ssrd': 'ghi', |
| 14 | + 'tp': 'precipitation', |
| 15 | + |
| 16 | + # long names |
| 17 | + '2m_dewpoint_temperature': 'temp_dew', |
| 18 | + '2m_temperature': 'temp_air', |
| 19 | + 'surface_pressure': 'pressure', |
| 20 | + 'surface_solar_radiation_downwards': 'ghi', |
| 21 | + 'total_precipitation': 'precipitation', |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +def _same(x): |
| 26 | + return x |
| 27 | + |
| 28 | + |
| 29 | +def _k_to_c(temp_k): |
| 30 | + return temp_k - 273.15 |
| 31 | + |
| 32 | + |
| 33 | +def _j_to_w(j): |
| 34 | + return j / 3600 |
| 35 | + |
| 36 | + |
| 37 | +def _m_to_cm(m): |
| 38 | + return m / 100 |
| 39 | + |
| 40 | + |
| 41 | +UNITS = { |
| 42 | + 'u100': _same, |
| 43 | + 'v100': _same, |
| 44 | + 'u10': _same, |
| 45 | + 'v10': _same, |
| 46 | + 'd2m': _k_to_c, |
| 47 | + 't2m': _k_to_c, |
| 48 | + 'msl': _same, |
| 49 | + 'sst': _k_to_c, |
| 50 | + 'skt': _k_to_c, |
| 51 | + 'sp': _same, |
| 52 | + 'ssrd': _j_to_w, |
| 53 | + 'strd': _j_to_w, |
| 54 | + 'tp': _m_to_cm, |
| 55 | +} |
| 56 | + |
| 57 | + |
| 58 | +def get_era5(latitude, longitude, start, end, variables, api_key, |
| 59 | + map_variables=True, timeout=60, |
| 60 | + url='https://cds.climate.copernicus.eu/api/retrieve/v1/'): |
| 61 | + """ |
| 62 | + Retrieve ERA5 reanalysis data from the ECMWF's Copernicus Data Store. |
| 63 | +
|
| 64 | + A CDS API key is needed to access this API. Register for one at [1]_. |
| 65 | +
|
| 66 | + This API [2]_ provides a subset of the full ERA5 dataset. See [3]_ for |
| 67 | + the available variables. Data are available on a 0.25° x 0.25° grid. |
| 68 | +
|
| 69 | + Parameters |
| 70 | + ---------- |
| 71 | + latitude : float |
| 72 | + In decimal degrees, north is positive (ISO 19115). |
| 73 | + longitude: float |
| 74 | + In decimal degrees, east is positive (ISO 19115). |
| 75 | + start : datetime like or str |
| 76 | + First day of the requested period. Assumed to be UTC if not localized. |
| 77 | + end : datetime like or str |
| 78 | + Last day of the requested period. Assumed to be UTC if not localized. |
| 79 | + variables : list of str |
| 80 | + List of variable names to retrieve, for example |
| 81 | + ``['ghi', 'temp_air']``. Both pvlib and ERA5 names can be used. |
| 82 | + See [1]_ for additional options. |
| 83 | + api_key : str |
| 84 | + ECMWF CDS API key. |
| 85 | + map_variables : bool, default True |
| 86 | + When true, renames columns of the DataFrame to pvlib variable names |
| 87 | + where applicable. Also converts units of some variables. See variable |
| 88 | + :const:`VARIABLE_MAP` and :const:`UNITS`. |
| 89 | + timeout : int, default 60 |
| 90 | + Number of seconds to wait for the requested data to become available |
| 91 | + before timeout. |
| 92 | + url : str, optional |
| 93 | + API endpoint URL. |
| 94 | +
|
| 95 | + Raises |
| 96 | + ------ |
| 97 | + Exception |
| 98 | + If ``timeout`` is reached without the job finishing. |
| 99 | +
|
| 100 | + Returns |
| 101 | + ------- |
| 102 | + data : pd.DataFrame |
| 103 | + Time series data. The index corresponds to the start of the interval. |
| 104 | + meta : dict |
| 105 | + Metadata. |
| 106 | +
|
| 107 | + References |
| 108 | + ---------- |
| 109 | + .. [1] https://cds.climate.copernicus.eu/ |
| 110 | + .. [2] https://cds.climate.copernicus.eu/datasets/reanalysis-era5-single-levels-timeseries?tab=overview |
| 111 | + .. [3] https://confluence.ecmwf.int/pages/viewpage.action?pageId=505390919 |
| 112 | + """ # noqa: E501 |
| 113 | + |
| 114 | + def _to_utc_dt_notz(dt): |
| 115 | + dt = pd.to_datetime(dt) |
| 116 | + if dt.tzinfo is not None: |
| 117 | + dt = dt.tz_convert("UTC") |
| 118 | + return dt |
| 119 | + |
| 120 | + start = _to_utc_dt_notz(start).strftime("%Y-%m-%d") |
| 121 | + end = _to_utc_dt_notz(end).strftime("%Y-%m-%d") |
| 122 | + |
| 123 | + headers = {'PRIVATE-TOKEN': api_key} |
| 124 | + |
| 125 | + # allow variables to be specified with pvlib names |
| 126 | + reverse_map = {v: k for k, v in VARIABLE_MAP.items()} |
| 127 | + variables = [reverse_map.get(k, k) for k in variables] |
| 128 | + |
| 129 | + # Step 1: submit data request (add it to the queue) |
| 130 | + params = { |
| 131 | + "inputs": { |
| 132 | + "variable": variables, |
| 133 | + "location": {"longitude": longitude, "latitude": latitude}, |
| 134 | + "date": [f"{start}/{end}"], |
| 135 | + "data_format": "csv" |
| 136 | + } |
| 137 | + } |
| 138 | + slug = "processes/reanalysis-era5-single-levels-timeseries/execution" |
| 139 | + response = requests.post(url + slug, json=params, headers=headers, |
| 140 | + timeout=timeout) |
| 141 | + submission_response = response.json() |
| 142 | + if not response.ok: |
| 143 | + raise Exception(submission_response) # likely need to accept license |
| 144 | + |
| 145 | + job_id = submission_response['jobID'] |
| 146 | + |
| 147 | + # Step 2: poll until the data request is ready |
| 148 | + slug = "jobs/" + job_id |
| 149 | + poll_interval = 1 |
| 150 | + num_polls = 0 |
| 151 | + while True: |
| 152 | + response = requests.get(url + slug, headers=headers, timeout=timeout) |
| 153 | + poll_response = response.json() |
| 154 | + job_status = poll_response['status'] |
| 155 | + |
| 156 | + if job_status == 'successful': |
| 157 | + break # ready to proceed to next step |
| 158 | + elif job_status == 'failed': |
| 159 | + msg = ( |
| 160 | + 'Request failed. Please check the ECMWF website for details: ' |
| 161 | + 'https://cds.climate.copernicus.eu/requests?tab=all' |
| 162 | + ) |
| 163 | + raise Exception(msg) |
| 164 | + |
| 165 | + num_polls += 1 |
| 166 | + if num_polls * poll_interval > timeout: |
| 167 | + raise requests.exceptions.Timeout( |
| 168 | + 'Request timed out. Try increasing the timeout parameter or ' |
| 169 | + 'reducing the request size.' |
| 170 | + ) |
| 171 | + |
| 172 | + time.sleep(1) |
| 173 | + |
| 174 | + # Step 3: get the download link for our requested dataset |
| 175 | + slug = "jobs/" + job_id + "/results" |
| 176 | + response = requests.get(url + slug, headers=headers, timeout=timeout) |
| 177 | + results_response = response.json() |
| 178 | + download_url = results_response['asset']['value']['href'] |
| 179 | + |
| 180 | + # Step 4: finally, download our dataset. it's a zipfile of one CSV |
| 181 | + response = requests.get(download_url, timeout=timeout) |
| 182 | + zipbuffer = BytesIO(response.content) |
| 183 | + archive = zipfile.ZipFile(zipbuffer) |
| 184 | + filename = archive.filelist[0].filename |
| 185 | + csvbuffer = StringIO(archive.read(filename).decode('utf-8')) |
| 186 | + df = pd.read_csv(csvbuffer) |
| 187 | + |
| 188 | + # and parse into the usual formats |
| 189 | + metadata = submission_response['metadata'] # include messages from ECMWF |
| 190 | + metadata['jobID'] = job_id |
| 191 | + if not df.empty: |
| 192 | + metadata['latitude'] = df['latitude'].values[0] |
| 193 | + metadata['longitude'] = df['longitude'].values[0] |
| 194 | + |
| 195 | + df.index = pd.to_datetime(df['valid_time']).dt.tz_localize('UTC') |
| 196 | + df = df.drop(columns=['valid_time', 'latitude', 'longitude']) |
| 197 | + |
| 198 | + if map_variables: |
| 199 | + # convert units and rename |
| 200 | + for shortname in df.columns: |
| 201 | + converter = UNITS.get(shortname, _same) |
| 202 | + df[shortname] = converter(df[shortname]) |
| 203 | + df = df.rename(columns=VARIABLE_MAP) |
| 204 | + |
| 205 | + return df, metadata |
0 commit comments