Example #1
0
def save_dummy_seas5(
    tmp_path,
    date_str,
    to_grib=False,
    dataset="seasonal-monthly-pressure-levels",
    variable="temperature",
) -> Path:
    """
    filename structure:
     data/raw/seasonal-monthly-pressure-levels/temperature/2017/01.grib
    """
    year = pd.to_datetime(date_str).year
    month = pd.to_datetime(date_str).month
    out_dir = tmp_path / "data" / "raw" / dataset / variable / str(year)
    if not out_dir.exists():
        out_dir.mkdir(exist_ok=True, parents=True)

    ds = make_dummy_seas5_data(date_str)
    if to_grib:
        cfgrib.to_grib(
            ds,
            out_dir / f"{month:02}.grib",
            grib_keys={"edition": 2, "gridType": "regular_ll"},
        )
    else:
        ds.to_netcdf(out_dir / f"{month:02}.nc")

    return out_dir
Example #2
0
def dataset_to_fieldset(val, **kwarg):
    # we try to import xarray as locally as possible to reduce startup time
    # try to write the xarray as a GRIB file, then read into a fieldset
    import xarray as xr
    import cfgrib

    if not isinstance(val, xr.core.dataset.Dataset):
        raise TypeError(
            'dataset_to_fieldset requires a variable of type xr.core.dataset.Dataset;'
            ' was supplied with ', builtins.type(val))

    f, tmp = tempfile.mkstemp(".grib")
    os.close(f)

    try:
        # could add keys, e.g. grib_keys={'centre': 'ecmf'})
        cfgrib.to_grib(val, tmp, **kwarg)
    except:
        print(
            "Error trying to write xarray dataset to GRIB for conversion to Metview Fieldset"
        )
        raise

    # TODO: tell Metview that this is a temporary file that should be deleted when no longer needed
    fs = read(tmp)
    return fs