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