<jupyter_start><jupyter_text>Download CMIP5 from Copernicus Climate Data Store<jupyter_code>import cdsapi

c = cdsapi.Client()

c.retrieve(
    'projections-cmip5-monthly-single-levels',
    {
        'variable':[
            '2m_temperature','mean_precipitation_flux'
        ],
        'model':'noresm1_m',
        'experiment':'historical',
        'ensemble_member':'r1i1p1',
        'period':'185001-200512',
        'format':'tgz'
    },
    'cmip5_sfc_monthly_1850-200512.zip')<jupyter_output>2019-06-07 18:20:10,584 INFO Sending request to https://cds.climate.copernicus.eu/api/v2/resources/projections-cmip5-monthly-single-levels
2019-06-07 18:20:11,378 INFO Request is completed
2019-06-07 18:20:11,381 INFO Downloading http://136.156.132.105/cache-compute-0000/cache/data9/dataset-projections-cmip5-monthly-single-levels-f44286ff-5002-4beb-8ea5-91ce725c6499.zip to cmip5_sfc_monthly_1850-200512.zip (162M)
2019-06-07 18:20:28,718 INFO Download rate 9.3M/s<jupyter_text>Uncompress tarball- If you select one variable, one experiment, one model, etc. then you get one file only and it is a netCDF file (even if it says otherwise!)- As soon as you select more than one variable, or more than one experiment, etc. then you get a zip or tgz (depending on the format you chose)<jupyter_code>import zipfile
zip_ref = zipfile.ZipFile('cmip5_sfc_monthly_1850-200512.zip', 'r')
# extract all the files in the directory /opt/uio/GyHoCd/data/
zip_ref.extractall('/opt/uio/GyHoCd/data/cmip5/')
zip_ref.close()<jupyter_output><empty_output><jupyter_text>Open files- we have two files:    * pr_Amon_NorESM1-M_historical_r1i1p1_185001-200512.nc      * tas_Amon_NorESM1-M_historical_r1i1p1_185001-200512.nc<jupyter_code>import xarray as xr

# use open_mfdataset to open several netCDF files 
dset = xr.open_mfdataset("/opt/uio/GyHoCd/data/cmip5/*.nc")
print(dset)<jupyter_output><xarray.Dataset>
Dimensions:    (bnds: 2, lat: 96, lon: 144, time: 1872)
Coordinates:
  * time       (time) object 1850-01-16 12:00:00 ... 2005-12-16 12:00:00
  * lat        (lat) float64 -90.0 -88.11 -86.21 -84.32 ... 86.21 88.11 90.0
  * lon        (lon) float64 0.0 2.5 5.0 7.5 10.0 ... 350.0 352.5 355.0 357.5
    height     float64 ...
Dimensions without coordinates: bnds
Data variables:
    time_bnds  (time, bnds) object dask.array<shape=(1872, 2), chunksize=(1872, 2)>
    lat_bnds   (lat, bnds) float64 dask.array<shape=(96, 2), chunksize=(96, 2)>
    lon_bnds   (lon, bnds) float64 dask.array<shape=(144, 2), chunksize=(144, 2)>
    pr         (time, lat, lon) float32 dask.array<shape=(1872, 96, 144), chunksize=(1872, 96, 144)>
    tas        (time, lat, lon) float32 dask.array<shape=(1872, 96, 144), chunksize=(1872, 96, 144)>
Attributes:
    institution:            Norwegian Climate Centre
    institute_id:           NCC
    experiment_id:          historical
    source:           [...]<jupyter_text>Get the list of variables<jupyter_code>for varname, variable in dset.items():
    print(varname)<jupyter_output>time_bnds
lat_bnds
lon_bnds
pr
tas<jupyter_text>Create a python dictionary with variable and long name<jupyter_code>dict_variables = {}
for varname, variable in dset.items():
    if len(dset[varname].attrs) > 0:
        dict_variables[dset[varname].attrs['long_name']] = varname
print(dict_variables)
print(list(dict_variables.keys()))<jupyter_output>{'Precipitation': 'pr', 'Near-Surface Air Temperature': 'tas'}
['Precipitation', 'Near-Surface Air Temperature']<jupyter_text>Select temperature (tas)- two notations for accessing variables<jupyter_code>dset.tas
dset['tas']<jupyter_output><empty_output><jupyter_text>Get attributes<jupyter_code>dset['tas'].attrs['long_name']
dset['tas'].attrs['units']<jupyter_output><empty_output><jupyter_text>Create a widget to select available variables<jupyter_code>%matplotlib inline
import ipywidgets as widgets
select_variable = widgets.Select(
    options=['2m temperature', 'precipitation'],
    value='2m temperature',
    rows=2,
    description='Variable:',
    disabled=False
)

display(select_variable)<jupyter_output><empty_output><jupyter_text>Create a widget to select date (year and month)<jupyter_code>%matplotlib inline
import ipywidgets as widgets
select_date = widgets.Dropdown(
    options=dset.time.values.tolist(),
    rows=2,
    description='Date:',
    disabled=False
)

display(select_date)<jupyter_output><empty_output><jupyter_text>Create a function to generate a plot for a given date and given variable<jupyter_code>import matplotlib.pyplot as plt
import cartopy.crs as ccrs

def generate_plot(date, variable):
    
    fig = plt.figure(figsize=[12,5])

    # 111 means 1 row, 1 col and index 1
    ax = fig.add_subplot(111, projection=ccrs.PlateCarree(central_longitude=0))
    
    dset[variable].sel(time=date).plot(cmap='jet', 
                                      transform=ccrs.PlateCarree())
    ax.coastlines(color='white', linewidth=2.)<jupyter_output><empty_output><jupyter_text>Plot 2m temperature<jupyter_code>generate_plot(dset.time.values.tolist()[0], 'tas')<jupyter_output><empty_output><jupyter_text>Use widgets to plot the chosen variable at the chosen date<jupyter_code>import ipywidgets as widgets
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# widget for variables
list_variables = list(dict_variables.keys())
select_variable = widgets.Select(
    options=list_variables,
    value=list_variables[0],
    rows=2,
    description='Variable:',
    disabled=False
)

# Widget for date
select_date = widgets.Dropdown(
    options=dset.time.values.tolist(),
    rows=2,
    description='Date:',
    disabled=False
)

# generate plot 
def generate_plot(date, variable):
    
    fig = plt.figure(figsize=[12,5])

    # 111 means 1 row, 1 col and index 1
    ax = fig.add_subplot(111, projection=ccrs.PlateCarree(central_longitude=0))
    
    dset[dict_variables[variable]].sel(time=date).plot(cmap='jet', 
                                      transform=ccrs.PlateCarree())
    ax.coastlines(color='white', linewidth=2.)


interact_plot = widgets.interact(generate_plot, date = select_date, variable = select_variable);<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12302941654477491, 'fraction_numerical': 0.06549650576954331, 'mean_word_length': 4.402985074626866, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 52, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '381460', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 2490, 'n_tokens_neox': 2191, 'n_words': 449, 'path': 'files/python_widgets.ipynb', 'repo_name': 'NordicESMhub/climate-data', 'size': '6153'}