Commit f9086e29 authored by Ludvig Isaksson's avatar Ludvig Isaksson
Browse files

Plot example added.

parent bf8c98c4
......@@ -27,5 +27,8 @@ Modify the time, parameters, levels etc. to match your specific needs.
The folder ["mars_retrieve_total"](mars_retrieve_total/) contains python scripts for retrieving all datasets from the Copernicus Climate Change Service regional reanalysis for Europe reanalysis via the ECMWF MARS system.<br />
The scripts are provided as a complete base showing all available data. Please note that this means a lot of data. Modify the time, parameters, levels etc. to match your specific needs.
## CDS retrieval and plotting example
The folder ["retrieve_and_plot_example"](retrieve_and_plot_example/) contains 2 scripts. One to retrieve some data from Copernicus Climate Change Service regional reanalysis for Europe via the CDS API. The other script plots the data on a map and optionally creates an animation of the resulting images.
## Create forcing data for NEMO-Nordic
The folder ["create_forcing_for_NEMO"](create_forcing_for_NEMO/) contains a script system, which can be used to prepare forcing data for NEMO-Nordic (a regional ocean model). The scripts retrieve hourly data from MARS and mix analyses and forecasts. Then, the data is post-processed for the usage with NEMO-Nordic. For instance, relative humidity is transferred to specific humidity. At the end, the data is stored in netcdf-format as needed by NEMO.
# Retrieve and plot UERRA data
These scripts are an example of how to retrieve UERRA data from CDS API and plot GRIB or netCDF data with Python.
## The objectives of the scripts
These scripts will:
1. Retrieve data with CDS API.
2. Plot GRIB or netCDF data.
3. Make an animation.
## Instructions
1. Set the dates your are interested in.
2. Define directory for the downloaded file.
3. Set GRIB or netCDF and whether to animate or not.
4. Run to retrieve data.
5. Run to plot the data.
## Good to know
The scripts need some time if you are downloading a lot of data.
## Technical details
The scripts were developed and tested with Python 2.7.9 in Linux.
Used modules:
pygrib version : 2.0.0
netCDF4 version : 1.1.3
matplotlib version : 1.4.2
The plot script use the [CDO program]( and it's python bindings to transform from GRIB to netCDF.
If you don't need to transform you don't need CDO.
Below is info from the cdo -V command:
Climate Data Operators version 1.7.0 (
Libraries: HDF5/1.8.14 proj/4.7
Filetypes: srv ext ieg grb grb2 nc nc2 nc4 nc4c
CDI library version : 1.7.0
CGRIBEX library version : 1.7.3
GRIB_API library version : 1.14.0
netCDF library version : 4.3.2
HDF5 library version : 1.8.14
Moreover, to fetch data from CDS, you will need a account at [Copernicus Climate Data Store](
## General information
This project contains example code for users of the Copernicus Climate Change Service regional reanalysis for Europe (C3S_322_Lot1) data.
More information about the service can be found at the [Copernicus Climate Change Service regional reanalysis for Europe website](
The reanalysis data were initially produced within the FP7 pre-operational UERRA project.
More information about the reanalyses systems and data can be found at the [UERRA website](
These scripts belong to a lesson at [Copernicus user lerning service (ULS)](
#!/usr/bin/env python
import pygrib
# Date
from datetime import datetime
# Plot
import matplotlib
import pylab as plt
import matplotlib.colors as clr
from mpl_toolkits.basemap import Basemap
from cdo import *
cdo = Cdo()
# NetCDF
import netCDF4
from netCDF4 import Dataset
# path to data
data_path = ''
# file name
data_file = 'download.grib'
# select dates to plot
year = [2005]
month = [1]
day = [8,9]
hour = [0,6,12,18]
# plot GRIB or netCDF and animate or not
grib = True
netcdf = False
animate = False
def select_date(data):
a function to compare dates and return an array of locations to select datest
sel_data = []
i = 0
for d in data:
if d.year in year and d.month in month and in day and d.hour in hour:
i = i+1
return sel_data
def plotting(lon, lat, wind, MSLP, title=None, savename=None, levels=None, cmap=None):
A function to plot wind and pressure data
m = Basemap(llcrnrlon=-15, llcrnrlat=40, urcrnrlon=25, urcrnrlat=75, resolution='l')
x, y = m(lon, lat) # koordinater grid
draw_extras(m) # draw coastlines, countries, rivers
# Wind
CS_wind = m.contourf(x, y, wind, extend='max', levels=levels, cmap=cmap)
cbar = m.colorbar(CS_wind)'[m/s]')
CS_mslp = m.contour(x, y, MSLP/100, levels=range(950,1050,5), colors='k', linewidths=1)
plt.clabel(CS_mslp, inline=1, forntsize=10, fmt='%i', zoder=0)
if title:
if savename:
def draw_extras(m):
A function to draw coastlines, countries, rivers
m.drawcountries(linewidth=0.4, color='k', zorder=4)
m.drawcoastlines(linewidth=0.4, color='k', zorder=4)
def to_netcdf(data):
A function to transform data to netCDF-file
Return data as netCDF
nc_data = cdo.setgridtype('curvilinear', input=data, options='-f nc')
return nc_data
def read_netcdf(data, variable):
A function to read data from netCDF-file
Return time, longitude, latitude and value of 'variable'
nc_fid = Dataset(data, 'r')
time_var = nc_fid.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
lats = nc_fid.variables['lat'][:]
lons = nc_fid.variables['lon'][:]
data = nc_fid.variables[variable][:].squeeze()
return dtime, lons, lats, data
if __name__ == '__main__':
if grib:
grb_data = # read GRIB
wind ='10 metre wind speed') # select wind data
MSLP ='Mean sea level pressure') # select pressure data
sel_data = select_date(wind) # select time
for i in sel_data:
lats, lons = wind[i].latlons() # read longitude and lattitude from GRIB
values_wind = wind[i].values
values_MSLP = MSLP[i].values
time = datetime(wind[i].year, wind[i].month, wind[i].day, wind[i].hour)
title = 'Storm ' + time.strftime('%Y-%b-%d %H:%M')
savename = data_path + 'Storm_' + time.strftime('%Y%m%d_%H%M') + '.png'
levels = [0,0.3,1.6,3.4,5.5,8,10.8,13.9,17.2,20.8,24.5,28.5,32.7]
colors = ['#5EBC32','#ffff00','#AF111A','#764285']
cmap = clr.LinearSegmentedColormap.from_list('wind speed', colors, N=256)
plotting(lons, lats, values_wind, values_MSLP, title=title, savename=savename, levels=levels, cmap=cmap) #plotting GRIB-data
if netcdf:
nc_data = to_netcdf(data_path+data_file) # transform GRIB to netCDF
[time, lons, lats, wind] = read_netcdf(nc_data, '10si') # read wind data from netCDF
[time, lons, lats, MSLP] = read_netcdf(nc_data, 'msl') # read pressure data from netCDF
sel_data = select_date(time) # select time
for i in sel_data:
values_wind = wind[i,:,:]
values_MSLP = MSLP[i,:,:]
title = 'Storm ' + str(time[i].strftime('%Y-%b-%d %H:%M'))
savename = data_path + 'Storm_' + str(time[i].strftime('%Y%m%d_%H%M')) + '.png'
levels = [0,0.3,1.6,3.4,5.5,8,10.8,13.9,17.2,20.8,24.5,28.5,32.7]
colors = ['#5EBC32','#ffff00','#AF111A','#764285']
cmap = clr.LinearSegmentedColormap.from_list('wind speed', colors, N=256)
plotting(lons, lats, values_wind, values_MSLP, title=title, savename=savename, levels=levels, cmap=cmap) #plotting NetCDF-data
if animate:
figurename = data_path + 'Storm_*.png'
animationname = data_path + 'stormanimation.gif''convert -delay 100 ' + figurename + ' ' + animationname, shell=True)
#!/usr/bin/env python
import cdsapi
# Change the variables for year, month and day to a time as you wish
year = ['2005']
month = ['01']
day = ['6','7','8','9','10']
c = cdsapi.Client()
def uerra_request(reqYear, reqMonth, reqDates):
A UERRA request for the variables in the array 'variables'.
Origin uerra_harmonie, single levels, analysis fields.
Request cost per day is 8 fields, ca 5 Mbytes.
'origin': 'uerra_harmonie',
'variable': ['10m_wind_speed','mean_sea_level_pressure'],
'year': reqYear,
'month': reqMonth,
'day': reqDates,
'time': ['00:00','06:00','12:00','18:00'],
'format': 'grib',
if __name__ == '__main__':
uerra_request(year, month, day)
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment