|
| 1 | +import pandas as pd |
| 2 | +import requests |
| 3 | +from io import StringIO |
| 4 | + |
| 5 | + |
| 6 | +VARIABLE_MAP = { |
| 7 | + 'SWGDN': 'ghi', |
| 8 | + 'SWGDNCLR': 'ghi_clear', |
| 9 | + 'ALBEDO': 'albedo', |
| 10 | + 'LWGNT': 'longwave_net', |
| 11 | + 'LWGEM': 'longwave_up', |
| 12 | + 'LWGAB': 'longwave_down', |
| 13 | + 'T2M': 'temp_air', |
| 14 | + 'T2MDEW': 'temp_dew', |
| 15 | + 'PS': 'pressure', |
| 16 | + 'TOTEXTTAU': 'aod550', |
| 17 | +} |
| 18 | + |
| 19 | + |
| 20 | +def get_merra2(latitude, longitude, start, end, username, password, dataset, |
| 21 | + variables, map_variables=True): |
| 22 | + """ |
| 23 | + Retrieve MERRA-2 time-series irradiance and meteorological reanalysis data |
| 24 | + from NASA's GESDISC data archive. |
| 25 | +
|
| 26 | + MERRA-2 [1]_ offers modeled data for many atmospheric quantities at hourly |
| 27 | + resolution on a 0.5° x 0.625° global grid. |
| 28 | +
|
| 29 | + Access must be granted to the GESDISC data archive before EarthData |
| 30 | + credentials will work. See [2]_ for instructions. |
| 31 | +
|
| 32 | + Parameters |
| 33 | + ---------- |
| 34 | + latitude : float |
| 35 | + In decimal degrees, north is positive (ISO 19115). |
| 36 | + longitude: float |
| 37 | + In decimal degrees, east is positive (ISO 19115). |
| 38 | + start : datetime like or str |
| 39 | + First timestamp of the requested period. If a timezone is not |
| 40 | + specified, UTC is assumed. |
| 41 | + end : datetime like or str |
| 42 | + Last timestamp of the requested period. If a timezone is not |
| 43 | + specified, UTC is assumed. Must be in the same year as ``start``. |
| 44 | + username : str |
| 45 | + NASA EarthData username. |
| 46 | + password : str |
| 47 | + NASA EarthData password. |
| 48 | + dataset : str |
| 49 | + Dataset name (with version), e.g. "M2T1NXRAD.5.12.4". |
| 50 | + variables : list of str |
| 51 | + List of variable names to retrieve. See the documentation of the |
| 52 | + specific dataset you are accessing for options. |
| 53 | + map_variables : bool, default True |
| 54 | + When true, renames columns of the DataFrame to pvlib variable names |
| 55 | + where applicable. See variable :const:`VARIABLE_MAP`. |
| 56 | +
|
| 57 | + Raises |
| 58 | + ------ |
| 59 | + ValueError |
| 60 | + If ``start`` and ``end`` are in different years, when converted to UTC. |
| 61 | +
|
| 62 | + Returns |
| 63 | + ------- |
| 64 | + data : pd.DataFrame |
| 65 | + Time series data. The index corresponds to the middle of the interval. |
| 66 | + meta : dict |
| 67 | + Metadata. |
| 68 | +
|
| 69 | + Notes |
| 70 | + ----- |
| 71 | + The following datasets provide quantities useful for PV modeling: |
| 72 | +
|
| 73 | + +------------------------------------+-----------+---------------+ |
| 74 | + | Dataset | Variable | pvlib name | |
| 75 | + +====================================+===========+===============+ |
| 76 | + | `M2T1NXRAD.5.12.4 <M2T1NXRAD_>`_ | SWGDN | ghi | |
| 77 | + | +-----------+---------------+ |
| 78 | + | | SWGDNCLR | ghi_clear | |
| 79 | + | +-----------+---------------+ |
| 80 | + | | ALBEDO | albedo | |
| 81 | + | +-----------+---------------+ |
| 82 | + | | LWGAB | longwave_down | |
| 83 | + | +-----------+---------------+ |
| 84 | + | | LWGNT | longwave_net | |
| 85 | + | +-----------+---------------+ |
| 86 | + | | LWGEM | longwave_up | |
| 87 | + +------------------------------------+-----------+---------------+ |
| 88 | + | `M2T1NXSLV.5.12.4 <M2T1NXSLV_>`_ | T2M | temp_air | |
| 89 | + | +-----------+---------------+ |
| 90 | + | | U10 | n/a | |
| 91 | + | +-----------+---------------+ |
| 92 | + | | V10 | n/a | |
| 93 | + | +-----------+---------------+ |
| 94 | + | | T2MDEW | temp_dew | |
| 95 | + | +-----------+---------------+ |
| 96 | + | | PS | pressure | |
| 97 | + | +-----------+---------------+ |
| 98 | + | | TO3 | n/a | |
| 99 | + | +-----------+---------------+ |
| 100 | + | | TQV | n/a | |
| 101 | + +------------------------------------+-----------+---------------+ |
| 102 | + | `M2T1NXAER.5.12.4 <M2T1NXAER_>`_ | TOTEXTTAU | aod550 | |
| 103 | + | +-----------+---------------+ |
| 104 | + | | TOTSCATAU | n/a | |
| 105 | + | +-----------+---------------+ |
| 106 | + | | TOTANGSTR | n/a | |
| 107 | + +------------------------------------+-----------+---------------+ |
| 108 | +
|
| 109 | + .. _M2T1NXRAD: https://disc.gsfc.nasa.gov/datasets/M2T1NXRAD_5.12.4/summary |
| 110 | + .. _M2T1NXSLV: https://disc.gsfc.nasa.gov/datasets/M2T1NXSLV_5.12.4/summary |
| 111 | + .. _M2T1NXAER: https://disc.gsfc.nasa.gov/datasets/M2T1NXAER_5.12.4/summary |
| 112 | +
|
| 113 | + A complete list of datasets and their documentation is available at [3]_. |
| 114 | +
|
| 115 | + Note that MERRA2 does not currently provide DNI or DHI. |
| 116 | +
|
| 117 | + References |
| 118 | + ---------- |
| 119 | + .. [1] https://gmao.gsfc.nasa.gov/gmao-products/merra-2/ |
| 120 | + .. [2] https://disc.gsfc.nasa.gov/earthdata-login |
| 121 | + .. [3] https://disc.gsfc.nasa.gov/datasets?project=MERRA-2 |
| 122 | + """ |
| 123 | + |
| 124 | + # general API info here: |
| 125 | + # https://docs.unidata.ucar.edu/tds/5.0/userguide/netcdf_subset_service_ref.html # noqa: E501 |
| 126 | + |
| 127 | + def _to_utc_dt_notz(dt): |
| 128 | + dt = pd.to_datetime(dt) |
| 129 | + if dt.tzinfo is not None: |
| 130 | + # convert to utc, then drop tz so that isoformat() is clean |
| 131 | + dt = dt.tz_convert("UTC").tz_localize(None) |
| 132 | + return dt |
| 133 | + |
| 134 | + start = _to_utc_dt_notz(start) |
| 135 | + end = _to_utc_dt_notz(end) |
| 136 | + |
| 137 | + if (year := start.year) != end.year: |
| 138 | + raise ValueError("start and end must be in the same year (in UTC)") |
| 139 | + |
| 140 | + url = ( |
| 141 | + "https://goldsmr4.gesdisc.eosdis.nasa.gov/thredds/ncss/grid/" |
| 142 | + f"MERRA2_aggregation/{dataset}/{dataset}_Aggregation_{year}.ncml" |
| 143 | + ) |
| 144 | + |
| 145 | + parameters = { |
| 146 | + 'var': ",".join(variables), |
| 147 | + 'latitude': latitude, |
| 148 | + 'longitude': longitude, |
| 149 | + 'time_start': start.isoformat() + "Z", |
| 150 | + 'time_end': end.isoformat() + "Z", |
| 151 | + 'accept': 'csv', |
| 152 | + } |
| 153 | + |
| 154 | + auth = (username, password) |
| 155 | + |
| 156 | + with requests.Session() as session: |
| 157 | + session.auth = auth |
| 158 | + login = session.request('get', url, params=parameters) |
| 159 | + response = session.get(login.url, auth=auth, params=parameters) |
| 160 | + |
| 161 | + response.raise_for_status() |
| 162 | + |
| 163 | + content = response.content.decode('utf-8') |
| 164 | + buffer = StringIO(content) |
| 165 | + df = pd.read_csv(buffer) |
| 166 | + |
| 167 | + df.index = pd.to_datetime(df['time']) |
| 168 | + |
| 169 | + meta = {} |
| 170 | + meta['dataset'] = dataset |
| 171 | + meta['station'] = df['station'].values[0] |
| 172 | + meta['latitude'] = df['latitude[unit="degrees_north"]'].values[0] |
| 173 | + meta['longitude'] = df['longitude[unit="degrees_east"]'].values[0] |
| 174 | + |
| 175 | + # drop the non-data columns |
| 176 | + dropcols = ['time', 'station', 'latitude[unit="degrees_north"]', |
| 177 | + 'longitude[unit="degrees_east"]'] |
| 178 | + df = df.drop(columns=dropcols) |
| 179 | + |
| 180 | + # column names are like T2M[unit="K"] by default. extract the unit |
| 181 | + # for the metadata, then rename col to just T2M |
| 182 | + units = {} |
| 183 | + rename = {} |
| 184 | + for col in df.columns: |
| 185 | + name, _ = col.split("[", maxsplit=1) |
| 186 | + unit = col.split('"')[1] |
| 187 | + units[name] = unit |
| 188 | + rename[col] = name |
| 189 | + |
| 190 | + meta['units'] = units |
| 191 | + df = df.rename(columns=rename) |
| 192 | + |
| 193 | + if map_variables: |
| 194 | + df = df.rename(columns=VARIABLE_MAP) |
| 195 | + |
| 196 | + return df, meta |
0 commit comments