Xarray and OPeNDAP

This is a minimal example of RID usage using Xarray and OPeNDAP in Python. This script may be modified to load locally-stored NetCDF files (instead of OPeNDAP URLs). Thanks to Tobias Kerzenmacher for providing this example.

import xarray as xr

# Generate the list of URLs based on the known pattern
base_url = "https://www.jamstec.go.jp/RID/thredds/dodsC/testAll/zonal/common-grid/monthly/tem-qg/ERA5/ERA5_zonal_common-grid_monthly_tem-qg_20{}-{}.nc"
years = [f"{year:02d}" for year in range(2, 13)]  # Adjust the range as needed
months = [f"{month:02d}" for month in range(1, 13)]

# Create a list of all URLs
urls = [base_url.format(year, month) for year in years for month in months]

def prepro(ds):
    ds=ds.drop_vars('days_included').drop_vars('days_averaged')
    return ds

# Open the dataset using xarray's open_mfdataset
ds = xr.open_mfdataset(urls, preprocess = prepro, combine='by_coords')[['wres', 'vres']]

# Remove problematic attributes
ds_cleaned = ds.copy()
if '_NCProperties' in ds_cleaned.attrs:
    del ds_cleaned.attrs['_NCProperties']  # Remove the _NCProperties attribute
    
# Save the dataset to a NetCDF file
output_file = 'jamstec_era5_vres_wres.nc'
ds_cleaned.to_netcdf(output_file)

print(f"Dataset saved to {output_file}")

ds_cleaned.wres.isel(time=1).T.plot.contourf(yscale='log', levels=11, yincrease=False, xlim=[-45, 45], ylim=[10000,100], vmin=-0.0001, vmax=0.0001, extend='both')