Skip to content

gfs

GFS, GEFS, and GDAS Readers for AWS Open Data

GDASReader

Bases: NCEPPDSReader

Reader for GDAS (Global Data Assimilation System) on AWS.

Source code in monetio/readers/gfs.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
@register_reader("gdas")
class GDASReader(NCEPPDSReader):
    """
    Reader for GDAS (Global Data Assimilation System) on AWS.
    """

    def build_urls(
        self,
        dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
        hour: int = 0,
        lead_time: int | list[int] = 0,
        product: str = "pgrb2.0p25",
    ) -> list[str]:
        """
        Build S3 URLs for GDAS data.
        """
        if isinstance(dates, str | datetime.datetime | pd.Timestamp):
            dates = pd.DatetimeIndex([pd.to_datetime(dates)])
        else:
            dates = pd.to_datetime(dates)

        if isinstance(lead_time, int):
            lead_times = [lead_time]
        else:
            lead_times = lead_time

        bucket = "noaa-gfs-bdp-pds"
        urls = []
        for d in dates:
            d_str = d.strftime("%Y%m%d")
            h_str = f"{hour:02d}"
            for lt in lead_times:
                lt_str = f"{lt:03d}"
                # s3://noaa-gfs-bdp-pds/gdas.20250324/00/atmos/gdas.t00z.pgrb2.0p25.f000
                url = f"s3://{bucket}/gdas.{d_str}/{h_str}/atmos/gdas.t{h_str}z.{product}.f{lt_str}"
                urls.append(url)
        return urls

build_urls(dates, hour=0, lead_time=0, product='pgrb2.0p25')

Build S3 URLs for GDAS data.

Source code in monetio/readers/gfs.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def build_urls(
    self,
    dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
    hour: int = 0,
    lead_time: int | list[int] = 0,
    product: str = "pgrb2.0p25",
) -> list[str]:
    """
    Build S3 URLs for GDAS data.
    """
    if isinstance(dates, str | datetime.datetime | pd.Timestamp):
        dates = pd.DatetimeIndex([pd.to_datetime(dates)])
    else:
        dates = pd.to_datetime(dates)

    if isinstance(lead_time, int):
        lead_times = [lead_time]
    else:
        lead_times = lead_time

    bucket = "noaa-gfs-bdp-pds"
    urls = []
    for d in dates:
        d_str = d.strftime("%Y%m%d")
        h_str = f"{hour:02d}"
        for lt in lead_times:
            lt_str = f"{lt:03d}"
            # s3://noaa-gfs-bdp-pds/gdas.20250324/00/atmos/gdas.t00z.pgrb2.0p25.f000
            url = f"s3://{bucket}/gdas.{d_str}/{h_str}/atmos/gdas.t{h_str}z.{product}.f{lt_str}"
            urls.append(url)
    return urls

GEFSReader

Bases: NCEPPDSReader

Reader for GEFS (Global Ensemble Forecast System) on AWS.

Source code in monetio/readers/gfs.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@register_reader("gefs")
class GEFSReader(NCEPPDSReader):
    """
    Reader for GEFS (Global Ensemble Forecast System) on AWS.
    """

    def build_urls(
        self,
        dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
        hour: int = 0,
        lead_time: int | list[int] = 0,
        product: str = "geavg.tHHz.pgrb2a.0p50",
    ) -> list[str]:
        """
        Build S3 URLs for GEFS data.
        Note: product here usually specifies the member and resolution.
        Example: 'geavg.tHHz.pgrb2a.0p50' for ensemble mean 0.5 deg.
        """
        if isinstance(dates, str | datetime.datetime | pd.Timestamp):
            dates = pd.DatetimeIndex([pd.to_datetime(dates)])
        else:
            dates = pd.to_datetime(dates)

        if isinstance(lead_time, int):
            lead_times = [lead_time]
        else:
            lead_times = lead_time

        bucket = "noaa-gefs-pds"
        urls = []
        h_str = f"{hour:02d}"
        for d in dates:
            d_str = d.strftime("%Y%m%d")
            for lt in lead_times:
                lt_str = f"{lt:03d}"
                # The product string might have 'tHHz' as a placeholder
                prod = product.replace("tHHz", f"t{h_str}z")
                # s3://noaa-gefs-pds/gefs.20250324/00/atmos/pgrb2ap5/geavg.t00z.pgrb2a.0p50.f000
                # Note: pgrb2ap5 is a subdirectory for 0.5 deg products
                res_dir = "pgrb2ap5" if "0p50" in prod else "pgrb2bp5"
                url = f"s3://{bucket}/gefs.{d_str}/{h_str}/atmos/{res_dir}/{prod}.f{lt_str}"
                urls.append(url)
        return urls

build_urls(dates, hour=0, lead_time=0, product='geavg.tHHz.pgrb2a.0p50')

Build S3 URLs for GEFS data. Note: product here usually specifies the member and resolution. Example: 'geavg.tHHz.pgrb2a.0p50' for ensemble mean 0.5 deg.

Source code in monetio/readers/gfs.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def build_urls(
    self,
    dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
    hour: int = 0,
    lead_time: int | list[int] = 0,
    product: str = "geavg.tHHz.pgrb2a.0p50",
) -> list[str]:
    """
    Build S3 URLs for GEFS data.
    Note: product here usually specifies the member and resolution.
    Example: 'geavg.tHHz.pgrb2a.0p50' for ensemble mean 0.5 deg.
    """
    if isinstance(dates, str | datetime.datetime | pd.Timestamp):
        dates = pd.DatetimeIndex([pd.to_datetime(dates)])
    else:
        dates = pd.to_datetime(dates)

    if isinstance(lead_time, int):
        lead_times = [lead_time]
    else:
        lead_times = lead_time

    bucket = "noaa-gefs-pds"
    urls = []
    h_str = f"{hour:02d}"
    for d in dates:
        d_str = d.strftime("%Y%m%d")
        for lt in lead_times:
            lt_str = f"{lt:03d}"
            # The product string might have 'tHHz' as a placeholder
            prod = product.replace("tHHz", f"t{h_str}z")
            # s3://noaa-gefs-pds/gefs.20250324/00/atmos/pgrb2ap5/geavg.t00z.pgrb2a.0p50.f000
            # Note: pgrb2ap5 is a subdirectory for 0.5 deg products
            res_dir = "pgrb2ap5" if "0p50" in prod else "pgrb2bp5"
            url = f"s3://{bucket}/gefs.{d_str}/{h_str}/atmos/{res_dir}/{prod}.f{lt_str}"
            urls.append(url)
    return urls

GFSReader

Bases: NCEPPDSReader

Reader for GFS (Global Forecast System) on AWS.

Source code in monetio/readers/gfs.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@register_reader("gfs")
class GFSReader(NCEPPDSReader):
    """
    Reader for GFS (Global Forecast System) on AWS.
    """

    def build_urls(
        self,
        dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
        hour: int = 0,
        lead_time: int | list[int] = 0,
        product: str = "pgrb2.0p25",
    ) -> list[str]:
        """
        Build S3 URLs for GFS data.
        """
        if isinstance(dates, str | datetime.datetime | pd.Timestamp):
            dates = pd.DatetimeIndex([pd.to_datetime(dates)])
        else:
            dates = pd.to_datetime(dates)

        if isinstance(lead_time, int):
            lead_times = [lead_time]
        else:
            lead_times = lead_time

        bucket = "noaa-gfs-bdp-pds"
        urls = []
        for d in dates:
            d_str = d.strftime("%Y%m%d")
            h_str = f"{hour:02d}"
            for lt in lead_times:
                lt_str = f"{lt:03d}"
                # s3://noaa-gfs-bdp-pds/gfs.20250324/00/atmos/gfs.t00z.pgrb2.0p25.f000
                url = f"s3://{bucket}/gfs.{d_str}/{h_str}/atmos/gfs.t{h_str}z.{product}.f{lt_str}"
                urls.append(url)
        return urls

build_urls(dates, hour=0, lead_time=0, product='pgrb2.0p25')

Build S3 URLs for GFS data.

Source code in monetio/readers/gfs.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def build_urls(
    self,
    dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str,
    hour: int = 0,
    lead_time: int | list[int] = 0,
    product: str = "pgrb2.0p25",
) -> list[str]:
    """
    Build S3 URLs for GFS data.
    """
    if isinstance(dates, str | datetime.datetime | pd.Timestamp):
        dates = pd.DatetimeIndex([pd.to_datetime(dates)])
    else:
        dates = pd.to_datetime(dates)

    if isinstance(lead_time, int):
        lead_times = [lead_time]
    else:
        lead_times = lead_time

    bucket = "noaa-gfs-bdp-pds"
    urls = []
    for d in dates:
        d_str = d.strftime("%Y%m%d")
        h_str = f"{hour:02d}"
        for lt in lead_times:
            lt_str = f"{lt:03d}"
            # s3://noaa-gfs-bdp-pds/gfs.20250324/00/atmos/gfs.t00z.pgrb2.0p25.f000
            url = f"s3://{bucket}/gfs.{d_str}/{h_str}/atmos/gfs.t{h_str}z.{product}.f{lt_str}"
            urls.append(url)
    return urls

NCEPPDSReader

Bases: GriddedReader

Base reader for NCEP products on AWS Public Dataset (PDS).

Source code in monetio/readers/gfs.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class NCEPPDSReader(GriddedReader):
    """
    Base reader for NCEP products on AWS Public Dataset (PDS).
    """

    def open_dataset(
        self,
        files: str | list[str] = None,
        dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str = None,
        hour: int = 0,
        lead_time: int | list[int] = 0,
        product: str = "pgrb2.0p25",
        **kwargs,
    ) -> xr.Dataset:
        """
        Reads NCEP GRIB2 data from AWS S3.

        Parameters
        ----------
        files : Union[str, List[str]], optional
            File path(s) or S3 URL(s).
        dates : Union[pd.DatetimeIndex, List[datetime], datetime, str], optional
            Dates to retrieve. If files is None, this is used to build URLs.
        hour : int, optional
            Forecast cycle hour (0, 6, 12, 18). Default is 0.
        lead_time : Union[int, List[int]], optional
            Forecast lead time(s) in hours. Default is 0.
        product : str, optional
            Product string (e.g., 'pgrb2.0p25').
        **kwargs : dict
            Additional arguments passed to XarrayDriver.open.

        Returns
        -------
        xr.Dataset
            The dataset.
        """
        if files is None:
            if dates is None:
                raise ValueError("Either 'files' or 'dates' must be provided.")
            files = self.build_urls(dates, hour=hour, lead_time=lead_time, product=product)

        if "engine" not in kwargs:
            kwargs["engine"] = "grib2io"

        # grib2io engine generally requires local files or file-like objects.
        # XarrayDriver handles S3 URLs by opening them via fsspec.
        ds = super().open_dataset(files, **kwargs)

        # Apply standard harmonization
        ds = self.harmonize(ds)

        # Update history
        ds = update_history(ds, f"Read {self.__class__.__name__} data from AWS PDS.")

        return ds

    def harmonize(self, ds: xr.Dataset) -> xr.Dataset:
        """
        Harmonize NCEP metadata to monetio standards.
        """
        # Coordinate Renaming
        rename_dict = {
            "latitude": "latitude",
            "longitude": "longitude",
            "lat": "latitude",
            "lon": "longitude",
            "lat_0": "latitude",
            "lon_0": "longitude",
            "time": "time",
            "valid_time": "time",
            "step": "step",
        }

        actual_rename = {}
        for k, v in rename_dict.items():
            if (k in ds.variables or k in ds.dims) and v not in ds.variables and k != v:
                actual_rename[k] = v

        if actual_rename:
            ds = ds.rename(actual_rename)

        # Variable Mapping
        var_mapping = {
            "O3MR": "ozone",
            "TMP": "temperature",
            "UGRD": "u_wind",
            "VGRD": "v_wind",
            "PRES": "pressure",
            "HGT": "height",
            "RH": "relative_humidity",
            "PRMSL": "mslp",
        }
        actual_var_rename = {}
        for var in ds.variables:
            for k, v in var_mapping.items():
                # Check for exact match or suffix (e.g., 'TMP:isobaricInhPa')
                if (var == k or var.startswith(f"{k}:")) and v not in ds.variables:
                    actual_var_rename[var] = v
                    break
        if actual_var_rename:
            ds = ds.rename(actual_var_rename)

        # Ensure latitude/longitude are coordinates
        coord_vars = [v for v in ["latitude", "longitude", "time"] if v in ds.variables]
        if coord_vars:
            ds = ds.set_coords(coord_vars)

        # Scientific Hygiene: Strip whitespace from string attributes
        for var in ds.variables:
            for attr, val in ds[var].attrs.items():
                if isinstance(val, str):
                    ds[var].attrs[attr] = val.strip()

        return ds

harmonize(ds)

Harmonize NCEP metadata to monetio standards.

Source code in monetio/readers/gfs.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def harmonize(self, ds: xr.Dataset) -> xr.Dataset:
    """
    Harmonize NCEP metadata to monetio standards.
    """
    # Coordinate Renaming
    rename_dict = {
        "latitude": "latitude",
        "longitude": "longitude",
        "lat": "latitude",
        "lon": "longitude",
        "lat_0": "latitude",
        "lon_0": "longitude",
        "time": "time",
        "valid_time": "time",
        "step": "step",
    }

    actual_rename = {}
    for k, v in rename_dict.items():
        if (k in ds.variables or k in ds.dims) and v not in ds.variables and k != v:
            actual_rename[k] = v

    if actual_rename:
        ds = ds.rename(actual_rename)

    # Variable Mapping
    var_mapping = {
        "O3MR": "ozone",
        "TMP": "temperature",
        "UGRD": "u_wind",
        "VGRD": "v_wind",
        "PRES": "pressure",
        "HGT": "height",
        "RH": "relative_humidity",
        "PRMSL": "mslp",
    }
    actual_var_rename = {}
    for var in ds.variables:
        for k, v in var_mapping.items():
            # Check for exact match or suffix (e.g., 'TMP:isobaricInhPa')
            if (var == k or var.startswith(f"{k}:")) and v not in ds.variables:
                actual_var_rename[var] = v
                break
    if actual_var_rename:
        ds = ds.rename(actual_var_rename)

    # Ensure latitude/longitude are coordinates
    coord_vars = [v for v in ["latitude", "longitude", "time"] if v in ds.variables]
    if coord_vars:
        ds = ds.set_coords(coord_vars)

    # Scientific Hygiene: Strip whitespace from string attributes
    for var in ds.variables:
        for attr, val in ds[var].attrs.items():
            if isinstance(val, str):
                ds[var].attrs[attr] = val.strip()

    return ds

open_dataset(files=None, dates=None, hour=0, lead_time=0, product='pgrb2.0p25', **kwargs)

Reads NCEP GRIB2 data from AWS S3.

Parameters:

Name Type Description Default
files Union[str, List[str]]

File path(s) or S3 URL(s).

None
dates Union[DatetimeIndex, List[datetime], datetime, str]

Dates to retrieve. If files is None, this is used to build URLs.

None
hour int

Forecast cycle hour (0, 6, 12, 18). Default is 0.

0
lead_time Union[int, List[int]]

Forecast lead time(s) in hours. Default is 0.

0
product str

Product string (e.g., 'pgrb2.0p25').

'pgrb2.0p25'
**kwargs dict

Additional arguments passed to XarrayDriver.open.

{}

Returns:

Type Description
Dataset

The dataset.

Source code in monetio/readers/gfs.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def open_dataset(
    self,
    files: str | list[str] = None,
    dates: pd.DatetimeIndex | list[datetime.datetime] | datetime.datetime | str = None,
    hour: int = 0,
    lead_time: int | list[int] = 0,
    product: str = "pgrb2.0p25",
    **kwargs,
) -> xr.Dataset:
    """
    Reads NCEP GRIB2 data from AWS S3.

    Parameters
    ----------
    files : Union[str, List[str]], optional
        File path(s) or S3 URL(s).
    dates : Union[pd.DatetimeIndex, List[datetime], datetime, str], optional
        Dates to retrieve. If files is None, this is used to build URLs.
    hour : int, optional
        Forecast cycle hour (0, 6, 12, 18). Default is 0.
    lead_time : Union[int, List[int]], optional
        Forecast lead time(s) in hours. Default is 0.
    product : str, optional
        Product string (e.g., 'pgrb2.0p25').
    **kwargs : dict
        Additional arguments passed to XarrayDriver.open.

    Returns
    -------
    xr.Dataset
        The dataset.
    """
    if files is None:
        if dates is None:
            raise ValueError("Either 'files' or 'dates' must be provided.")
        files = self.build_urls(dates, hour=hour, lead_time=lead_time, product=product)

    if "engine" not in kwargs:
        kwargs["engine"] = "grib2io"

    # grib2io engine generally requires local files or file-like objects.
    # XarrayDriver handles S3 URLs by opening them via fsspec.
    ds = super().open_dataset(files, **kwargs)

    # Apply standard harmonization
    ds = self.harmonize(ds)

    # Update history
    ds = update_history(ds, f"Read {self.__class__.__name__} data from AWS PDS.")

    return ds